diff --git a/shared/package-files/18/1803d258c010f0c5dd395c23de2a2730bbc6f16fcdf45a2513a7129d4dfdb923/test_fillna.py b/shared/package-files/18/1803d258c010f0c5dd395c23de2a2730bbc6f16fcdf45a2513a7129d4dfdb923/test_fillna.py new file mode 100644 index 0000000000000000000000000000000000000000..89c50a8c21e1c89dae9be9e267215c346474ffad --- /dev/null +++ b/shared/package-files/18/1803d258c010f0c5dd395c23de2a2730bbc6f16fcdf45a2513a7129d4dfdb923/test_fillna.py @@ -0,0 +1,932 @@ +import numpy as np +import pytest + +from pandas._config import using_pyarrow_string_dtype + +import pandas.util._test_decorators as td + +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + NaT, + PeriodIndex, + Series, + TimedeltaIndex, + Timestamp, + date_range, + to_datetime, +) +import pandas._testing as tm +from pandas.tests.frame.common import _check_mixed_float + + +class TestFillNA: + def test_fillna_dict_inplace_nonunique_columns( + self, using_copy_on_write, warn_copy_on_write + ): + df = DataFrame( + {"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]} + ) + df.columns = ["A", "A", "A"] + orig = df[:] + + # TODO(CoW-warn) better warning message + with tm.assert_cow_warning(warn_copy_on_write): + df.fillna({"A": 2}, inplace=True) + # The first and third columns can be set inplace, while the second cannot. + + expected = DataFrame( + {"A": [2.0] * 3, "B": [2, Timestamp(1), 2], "C": [2, "foo", 2]} + ) + expected.columns = ["A", "A", "A"] + tm.assert_frame_equal(df, expected) + + # TODO: what's the expected/desired behavior with CoW? + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 0], orig.iloc[:, 0]) + assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1]) + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2]) + + @td.skip_array_manager_not_yet_implemented + def test_fillna_on_column_view(self, using_copy_on_write): + # GH#46149 avoid unnecessary copies + arr = np.full((40, 50), np.nan) + df = DataFrame(arr, copy=False) + + if using_copy_on_write: + with tm.raises_chained_assignment_error(): + df[0].fillna(-1, inplace=True) + assert np.isnan(arr[:, 0]).all() + else: + with tm.assert_produces_warning(FutureWarning, match="inplace method"): + df[0].fillna(-1, inplace=True) + assert (arr[:, 0] == -1).all() + + # i.e. we didn't create a new 49-column block + assert len(df._mgr.arrays) == 1 + assert np.shares_memory(df.values, arr) + + def test_fillna_datetime(self, datetime_frame): + tf = datetime_frame + tf.loc[tf.index[:5], "A"] = np.nan + tf.loc[tf.index[-5:], "A"] = np.nan + + zero_filled = datetime_frame.fillna(0) + assert (zero_filled.loc[zero_filled.index[:5], "A"] == 0).all() + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + padded = datetime_frame.fillna(method="pad") + assert np.isnan(padded.loc[padded.index[:5], "A"]).all() + assert ( + padded.loc[padded.index[-5:], "A"] == padded.loc[padded.index[-5], "A"] + ).all() + + msg = "Must specify a fill 'value' or 'method'" + with pytest.raises(ValueError, match=msg): + datetime_frame.fillna() + msg = "Cannot specify both 'value' and 'method'" + with pytest.raises(ValueError, match=msg): + datetime_frame.fillna(5, method="ffill") + + @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="can't fill 0 in string") + def test_fillna_mixed_type(self, float_string_frame): + mf = float_string_frame + mf.loc[mf.index[5:20], "foo"] = np.nan + mf.loc[mf.index[-10:], "A"] = np.nan + # TODO: make stronger assertion here, GH 25640 + mf.fillna(value=0) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + mf.fillna(method="pad") + + def test_fillna_mixed_float(self, mixed_float_frame): + # mixed numeric (but no float16) + mf = mixed_float_frame.reindex(columns=["A", "B", "D"]) + mf.loc[mf.index[-10:], "A"] = np.nan + result = mf.fillna(value=0) + _check_mixed_float(result, dtype={"C": None}) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = mf.fillna(method="pad") + _check_mixed_float(result, dtype={"C": None}) + + def test_fillna_empty(self, using_copy_on_write): + if using_copy_on_write: + pytest.skip("condition is unnecessary complex and is deprecated anyway") + # empty frame (GH#2778) + df = DataFrame(columns=["x"]) + for m in ["pad", "backfill"]: + msg = "Series.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.x.fillna(method=m, inplace=True) + df.x.fillna(method=m) + + def test_fillna_different_dtype(self, using_infer_string): + # with different dtype (GH#3386) + df = DataFrame( + [["a", "a", np.nan, "a"], ["b", "b", np.nan, "b"], ["c", "c", np.nan, "c"]] + ) + + if using_infer_string: + with tm.assert_produces_warning(FutureWarning, match="Downcasting"): + result = df.fillna({2: "foo"}) + else: + result = df.fillna({2: "foo"}) + expected = DataFrame( + [["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]] + ) + tm.assert_frame_equal(result, expected) + + if using_infer_string: + with tm.assert_produces_warning(FutureWarning, match="Downcasting"): + return_value = df.fillna({2: "foo"}, inplace=True) + else: + return_value = df.fillna({2: "foo"}, inplace=True) + tm.assert_frame_equal(df, expected) + assert return_value is None + + def test_fillna_limit_and_value(self): + # limit and value + df = DataFrame(np.random.default_rng(2).standard_normal((10, 3))) + df.iloc[2:7, 0] = np.nan + df.iloc[3:5, 2] = np.nan + + expected = df.copy() + expected.iloc[2, 0] = 999 + expected.iloc[3, 2] = 999 + result = df.fillna(999, limit=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_datelike(self): + # with datelike + # GH#6344 + df = DataFrame( + { + "Date": [NaT, Timestamp("2014-1-1")], + "Date2": [Timestamp("2013-1-1"), NaT], + } + ) + + expected = df.copy() + expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"]) + result = df.fillna(value={"Date": df["Date2"]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_tzaware(self): + # with timezone + # GH#15855 + df = DataFrame({"A": [Timestamp("2012-11-11 00:00:00+01:00"), NaT]}) + exp = DataFrame( + { + "A": [ + Timestamp("2012-11-11 00:00:00+01:00"), + Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="pad") + tm.assert_frame_equal(res, exp) + + df = DataFrame({"A": [NaT, Timestamp("2012-11-11 00:00:00+01:00")]}) + exp = DataFrame( + { + "A": [ + Timestamp("2012-11-11 00:00:00+01:00"), + Timestamp("2012-11-11 00:00:00+01:00"), + ] + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="bfill") + tm.assert_frame_equal(res, exp) + + def test_fillna_tzaware_different_column(self): + # with timezone in another column + # GH#15522 + df = DataFrame( + { + "A": date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1, 2, np.nan, np.nan], + } + ) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="pad") + expected = DataFrame( + { + "A": date_range("20130101", periods=4, tz="US/Eastern"), + "B": [1.0, 2.0, 2.0, 2.0], + } + ) + tm.assert_frame_equal(result, expected) + + def test_na_actions_categorical(self): + cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) + vals = ["a", "b", np.nan, "d"] + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3]) + vals2 = ["a", "b", "b", "d"] + df_exp_fill = DataFrame({"cats": cat2, "vals": vals2}) + cat3 = Categorical([1, 2, 3], categories=[1, 2, 3]) + vals3 = ["a", "b", np.nan] + df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3}) + cat4 = Categorical([1, 2], categories=[1, 2, 3]) + vals4 = ["a", "b"] + df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4}) + + # fillna + res = df.fillna(value={"cats": 3, "vals": "b"}) + tm.assert_frame_equal(res, df_exp_fill) + + msg = "Cannot setitem on a Categorical with a new category" + with pytest.raises(TypeError, match=msg): + df.fillna(value={"cats": 4, "vals": "c"}) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.fillna(method="pad") + tm.assert_frame_equal(res, df_exp_fill) + + # dropna + res = df.dropna(subset=["cats"]) + tm.assert_frame_equal(res, df_exp_drop_cats) + + res = df.dropna() + tm.assert_frame_equal(res, df_exp_drop_all) + + # make sure that fillna takes missing values into account + c = Categorical([np.nan, "b", np.nan], categories=["a", "b"]) + df = DataFrame({"cats": c, "vals": [1, 2, 3]}) + + cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"]) + df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]}) + + res = df.fillna("a") + tm.assert_frame_equal(res, df_exp) + + def test_fillna_categorical_nan(self): + # GH#14021 + # np.nan should always be a valid filler + cat = Categorical([np.nan, 2, np.nan]) + val = Categorical([np.nan, np.nan, np.nan]) + df = DataFrame({"cats": cat, "vals": val}) + + # GH#32950 df.median() is poorly behaved because there is no + # Categorical.median + median = Series({"cats": 2.0, "vals": np.nan}) + + res = df.fillna(median) + v_exp = [np.nan, np.nan, np.nan] + df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, dtype="category") + tm.assert_frame_equal(res, df_exp) + + result = df.cats.fillna(np.nan) + tm.assert_series_equal(result, df.cats) + + result = df.vals.fillna(np.nan) + tm.assert_series_equal(result, df.vals) + + idx = DatetimeIndex( + ["2011-01-01 09:00", "2016-01-01 23:45", "2011-01-01 09:00", NaT, NaT] + ) + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + idx = PeriodIndex(["2011-01", "2011-01", "2011-01", NaT, NaT], freq="M") + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + idx = TimedeltaIndex(["1 days", "2 days", "1 days", NaT, NaT]) + df = DataFrame({"a": Categorical(idx)}) + tm.assert_frame_equal(df.fillna(value=NaT), df) + + def test_fillna_downcast(self): + # GH#15277 + # infer int64 from float64 + df = DataFrame({"a": [1.0, np.nan]}) + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(0, downcast="infer") + expected = DataFrame({"a": [1, 0]}) + tm.assert_frame_equal(result, expected) + + # infer int64 from float64 when fillna value is a dict + df = DataFrame({"a": [1.0, np.nan]}) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna({"a": 0}, downcast="infer") + expected = DataFrame({"a": [1, 0]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_downcast_false(self, frame_or_series): + # GH#45603 preserve object dtype with downcast=False + obj = frame_or_series([1, 2, 3], dtype="object") + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.fillna("", downcast=False) + tm.assert_equal(result, obj) + + def test_fillna_downcast_noop(self, frame_or_series): + # GH#45423 + # Two relevant paths: + # 1) not _can_hold_na (e.g. integer) + # 2) _can_hold_na + noop + not can_hold_element + + obj = frame_or_series([1, 2, 3], dtype=np.int64) + + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#40988 + res = obj.fillna("foo", downcast=np.dtype(np.int32)) + expected = obj.astype(np.int32) + tm.assert_equal(res, expected) + + obj2 = obj.astype(np.float64) + with tm.assert_produces_warning(FutureWarning, match=msg): + res2 = obj2.fillna("foo", downcast="infer") + expected2 = obj # get back int64 + tm.assert_equal(res2, expected2) + + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#40988 + res3 = obj2.fillna("foo", downcast=np.dtype(np.int32)) + tm.assert_equal(res3, expected) + + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) + def test_fillna_dictlike_value_duplicate_colnames(self, columns): + # GH#43476 + df = DataFrame(np.nan, index=[0, 1], columns=columns) + with tm.assert_produces_warning(None): + result = df.fillna({"A": 0}) + + expected = df.copy() + expected["A"] = 0.0 + tm.assert_frame_equal(result, expected) + + def test_fillna_dtype_conversion(self, using_infer_string): + # make sure that fillna on an empty frame works + df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) + result = df.dtypes + expected = Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5]) + tm.assert_series_equal(result, expected) + + msg = "Downcasting object dtype arrays" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(1) + expected = DataFrame(1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) + tm.assert_frame_equal(result, expected) + + # empty block + df = DataFrame(index=range(3), columns=["A", "B"], dtype="float64") + if using_infer_string: + with tm.assert_produces_warning(FutureWarning, match="Downcasting"): + result = df.fillna("nan") + else: + result = df.fillna("nan") + expected = DataFrame("nan", index=range(3), columns=["A", "B"]) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("val", ["", 1, np.nan, 1.0]) + def test_fillna_dtype_conversion_equiv_replace(self, val): + df = DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]}) + expected = df.replace(np.nan, val) + result = df.fillna(val) + tm.assert_frame_equal(result, expected) + + def test_fillna_datetime_columns(self): + # GH#7095 + df = DataFrame( + { + "A": [-1, -2, np.nan], + "B": date_range("20130101", periods=3), + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=date_range("20130110", periods=3), + ) + result = df.fillna("?") + expected = DataFrame( + { + "A": [-1, -2, "?"], + "B": date_range("20130101", periods=3), + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + df = DataFrame( + { + "A": [-1, -2, np.nan], + "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), NaT], + "C": ["foo", "bar", None], + "D": ["foo2", "bar2", None], + }, + index=date_range("20130110", periods=3), + ) + result = df.fillna("?") + expected = DataFrame( + { + "A": [-1, -2, "?"], + "B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), "?"], + "C": ["foo", "bar", "?"], + "D": ["foo2", "bar2", "?"], + }, + index=date_range("20130110", periods=3), + ) + tm.assert_frame_equal(result, expected) + + def test_ffill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + alt = datetime_frame.fillna(method="ffill") + tm.assert_frame_equal(datetime_frame.ffill(), alt) + + def test_bfill(self, datetime_frame): + datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan + datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + alt = datetime_frame.fillna(method="bfill") + + tm.assert_frame_equal(datetime_frame.bfill(), alt) + + def test_frame_pad_backfill_limit(self): + index = np.arange(10) + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index) + + result = df[:2].reindex(index, method="pad", limit=5) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[:2].reindex(index).fillna(method="pad") + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index, method="backfill", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[-2:].reindex(index).fillna(method="backfill") + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_frame_fillna_limit(self): + index = np.arange(10) + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index) + + result = df[:2].reindex(index) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = result.fillna(method="pad", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[:2].reindex(index).fillna(method="pad") + expected.iloc[-3:] = np.nan + tm.assert_frame_equal(result, expected) + + result = df[-2:].reindex(index) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = result.fillna(method="backfill", limit=5) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df[-2:].reindex(index).fillna(method="backfill") + expected.iloc[:3] = np.nan + tm.assert_frame_equal(result, expected) + + def test_fillna_skip_certain_blocks(self): + # don't try to fill boolean, int blocks + + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)).astype(int)) + + # it works! + df.fillna(np.nan) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_positive_limit(self, type): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type) + + msg = "Limit must be greater than 0" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=-5) + + @pytest.mark.parametrize("type", [int, float]) + def test_fillna_integer_limit(self, type): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type) + + msg = "Limit must be an integer" + with pytest.raises(ValueError, match=msg): + df.fillna(0, limit=0.5) + + def test_fillna_inplace(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))) + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + + expected = df.fillna(value=0) + assert expected is not df + + df.fillna(value=0, inplace=True) + tm.assert_frame_equal(df, expected) + + expected = df.fillna(value={0: 0}, inplace=True) + assert expected is None + + df.loc[:4, 1] = np.nan + df.loc[-4:, 3] = np.nan + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.fillna(method="ffill") + assert expected is not df + + with tm.assert_produces_warning(FutureWarning, match=msg): + df.fillna(method="ffill", inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_dict_series(self): + df = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + } + ) + + result = df.fillna({"a": 0, "b": 5}) + + expected = df.copy() + expected["a"] = expected["a"].fillna(0) + expected["b"] = expected["b"].fillna(5) + tm.assert_frame_equal(result, expected) + + # it works + result = df.fillna({"a": 0, "b": 5, "d": 7}) + + # Series treated same as dict + result = df.fillna(df.max()) + expected = df.fillna(df.max().to_dict()) + tm.assert_frame_equal(result, expected) + + # disable this for now + with pytest.raises(NotImplementedError, match="column by column"): + df.fillna(df.max(1), axis=1) + + def test_fillna_dataframe(self): + # GH#8377 + df = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, np.nan], + "b": [1, 2, 3, np.nan, np.nan], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + # df2 may have different index and columns + df2 = DataFrame( + { + "a": [np.nan, 10, 20, 30, 40], + "b": [50, 60, 70, 80, 90], + "foo": ["bar"] * 5, + }, + index=list("VWXuZ"), + ) + + result = df.fillna(df2) + + # only those columns and indices which are shared get filled + expected = DataFrame( + { + "a": [np.nan, 1, 2, np.nan, 40], + "b": [1, 2, 3, np.nan, 90], + "c": [np.nan, 1, 2, 3, 4], + }, + index=list("VWXYZ"), + ) + + tm.assert_frame_equal(result, expected) + + def test_fillna_columns(self): + arr = np.random.default_rng(2).standard_normal((10, 10)) + arr[:, ::2] = np.nan + df = DataFrame(arr) + + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="ffill", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.T.fillna(method="pad").T + tm.assert_frame_equal(result, expected) + + df.insert(6, "foo", 5) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna(method="ffill", axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.astype(float).fillna(method="ffill", axis=1) + tm.assert_frame_equal(result, expected) + + def test_fillna_invalid_method(self, float_frame): + with pytest.raises(ValueError, match="ffil"): + float_frame.fillna(method="ffil") + + def test_fillna_invalid_value(self, float_frame): + # list + msg = '"value" parameter must be a scalar or dict, but you passed a "{}"' + with pytest.raises(TypeError, match=msg.format("list")): + float_frame.fillna([1, 2]) + # tuple + with pytest.raises(TypeError, match=msg.format("tuple")): + float_frame.fillna((1, 2)) + # frame with series + msg = ( + '"value" parameter must be a scalar, dict or Series, but you ' + 'passed a "DataFrame"' + ) + with pytest.raises(TypeError, match=msg): + float_frame.iloc[:, 0].fillna(float_frame) + + def test_fillna_col_reordering(self): + cols = ["COL." + str(i) for i in range(5, 0, -1)] + data = np.random.default_rng(2).random((20, 5)) + df = DataFrame(index=range(20), columns=cols, data=data) + msg = "DataFrame.fillna with 'method' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + filled = df.fillna(method="ffill") + assert df.columns.tolist() == filled.columns.tolist() + + @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="can't fill 0 in string") + def test_fill_corner(self, float_frame, float_string_frame): + mf = float_string_frame + mf.loc[mf.index[5:20], "foo"] = np.nan + mf.loc[mf.index[-10:], "A"] = np.nan + + filled = float_string_frame.fillna(value=0) + assert (filled.loc[filled.index[5:20], "foo"] == 0).all() + del float_string_frame["foo"] + + float_frame.reindex(columns=[]).fillna(value=0) + + def test_fillna_downcast_dict(self): + # GH#40809 + df = DataFrame({"col1": [1, np.nan]}) + + msg = "The 'downcast' keyword in fillna" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.fillna({"col1": 2}, downcast={"col1": "int64"}) + expected = DataFrame({"col1": [1, 2]}) + tm.assert_frame_equal(result, expected) + + def test_fillna_with_columns_and_limit(self): + # GH40989 + df = DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + result = df.fillna(axis=1, value=100, limit=1) + result2 = df.fillna(axis=1, value=100, limit=2) + + expected = DataFrame( + { + "A": Series([100, 3, 100, 100], dtype="float64"), + "B": [2, 4, np.nan, 3], + "C": [np.nan, 100, np.nan, np.nan], + "D": Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + expected2 = DataFrame( + { + "A": Series([100, 3, 100, 100], dtype="float64"), + "B": Series([2, 4, 100, 3], dtype="float64"), + "C": [100, 100, np.nan, 100], + "D": Series([0, 1, 5, 4], dtype="float64"), + }, + index=[0, 1, 2, 3], + ) + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected2) + + def test_fillna_datetime_inplace(self): + # GH#48863 + df = DataFrame( + { + "date1": to_datetime(["2018-05-30", None]), + "date2": to_datetime(["2018-09-30", None]), + } + ) + expected = df.copy() + df.fillna(np.nan, inplace=True) + tm.assert_frame_equal(df, expected) + + def test_fillna_inplace_with_columns_limit_and_value(self): + # GH40989 + df = DataFrame( + [ + [np.nan, 2, np.nan, 0], + [3, 4, np.nan, 1], + [np.nan, np.nan, np.nan, 5], + [np.nan, 3, np.nan, 4], + ], + columns=list("ABCD"), + ) + + expected = df.fillna(axis=1, value=100, limit=1) + assert expected is not df + + df.fillna(axis=1, value=100, limit=1, inplace=True) + tm.assert_frame_equal(df, expected) + + @td.skip_array_manager_invalid_test + @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}]) + def test_inplace_dict_update_view( + self, val, using_copy_on_write, warn_copy_on_write + ): + # GH#47188 + df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]}) + df_orig = df.copy() + result_view = df[:] + with tm.assert_cow_warning(warn_copy_on_write): + df.fillna(val, inplace=True) + expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]}) + tm.assert_frame_equal(df, expected) + if using_copy_on_write: + tm.assert_frame_equal(result_view, df_orig) + else: + tm.assert_frame_equal(result_view, expected) + + def test_single_block_df_with_horizontal_axis(self): + # GH 47713 + df = DataFrame( + { + "col1": [5, 0, np.nan, 10, np.nan], + "col2": [7, np.nan, np.nan, 5, 3], + "col3": [12, np.nan, 1, 2, 0], + "col4": [np.nan, 1, 1, np.nan, 18], + } + ) + result = df.fillna(50, limit=1, axis=1) + expected = DataFrame( + [ + [5.0, 7.0, 12.0, 50.0], + [0.0, 50.0, np.nan, 1.0], + [50.0, np.nan, 1.0, 1.0], + [10.0, 5.0, 2.0, 50.0], + [50.0, 3.0, 0.0, 18.0], + ], + columns=["col1", "col2", "col3", "col4"], + ) + tm.assert_frame_equal(result, expected) + + def test_fillna_with_multi_index_frame(self): + # GH 47649 + pdf = DataFrame( + { + ("x", "a"): [np.nan, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, np.nan], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + expected = DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -1.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({"x": -1}), expected) + tm.assert_frame_equal(pdf.fillna({"x": -1, ("x", "b"): -2}), expected) + + expected = DataFrame( + { + ("x", "a"): [-1.0, 2.0, 3.0], + ("x", "b"): [1.0, 2.0, -2.0], + ("y", "c"): [1.0, 2.0, np.nan], + } + ) + tm.assert_frame_equal(pdf.fillna({("x", "b"): -2, "x": -1}), expected) + + +def test_fillna_nonconsolidated_frame(): + # https://github.com/pandas-dev/pandas/issues/36495 + df = DataFrame( + [ + [1, 1, 1, 1.0], + [2, 2, 2, 2.0], + [3, 3, 3, 3.0], + ], + columns=["i1", "i2", "i3", "f1"], + ) + df_nonconsol = df.pivot(index="i1", columns="i2") + result = df_nonconsol.fillna(0) + assert result.isna().sum().sum() == 0 + + +def test_fillna_nones_inplace(): + # GH 48480 + df = DataFrame( + [[None, None], [None, None]], + columns=["A", "B"], + ) + msg = "Downcasting object dtype arrays" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.fillna(value={"A": 1, "B": 2}, inplace=True) + + expected = DataFrame([[1, 2], [1, 2]], columns=["A", "B"]) + tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("func", ["pad", "backfill"]) +def test_pad_backfill_deprecated(func): + # GH#33396 + df = DataFrame({"a": [1, 2, 3]}) + with tm.assert_produces_warning(FutureWarning): + getattr(df, func)() + + +@pytest.mark.parametrize( + "data, expected_data, method, kwargs", + ( + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan], + "ffill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0], + "ffill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + range(5), + range(5), + "ffill", + {"limit_area": "outside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "inside", "limit": 1}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside"}, + ), + ( + [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], + [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], + "bfill", + {"limit_area": "outside", "limit": 1}, + ), + ), +) +def test_ffill_bfill_limit_area(data, expected_data, method, kwargs): + # GH#56492 + df = DataFrame(data) + expected = DataFrame(expected_data) + result = getattr(df, method)(**kwargs) + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/18/180f0539d35295855bfb29426e4bc3975151a2d08857ed009d3dd2441c1de747/union_find.cpython-311.pyc b/shared/package-files/18/180f0539d35295855bfb29426e4bc3975151a2d08857ed009d3dd2441c1de747/union_find.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7927345a4e1c1388254ef0e45b7a04b70c37925 Binary files /dev/null and b/shared/package-files/18/180f0539d35295855bfb29426e4bc3975151a2d08857ed009d3dd2441c1de747/union_find.cpython-311.pyc differ diff --git a/shared/package-files/18/181a71d8310cd917e57afd1c022a6fbf3651d6008e4bf6d637cbf34970f93912/take_along_dim_native.h b/shared/package-files/18/181a71d8310cd917e57afd1c022a6fbf3651d6008e4bf6d637cbf34970f93912/take_along_dim_native.h new file mode 100644 index 0000000000000000000000000000000000000000..9480d140983945162956e000063a77c90b21c55a --- /dev/null +++ b/shared/package-files/18/181a71d8310cd917e57afd1c022a6fbf3651d6008e4bf6d637cbf34970f93912/take_along_dim_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor take_along_dim(const at::Tensor & self, const at::Tensor & indices, ::std::optional dim=::std::nullopt); +TORCH_API at::Tensor & take_along_dim_out(const at::Tensor & self, const at::Tensor & indices, ::std::optional dim, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/18/1822d1c4023fdcfc260e63a5a36617872615921327c5a6341ec75a80535d459f/nll_loss_nd.h b/shared/package-files/18/1822d1c4023fdcfc260e63a5a36617872615921327c5a6341ec75a80535d459f/nll_loss_nd.h new file mode 100644 index 0000000000000000000000000000000000000000..102834efe4c939837d4b30e510a6fbac05445fc6 --- /dev/null +++ b/shared/package-files/18/1822d1c4023fdcfc260e63a5a36617872615921327c5a6341ec75a80535d459f/nll_loss_nd.h @@ -0,0 +1,48 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor +inline at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); +} +namespace symint { + template >> + at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); + } +} + +// aten::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor +inline at::Tensor nll_loss_nd_symint(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); +} +namespace symint { + template >> + at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) { + return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index); + } +} + +} diff --git a/shared/package-files/18/182d24026129d741f141943e1883646af15d3ba8fe6886b83accf6077c8afad6/conv.cpython-311.pyc b/shared/package-files/18/182d24026129d741f141943e1883646af15d3ba8fe6886b83accf6077c8afad6/conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4746cecd3516faf53abf7d93800bb4d9c69b02be Binary files /dev/null and b/shared/package-files/18/182d24026129d741f141943e1883646af15d3ba8fe6886b83accf6077c8afad6/conv.cpython-311.pyc differ diff --git a/shared/package-files/18/1836c8c8830b13005f7e086e2d1f4ecef3818fc59a558065981bbaf221d27465/METADATA b/shared/package-files/18/1836c8c8830b13005f7e086e2d1f4ecef3818fc59a558065981bbaf221d27465/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..783ffef45789467382ada3be6880b21006b96129 --- /dev/null +++ b/shared/package-files/18/1836c8c8830b13005f7e086e2d1f4ecef3818fc59a558065981bbaf221d27465/METADATA @@ -0,0 +1,35 @@ +Metadata-Version: 2.1 +Name: nvidia-cublas-cu12 +Version: 12.6.4.1 +Summary: CUBLAS native runtime libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt + +CUBLAS native runtime libraries diff --git a/shared/package-files/18/1841ca6850b8f13de8fbf4a61f8f3ae06bcacb1d4881b542e884883d5971edae/core.py b/shared/package-files/18/1841ca6850b8f13de8fbf4a61f8f3ae06bcacb1d4881b542e884883d5971edae/core.py new file mode 100644 index 0000000000000000000000000000000000000000..bd62546bdd9d35dcc46e0b46a46b0c61a43fd0ba --- /dev/null +++ b/shared/package-files/18/1841ca6850b8f13de8fbf4a61f8f3ae06bcacb1d4881b542e884883d5971edae/core.py @@ -0,0 +1,289 @@ +"""distutils.core + +The only module that needs to be imported to use the Distutils; provides +the 'setup' function (which is to be called from the setup script). Also +indirectly provides the Distribution and Command classes, although they are +really defined in distutils.dist and distutils.cmd. +""" + +from __future__ import annotations + +import os +import sys +import tokenize +from collections.abc import Iterable + +from .cmd import Command +from .debug import DEBUG + +# Mainly import these so setup scripts can "from distutils.core import" them. +from .dist import Distribution +from .errors import ( + CCompilerError, + DistutilsArgError, + DistutilsError, + DistutilsSetupError, +) +from .extension import Extension + +__all__ = ['Distribution', 'Command', 'Extension', 'setup'] + +# This is a barebones help message generated displayed when the user +# runs the setup script with no arguments at all. More useful help +# is generated with various --help options: global help, list commands, +# and per-command help. +USAGE = """\ +usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] + or: %(script)s --help [cmd1 cmd2 ...] + or: %(script)s --help-commands + or: %(script)s cmd --help +""" + + +def gen_usage(script_name): + script = os.path.basename(script_name) + return USAGE % locals() + + +# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'. +_setup_stop_after = None +_setup_distribution = None + +# Legal keyword arguments for the setup() function +setup_keywords = ( + 'distclass', + 'script_name', + 'script_args', + 'options', + 'name', + 'version', + 'author', + 'author_email', + 'maintainer', + 'maintainer_email', + 'url', + 'license', + 'description', + 'long_description', + 'keywords', + 'platforms', + 'classifiers', + 'download_url', + 'requires', + 'provides', + 'obsoletes', +) + +# Legal keyword arguments for the Extension constructor +extension_keywords = ( + 'name', + 'sources', + 'include_dirs', + 'define_macros', + 'undef_macros', + 'library_dirs', + 'libraries', + 'runtime_library_dirs', + 'extra_objects', + 'extra_compile_args', + 'extra_link_args', + 'swig_opts', + 'export_symbols', + 'depends', + 'language', +) + + +def setup(**attrs): # noqa: C901 + """The gateway to the Distutils: do everything your setup script needs + to do, in a highly flexible and user-driven way. Briefly: create a + Distribution instance; find and parse config files; parse the command + line; run each Distutils command found there, customized by the options + supplied to 'setup()' (as keyword arguments), in config files, and on + the command line. + + The Distribution instance might be an instance of a class supplied via + the 'distclass' keyword argument to 'setup'; if no such class is + supplied, then the Distribution class (in dist.py) is instantiated. + All other arguments to 'setup' (except for 'cmdclass') are used to set + attributes of the Distribution instance. + + The 'cmdclass' argument, if supplied, is a dictionary mapping command + names to command classes. Each command encountered on the command line + will be turned into a command class, which is in turn instantiated; any + class found in 'cmdclass' is used in place of the default, which is + (for command 'foo_bar') class 'foo_bar' in module + 'distutils.command.foo_bar'. The command class must provide a + 'user_options' attribute which is a list of option specifiers for + 'distutils.fancy_getopt'. Any command-line options between the current + and the next command are used to set attributes of the current command + object. + + When the entire command-line has been successfully parsed, calls the + 'run()' method on each command object in turn. This method will be + driven entirely by the Distribution object (which each command object + has a reference to, thanks to its constructor), and the + command-specific options that became attributes of each command + object. + """ + + global _setup_stop_after, _setup_distribution + + # Determine the distribution class -- either caller-supplied or + # our Distribution (see below). + klass = attrs.get('distclass') + if klass: + attrs.pop('distclass') + else: + klass = Distribution + + if 'script_name' not in attrs: + attrs['script_name'] = os.path.basename(sys.argv[0]) + if 'script_args' not in attrs: + attrs['script_args'] = sys.argv[1:] + + # Create the Distribution instance, using the remaining arguments + # (ie. everything except distclass) to initialize it + try: + _setup_distribution = dist = klass(attrs) + except DistutilsSetupError as msg: + if 'name' not in attrs: + raise SystemExit(f"error in setup command: {msg}") + else: + raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg)) + + if _setup_stop_after == "init": + return dist + + # Find and parse the config file(s): they will override options from + # the setup script, but be overridden by the command line. + dist.parse_config_files() + + if DEBUG: + print("options (after parsing config files):") + dist.dump_option_dicts() + + if _setup_stop_after == "config": + return dist + + # Parse the command line and override config files; any + # command-line errors are the end user's fault, so turn them into + # SystemExit to suppress tracebacks. + try: + ok = dist.parse_command_line() + except DistutilsArgError as msg: + raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}") + + if DEBUG: + print("options (after parsing command line):") + dist.dump_option_dicts() + + if _setup_stop_after == "commandline": + return dist + + # And finally, run all the commands found on the command line. + if ok: + return run_commands(dist) + + return dist + + +# setup () + + +def run_commands(dist): + """Given a Distribution object run all the commands, + raising ``SystemExit`` errors in the case of failure. + + This function assumes that either ``sys.argv`` or ``dist.script_args`` + is already set accordingly. + """ + try: + dist.run_commands() + except KeyboardInterrupt: + raise SystemExit("interrupted") + except OSError as exc: + if DEBUG: + sys.stderr.write(f"error: {exc}\n") + raise + else: + raise SystemExit(f"error: {exc}") + + except (DistutilsError, CCompilerError) as msg: + if DEBUG: + raise + else: + raise SystemExit("error: " + str(msg)) + + return dist + + +def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"): + """Run a setup script in a somewhat controlled environment, and + return the Distribution instance that drives things. This is useful + if you need to find out the distribution meta-data (passed as + keyword args from 'script' to 'setup()', or the contents of the + config files or command-line. + + 'script_name' is a file that will be read and run with 'exec()'; + 'sys.argv[0]' will be replaced with 'script' for the duration of the + call. 'script_args' is a list of strings; if supplied, + 'sys.argv[1:]' will be replaced by 'script_args' for the duration of + the call. + + 'stop_after' tells 'setup()' when to stop processing; possible + values: + init + stop after the Distribution instance has been created and + populated with the keyword arguments to 'setup()' + config + stop after config files have been parsed (and their data + stored in the Distribution instance) + commandline + stop after the command-line ('sys.argv[1:]' or 'script_args') + have been parsed (and the data stored in the Distribution) + run [default] + stop after all commands have been run (the same as if 'setup()' + had been called in the usual way + + Returns the Distribution instance, which provides all information + used to drive the Distutils. + """ + if stop_after not in ('init', 'config', 'commandline', 'run'): + raise ValueError(f"invalid value for 'stop_after': {stop_after!r}") + + global _setup_stop_after, _setup_distribution + _setup_stop_after = stop_after + + save_argv = sys.argv.copy() + g = {'__file__': script_name, '__name__': '__main__'} + try: + try: + sys.argv[0] = script_name + if script_args is not None: + sys.argv[1:] = script_args + # tokenize.open supports automatic encoding detection + with tokenize.open(script_name) as f: + code = f.read().replace(r'\r\n', r'\n') + exec(code, g) + finally: + sys.argv = save_argv + _setup_stop_after = None + except SystemExit: + # Hmm, should we do something if exiting with a non-zero code + # (ie. error)? + pass + + if _setup_distribution is None: + raise RuntimeError( + "'distutils.core.setup()' was never called -- " + f"perhaps '{script_name}' is not a Distutils setup script?" + ) + + # I wonder if the setup script's namespace -- g and l -- would be of + # any interest to callers? + # print "_setup_distribution:", _setup_distribution + return _setup_distribution + + +# run_setup () diff --git a/shared/package-files/18/184be769d39367769f56b6cde56139d8e8423fc83330823f00de281d0c6f129a/algorithms.py b/shared/package-files/18/184be769d39367769f56b6cde56139d8e8423fc83330823f00de281d0c6f129a/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..f4890eb8c25e565095600e2713c0de270aa0cf97 --- /dev/null +++ b/shared/package-files/18/184be769d39367769f56b6cde56139d8e8423fc83330823f00de281d0c6f129a/algorithms.py @@ -0,0 +1,180 @@ +from sympy.core.containers import Tuple +from sympy.core.numbers import oo +from sympy.core.relational import (Gt, Lt) +from sympy.core.symbol import (Dummy, Symbol) +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.logic.boolalg import And +from sympy.codegen.ast import ( + Assignment, AddAugmentedAssignment, break_, CodeBlock, Declaration, FunctionDefinition, + Print, Return, Scope, While, Variable, Pointer, real +) +from sympy.codegen.cfunctions import isnan + +""" This module collects functions for constructing ASTs representing algorithms. """ + +def newtons_method(expr, wrt, atol=1e-12, delta=None, *, rtol=4e-16, debug=False, + itermax=None, counter=None, delta_fn=lambda e, x: -e/e.diff(x), + cse=False, handle_nan=None, + bounds=None): + """ Generates an AST for Newton-Raphson method (a root-finding algorithm). + + Explanation + =========== + + Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's + method of root-finding. + + Parameters + ========== + + expr : expression + wrt : Symbol + With respect to, i.e. what is the variable. + atol : number or expression + Absolute tolerance (stopping criterion) + rtol : number or expression + Relative tolerance (stopping criterion) + delta : Symbol + Will be a ``Dummy`` if ``None``. + debug : bool + Whether to print convergence information during iterations + itermax : number or expr + Maximum number of iterations. + counter : Symbol + Will be a ``Dummy`` if ``None``. + delta_fn: Callable[[Expr, Symbol], Expr] + computes the step, default is newtons method. For e.g. Halley's method + use delta_fn=lambda e, x: -2*e*e.diff(x)/(2*e.diff(x)**2 - e*e.diff(x, 2)) + cse: bool + Perform common sub-expression elimination on delta expression + handle_nan: Token + How to handle occurrence of not-a-number (NaN). + bounds: Optional[tuple[Expr, Expr]] + Perform optimization within bounds + + Examples + ======== + + >>> from sympy import symbols, cos + >>> from sympy.codegen.ast import Assignment + >>> from sympy.codegen.algorithms import newtons_method + >>> x, dx, atol = symbols('x dx atol') + >>> expr = cos(x) - x**3 + >>> algo = newtons_method(expr, x, atol=atol, delta=dx) + >>> algo.has(Assignment(dx, -expr/expr.diff(x))) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Newton%27s_method + + """ + + if delta is None: + delta = Dummy() + Wrapper = Scope + name_d = 'delta' + else: + Wrapper = lambda x: x + name_d = delta.name + + delta_expr = delta_fn(expr, wrt) + if cse: + from sympy.simplify.cse_main import cse + cses, (red,) = cse([delta_expr.factor()]) + whl_bdy = [Assignment(dum, sub_e) for dum, sub_e in cses] + whl_bdy += [Assignment(delta, red)] + else: + whl_bdy = [Assignment(delta, delta_expr)] + if handle_nan is not None: + whl_bdy += [While(isnan(delta), CodeBlock(handle_nan, break_))] + whl_bdy += [AddAugmentedAssignment(wrt, delta)] + if bounds is not None: + whl_bdy += [Assignment(wrt, Min(Max(wrt, bounds[0]), bounds[1]))] + if debug: + prnt = Print([wrt, delta], r"{}=%12.5g {}=%12.5g\n".format(wrt.name, name_d)) + whl_bdy += [prnt] + req = Gt(Abs(delta), atol + rtol*Abs(wrt)) + declars = [Declaration(Variable(delta, type=real, value=oo))] + if itermax is not None: + counter = counter or Dummy(integer=True) + v_counter = Variable.deduced(counter, 0) + declars.append(Declaration(v_counter)) + whl_bdy.append(AddAugmentedAssignment(counter, 1)) + req = And(req, Lt(counter, itermax)) + whl = While(req, CodeBlock(*whl_bdy)) + blck = declars + if debug: + blck.append(Print([wrt], r"{}=%12.5g\n".format(wrt.name))) + blck += [whl] + return Wrapper(CodeBlock(*blck)) + + +def _symbol_of(arg): + if isinstance(arg, Declaration): + arg = arg.variable.symbol + elif isinstance(arg, Variable): + arg = arg.symbol + return arg + + +def newtons_method_function(expr, wrt, params=None, func_name="newton", attrs=Tuple(), *, delta=None, **kwargs): + """ Generates an AST for a function implementing the Newton-Raphson method. + + Parameters + ========== + + expr : expression + wrt : Symbol + With respect to, i.e. what is the variable + params : iterable of symbols + Symbols appearing in expr that are taken as constants during the iterations + (these will be accepted as parameters to the generated function). + func_name : str + Name of the generated function. + attrs : Tuple + Attribute instances passed as ``attrs`` to ``FunctionDefinition``. + \\*\\*kwargs : + Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`. + + Examples + ======== + + >>> from sympy import symbols, cos + >>> from sympy.codegen.algorithms import newtons_method_function + >>> from sympy.codegen.pyutils import render_as_module + >>> x = symbols('x') + >>> expr = cos(x) - x**3 + >>> func = newtons_method_function(expr, x) + >>> py_mod = render_as_module(func) # source code as string + >>> namespace = {} + >>> exec(py_mod, namespace, namespace) + >>> res = eval('newton(0.5)', namespace) + >>> abs(res - 0.865474033102) < 1e-12 + True + + See Also + ======== + + sympy.codegen.algorithms.newtons_method + + """ + if params is None: + params = (wrt,) + pointer_subs = {p.symbol: Symbol('(*%s)' % p.symbol.name) + for p in params if isinstance(p, Pointer)} + if delta is None: + delta = Symbol('d_' + wrt.name) + if expr.has(delta): + delta = None # will use Dummy + algo = newtons_method(expr, wrt, delta=delta, **kwargs).xreplace(pointer_subs) + if isinstance(algo, Scope): + algo = algo.body + not_in_params = expr.free_symbols.difference({_symbol_of(p) for p in params}) + if not_in_params: + raise ValueError("Missing symbols in params: %s" % ', '.join(map(str, not_in_params))) + declars = tuple(Variable(p, real) for p in params) + body = CodeBlock(algo, Return(wrt)) + return FunctionDefinition(real, func_name, declars, body, attrs=attrs) diff --git a/shared/package-files/18/1855a71ae746e0bd92c9d8088768f15409d6c10fe017b666c406c5d90ca0473e/exceptions.cpython-311.pyc b/shared/package-files/18/1855a71ae746e0bd92c9d8088768f15409d6c10fe017b666c406c5d90ca0473e/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ac770cc74e5621879d8b143c066a902ef2e1d8e Binary files /dev/null and b/shared/package-files/18/1855a71ae746e0bd92c9d8088768f15409d6c10fe017b666c406c5d90ca0473e/exceptions.cpython-311.pyc differ diff --git a/shared/package-files/18/1858f22f67ad031bd5337abb36114419c5d2e60c8a8fc5736ea71b2b3a6a6ce9/test_dist.py b/shared/package-files/18/1858f22f67ad031bd5337abb36114419c5d2e60c8a8fc5736ea71b2b3a6a6ce9/test_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..e65ab310e7f2ad98b591affb352c855a2f86eda1 --- /dev/null +++ b/shared/package-files/18/1858f22f67ad031bd5337abb36114419c5d2e60c8a8fc5736ea71b2b3a6a6ce9/test_dist.py @@ -0,0 +1,278 @@ +import os +import re +import urllib.parse +import urllib.request + +import pytest + +from setuptools import Distribution +from setuptools.dist import check_package_data, check_specifier + +from .test_easy_install import make_trivial_sdist +from .test_find_packages import ensure_files +from .textwrap import DALS + +from distutils.errors import DistutilsSetupError + + +def test_dist_fetch_build_egg(tmpdir): + """ + Check multiple calls to `Distribution.fetch_build_egg` work as expected. + """ + index = tmpdir.mkdir('index') + index_url = urllib.parse.urljoin('file://', urllib.request.pathname2url(str(index))) + + def sdist_with_index(distname, version): + dist_dir = index.mkdir(distname) + dist_sdist = f'{distname}-{version}.tar.gz' + make_trivial_sdist(str(dist_dir.join(dist_sdist)), distname, version) + with dist_dir.join('index.html').open('w') as fp: + fp.write( + DALS( + """ + + {dist_sdist}
+ + """ + ).format(dist_sdist=dist_sdist) + ) + + sdist_with_index('barbazquux', '3.2.0') + sdist_with_index('barbazquux-runner', '2.11.1') + with tmpdir.join('setup.cfg').open('w') as fp: + fp.write( + DALS( + """ + [easy_install] + index_url = {index_url} + """ + ).format(index_url=index_url) + ) + reqs = """ + barbazquux-runner + barbazquux + """.split() + with tmpdir.as_cwd(): + dist = Distribution() + dist.parse_config_files() + resolved_dists = [dist.fetch_build_egg(r) for r in reqs] + assert [dist.key for dist in resolved_dists if dist] == reqs + + +EXAMPLE_BASE_INFO = dict( + name="package", + version="0.0.1", + author="Foo Bar", + author_email="foo@bar.net", + long_description="Long\ndescription", + description="Short description", + keywords=["one", "two"], +) + + +def test_provides_extras_deterministic_order(): + attrs = dict(extras_require=dict(a=['foo'], b=['bar'])) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['a', 'b'] + attrs['extras_require'] = dict(reversed(attrs['extras_require'].items())) + dist = Distribution(attrs) + assert list(dist.metadata.provides_extras) == ['b', 'a'] + + +CHECK_PACKAGE_DATA_TESTS = ( + # Valid. + ( + { + '': ['*.txt', '*.rst'], + 'hello': ['*.msg'], + }, + None, + ), + # Not a dictionary. + ( + ( + ('', ['*.txt', '*.rst']), + ('hello', ['*.msg']), + ), + ( + "'package_data' must be a dictionary mapping package" + " names to lists of string wildcard patterns" + ), + ), + # Invalid key type. + ( + { + 400: ['*.txt', '*.rst'], + }, + ("keys of 'package_data' dict must be strings (got 400)"), + ), + # Invalid value type. + ( + { + 'hello': '*.msg', + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got '*.msg')" + ), + ), + # Invalid value type (generators are single use) + ( + { + 'hello': (x for x in "generator"), + }, + ( + "\"values of 'package_data' dict\" must be of type " + " (got =3.0, !=3.1'} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + attrs = {'name': 'foo', 'python_requires': ['>=3.0', '!=3.1']} + dist = Distribution(attrs) + check_specifier(dist, attrs, attrs['python_requires']) + + # invalid specifier value + attrs = {'name': 'foo', 'python_requires': '>=invalid-version'} + with pytest.raises(DistutilsSetupError): + dist = Distribution(attrs) + + +def test_metadata_name(): + with pytest.raises(DistutilsSetupError, match='missing.*name'): + Distribution()._validate_metadata() + + +@pytest.mark.parametrize( + ('dist_name', 'py_module'), + [ + ("my.pkg", "my_pkg"), + ("my-pkg", "my_pkg"), + ("my_pkg", "my_pkg"), + ("pkg", "pkg"), + ], +) +def test_dist_default_py_modules(tmp_path, dist_name, py_module): + (tmp_path / f"{py_module}.py").touch() + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- make sure common tool files are ignored + + attrs = {**EXAMPLE_BASE_INFO, "name": dist_name, "src_root": str(tmp_path)} + # Find `py_modules` corresponding to dist_name if not given + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules == [py_module] + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicity_py_module"]}) + dist.set_defaults() + assert dist.py_modules == ["explicity_py_module"] + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicity_package"]}) + dist.set_defaults() + assert not dist.py_modules + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files', 'packages'), + [ + ("my.pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my-pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]), + ("my.pkg", None, ["my/pkg/__init__.py"], ["my", "my.pkg"]), + ( + "my_pkg", + None, + ["src/my_pkg/__init__.py", "src/my_pkg2/__init__.py"], + ["my_pkg", "my_pkg2"], + ), + ( + "my_pkg", + {"pkg": "lib", "pkg2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ["pkg", "pkg.nested", "pkg2"], + ), + ], +) +def test_dist_default_packages( + tmp_path, dist_name, package_dir, package_files, packages +): + ensure_files(tmp_path, package_files) + + (tmp_path / "setup.py").touch() + (tmp_path / "noxfile.py").touch() + # ^-- should not be included by default + + attrs = { + **EXAMPLE_BASE_INFO, + "name": dist_name, + "src_root": str(tmp_path), + "package_dir": package_dir, + } + # Find `packages` either corresponding to dist_name or inside src + dist = Distribution(attrs) + dist.set_defaults() + assert not dist.py_modules + assert not dist.py_modules + assert set(dist.packages) == set(packages) + # When `py_modules` is given, don't do anything + dist = Distribution({**attrs, "py_modules": ["explicit_py_module"]}) + dist.set_defaults() + assert not dist.packages + assert set(dist.py_modules) == {"explicit_py_module"} + # When `packages` is given, don't do anything + dist = Distribution({**attrs, "packages": ["explicit_package"]}) + dist.set_defaults() + assert not dist.py_modules + assert set(dist.packages) == {"explicit_package"} + + +@pytest.mark.parametrize( + ('dist_name', 'package_dir', 'package_files'), + [ + ("my.pkg.nested", None, ["my/pkg/nested/__init__.py"]), + ("my.pkg", None, ["my/pkg/__init__.py", "my/pkg/file.py"]), + ("my_pkg", None, ["my_pkg.py"]), + ("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/nested/__init__.py"]), + ("my_pkg", None, ["src/my_pkg/__init__.py", "src/my_pkg/nested/__init__.py"]), + ( + "my_pkg", + {"my_pkg": "lib", "my_pkg.lib2": "lib2"}, + ["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"], + ), + # Should not try to guess a name from multiple py_modules/packages + ("UNKNOWN", None, ["src/mod1.py", "src/mod2.py"]), + ("UNKNOWN", None, ["src/pkg1/__ini__.py", "src/pkg2/__init__.py"]), + ], +) +def test_dist_default_name(tmp_path, dist_name, package_dir, package_files): + """Make sure dist.name is discovered from packages/py_modules""" + ensure_files(tmp_path, package_files) + attrs = { + **EXAMPLE_BASE_INFO, + "src_root": "/".join(os.path.split(tmp_path)), # POSIX-style + "package_dir": package_dir, + } + del attrs["name"] + + dist = Distribution(attrs) + dist.set_defaults() + assert dist.py_modules or dist.packages + assert dist.get_name() == dist_name diff --git a/shared/package-files/18/18710c3cbccb74d874bc184bf77629cbfc5f77d6a35b873841c1a6f488cdf7cc/vcfconcat.c.pysam.c b/shared/package-files/18/18710c3cbccb74d874bc184bf77629cbfc5f77d6a35b873841c1a6f488cdf7cc/vcfconcat.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..d238dc0455d3655d7887189140aac2b87801df7a --- /dev/null +++ b/shared/package-files/18/18710c3cbccb74d874bc184bf77629cbfc5f77d6a35b873841c1a6f488cdf7cc/vcfconcat.c.pysam.c @@ -0,0 +1,1131 @@ +#include "bcftools.pysam.h" + +/* vcfconcat.c -- Concatenate or combine VCF/BCF files. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for hts_get_bgzfp() +#include +#include +#include +#include "bcftools.h" + +typedef struct _args_t +{ + bcf_srs_t *files; + htsFile *out_fh; + int output_type, n_threads, record_cmd_line, clevel; + bcf_hdr_t *out_hdr; + int *seen_seq; + char *index_fn; + int write_index; + + // phasing + int *start_pos, start_tid, ifname; + int *swap_phase, nswap, *nmatch, *nmism; + bcf1_t **buf; + uint8_t *buf_mask; + int nbuf, mbuf, prev_chr, min_PQ, prev_pos_check; + int32_t *GTa, *GTb, mGTa, mGTb, *phase_qual, *phase_set; + + char **argv, *output_fname, *file_list, **fnames, *remove_dups, *regions_list; + int argc, nfnames, allow_overlaps, phased_concat, regions_is_file, regions_overlap; + int compact_PS, phase_set_changed, naive_concat, naive_concat_trust_headers; + int verbose, explicit_output_type, ligate_force, ligate_warn; + int sites_only; + htsThreadPool *tpool; +} +args_t; + +static bcf_hdr_t *drop_hdr_genotypes(args_t *args, bcf_hdr_t *hdr) +{ + if ( !args->sites_only ) return hdr; + bcf_hdr_t *rmme = hdr; + hdr = bcf_hdr_subset(rmme, 0, 0, 0); + bcf_hdr_remove(hdr, BCF_HL_FMT, NULL); + bcf_hdr_destroy(rmme); + return hdr; +} + +static void init_data(args_t *args) +{ + bcf1_t *line = NULL; + + // With phased concat, the chunks overlap and come in the right order. To + // avoid opening all files at once, store start positions to recognise need + // for the next one. This way we can keep only two open chunks at once. + if ( args->phased_concat ) + { + args->start_pos = (int*) malloc(sizeof(int)*args->nfnames); + line = bcf_init(); + } + + if ( args->verbose ) fprintf(bcftools_stderr,"Checking the headers and starting positions of %d files\n", args->nfnames); + kstring_t str = {0,0,0}; + int i, prev_chrid = -1; + for (i=0; infnames; i++) + { + htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]); + bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]); + hdr = drop_hdr_genotypes(args, hdr); + + args->out_hdr = bcf_hdr_merge(args->out_hdr,hdr); + if ( bcf_hdr_nsamples(hdr) != bcf_hdr_nsamples(args->out_hdr) ) + error("Different number of samples in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]); + + int j; + for (j=0; jout_hdr->samples[j],hdr->samples[j]) ) + error("Different sample names in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]); + + if ( args->phased_concat ) + { + int ret = bcf_read(fp, hdr, line); + if ( ret!=0 ) args->start_pos[i] = -2; // empty file + else + { + int chrid = bcf_hdr_id2int(args->out_hdr,BCF_DT_CTG,bcf_seqname(hdr,line)); + args->start_pos[i] = chrid==prev_chrid ? line->pos : -1; + prev_chrid = chrid; + } + } + bcf_hdr_destroy(hdr); + if ( hts_close(fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fnames[i]); + } + free(str.s); + if ( line ) bcf_destroy(line); + + args->seen_seq = (int*) calloc(args->out_hdr->n[BCF_DT_CTG],sizeof(int)); + + if ( args->phased_concat ) + { + bcf_hdr_append(args->out_hdr,"##FORMAT="); + bcf_hdr_append(args->out_hdr,"##FORMAT="); + } + if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_concat"); + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno)); + if ( args->allow_overlaps || args->phased_concat ) + { + args->files = bcf_sr_init(); + args->files->require_index = 1; + } + if ( args->n_threads ) + { + if ( args->files ) + { + if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n"); + args->tpool = args->files->p; + } + else + { + args->tpool = (htsThreadPool*) calloc(1, sizeof(htsThreadPool)); + if ( !args->tpool ) error("Failed to allocate memory\n"); + if ( !(args->tpool->pool = hts_tpool_init(args->n_threads)) ) error("Failed to initialize %d threads\n",args->n_threads); + } + hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->tpool); + } + if ( bcf_hdr_write(args->out_fh, args->out_hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname); + if ( init_index2(args->out_fh,args->out_hdr,args->output_fname, + &args->index_fn, args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->output_fname); + + if ( args->allow_overlaps ) + { + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + if ( args->remove_dups ) + { + if ( !strcmp(args->remove_dups,"snps") ) args->files->collapse |= COLLAPSE_SNPS; + else if ( !strcmp(args->remove_dups,"indels") ) args->files->collapse |= COLLAPSE_INDELS; + else if ( !strcmp(args->remove_dups,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS; + else if ( !strcmp(args->remove_dups,"any") ) args->files->collapse |= COLLAPSE_ANY; + else if ( !strcmp(args->remove_dups,"all") ) args->files->collapse |= COLLAPSE_ANY; + else if ( !strcmp(args->remove_dups,"none") ) args->files->collapse = COLLAPSE_NONE; + else if ( !strcmp(args->remove_dups,"exact") ) args->files->collapse = COLLAPSE_NONE; + else error("The -D string \"%s\" not recognised.\n", args->remove_dups); + } + for (i=0; infnames; i++) + if ( !bcf_sr_add_reader(args->files,args->fnames[i]) ) error("Failed to open %s: %s\n", args->fnames[i],bcf_sr_strerror(args->files->errnum)); + } + else if ( args->phased_concat ) + { + // Remove empty files from the list + int nok = 0; + while (1) + { + while ( noknfnames && args->start_pos[nok]!=-2 ) nok++; + if ( nok==args->nfnames ) break; + + i = nok; + while ( infnames && args->start_pos[i]==-2 ) i++; + if ( i==args->nfnames ) break; + + int tmp = args->start_pos[nok]; args->start_pos[nok] = args->start_pos[i]; args->start_pos[i] = tmp; + char *str = args->fnames[nok]; args->fnames[nok] = args->fnames[i]; args->fnames[i] = str; + } + for (i=nok; infnames; i++) free(args->fnames[i]); + args->nfnames = nok; + + for (i=1; infnames; i++) + if ( args->start_pos[i-1]!=-1 && args->start_pos[i]!=-1 && args->start_pos[i]start_pos[i-1] ) + error("The files not in ascending order: %d in %s, %d in %s\n", args->start_pos[i-1]+1,args->fnames[i-1],args->start_pos[i]+1,args->fnames[i]); + + args->prev_chr = -1; + args->swap_phase = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int)); + args->nmatch = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int)); + args->nmism = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int)); + args->phase_qual = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t)); + args->phase_set = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t)); + args->ifname = 0; + } +} + +static void destroy_data(args_t *args) +{ + int i; + if ( args->out_fh ) + { + if ( args->write_index ) + { + if ( bcf_idx_save(args->out_fh)<0 ) + { + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n",args->output_fname?args->output_fname:"bcftools_stdout"); + } + if ( args->tpool && !args->files ) + { + hts_tpool_destroy(args->tpool->pool); + free(args->tpool); + } + if ( args->files ) bcf_sr_destroy(args->files); + if ( args->out_hdr ) bcf_hdr_destroy(args->out_hdr); + free(args->seen_seq); + free(args->start_pos); + free(args->swap_phase); + for (i=0; imbuf; i++) bcf_destroy(args->buf[i]); + free(args->buf); + free(args->buf_mask); + free(args->GTa); + free(args->GTb); + free(args->nmatch); + free(args->nmism); + free(args->phase_qual); + free(args->phase_set); + for (i=0; infnames; i++) free(args->fnames[i]); + free(args->fnames); +} + +int vcf_write_line(htsFile *fp, kstring_t *line); + +#define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; } +static void phase_update(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec) +{ + int i, nGTs = bcf_get_genotypes(hdr, rec, &args->GTa, &args->mGTa); + if ( nGTs <= 0 ) return; // GT field is not present + for (i=0; iswap_phase[i] ) continue; + int *gt = &args->GTa[i*2]; + if ( bcf_gt_is_missing(gt[0]) || gt[1]==bcf_int32_vector_end ) continue; + if ( !bcf_gt_is_phased(gt[1]) ) continue; + SWAP(int, gt[0], gt[1]); + gt[1] |= 1; + } + bcf_update_genotypes(hdr,rec,args->GTa,nGTs); +} + +static void phased_flush(args_t *args) +{ + if ( !args->nbuf ) return; + + bcf_hdr_t *ahdr = args->files->readers[0].header; + bcf_hdr_t *bhdr = args->files->readers[1].header; + + int i, j, nsmpl = bcf_hdr_nsamples(args->out_hdr); + static int gt_absent_warned = 0; + for (i=0; inbuf; i+=2) + { + if ( args->buf_mask[i/2]!=3 ) continue; + + bcf1_t *arec = args->buf[i]; + bcf1_t *brec = args->buf[i+1]; + + int nGTs = bcf_get_genotypes(ahdr, arec, &args->GTa, &args->mGTa); + if ( nGTs < 0 ) + { + if ( !gt_absent_warned ) + { + fprintf(bcftools_stderr,"GT is not present at %s:%"PRId64". (This warning is printed only once.)\n", bcf_seqname(ahdr,arec), (int64_t) arec->pos+1); + gt_absent_warned = 1; + } + continue; + } + if ( nGTs != 2*nsmpl ) continue; // not diploid + nGTs = bcf_get_genotypes(bhdr, brec, &args->GTb, &args->mGTb); + if ( nGTs < 0 ) + { + if ( !gt_absent_warned ) + { + fprintf(bcftools_stderr,"GT is not present at %s:%"PRId64". (This warning is printed only once.)\n", bcf_seqname(bhdr,brec), (int64_t) brec->pos+1); + gt_absent_warned = 1; + } + continue; + } + if ( nGTs != 2*nsmpl ) continue; // not diploid + + for (j=0; jGTa[j*2]; + int *gtb = &args->GTb[j*2]; + if ( gta[1]==bcf_int32_vector_end || gtb[1]==bcf_int32_vector_end ) continue; + if ( bcf_gt_is_missing(gta[0]) || bcf_gt_is_missing(gta[1]) || bcf_gt_is_missing(gtb[0]) || bcf_gt_is_missing(gtb[1]) ) continue; + if ( !bcf_gt_is_phased(gta[1]) || !bcf_gt_is_phased(gtb[1]) ) continue; + if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gta[1]) || bcf_gt_allele(gtb[0])==bcf_gt_allele(gtb[1]) ) continue; + if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[0]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[1]) ) + { + if ( args->swap_phase[j] ) args->nmism[j]++; else args->nmatch[j]++; + } + if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[1]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[0]) ) + { + if ( args->swap_phase[j] ) args->nmatch[j]++; else args->nmism[j]++; + } + } + } + for (i=0; inbuf/2; i+=2) + { + bcf1_t *rec; + bcf_hdr_t *hdr; + int mask = args->buf_mask[i/2]; + if ( mask & 1 ) { rec = args->buf[i]; hdr = args->files->readers[0].header; } + else { rec = args->buf[i+1]; hdr = args->files->readers[1].header; } + bcf_translate(args->out_hdr, hdr, rec); + if ( args->nswap && (mask&1) ) + phase_update(args, args->out_hdr, rec); + if ( !args->compact_PS || args->phase_set_changed ) + { + bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl); + args->phase_set_changed = 0; + } + if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + + if ( rec->pos < args->prev_pos_check ) error("FIXME, disorder: %s:%"PRId64" vs %d [1]\n", bcf_seqname(hdr,rec),(int64_t)rec->pos+1,args->prev_pos_check+1); + args->prev_pos_check = rec->pos; + } + args->nswap = 0; + for (j=0; jnmatch[j] >= args->nmism[j] ) + args->swap_phase[j] = 0; + else + { + args->swap_phase[j] = 1; + args->nswap++; + } + if ( args->nmatch[j] && args->nmism[j] ) + { + // Entropy-inspired quality. The factor 0.7 shifts and scales to (0,1) + double f = (double)args->nmatch[j]/(args->nmatch[j]+args->nmism[j]); + args->phase_qual[j] = 99*(0.7 + f*log(f) + (1-f)*log(1-f))/0.7; + } + else + args->phase_qual[j] = 99; + args->nmatch[j] = 0; + args->nmism[j] = 0; + } + int PQ_printed = 0; + for (; inbuf; i+=2) + { + bcf1_t *rec; + bcf_hdr_t *hdr; + int mask = args->buf_mask[i/2]; + if ( mask & 2 ) { rec = args->buf[i+1]; hdr = args->files->readers[1].header; } + else { rec = args->buf[i]; hdr = args->files->readers[0].header; } + bcf_translate(args->out_hdr, hdr, rec); + if ( !PQ_printed && mask==3 ) + { + bcf_update_format_int32(args->out_hdr,rec,"PQ",args->phase_qual,nsmpl); + PQ_printed = 1; + for (j=0; jphase_qual[j] < args->min_PQ ) + { + args->phase_set[j] = rec->pos+1; + args->phase_set_changed = 1; + } + else if ( args->compact_PS ) args->phase_set[j] = bcf_int32_missing; + } + if ( args->nswap ) + phase_update(args, args->out_hdr, rec); + if ( !args->compact_PS || args->phase_set_changed ) + { + bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl); + args->phase_set_changed = 0; + } + if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + + if ( rec->pos < args->prev_pos_check ) error("FIXME, disorder: %s:%"PRId64" vs %d [2]\n", bcf_seqname(hdr,rec),(int64_t)rec->pos+1,args->prev_pos_check+1); + args->prev_pos_check = rec->pos; + } + args->nbuf = 0; +} + +static void phased_push(args_t *args, bcf1_t *arec, bcf1_t *brec, int is_overlap) +{ + bcf_hdr_t *ahdr = arec ? bcf_sr_get_header(args->files,0) : NULL; + bcf_hdr_t *bhdr = brec ? bcf_sr_get_header(args->files,1) : NULL; + + if ( arec && arec->errcode ) + error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(ahdr,arec),(int64_t) arec->pos+1, args->files->readers[0].fname); + if ( brec && brec->errcode ) + error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(bhdr,brec),(int64_t) brec->pos+1, args->files->readers[1].fname); + + int i, nsmpl = bcf_hdr_nsamples(args->out_hdr); + int chr_id = arec ? bcf_hdr_name2id(args->out_hdr,bcf_seqname(ahdr,arec)) : bcf_hdr_name2id(args->out_hdr,bcf_seqname(bhdr,brec)); + if ( args->prev_chr<0 || args->prev_chr!=chr_id ) + { + if ( args->prev_chr>=0 ) phased_flush(args); + + for (i=0; iphase_set[i] = arec ? arec->pos+1 : brec->pos+1; + args->phase_set_changed = 1; + + if ( args->seen_seq[chr_id] ) error("The chromosome block %s is not contiguous\n", arec ? bcf_seqname(ahdr,arec) : bcf_seqname(bhdr,brec)); + args->seen_seq[chr_id] = 1; + args->prev_chr = chr_id; + args->prev_pos_check = -1; + } + + if ( !is_overlap ) + { + assert(arec); + + bcf_translate(args->out_hdr, ahdr, arec); + if ( args->nswap ) + phase_update(args, args->out_hdr, arec); + if ( !args->compact_PS || args->phase_set_changed ) + { + bcf_update_format_int32(args->out_hdr,arec,"PS",args->phase_set,nsmpl); + args->phase_set_changed = 0; + } + if ( bcf_write(args->out_fh, args->out_hdr, arec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + + if ( arec->pos < args->prev_pos_check ) + error("FIXME, disorder: %s:%"PRId64" in %s vs %d written [3]\n", bcf_seqname(ahdr,arec), (int64_t) arec->pos+1,args->files->readers[0].fname, args->prev_pos_check+1); + args->prev_pos_check = arec->pos; + return; + } + + int m = args->mbuf; + args->nbuf += 2; + hts_expand(bcf1_t*,args->nbuf,args->mbuf,args->buf); + if ( m < args->mbuf ) args->buf_mask = (uint8_t*)realloc(args->buf_mask,sizeof(*args->buf_mask)*args->mbuf); + for (i=m; imbuf; i++) + args->buf[i] = bcf_init1(); + + if ( arec ) SWAP(bcf1_t*, args->files->readers[0].buffer[0], args->buf[args->nbuf-2]); + if ( brec ) SWAP(bcf1_t*, args->files->readers[1].buffer[0], args->buf[args->nbuf-1]); + args->buf_mask[args->nbuf/2-1] = (arec?1:0) | (brec?2:0); +} + +static int _get_active_index(bcf_srs_t *sr) +{ + int i; + for (i=0; inreaders; i++) + if ( bcf_sr_has_line(sr,i) ) return i; + return -1; +} + +static void concat(args_t *args) +{ + static int site_drop_warned = 0; + int i; + if ( args->phased_concat ) // phased concat + { + // keep only two open files at a time + while ( args->ifname < args->nfnames ) + { + int new_file = 0; + while ( args->files->nreaders < 2 && args->ifname < args->nfnames ) + { + if ( !bcf_sr_add_reader(args->files,args->fnames[args->ifname]) ) error("Failed to open %s: %s\n", args->fnames[args->ifname],bcf_sr_strerror(args->files->errnum)); + new_file = 1; + + args->ifname++; + if ( args->start_pos[args->ifname-1]==-1 ) break; // new chromosome, start with only one file open + if ( args->ifname < args->nfnames && args->start_pos[args->ifname]==-1 ) break; // next file starts on a different chromosome + } + + // is there a line from the previous run? Seek the newly opened reader to that position + int seek_pos = -1; + int seek_chr = -1; + if ( bcf_sr_has_line(args->files,0) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + bcf_sr_seek(args->files, bcf_seqname(args->files->readers[0].header,line), line->pos); + seek_pos = line->pos; + seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[0].header,line)); + } + else if ( new_file ) + bcf_sr_seek(args->files,NULL,0); // set to start + + int nret, ir; + while ( (nret = bcf_sr_next_line(args->files)) ) + { + int is_overlap = args->files->nreaders==1 ? 0 : 1; + if ( !bcf_sr_has_line(args->files,0) ) // no input from the first reader + { + // We are assuming that there is a perfect overlap, sites which are not present in both files are dropped + if ( bcf_sr_region_done(args->files,0) ) + { + phased_flush(args); + bcf_sr_remove_reader(args->files, 0); + is_overlap = 0; + } + else if ( args->ligate_warn ) + { + if ( !site_drop_warned ) + { + ir = _get_active_index(args->files); + fprintf(bcftools_stderr, + "Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n" + " overlap, sites in overlapping regions present in one but missing in other are dropped.\n" + " This warning is printed only once.\n", + bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1); + site_drop_warned = 1; + } + continue; + } + else if ( !args->ligate_force ) + { + ir = _get_active_index(args->files); + error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n", + bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1); + } + } + + // Get a line to learn about current position + ir = _get_active_index(args->files); + bcf1_t *line = bcf_sr_get_line(args->files,ir); + + // This can happen after bcf_sr_seek: indel may start before the coordinate which we seek to. + if ( seek_chr>=0 && seek_pos>line->pos && seek_chr==bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[ir].header,line)) ) continue; + seek_pos = seek_chr = -1; + + // Check if the position overlaps with the next, yet unopened, reader + int must_seek = 0; + while ( args->ifname < args->nfnames && args->start_pos[args->ifname]!=-1 && line->pos >= args->start_pos[args->ifname] ) + { + must_seek = 1; + if ( !bcf_sr_add_reader(args->files,args->fnames[args->ifname]) ) error("Failed to open %s: %s\n", args->fnames[args->ifname],bcf_sr_strerror(args->files->errnum)); + args->ifname++; + } + if ( must_seek ) + { + bcf_sr_seek(args->files, bcf_seqname(args->files->readers[ir].header,line), line->pos); + seek_pos = line->pos; + seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[ir].header,line)); + continue; + } + + // We are assuming that there is a perfect overlap, sites which are not present in both files are dropped + if ( args->files->nreaders>1 && !bcf_sr_has_line(args->files,1) && !bcf_sr_region_done(args->files,1) && !args->ligate_force ) + { + if ( args->ligate_warn && !site_drop_warned ) + { + ir = _get_active_index(args->files); + fprintf(bcftools_stderr, + "Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n" + " overlap, sites in overlapping regions present in one but missing in other are dropped.\n" + " This warning is printed only once.\n", + bcf_seqname(bcf_sr_get_header(args->files,ir),line), (int64_t) line->pos+1); + site_drop_warned = 1; + } + else if ( !args->ligate_warn ) + { + ir = _get_active_index(args->files); + error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n", + bcf_seqname(bcf_sr_get_header(args->files,ir),bcf_sr_get_line(args->files,ir)), (int64_t) bcf_sr_get_line(args->files,ir)->pos+1); + } + continue; + } + + bcf1_t *line0 = bcf_sr_get_line(args->files,0); + bcf1_t *line1 = args->files->nreaders > 1 ? bcf_sr_get_line(args->files,1) : NULL; + phased_push(args, line0, line1, is_overlap); + } + + if ( args->files->nreaders ) + { + phased_flush(args); + while ( args->files->nreaders ) + bcf_sr_remove_reader(args->files, 0); + } + } + } + else if ( args->files ) // combining overlapping files, using synced reader + { + while ( bcf_sr_next_line(args->files) ) + { + for (i=0; ifiles->nreaders; i++) + { + bcf1_t *line = bcf_sr_get_line(args->files,i); + if ( !line ) continue; + if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0); + bcf_translate(args->out_hdr, args->files->readers[i].header, line); + if ( bcf_write1(args->out_fh, args->out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + if ( args->remove_dups ) break; + } + } + } + else // concatenate as is + { + struct timeval t0, t1; + kstring_t tmp = {0,0,0}; + int prev_chr_id = -1, prev_pos; + bcf1_t *line = bcf_init(); + for (i=0; infnames; i++) + { + if ( args->verbose ) + { + fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]); + gettimeofday(&t0, NULL); + } + htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("\nFailed to open: %s\n", args->fnames[i]); + if ( args->n_threads ) hts_set_opt(fp, HTS_OPT_THREAD_POOL, args->tpool); + bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("\nFailed to parse header: %s\n", args->fnames[i]); + if ( args->sites_only ) + { + bcf_hdr_t *hdr_ori = hdr; + hdr = bcf_hdr_subset(hdr_ori, 0, 0, 0); + bcf_hdr_remove(hdr, BCF_HL_FMT, NULL); + bcf_hdr_destroy(hdr_ori); + } + if ( !fp->is_bin && args->output_type&FT_VCF ) + { + line->max_unpack = BCF_UN_STR; + // if VCF is on both input and output, avoid VCF to BCF conversion + while ( hts_getline(fp, KS_SEP_LINE, &fp->line) >=0 ) + { + char *str = fp->line.s; + + // remove genotypes + if ( args->sites_only ) + { + int ntab = 0; + while ( *str ) + { + if ( *str == '\t' && ++ntab==8 ) + { + *str = 0; + break; + } + str++; + } + str = fp->line.s; + } + while ( *str && *str!='\t' ) str++; + tmp.l = 0; + kputsn(fp->line.s,str-fp->line.s,&tmp); + int chr_id = bcf_hdr_name2id(args->out_hdr, tmp.s); + if ( chr_id<0 ) error("\nThe sequence \"%s\" not defined in the header: %s\n(Quick workaround: index the file.)\n", tmp.s, args->fnames[i]); + if ( prev_chr_id!=chr_id ) + { + prev_pos = -1; + if ( args->seen_seq[chr_id] ) + error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", tmp.s); + } + char *end; + int pos = strtol(str+1,&end,10) - 1; + if ( end==str+1 ) error("Could not parse line: %s\n", fp->line.s); + if ( prev_pos > pos ) + error("\nThe chromosome block %s is not sorted, consider running with -a.\n", tmp.s); + args->seen_seq[chr_id] = 1; + prev_chr_id = chr_id; + + if ( vcf_write_line(args->out_fh, &fp->line)!=0 ) error("\nFailed to write %"PRIu64" bytes\n", (uint64_t)fp->line.l); + } + } + else + { + // BCF conversion is required + line->max_unpack = 0; + while ( bcf_read(fp, hdr, line)==0 ) + { + if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0); + bcf_translate(args->out_hdr, hdr, line); + + if ( prev_chr_id!=line->rid ) + { + prev_pos = -1; + if ( args->seen_seq[line->rid] ) + error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", bcf_seqname(args->out_hdr, line)); + } + if ( prev_pos > line->pos ) + error("\nThe chromosome block %s is not sorted, consider running with -a.\n", bcf_seqname(args->out_hdr, line)); + args->seen_seq[line->rid] = 1; + prev_chr_id = line->rid; + + if ( bcf_write(args->out_fh, args->out_hdr, line)!=0 ) error("\nFailed to write\n"); + } + } + bcf_hdr_destroy(hdr); + hts_close(fp); + if ( args->verbose ) + { + gettimeofday(&t1, NULL); + double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec); + fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6); + } + } + bcf_destroy(line); + free(tmp.s); + } +} + +int print_vcf_gz_header(BGZF *fp, BGZF *bgzf_out, int print_header, kstring_t *tmp) +{ + char *buffer = (char*) fp->uncompressed_block; + + // Read the header and find the position of the data block + if ( buffer[0]!='#' ) error("Could not parse the header, expected '#', found '%c'\n", buffer[0]); + + int nskip = 1; // end of the header in the current uncompressed block + while (1) + { + if ( buffer[nskip]=='\n' ) + { + nskip++; + if ( nskip>=fp->block_length ) + { + kputsn(buffer,nskip,tmp); + if ( bgzf_read_block(fp) != 0 ) return -1; + if ( !fp->block_length ) break; + nskip = 0; + } + // The header has finished + if ( buffer[nskip]!='#' ) + { + kputsn(buffer,nskip,tmp); + break; + } + } + nskip++; + if ( nskip>=fp->block_length ) + { + kputsn(buffer,fp->block_length,tmp); + if ( bgzf_read_block(fp) != 0 ) return -1; + if ( !fp->block_length ) break; + nskip = 0; + } + } + if ( print_header ) + { + if ( bgzf_write(bgzf_out,tmp->s,tmp->l) != tmp->l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)tmp->l); + tmp->l = 0; + } + return nskip; +} + +static inline int unpackInt16(const uint8_t *buffer) +{ + return buffer[0] | buffer[1] << 8; +} +static int check_header(const uint8_t *header) +{ + if ( header[0] != 31 || header[1] != 139 || header[2] != 8 ) return -2; + return ((header[3] & 4) != 0 + && unpackInt16((uint8_t*)&header[10]) == 6 + && header[12] == 'B' && header[13] == 'C' + && unpackInt16((uint8_t*)&header[14]) == 2) ? 0 : -1; +} +static void _check_hrecs(const bcf_hdr_t *hdr0, const bcf_hdr_t *hdr, char *fname0, char *fname) +{ + int j; + for (j=0; jnhrec; j++) + { + bcf_hrec_t *hrec0 = hdr0->hrec[j]; + if ( hrec0->type!=BCF_HL_FLT && hrec0->type!=BCF_HL_INFO && hrec0->type!=BCF_HL_FMT && hrec0->type!=BCF_HL_CTG ) continue; // skip fields w/o IDX + int itag = bcf_hrec_find_key(hrec0, "ID"); + bcf_hrec_t *hrec = bcf_hdr_get_hrec(hdr, hrec0->type, "ID", hrec0->vals[itag], NULL); + + char *type = NULL; + if ( hrec0->type==BCF_HL_FLT ) type = "FILTER"; + if ( hrec0->type==BCF_HL_INFO ) type = "INFO"; + if ( hrec0->type==BCF_HL_FMT ) type = "FORMAT"; + if ( hrec0->type==BCF_HL_CTG ) type = "contig"; + + if ( !hrec ) + error("Cannot use --naive, incompatible headers, the tag %s/%s not present in %s\n",type,hrec0->vals[itag],fname); + + int idx0 = bcf_hrec_find_key(hrec0, "IDX"); + int idx = bcf_hrec_find_key(hrec, "IDX"); + if ( idx0<0 || idx<0 ) + error("fixme: unexpected IDX<0 for %s/%s in %s or %s\n",type,hrec0->vals[itag],fname0,fname); + if ( strcmp(hrec0->vals[idx0],hrec->vals[idx]) ) + error("Cannot use --naive, use --naive-force instead: different order the tag %s/%s in %s vs %s\n",type,hrec0->vals[itag],fname0,fname); + } +} +static void naive_concat_check_headers(args_t *args) +{ + fprintf(bcftools_stderr,"Checking the headers of %d files.\n",args->nfnames); + bcf_hdr_t *hdr0 = NULL; + int i,j; + for (i=0; infnames; i++) + { + htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]); + bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]); + htsFormat type = *hts_get_format(fp); + hts_close(fp); + + if ( i==0 ) + { + hdr0 = hdr; + continue; + } + + // check the samples + if ( bcf_hdr_nsamples(hdr0)!=bcf_hdr_nsamples(hdr) ) + error("Cannot concatenate, different number of samples: %d vs %d in %s vs %s\n",bcf_hdr_nsamples(hdr0),bcf_hdr_nsamples(hdr),args->fnames[0],args->fnames[i]); + for (j=0; jsamples[j],hdr->samples[j]) ) + error("Cannot concatenate, different samples in %s vs %s\n",args->fnames[0],args->fnames[i]); + + // if BCF, check if tag IDs are consistent in the dictionary of strings + if ( type.compression!=bgzf ) + error("The --naive option works only for compressed BCFs or VCFs, sorry :-/\n"); + + _check_hrecs(hdr0,hdr,args->fnames[0],args->fnames[i]); + _check_hrecs(hdr,hdr0,args->fnames[i],args->fnames[0]); + + bcf_hdr_destroy(hdr); + } + if ( hdr0 ) bcf_hdr_destroy(hdr0); + fprintf(bcftools_stderr,"Done, the headers are compatible.\n"); +} +static void naive_concat(args_t *args) +{ + if ( !args->naive_concat_trust_headers ) + naive_concat_check_headers(args); + + // only compressed BCF atm + BGZF *bgzf_out = bgzf_open(args->output_fname,"w");; + + htsFormat output_type; + output_type.format = (args->output_type & FT_VCF) ? vcf : bcf; + output_type.compression = (args->output_type & FT_GZ) ? bgzf : no_compression; + + struct timeval t0, t1; + const size_t page_size = BGZF_MAX_BLOCK_SIZE; + uint8_t *buf = (uint8_t*) malloc(page_size); + kstring_t tmp = {0,0,0}; + int i, file_types = 0; + for (i=0; infnames; i++) + { + if ( args->verbose ) + { + fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]); + gettimeofday(&t0, NULL); + } + htsFile *hts_fp = hts_open(args->fnames[i],"r"); + if ( !hts_fp ) error("\nFailed to open: %s\n", args->fnames[i]); + htsFormat type = *hts_get_format(hts_fp); + + if ( type.compression!=bgzf ) + error("\nThe --naive option works only for compressed BCFs or VCFs\n"); + file_types |= type.format==vcf ? 1 : 2; + if ( file_types==3 ) + error("\nThe --naive option works only for compressed files of the same type, all BCFs or all VCFs\n"); + if ( args->explicit_output_type ) + { + if ( output_type.format!=type.format ) + error("\nThe --naive option works only for the output of the same type, all BCFs or all VCFs\n"); + if ( output_type.compression!=type.compression ) + error("\nThe --naive option works only for the output of the same compression type\n"); + } + + BGZF *fp = hts_get_bgzfp(hts_fp); + if ( !fp || bgzf_read_block(fp) != 0 || !fp->block_length ) + error("\nFailed to read %s: %s\n", args->fnames[i], strerror(errno)); + + int nskip; + if ( type.format==bcf ) + { + const size_t magic_len = 5 + 4; // "Magic" string + header length + uint8_t magic[magic_len]; + if ( bgzf_read(fp, magic, magic_len) != magic_len ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]); + // First five bytes are the "Magic" string + if (strncmp((char*)magic, "BCF\2\2", 5) != 0) error("\nInvalid BCF magic string in %s\n", args->fnames[i]); + // Next four are the header length (little-endian) + tmp.l = le_to_u32(magic + 5); + hts_expand(char,tmp.l,tmp.m,tmp.s); + if ( bgzf_read(fp, tmp.s, tmp.l) != tmp.l ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]); + + // write only the first header + if ( i==0 ) + { + if ( bgzf_write(bgzf_out, magic, magic_len) != magic_len ) error("\nFailed to write %zu bytes to %s\n", magic_len,args->output_fname); + if ( bgzf_write(bgzf_out, tmp.s, tmp.l) != tmp.l) error("\nFailed to write %"PRId64" bytes to %s\n", (uint64_t)tmp.l,args->output_fname); + } + nskip = fp->block_offset; + } + else + { + nskip = print_vcf_gz_header(fp, bgzf_out, i==0?1:0, &tmp); + if ( nskip==-1 ) error("\nError reading %s\n", args->fnames[i]); + } + + // Output all non-header data that were read together with the header block + if ( fp->block_length - nskip > 0 ) + { + if ( bgzf_write(bgzf_out, (char *)fp->uncompressed_block+nskip, fp->block_length-nskip)<0 ) error("\nError: %d\n",fp->errcode); + } + if ( bgzf_flush(bgzf_out)<0 ) error("\nError: %d\n",bgzf_out->errcode); + + + // Stream the rest of the file as it is, without recompressing, but remove BGZF EOF blocks + // The final bgzf eof block will be added by bgzf_close. + ssize_t nread, nblock, nwr; + const int nheader = 18, neof = 28; + const uint8_t *eof = (uint8_t*) "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\033\0\3\0\0\0\0\0\0\0\0\0"; + while (1) + { + nread = bgzf_raw_read(fp, buf, nheader); + if ( !nread ) break; + if ( nread != nheader || check_header(buf)!=0 ) error("\nCould not parse the header of a bgzf block: %s\n",args->fnames[i]); + nblock = unpackInt16(buf+16) + 1; + assert( nblock <= page_size && nblock >= nheader ); + nread += bgzf_raw_read(fp, buf+nheader, nblock - nheader); + if ( nread!=nblock ) error("\nCould not read %"PRId64" bytes: %s\n",(uint64_t)nblock,args->fnames[i]); + if ( nread==neof && !memcmp(buf,eof,neof) ) continue; + nwr = bgzf_raw_write(bgzf_out, buf, nread); + if ( nwr != nread ) error("\nWrite failed, wrote %"PRId64" instead of %d bytes.\n", (uint64_t)nwr,(int)nread); + } + if (hts_close(hts_fp)) error("\nClose failed: %s\n",args->fnames[i]); + if ( args->verbose ) + { + gettimeofday(&t1, NULL); + double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec); + fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6); + } + } + free(buf); + free(tmp.s); + if (bgzf_close(bgzf_out) < 0) error("Error: %d\n",bgzf_out->errcode); +} + +static void usage(args_t *args) +{ + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "About: Concatenate or combine VCF/BCF files. All source files must have the same sample\n"); + fprintf(bcftools_stderr, " columns appearing in the same order. The program can be used, for example, to\n"); + fprintf(bcftools_stderr, " concatenate chromosome VCFs into one VCF, or combine a SNP VCF and an indel\n"); + fprintf(bcftools_stderr, " VCF into one. The input files must be sorted by chr and position. The files\n"); + fprintf(bcftools_stderr, " must be given in the correct order to produce sorted VCF on output unless\n"); + fprintf(bcftools_stderr, " the -a, --allow-overlaps option is specified. With the --naive option, the files\n"); + fprintf(bcftools_stderr, " are concatenated without being recompressed, which is very fast.\n"); + fprintf(bcftools_stderr, "Usage: bcftools concat [options] [ [...]]\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "Options:\n"); + fprintf(bcftools_stderr, " -a, --allow-overlaps First coordinate of the next file can precede last record of the current file.\n"); + fprintf(bcftools_stderr, " -c, --compact-PS Do not output PS tag at each site, only at the start of a new phase set block.\n"); + fprintf(bcftools_stderr, " -d, --rm-dups STRING Output duplicate records present in multiple files only once: \n"); + fprintf(bcftools_stderr, " -D, --remove-duplicates Alias for -d exact\n"); + fprintf(bcftools_stderr, " -f, --file-list FILE Read the list of files from a file.\n"); + fprintf(bcftools_stderr, " -G, --drop-genotypes Drop individual genotype information.\n"); + fprintf(bcftools_stderr, " -l, --ligate Ligate phased VCFs by matching phase at overlapping haplotypes\n"); + fprintf(bcftools_stderr, " --ligate-force Ligate even non-overlapping chunks, keep all sites\n"); + fprintf(bcftools_stderr, " --ligate-warn Drop sites in imperfect overlaps\n"); + fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(bcftools_stderr, " -n, --naive Concatenate files without recompression, a header check compatibility is performed\n"); + fprintf(bcftools_stderr, " --naive-force Same as --naive, but header compatibility is not checked. Dangerous, use with caution.\n"); + fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(bcftools_stderr, " -q, --min-PQ INT Break phase set if phasing quality is lower than [30]\n"); + fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(bcftools_stderr, " --threads INT Use multithreading with worker threads [0]\n"); + fprintf(bcftools_stderr, " -v, --verbose 0|1 Set verbosity level [1]\n"); + fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(bcftools_stderr, "\n"); + bcftools_exit(1); +} + +int main_vcfconcat(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->output_fname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->min_PQ = 30; + args->verbose = 1; + args->clevel = -1; + + static struct option loptions[] = + { + {"verbose",required_argument,NULL,'v'}, + {"naive",no_argument,NULL,'n'}, + {"naive-force",no_argument,NULL,7}, + {"compact-PS",no_argument,NULL,'c'}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,12}, + {"remove-duplicates",no_argument,NULL,'D'}, + {"rm-dups",required_argument,NULL,'d'}, + {"allow-overlaps",no_argument,NULL,'a'}, + {"ligate",no_argument,NULL,'l'}, + {"ligate-force",no_argument,NULL,10}, + {"ligate-warn",no_argument,NULL,11}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"file-list",required_argument,NULL,'f'}, + {"min-PQ",required_argument,NULL,'q'}, + {"no-version",no_argument,NULL,8}, + {"write-index",optional_argument,NULL,'W'}, + {"drop-genotypes",no_argument,NULL,'G'}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "h:?o:O:f:alq:Dd:Gr:R:cnv:W::",loptions,NULL)) >= 0) + { + switch (c) { + case 'c': args->compact_PS = 1; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; args->regions_is_file = 1; break; + case 'd': args->remove_dups = optarg; break; + case 'D': args->remove_dups = "exact"; break; + case 'q': + args->min_PQ = strtol(optarg,&tmp,10); + if ( *tmp ) error("Could not parse argument: --min-PQ %s\n", optarg); + break; + case 'n': args->naive_concat = 1; break; + case 'a': args->allow_overlaps = 1; break; + case 'l': args->phased_concat = 1; break; + case 'f': args->file_list = optarg; break; + case 'G': args->sites_only = 1; break; + case 'o': args->output_fname = optarg; break; + case 'O': + args->explicit_output_type = 1; + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + }; + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 10 : args->ligate_force = 1; break; + case 11 : args->ligate_warn = 1; break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 8 : args->record_cmd_line = 0; break; + case 7 : args->naive_concat = 1; args->naive_concat_trust_headers = 1; break; + case 12 : + args->regions_overlap = parse_overlap_option(optarg); + if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 'v': + args->verbose = strtol(optarg, &tmp, 0); + if ( *tmp || args->verbose<0 || args->verbose>1 ) error("Error: currently only --verbose 0 or --verbose 1 is supported\n"); + break; + case 'W': + if (!(args->write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + case 'h': + case '?': usage(args); break; + default: error("Unknown argument: %s\n", optarg); + } + } + while ( optindnfnames++; + args->fnames = (char **)realloc(args->fnames,sizeof(char*)*args->nfnames); + args->fnames[args->nfnames-1] = strdup(argv[optind]); + optind++; + } + if ( args->ligate_force && args->ligate_warn ) error("The options cannot be combined: --ligate-force and --ligate-warn\n"); + if ( args->allow_overlaps && args->phased_concat ) error("The options -a and -l should not be combined. Please run with -l only.\n"); + if ( args->sites_only && args->phased_concat ) error("The options --drop-genotypes and --ligate cannot be combined\n"); + if ( args->compact_PS && !args->phased_concat ) error("The -c option is intended only with -l\n"); + if ( args->file_list ) + { + if ( args->nfnames ) error("Cannot combine -l with file names on command line.\n"); + args->fnames = hts_readlines(args->file_list, &args->nfnames); + if ( !args->fnames ) error("Could not read the file: %s\n", args->file_list); + } + if ( !args->nfnames ) usage(args); + if ( args->remove_dups && !args->allow_overlaps ) error("The -D option is supported only with -a\n"); + if ( args->regions_list && !args->allow_overlaps ) error("The -r/-R option is supported only with -a\n"); + if ( args->naive_concat ) + { + if ( args->write_index ) error("Error: cannot --write-index in the %s mode\n",args->naive_concat_trust_headers?"--naive-force":"--naive"); + if ( args->allow_overlaps ) error("The option --naive cannot be combined with --allow-overlaps\n"); + if ( args->phased_concat ) error("The option --naive cannot be combined with --ligate\n"); + if ( args->sites_only ) error("The option --naive cannot be combined with --drop-genotypes\n"); + naive_concat(args); + destroy_data(args); + free(args); + return 0; + } + init_data(args); + concat(args); + destroy_data(args); + free(args); + return 0; +} diff --git a/shared/package-files/18/1895dbf616c666a60e0d82ce37cac9f0d6dcb4f697d05db990675842610f3309/_python_dispatcher.py b/shared/package-files/18/1895dbf616c666a60e0d82ce37cac9f0d6dcb4f697d05db990675842610f3309/_python_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..2dfdbb296a4b2deb7c6c9a14d842e75d6aed6ffa --- /dev/null +++ b/shared/package-files/18/1895dbf616c666a60e0d82ce37cac9f0d6dcb4f697d05db990675842610f3309/_python_dispatcher.py @@ -0,0 +1,182 @@ +# mypy: allow-untyped-defs +import re + +import torch._C as C + + +""" +PythonDispatcher class is a thin python-binding to C++ dispatcher and it +is designed to show how dispatcher precompute works. In particular, +it shows for a certain op `foo`, what the computed dispatch table looks +like after user register their kernels to certains dispatch keys. + +In the real C++ dispatcher we support many dispatch keys for different +functionalities. For simplicity PythonDispatcher only supports dispatch +keys for a single example of each use case. These use cases are listed below: + +- CPU/AutogradCPU: represents in-tree backends which we usually have dedicated inference & + autograd kernel in pytorch core library. + E.g. CPU, CUDA +- FPGA/AutogradOther: represents in-tree backends which we usually have backend specific + inference kernels, but they share the same autograd kernel specified in AutogradOther. + E.g. FPGA, SparseCsrCPU +- XLA/AutogradXLA: represents out-of-tree backends which we don't have either inference or autograd + kernel defined in pytorch core library. Backend owner is responsible for registering both + inference & autograd kernels in their extensions(e.g. torch-xla) for the operators they support. + E.g. XLA, XPU, MPS +- CompositeExplicitAutograd: alias key mapped to inference kernels of all backends like CPU, CUDA, XLA etc. + Kernels registered to this key MUST work for inference for all backends. +- Autograd: alias key mapped to autograd of all backends like AutogradCPU, AutogradXLA, AutogradOther. + Kernels registered to this key MUST work for autograd for all backends. +- CompositeImplicitAutograd: alias key CompositeImplicitAutograd = CompositeExplicitAutograd + Autograd + Kernels registered to this key MUST work for both inference + autograd for all backends. + +Note we only allow registrations to alias keys inside pytorch core library. E.g +you shouldn't register a CompositeImplicitAutograd or CompositeExplicitAutograd +kernel from torch-xla extension, instead you should upstream the kernel into +pytorch/pytorch repo so that it's available for all backends and continuously +tested even without the extension. + +Usage: + dispatcher = PythonDispatcher() + dispatcher.register(["CPU", "XLA", "CompositeImplicitAutograd"]) + print(dispatcher.dispatchTable()) # This tells you exactly which kernel is used for certain backend. + # For more debugging information + # print(dispatcher.keys()) + # print(dispatcher.registrations()) + # print(dispatcher.rawRegistrations()) + # print(dispatcher.rawDispatchTable()) +PythonDispatcher calls C++ dispatcher under the hood for to precompute dispatch table. +This file only provides the simplified API for developers, relevant test code is located in +test/test_dispatch.py +""" + + +class PythonDispatcher: + namespace = "__test__" + name = "foo" + # fmt: off + runtime_keys = [ + "CPU", "AutogradCPU", + "FPGA", "AutogradOther", + "XLA", "AutogradXLA", + "Lazy", "AutogradLazy", + ] + # fmt: on + alias_keys = [ + "CompositeExplicitAutograd", + "Autograd", + "CompositeImplicitAutograd", + ] + supported_keys = runtime_keys + alias_keys + + def __init__(self) -> None: + C._dispatch_check_invariants(self.name) # type: ignore[attr-defined] + self.ref = C._dispatch_library("FRAGMENT", self.namespace, "") + self.ref.def_("foo(Tensor x) -> Tensor") + + """ + Returns a list of dispatch keys supported by PythonDispatcher. + You can register kernels to these keys. + """ + + def keys(self): + return self.supported_keys + + """ + Register kernels to the target dispatchKeys. + dispatchKeys(list[str]): a list of dispatch keys that you want to register + your own kernel. Note that you don't need to write the kernel yourself in + this PythonDispatcher.E.g. for CPU key, a kernel(e.g fn_CPU for CPU) is + automatically generated and registered. + """ + + def register(self, dispatchKeys): + # Overriden is not supported and triggers a warning in C++ dispatcher. + if len(set(dispatchKeys)) != len(dispatchKeys): + raise RuntimeError( + f"Overriden is not allowed but found duplicates in {dispatchKeys}." + ) + # We currently forbid this in codegen instead of C++ dispatcher. + if ( + "CompositeImplicitAutograd" in dispatchKeys + and "CompositeExplicitAutograd" in dispatchKeys + ): + raise RuntimeError( + "Registration to both CompositeImplicitAutograd and CompositeExplicitAutograd is not allowed." + ) + for key in dispatchKeys: + if key not in self.supported_keys: + raise RuntimeError( + f"{key} is not supported, please select a dispatch key in {self.supported_keys}." + ) + self.ref.impl_t_t("foo", dispatch=key, debug="fn_" + key) + + """ + Helper function to format (key, kernel). + """ + + def _format_line(self, key, kernel): + return f"{key:<15} {kernel}\n" + + """ + Helper function to print a table header. + """ + + def _format_header(self, header): + s = f""" +{header} +""" + s += self._format_line("key", "kernel") + s += "---------------------------\n" + return s + + """ + Returns raw output of all registration info for debugging only. + Use registrations() for a simplified version. + """ + + def rawRegistrations(self): + return C._dispatch_dump(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns raw output of computed dispatch table for debugging only. + Use dispatchTable() for a simplified version. + """ + + def rawDispatchTable(self): + return C._dispatch_dump_table(f"{self.namespace}::{self.name}") # type: ignore[attr-defined] + + """ + Returns a table(str) including all the registrations from users. + Note this includes registrations to both runtime keys and alias keys. + """ + + def registrations(self): + output = self._format_header("Registered Kernels") + state = self.rawRegistrations() + state_entries = state.split("\n") + for line in state_entries: + first = line.split(":")[0] + if any(first.startswith(k) for k in self.supported_keys): + kernel = line.split("::")[0].split(" ")[1] + output += self._format_line(first, kernel) + return output + + """ + Returns the computed dispatch table(str). Note this only include + runtime keys, registrations to alias keys have been decoded to their + mapped runtime keys. + """ + + def dispatchTable(self): + output = self._format_header("Computed Dispatch Table") + table = self.rawDispatchTable() + table_entries = table.split("\n") + regex = re.compile(r"registered at .*FallbackKernel\.cpp.*(\[)") + for line in table_entries: + k = line.split(":")[0] + if k in self.runtime_keys: + entry = regex.sub("[", line) + output += self._format_line(k, entry.split(": ")[1]) + return output diff --git a/shared/package-files/18/18997fb64e74e3ee39580491803bf92fd48372c763b6c651523246ba4672ab17/masked_select_native.h b/shared/package-files/18/18997fb64e74e3ee39580491803bf92fd48372c763b6c651523246ba4672ab17/masked_select_native.h new file mode 100644 index 0000000000000000000000000000000000000000..915ae34ec84befc83af9f904a2092eeb8ef465b0 --- /dev/null +++ b/shared/package-files/18/18997fb64e74e3ee39580491803bf92fd48372c763b6c651523246ba4672ab17/masked_select_native.h @@ -0,0 +1,24 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor masked_select_cpu(const at::Tensor & self, const at::Tensor & mask); +TORCH_API at::Tensor & masked_select_out_cpu(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out); +TORCH_API at::Tensor masked_select_cuda(const at::Tensor & self, const at::Tensor & mask); +TORCH_API at::Tensor & masked_select_out_cuda(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/18/18a3580068ace53b220c9308bb42fa6c7dbf7083a9583be2470c427cf37d3eff/test_csv.py b/shared/package-files/18/18a3580068ace53b220c9308bb42fa6c7dbf7083a9583be2470c427cf37d3eff/test_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..6a36b41daf302d80f228bb754e10de8b25cd2f33 --- /dev/null +++ b/shared/package-files/18/18a3580068ace53b220c9308bb42fa6c7dbf7083a9583be2470c427cf37d3eff/test_csv.py @@ -0,0 +1,2052 @@ +# 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 abc +import bz2 +from datetime import date, datetime +from decimal import Decimal +import gc +import gzip +import io +import itertools +import os +import random +import select +import shutil +import signal +import string +import tempfile +import threading +import time +import unittest +import weakref + +import pytest + +import pyarrow as pa +from pyarrow.csv import ( + open_csv, read_csv, ReadOptions, ParseOptions, ConvertOptions, ISO8601, + write_csv, WriteOptions, CSVWriter, InvalidRow) +from pyarrow.tests import util + + +def generate_col_names(): + # 'a', 'b'... 'z', then 'aa', 'ab'... + letters = string.ascii_lowercase + yield from letters + for first in letters: + for second in letters: + yield first + second + + +def split_rows(arr, num_cols, num_rows): + # Split a num_cols x num_rows array into rows + for i in range(0, num_rows * num_cols, num_cols): + yield arr[i:i + num_cols] + + +def split_columns(arr, num_cols, num_rows): + # Split a num_cols x num_rows array into columns + for i in range(0, num_cols): + yield arr[i::num_cols] + + +def make_random_csv(num_cols=2, num_rows=10, linesep='\r\n', write_names=True): + rnd = random.Random(42) + arr = [rnd.randint(0, 1000) for _ in range(num_cols * num_rows)] + csv = io.StringIO() + col_names = list(itertools.islice(generate_col_names(), num_cols)) + if write_names: + csv.write(",".join(col_names)) + csv.write(linesep) + for row in split_rows(arr, num_cols, num_rows): + csv.write(",".join(map(str, row))) + csv.write(linesep) + csv = csv.getvalue().encode() + columns = [pa.array(row, type=pa.int64()) + for row in split_columns(arr, num_cols, num_rows)] + expected = pa.Table.from_arrays(columns, col_names) + return csv, expected + + +def make_empty_csv(column_names): + csv = io.StringIO() + csv.write(",".join(column_names)) + csv.write("\n") + return csv.getvalue().encode() + + +def check_options_class(cls, **attr_values): + """ + Check setting and getting attributes of an *Options class. + """ + opts = cls() + + for name, values in attr_values.items(): + assert getattr(opts, name) == values[0], \ + "incorrect default value for " + name + for v in values: + setattr(opts, name, v) + assert getattr(opts, name) == v, "failed setting value" + + with pytest.raises(AttributeError): + opts.zzz_non_existent = True + + # Check constructor named arguments + non_defaults = {name: values[1] for name, values in attr_values.items()} + opts = cls(**non_defaults) + for name, value in non_defaults.items(): + assert getattr(opts, name) == value + + +# The various options classes need to be picklable for dataset +def check_options_class_pickling(cls, pickler, **attr_values): + opts = cls(**attr_values) + new_opts = pickler.loads(pickler.dumps(opts, + protocol=pickler.HIGHEST_PROTOCOL)) + for name, value in attr_values.items(): + assert getattr(new_opts, name) == value + + +class InvalidRowHandler: + def __init__(self, result): + self.result = result + self.rows = [] + + def __call__(self, row): + self.rows.append(row) + return self.result + + def __eq__(self, other): + return (isinstance(other, InvalidRowHandler) and + other.result == self.result) + + def __ne__(self, other): + return (not isinstance(other, InvalidRowHandler) or + other.result != self.result) + + +def test_split_rows_and_columns_utility(): + num_cols = 5 + num_rows = 2 + arr = [x for x in range(1, 11)] + rows = list(split_rows(arr, num_cols, num_rows)) + assert rows == [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10] + ] + columns = list(split_columns(arr, num_cols, num_rows)) + assert columns == [ + [1, 6], + [2, 7], + [3, 8], + [4, 9], + [5, 10] + ] + + +def test_read_options(pickle_module): + cls = ReadOptions + opts = cls() + + check_options_class(cls, use_threads=[True, False], + skip_rows=[0, 3], + column_names=[[], ["ab", "cd"]], + autogenerate_column_names=[False, True], + encoding=['utf8', 'utf16'], + skip_rows_after_names=[0, 27]) + + check_options_class_pickling(cls, pickler=pickle_module, + use_threads=True, + skip_rows=3, + column_names=["ab", "cd"], + autogenerate_column_names=False, + encoding='utf16', + skip_rows_after_names=27) + + assert opts.block_size > 0 + opts.block_size = 12345 + assert opts.block_size == 12345 + + opts = cls(block_size=1234) + assert opts.block_size == 1234 + + opts.validate() + + match = "ReadOptions: block_size must be at least 1: 0" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.block_size = 0 + opts.validate() + + match = "ReadOptions: skip_rows cannot be negative: -1" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.skip_rows = -1 + opts.validate() + + match = "ReadOptions: skip_rows_after_names cannot be negative: -1" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.skip_rows_after_names = -1 + opts.validate() + + match = "ReadOptions: autogenerate_column_names cannot be true when" \ + " column_names are provided" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.autogenerate_column_names = True + opts.column_names = ('a', 'b') + opts.validate() + + +def test_parse_options(pickle_module): + cls = ParseOptions + skip_handler = InvalidRowHandler('skip') + + check_options_class(cls, delimiter=[',', 'x'], + escape_char=[False, 'y'], + quote_char=['"', 'z', False], + double_quote=[True, False], + newlines_in_values=[False, True], + ignore_empty_lines=[True, False], + invalid_row_handler=[None, skip_handler]) + + check_options_class_pickling(cls, pickler=pickle_module, + delimiter='x', + escape_char='y', + quote_char=False, + double_quote=False, + newlines_in_values=True, + ignore_empty_lines=False, + invalid_row_handler=skip_handler) + + cls().validate() + opts = cls() + opts.delimiter = "\t" + opts.validate() + + match = "ParseOptions: delimiter cannot be \\\\r or \\\\n" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.delimiter = "\n" + opts.validate() + + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.delimiter = "\r" + opts.validate() + + match = "ParseOptions: quote_char cannot be \\\\r or \\\\n" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.quote_char = "\n" + opts.validate() + + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.quote_char = "\r" + opts.validate() + + match = "ParseOptions: escape_char cannot be \\\\r or \\\\n" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.escape_char = "\n" + opts.validate() + + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.escape_char = "\r" + opts.validate() + + +def test_convert_options(pickle_module): + cls = ConvertOptions + opts = cls() + + check_options_class( + cls, check_utf8=[True, False], + strings_can_be_null=[False, True], + quoted_strings_can_be_null=[True, False], + decimal_point=['.', ','], + include_columns=[[], ['def', 'abc']], + include_missing_columns=[False, True], + auto_dict_encode=[False, True], + timestamp_parsers=[[], [ISO8601, '%y-%m']]) + + check_options_class_pickling( + cls, pickler=pickle_module, + check_utf8=False, + strings_can_be_null=True, + quoted_strings_can_be_null=False, + decimal_point=',', + include_columns=['def', 'abc'], + include_missing_columns=False, + auto_dict_encode=True, + timestamp_parsers=[ISO8601, '%y-%m']) + + with pytest.raises(ValueError): + opts.decimal_point = '..' + + assert opts.auto_dict_max_cardinality > 0 + opts.auto_dict_max_cardinality = 99999 + assert opts.auto_dict_max_cardinality == 99999 + + assert opts.column_types == {} + # Pass column_types as mapping + opts.column_types = {'b': pa.int16(), 'c': pa.float32()} + assert opts.column_types == {'b': pa.int16(), 'c': pa.float32()} + opts.column_types = {'v': 'int16', 'w': 'null'} + assert opts.column_types == {'v': pa.int16(), 'w': pa.null()} + # Pass column_types as schema + schema = pa.schema([('a', pa.int32()), ('b', pa.string())]) + opts.column_types = schema + assert opts.column_types == {'a': pa.int32(), 'b': pa.string()} + # Pass column_types as sequence + opts.column_types = [('x', pa.binary())] + assert opts.column_types == {'x': pa.binary()} + + with pytest.raises(TypeError, match='DataType expected'): + opts.column_types = {'a': None} + with pytest.raises(TypeError): + opts.column_types = 0 + + assert isinstance(opts.null_values, list) + assert '' in opts.null_values + assert 'N/A' in opts.null_values + opts.null_values = ['xxx', 'yyy'] + assert opts.null_values == ['xxx', 'yyy'] + + assert isinstance(opts.true_values, list) + opts.true_values = ['xxx', 'yyy'] + assert opts.true_values == ['xxx', 'yyy'] + + assert isinstance(opts.false_values, list) + opts.false_values = ['xxx', 'yyy'] + assert opts.false_values == ['xxx', 'yyy'] + + assert opts.timestamp_parsers == [] + opts.timestamp_parsers = [ISO8601] + assert opts.timestamp_parsers == [ISO8601] + + opts = cls(column_types={'a': pa.null()}, + null_values=['N', 'nn'], true_values=['T', 'tt'], + false_values=['F', 'ff'], auto_dict_max_cardinality=999, + timestamp_parsers=[ISO8601, '%Y-%m-%d']) + assert opts.column_types == {'a': pa.null()} + assert opts.null_values == ['N', 'nn'] + assert opts.false_values == ['F', 'ff'] + assert opts.true_values == ['T', 'tt'] + assert opts.auto_dict_max_cardinality == 999 + assert opts.timestamp_parsers == [ISO8601, '%Y-%m-%d'] + + +def test_write_options(): + cls = WriteOptions + opts = cls() + + check_options_class( + cls, include_header=[True, False], delimiter=[',', '\t', '|'], + quoting_style=['needed', 'none', 'all_valid']) + + assert opts.batch_size > 0 + opts.batch_size = 12345 + assert opts.batch_size == 12345 + + opts = cls(batch_size=9876) + assert opts.batch_size == 9876 + + opts.validate() + + match = "WriteOptions: batch_size must be at least 1: 0" + with pytest.raises(pa.ArrowInvalid, match=match): + opts = cls() + opts.batch_size = 0 + opts.validate() + + +class BaseTestCSV(abc.ABC): + """Common tests which are shared by streaming and non streaming readers""" + + @abc.abstractmethod + def read_bytes(self, b, **kwargs): + """ + :param b: bytes to be parsed + :param kwargs: arguments passed on to open the csv file + :return: b parsed as a single RecordBatch + """ + raise NotImplementedError + + @property + @abc.abstractmethod + def use_threads(self): + """Whether this test is multi-threaded""" + raise NotImplementedError + + @staticmethod + def check_names(table, names): + assert table.num_columns == len(names) + assert table.column_names == names + + def test_header_skip_rows(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + opts = ReadOptions() + opts.skip_rows = 1 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ef", "gh"]) + assert table.to_pydict() == { + "ef": ["ij", "mn"], + "gh": ["kl", "op"], + } + + opts.skip_rows = 3 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["mn", "op"]) + assert table.to_pydict() == { + "mn": [], + "op": [], + } + + opts.skip_rows = 4 + with pytest.raises(pa.ArrowInvalid): + # Not enough rows + table = self.read_bytes(rows, read_options=opts) + + # Can skip rows with a different number of columns + rows = b"abcd\n,,,,,\nij,kl\nmn,op\n" + opts.skip_rows = 2 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ij", "kl"]) + assert table.to_pydict() == { + "ij": ["mn"], + "kl": ["op"], + } + + # Can skip all rows exactly when columns are given + opts.skip_rows = 4 + opts.column_names = ['ij', 'kl'] + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ij", "kl"]) + assert table.to_pydict() == { + "ij": [], + "kl": [], + } + + def test_skip_rows_after_names(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + opts = ReadOptions() + opts.skip_rows_after_names = 1 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ab", "cd"]) + assert table.to_pydict() == { + "ab": ["ij", "mn"], + "cd": ["kl", "op"], + } + + # Can skip exact number of rows + opts.skip_rows_after_names = 3 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ab", "cd"]) + assert table.to_pydict() == { + "ab": [], + "cd": [], + } + + # Can skip beyond all rows + opts.skip_rows_after_names = 4 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["ab", "cd"]) + assert table.to_pydict() == { + "ab": [], + "cd": [], + } + + # Can skip rows with a different number of columns + rows = b"abcd\n,,,,,\nij,kl\nmn,op\n" + opts.skip_rows_after_names = 2 + opts.column_names = ["f0", "f1"] + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["f0", "f1"]) + assert table.to_pydict() == { + "f0": ["ij", "mn"], + "f1": ["kl", "op"], + } + opts = ReadOptions() + + # Can skip rows with new lines in the value + rows = b'ab,cd\n"e\nf","g\n\nh"\n"ij","k\nl"\nmn,op' + opts.skip_rows_after_names = 2 + parse_opts = ParseOptions() + parse_opts.newlines_in_values = True + table = self.read_bytes(rows, read_options=opts, + parse_options=parse_opts) + self.check_names(table, ["ab", "cd"]) + assert table.to_pydict() == { + "ab": ["mn"], + "cd": ["op"], + } + + # Can skip rows when block ends in middle of quoted value + opts.skip_rows_after_names = 2 + opts.block_size = 26 + table = self.read_bytes(rows, read_options=opts, + parse_options=parse_opts) + self.check_names(table, ["ab", "cd"]) + assert table.to_pydict() == { + "ab": ["mn"], + "cd": ["op"], + } + opts = ReadOptions() + + # Can skip rows that are beyond the first block without lexer + rows, expected = make_random_csv(num_cols=5, num_rows=1000) + opts.skip_rows_after_names = 900 + opts.block_size = len(rows) / 11 + table = self.read_bytes(rows, read_options=opts) + assert table.schema == expected.schema + assert table.num_rows == 100 + table_dict = table.to_pydict() + for name, values in expected.to_pydict().items(): + assert values[900:] == table_dict[name] + + # Can skip rows that are beyond the first block with lexer + table = self.read_bytes(rows, read_options=opts, + parse_options=parse_opts) + assert table.schema == expected.schema + assert table.num_rows == 100 + table_dict = table.to_pydict() + for name, values in expected.to_pydict().items(): + assert values[900:] == table_dict[name] + + # Skip rows and skip rows after names + rows, expected = make_random_csv(num_cols=5, num_rows=200, + write_names=False) + opts = ReadOptions() + opts.skip_rows = 37 + opts.skip_rows_after_names = 41 + opts.column_names = expected.schema.names + table = self.read_bytes(rows, read_options=opts, + parse_options=parse_opts) + assert table.schema == expected.schema + assert (table.num_rows == + expected.num_rows - opts.skip_rows - + opts.skip_rows_after_names) + table_dict = table.to_pydict() + for name, values in expected.to_pydict().items(): + assert (values[opts.skip_rows + opts.skip_rows_after_names:] == + table_dict[name]) + + @pytest.mark.numpy + def test_row_number_offset_in_errors(self): + # Row numbers are only correctly counted in serial reads + def format_msg(msg_format, row, *args): + if self.use_threads: + row_info = "" + else: + row_info = "Row #{}: ".format(row) + return msg_format.format(row_info, *args) + + csv, _ = make_random_csv(4, 100, write_names=True) + + read_options = ReadOptions() + read_options.block_size = len(csv) / 3 + convert_options = ConvertOptions() + convert_options.column_types = {"a": pa.int32()} + + # Test without skip_rows and column names in the csv + csv_bad_columns = csv + b"1,2\r\n" + message_columns = format_msg("{}Expected 4 columns, got 2", 102) + with pytest.raises(pa.ArrowInvalid, match=message_columns): + self.read_bytes(csv_bad_columns, + read_options=read_options, + convert_options=convert_options) + + csv_bad_type = csv + b"a,b,c,d\r\n" + message_value = format_msg( + "In CSV column #0: {}" + "CSV conversion error to int32: invalid value 'a'", + 102, csv) + with pytest.raises(pa.ArrowInvalid, match=message_value): + self.read_bytes(csv_bad_type, + read_options=read_options, + convert_options=convert_options) + + long_row = (b"this is a long row" * 15) + b",3\r\n" + csv_bad_columns_long = csv + long_row + message_long = format_msg("{}Expected 4 columns, got 2: {} ...", 102, + long_row[0:96].decode("utf-8")) + with pytest.raises(pa.ArrowInvalid, match=message_long): + self.read_bytes(csv_bad_columns_long, + read_options=read_options, + convert_options=convert_options) + + # Test skipping rows after the names + read_options.skip_rows_after_names = 47 + + with pytest.raises(pa.ArrowInvalid, match=message_columns): + self.read_bytes(csv_bad_columns, + read_options=read_options, + convert_options=convert_options) + + with pytest.raises(pa.ArrowInvalid, match=message_value): + self.read_bytes(csv_bad_type, + read_options=read_options, + convert_options=convert_options) + + with pytest.raises(pa.ArrowInvalid, match=message_long): + self.read_bytes(csv_bad_columns_long, + read_options=read_options, + convert_options=convert_options) + + read_options.skip_rows_after_names = 0 + + # Test without skip_rows and column names not in the csv + csv, _ = make_random_csv(4, 100, write_names=False) + read_options.column_names = ["a", "b", "c", "d"] + csv_bad_columns = csv + b"1,2\r\n" + message_columns = format_msg("{}Expected 4 columns, got 2", 101) + with pytest.raises(pa.ArrowInvalid, match=message_columns): + self.read_bytes(csv_bad_columns, + read_options=read_options, + convert_options=convert_options) + + csv_bad_columns_long = csv + long_row + message_long = format_msg("{}Expected 4 columns, got 2: {} ...", 101, + long_row[0:96].decode("utf-8")) + with pytest.raises(pa.ArrowInvalid, match=message_long): + self.read_bytes(csv_bad_columns_long, + read_options=read_options, + convert_options=convert_options) + + csv_bad_type = csv + b"a,b,c,d\r\n" + message_value = format_msg( + "In CSV column #0: {}" + "CSV conversion error to int32: invalid value 'a'", + 101) + message_value = message_value.format(len(csv)) + with pytest.raises(pa.ArrowInvalid, match=message_value): + self.read_bytes(csv_bad_type, + read_options=read_options, + convert_options=convert_options) + + # Test with skip_rows and column names not in the csv + read_options.skip_rows = 23 + with pytest.raises(pa.ArrowInvalid, match=message_columns): + self.read_bytes(csv_bad_columns, + read_options=read_options, + convert_options=convert_options) + + with pytest.raises(pa.ArrowInvalid, match=message_value): + self.read_bytes(csv_bad_type, + read_options=read_options, + convert_options=convert_options) + + def test_invalid_row_handler(self, pickle_module): + rows = b"a,b\nc\nd,e\nf,g,h\ni,j\n" + parse_opts = ParseOptions() + with pytest.raises( + ValueError, + match="Expected 2 columns, got 1: c"): + self.read_bytes(rows, parse_options=parse_opts) + + # Skip requested + parse_opts.invalid_row_handler = InvalidRowHandler('skip') + table = self.read_bytes(rows, parse_options=parse_opts) + assert table.to_pydict() == { + 'a': ["d", "i"], + 'b': ["e", "j"], + } + + def row_num(x): + return None if self.use_threads else x + expected_rows = [ + InvalidRow(2, 1, row_num(2), "c"), + InvalidRow(2, 3, row_num(4), "f,g,h"), + ] + assert parse_opts.invalid_row_handler.rows == expected_rows + + # Error requested + parse_opts.invalid_row_handler = InvalidRowHandler('error') + with pytest.raises( + ValueError, + match="Expected 2 columns, got 1: c"): + self.read_bytes(rows, parse_options=parse_opts) + expected_rows = [InvalidRow(2, 1, row_num(2), "c")] + assert parse_opts.invalid_row_handler.rows == expected_rows + + # Test ser/de + parse_opts.invalid_row_handler = InvalidRowHandler('skip') + parse_opts = pickle_module.loads(pickle_module.dumps(parse_opts)) + + table = self.read_bytes(rows, parse_options=parse_opts) + assert table.to_pydict() == { + 'a': ["d", "i"], + 'b': ["e", "j"], + } + + def test_chunker_out_of_sync(self): + # GH-39892: if there are newlines in values, the parser may become + # out of sync with the chunker. In this case, we try to produce an + # informative error message. + rows = b"""a,b,c\nd,e,"f\n"\ng,h,i\n""" + expected = { + 'a': ["d", "g"], + 'b': ["e", "h"], + 'c': ["f\n", "i"], + } + for block_size in range(8, 15): + # Sanity check: parsing works with newlines_in_values=True + d = self.read_bytes( + rows, parse_options=ParseOptions(newlines_in_values=True), + read_options=ReadOptions(block_size=block_size)).to_pydict() + assert d == expected + # With these block sizes, a block would end on the physical newline + # inside the quoted cell value, leading to a mismatch between + # CSV chunker and parser. + for block_size in range(8, 11): + with pytest.raises(ValueError, + match="cell values spanning multiple lines"): + self.read_bytes( + rows, read_options=ReadOptions(block_size=block_size)) + + +class BaseCSVTableRead(BaseTestCSV): + + def read_csv(self, csv, *args, validate_full=True, **kwargs): + """ + Reads the CSV file into memory using pyarrow's read_csv + csv The CSV bytes + args Positional arguments to be forwarded to pyarrow's read_csv + validate_full Whether or not to fully validate the resulting table + kwargs Keyword arguments to be forwarded to pyarrow's read_csv + """ + assert isinstance(self.use_threads, bool) # sanity check + read_options = kwargs.setdefault('read_options', ReadOptions()) + read_options.use_threads = self.use_threads + table = read_csv(csv, *args, **kwargs) + table.validate(full=validate_full) + return table + + def read_bytes(self, b, **kwargs): + return self.read_csv(pa.py_buffer(b), **kwargs) + + def test_file_object(self): + data = b"a,b\n1,2\n" + expected_data = {'a': [1], 'b': [2]} + bio = io.BytesIO(data) + table = self.read_csv(bio) + assert table.to_pydict() == expected_data + # Text files not allowed + sio = io.StringIO(data.decode()) + with pytest.raises(TypeError): + self.read_csv(sio) + + def test_header(self): + rows = b"abc,def,gh\n" + table = self.read_bytes(rows) + assert isinstance(table, pa.Table) + self.check_names(table, ["abc", "def", "gh"]) + assert table.num_rows == 0 + + def test_bom(self): + rows = b"\xef\xbb\xbfa,b\n1,2\n" + expected_data = {'a': [1], 'b': [2]} + table = self.read_bytes(rows) + assert table.to_pydict() == expected_data + + def test_one_chunk(self): + # ARROW-7661: lack of newline at end of file should not produce + # an additional chunk. + rows = [b"a,b", b"1,2", b"3,4", b"56,78"] + for line_ending in [b'\n', b'\r', b'\r\n']: + for file_ending in [b'', line_ending]: + data = line_ending.join(rows) + file_ending + table = self.read_bytes(data) + assert len(table.to_batches()) == 1 + assert table.to_pydict() == { + "a": [1, 3, 56], + "b": [2, 4, 78], + } + + def test_header_column_names(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + opts = ReadOptions() + opts.column_names = ["x", "y"] + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["x", "y"]) + assert table.to_pydict() == { + "x": ["ab", "ef", "ij", "mn"], + "y": ["cd", "gh", "kl", "op"], + } + + opts.skip_rows = 3 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["x", "y"]) + assert table.to_pydict() == { + "x": ["mn"], + "y": ["op"], + } + + opts.skip_rows = 4 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["x", "y"]) + assert table.to_pydict() == { + "x": [], + "y": [], + } + + opts.skip_rows = 5 + with pytest.raises(pa.ArrowInvalid): + # Not enough rows + table = self.read_bytes(rows, read_options=opts) + + # Unexpected number of columns + opts.skip_rows = 0 + opts.column_names = ["x", "y", "z"] + with pytest.raises(pa.ArrowInvalid, + match="Expected 3 columns, got 2"): + table = self.read_bytes(rows, read_options=opts) + + # Can skip rows with a different number of columns + rows = b"abcd\n,,,,,\nij,kl\nmn,op\n" + opts.skip_rows = 2 + opts.column_names = ["x", "y"] + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["x", "y"]) + assert table.to_pydict() == { + "x": ["ij", "mn"], + "y": ["kl", "op"], + } + + def test_header_autogenerate_column_names(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + opts = ReadOptions() + opts.autogenerate_column_names = True + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["f0", "f1"]) + assert table.to_pydict() == { + "f0": ["ab", "ef", "ij", "mn"], + "f1": ["cd", "gh", "kl", "op"], + } + + opts.skip_rows = 3 + table = self.read_bytes(rows, read_options=opts) + self.check_names(table, ["f0", "f1"]) + assert table.to_pydict() == { + "f0": ["mn"], + "f1": ["op"], + } + + # Not enough rows, impossible to infer number of columns + opts.skip_rows = 4 + with pytest.raises(pa.ArrowInvalid): + table = self.read_bytes(rows, read_options=opts) + + def test_include_columns(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + convert_options = ConvertOptions() + convert_options.include_columns = ['ab'] + table = self.read_bytes(rows, convert_options=convert_options) + self.check_names(table, ["ab"]) + assert table.to_pydict() == { + "ab": ["ef", "ij", "mn"], + } + + # Order of include_columns is respected, regardless of CSV order + convert_options.include_columns = ['cd', 'ab'] + table = self.read_bytes(rows, convert_options=convert_options) + schema = pa.schema([('cd', pa.string()), + ('ab', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + "cd": ["gh", "kl", "op"], + "ab": ["ef", "ij", "mn"], + } + + # Include a column not in the CSV file => raises by default + convert_options.include_columns = ['xx', 'ab', 'yy'] + with pytest.raises(KeyError, + match="Column 'xx' in include_columns " + "does not exist in CSV file"): + self.read_bytes(rows, convert_options=convert_options) + + def test_include_missing_columns(self): + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + read_options = ReadOptions() + convert_options = ConvertOptions() + convert_options.include_columns = ['xx', 'ab', 'yy'] + convert_options.include_missing_columns = True + table = self.read_bytes(rows, read_options=read_options, + convert_options=convert_options) + schema = pa.schema([('xx', pa.null()), + ('ab', pa.string()), + ('yy', pa.null())]) + assert table.schema == schema + assert table.to_pydict() == { + "xx": [None, None, None], + "ab": ["ef", "ij", "mn"], + "yy": [None, None, None], + } + + # Combining with `column_names` + read_options.column_names = ["xx", "yy"] + convert_options.include_columns = ["yy", "cd"] + table = self.read_bytes(rows, read_options=read_options, + convert_options=convert_options) + schema = pa.schema([('yy', pa.string()), + ('cd', pa.null())]) + assert table.schema == schema + assert table.to_pydict() == { + "yy": ["cd", "gh", "kl", "op"], + "cd": [None, None, None, None], + } + + # And with `column_types` as well + convert_options.column_types = {"yy": pa.binary(), + "cd": pa.int32()} + table = self.read_bytes(rows, read_options=read_options, + convert_options=convert_options) + schema = pa.schema([('yy', pa.binary()), + ('cd', pa.int32())]) + assert table.schema == schema + assert table.to_pydict() == { + "yy": [b"cd", b"gh", b"kl", b"op"], + "cd": [None, None, None, None], + } + + def test_simple_ints(self): + # Infer integer columns + rows = b"a,b,c\n1,2,3\n4,5,6\n" + table = self.read_bytes(rows) + schema = pa.schema([('a', pa.int64()), + ('b', pa.int64()), + ('c', pa.int64())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [1, 4], + 'b': [2, 5], + 'c': [3, 6], + } + + def test_simple_varied(self): + # Infer various kinds of data + rows = b"a,b,c,d\n1,2,3,0\n4.0,-5,foo,True\n" + table = self.read_bytes(rows) + schema = pa.schema([('a', pa.float64()), + ('b', pa.int64()), + ('c', pa.string()), + ('d', pa.bool_())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [1.0, 4.0], + 'b': [2, -5], + 'c': ["3", "foo"], + 'd': [False, True], + } + + def test_simple_nulls(self): + # Infer various kinds of data, with nulls + rows = (b"a,b,c,d,e,f\n" + b"1,2,,,3,N/A\n" + b"nan,-5,foo,,nan,TRUE\n" + b"4.5,#N/A,nan,,\xff,false\n") + table = self.read_bytes(rows) + schema = pa.schema([('a', pa.float64()), + ('b', pa.int64()), + ('c', pa.string()), + ('d', pa.null()), + ('e', pa.binary()), + ('f', pa.bool_())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [1.0, None, 4.5], + 'b': [2, -5, None], + 'c': ["", "foo", "nan"], + 'd': [None, None, None], + 'e': [b"3", b"nan", b"\xff"], + 'f': [None, True, False], + } + + def test_decimal_point(self): + # Infer floats with a custom decimal point + parse_options = ParseOptions(delimiter=';') + rows = b"a;b\n1.25;2,5\nNA;-3\n-4;NA" + + table = self.read_bytes(rows, parse_options=parse_options) + schema = pa.schema([('a', pa.float64()), + ('b', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [1.25, None, -4.0], + 'b': ["2,5", "-3", "NA"], + } + + convert_options = ConvertOptions(decimal_point=',') + table = self.read_bytes(rows, parse_options=parse_options, + convert_options=convert_options) + schema = pa.schema([('a', pa.string()), + ('b', pa.float64())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': ["1.25", "NA", "-4"], + 'b': [2.5, -3.0, None], + } + + def test_simple_timestamps(self): + # Infer a timestamp column + rows = (b"a,b,c\n" + b"1970,1970-01-01 00:00:00,1970-01-01 00:00:00.123\n" + b"1989,1989-07-14 01:00:00,1989-07-14 01:00:00.123456\n") + table = self.read_bytes(rows) + schema = pa.schema([('a', pa.int64()), + ('b', pa.timestamp('s')), + ('c', pa.timestamp('ns'))]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [1970, 1989], + 'b': [datetime(1970, 1, 1), datetime(1989, 7, 14, 1)], + 'c': [datetime(1970, 1, 1, 0, 0, 0, 123000), + datetime(1989, 7, 14, 1, 0, 0, 123456)], + } + + def test_timestamp_parsers(self): + # Infer timestamps with custom parsers + rows = b"a,b\n1970/01/01,1980-01-01 00\n1970/01/02,1980-01-02 00\n" + opts = ConvertOptions() + + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.string()), + ('b', pa.timestamp('s'))]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': ['1970/01/01', '1970/01/02'], + 'b': [datetime(1980, 1, 1), datetime(1980, 1, 2)], + } + + opts.timestamp_parsers = ['%Y/%m/%d'] + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.timestamp('s')), + ('b', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [datetime(1970, 1, 1), datetime(1970, 1, 2)], + 'b': ['1980-01-01 00', '1980-01-02 00'], + } + + opts.timestamp_parsers = ['%Y/%m/%d', ISO8601] + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.timestamp('s')), + ('b', pa.timestamp('s'))]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [datetime(1970, 1, 1), datetime(1970, 1, 2)], + 'b': [datetime(1980, 1, 1), datetime(1980, 1, 2)], + } + + def test_dates(self): + # Dates are inferred as date32 by default + rows = b"a,b\n1970-01-01,1970-01-02\n1971-01-01,1971-01-02\n" + table = self.read_bytes(rows) + schema = pa.schema([('a', pa.date32()), + ('b', pa.date32())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [date(1970, 1, 1), date(1971, 1, 1)], + 'b': [date(1970, 1, 2), date(1971, 1, 2)], + } + + # Can ask for date types explicitly + opts = ConvertOptions() + opts.column_types = {'a': pa.date32(), 'b': pa.date64()} + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.date32()), + ('b', pa.date64())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [date(1970, 1, 1), date(1971, 1, 1)], + 'b': [date(1970, 1, 2), date(1971, 1, 2)], + } + + # Can ask for timestamp types explicitly + opts = ConvertOptions() + opts.column_types = {'a': pa.timestamp('s'), 'b': pa.timestamp('ms')} + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.timestamp('s')), + ('b', pa.timestamp('ms'))]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [datetime(1970, 1, 1), datetime(1971, 1, 1)], + 'b': [datetime(1970, 1, 2), datetime(1971, 1, 2)], + } + + def test_times(self): + # Times are inferred as time32[s] by default + from datetime import time + + rows = b"a,b\n12:34:56,12:34:56.789\n23:59:59,23:59:59.999\n" + table = self.read_bytes(rows) + # Column 'b' has subseconds, so cannot be inferred as time32[s] + schema = pa.schema([('a', pa.time32('s')), + ('b', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [time(12, 34, 56), time(23, 59, 59)], + 'b': ["12:34:56.789", "23:59:59.999"], + } + + # Can ask for time types explicitly + opts = ConvertOptions() + opts.column_types = {'a': pa.time64('us'), 'b': pa.time32('ms')} + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.time64('us')), + ('b', pa.time32('ms'))]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [time(12, 34, 56), time(23, 59, 59)], + 'b': [time(12, 34, 56, 789000), time(23, 59, 59, 999000)], + } + + def test_auto_dict_encode(self): + opts = ConvertOptions(auto_dict_encode=True) + rows = "a,b\nab,1\ncdé,2\ncdé,3\nab,4".encode() + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.dictionary(pa.int32(), pa.string())), + ('b', pa.int64())]) + expected = { + 'a': ["ab", "cdé", "cdé", "ab"], + 'b': [1, 2, 3, 4], + } + assert table.schema == schema + assert table.to_pydict() == expected + + opts.auto_dict_max_cardinality = 2 + table = self.read_bytes(rows, convert_options=opts) + assert table.schema == schema + assert table.to_pydict() == expected + + # Cardinality above max => plain-encoded + opts.auto_dict_max_cardinality = 1 + table = self.read_bytes(rows, convert_options=opts) + assert table.schema == pa.schema([('a', pa.string()), + ('b', pa.int64())]) + assert table.to_pydict() == expected + + # With invalid UTF8, not checked + opts.auto_dict_max_cardinality = 50 + opts.check_utf8 = False + rows = b"a,b\nab,1\ncd\xff,2\nab,3" + table = self.read_bytes(rows, convert_options=opts, + validate_full=False) + assert table.schema == schema + dict_values = table['a'].chunk(0).dictionary + assert len(dict_values) == 2 + assert dict_values[0].as_py() == "ab" + assert dict_values[1].as_buffer() == b"cd\xff" + + # With invalid UTF8, checked + opts.check_utf8 = True + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.dictionary(pa.int32(), pa.binary())), + ('b', pa.int64())]) + expected = { + 'a': [b"ab", b"cd\xff", b"ab"], + 'b': [1, 2, 3], + } + assert table.schema == schema + assert table.to_pydict() == expected + + def test_custom_nulls(self): + # Infer nulls with custom values + opts = ConvertOptions(null_values=['Xxx', 'Zzz']) + rows = b"""a,b,c,d\nZzz,"Xxx",1,2\nXxx,#N/A,,Zzz\n""" + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.null()), + ('b', pa.string()), + ('c', pa.string()), + ('d', pa.int64())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': [None, None], + 'b': ["Xxx", "#N/A"], + 'c': ["1", ""], + 'd': [2, None], + } + + opts = ConvertOptions(null_values=['Xxx', 'Zzz'], + strings_can_be_null=True) + table = self.read_bytes(rows, convert_options=opts) + assert table.to_pydict() == { + 'a': [None, None], + 'b': [None, "#N/A"], + 'c': ["1", ""], + 'd': [2, None], + } + opts.quoted_strings_can_be_null = False + table = self.read_bytes(rows, convert_options=opts) + assert table.to_pydict() == { + 'a': [None, None], + 'b': ["Xxx", "#N/A"], + 'c': ["1", ""], + 'd': [2, None], + } + + opts = ConvertOptions(null_values=[]) + rows = b"a,b\n#N/A,\n" + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.string()), + ('b', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': ["#N/A"], + 'b': [""], + } + + def test_custom_bools(self): + # Infer booleans with custom values + opts = ConvertOptions(true_values=['T', 'yes'], + false_values=['F', 'no']) + rows = (b"a,b,c\n" + b"True,T,t\n" + b"False,F,f\n" + b"True,yes,yes\n" + b"False,no,no\n" + b"N/A,N/A,N/A\n") + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.string()), + ('b', pa.bool_()), + ('c', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'a': ["True", "False", "True", "False", "N/A"], + 'b': [True, False, True, False, None], + 'c': ["t", "f", "yes", "no", "N/A"], + } + + def test_column_types(self): + # Ask for specific column types in ConvertOptions + opts = ConvertOptions(column_types={'b': 'float32', + 'c': 'string', + 'd': 'boolean', + 'e': pa.decimal128(11, 2), + 'zz': 'null'}) + rows = b"a,b,c,d,e\n1,2,3,true,1.0\n4,-5,6,false,0\n" + table = self.read_bytes(rows, convert_options=opts) + schema = pa.schema([('a', pa.int64()), + ('b', pa.float32()), + ('c', pa.string()), + ('d', pa.bool_()), + ('e', pa.decimal128(11, 2))]) + expected = { + 'a': [1, 4], + 'b': [2.0, -5.0], + 'c': ["3", "6"], + 'd': [True, False], + 'e': [Decimal("1.00"), Decimal("0.00")] + } + assert table.schema == schema + assert table.to_pydict() == expected + # Pass column_types as schema + opts = ConvertOptions( + column_types=pa.schema([('b', pa.float32()), + ('c', pa.string()), + ('d', pa.bool_()), + ('e', pa.decimal128(11, 2)), + ('zz', pa.bool_())])) + table = self.read_bytes(rows, convert_options=opts) + assert table.schema == schema + assert table.to_pydict() == expected + # One of the columns in column_types fails converting + rows = b"a,b,c,d,e\n1,XXX,3,true,5\n4,-5,6,false,7\n" + with pytest.raises(pa.ArrowInvalid) as exc: + self.read_bytes(rows, convert_options=opts) + err = str(exc.value) + assert "In CSV column #1: " in err + assert "CSV conversion error to float: invalid value 'XXX'" in err + + def test_column_types_dict(self): + # Ask for dict-encoded column types in ConvertOptions + column_types = [ + ('a', pa.dictionary(pa.int32(), pa.utf8())), + ('b', pa.dictionary(pa.int32(), pa.int64())), + ('c', pa.dictionary(pa.int32(), pa.decimal128(11, 2))), + ('d', pa.dictionary(pa.int32(), pa.large_utf8()))] + + opts = ConvertOptions(column_types=dict(column_types)) + rows = (b"a,b,c,d\n" + b"abc,123456,1.0,zz\n" + b"defg,123456,0.5,xx\n" + b"abc,N/A,1.0,xx\n") + table = self.read_bytes(rows, convert_options=opts) + + schema = pa.schema(column_types) + expected = { + 'a': ["abc", "defg", "abc"], + 'b': [123456, 123456, None], + 'c': [Decimal("1.00"), Decimal("0.50"), Decimal("1.00")], + 'd': ["zz", "xx", "xx"], + } + assert table.schema == schema + assert table.to_pydict() == expected + + # Unsupported index type + column_types[0] = ('a', pa.dictionary(pa.int8(), pa.utf8())) + + opts = ConvertOptions(column_types=dict(column_types)) + with pytest.raises(NotImplementedError): + table = self.read_bytes(rows, convert_options=opts) + + def test_column_types_with_column_names(self): + # When both `column_names` and `column_types` are given, names + # in `column_types` should refer to names in `column_names` + rows = b"a,b\nc,d\ne,f\n" + read_options = ReadOptions(column_names=['x', 'y']) + convert_options = ConvertOptions(column_types={'x': pa.binary()}) + table = self.read_bytes(rows, read_options=read_options, + convert_options=convert_options) + schema = pa.schema([('x', pa.binary()), + ('y', pa.string())]) + assert table.schema == schema + assert table.to_pydict() == { + 'x': [b'a', b'c', b'e'], + 'y': ['b', 'd', 'f'], + } + + def test_no_ending_newline(self): + # No \n after last line + rows = b"a,b,c\n1,2,3\n4,5,6" + table = self.read_bytes(rows) + assert table.to_pydict() == { + 'a': [1, 4], + 'b': [2, 5], + 'c': [3, 6], + } + + def test_trivial(self): + # A bit pointless, but at least it shouldn't crash + rows = b",\n\n" + table = self.read_bytes(rows) + assert table.to_pydict() == {'': []} + + def test_empty_lines(self): + rows = b"a,b\n\r1,2\r\n\r\n3,4\r\n" + table = self.read_bytes(rows) + assert table.to_pydict() == { + 'a': [1, 3], + 'b': [2, 4], + } + parse_options = ParseOptions(ignore_empty_lines=False) + table = self.read_bytes(rows, parse_options=parse_options) + assert table.to_pydict() == { + 'a': [None, 1, None, 3], + 'b': [None, 2, None, 4], + } + read_options = ReadOptions(skip_rows=2) + table = self.read_bytes(rows, parse_options=parse_options, + read_options=read_options) + assert table.to_pydict() == { + '1': [None, 3], + '2': [None, 4], + } + + def test_invalid_csv(self): + # Various CSV errors + rows = b"a,b,c\n1,2\n4,5,6\n" + with pytest.raises(pa.ArrowInvalid, match="Expected 3 columns, got 2"): + self.read_bytes(rows) + rows = b"a,b,c\n1,2,3\n4" + with pytest.raises(pa.ArrowInvalid, match="Expected 3 columns, got 1"): + self.read_bytes(rows) + for rows in [b"", b"\n", b"\r\n", b"\r", b"\n\n"]: + with pytest.raises(pa.ArrowInvalid, match="Empty CSV file"): + self.read_bytes(rows) + + def test_options_delimiter(self): + rows = b"a;b,c\nde,fg;eh\n" + table = self.read_bytes(rows) + assert table.to_pydict() == { + 'a;b': ['de'], + 'c': ['fg;eh'], + } + opts = ParseOptions(delimiter=';') + table = self.read_bytes(rows, parse_options=opts) + assert table.to_pydict() == { + 'a': ['de,fg'], + 'b,c': ['eh'], + } + + def test_small_random_csv(self): + csv, expected = make_random_csv(num_cols=2, num_rows=10) + table = self.read_bytes(csv) + assert table.schema == expected.schema + assert table.equals(expected) + assert table.to_pydict() == expected.to_pydict() + + def test_stress_block_sizes(self): + # Test a number of small block sizes to stress block stitching + csv_base, expected = make_random_csv(num_cols=2, num_rows=500) + block_sizes = [11, 12, 13, 17, 37, 111] + csvs = [csv_base, csv_base.rstrip(b'\r\n')] + for csv in csvs: + for block_size in block_sizes: + read_options = ReadOptions(block_size=block_size) + table = self.read_bytes(csv, read_options=read_options) + assert table.schema == expected.schema + if not table.equals(expected): + # Better error output + assert table.to_pydict() == expected.to_pydict() + + def test_stress_convert_options_blowup(self): + # ARROW-6481: A convert_options with a very large number of columns + # should not blow memory and CPU time. + try: + clock = time.thread_time + except AttributeError: + clock = time.time + num_columns = 10000 + col_names = ["K{}".format(i) for i in range(num_columns)] + csv = make_empty_csv(col_names) + t1 = clock() + convert_options = ConvertOptions( + column_types={k: pa.string() for k in col_names[::2]}) + table = self.read_bytes(csv, convert_options=convert_options) + dt = clock() - t1 + # Check that processing time didn't blow up. + # This is a conservative check (it takes less than 300 ms + # in debug mode on my local machine). + assert dt <= 10.0 + # Check result + assert table.num_columns == num_columns + assert table.num_rows == 0 + assert table.column_names == col_names + + @pytest.mark.threading + def test_cancellation(self): + if (threading.current_thread().ident != + threading.main_thread().ident): + pytest.skip("test only works from main Python thread") + + def signal_from_thread(): + # Give our workload a chance to start up + time.sleep(0.2) + signal.raise_signal(signal.SIGINT) + + # We start with a small CSV reading workload and increase its size + # until it's large enough to get an interruption during it, even in + # release mode on fast machines. + last_duration = 0.0 + workload_size = 100_000 + attempts = 0 + + while last_duration < 5.0 and attempts < 10: + print("workload size:", workload_size) + large_csv = b"a,b,c\n" + b"1,2,3\n" * workload_size + exc_info = None + + try: + # We use a signal fd to reliably ensure that the signal + # has been delivered to Python, regardless of how exactly + # it was caught. + with util.signal_wakeup_fd() as sigfd: + try: + t = threading.Thread(target=signal_from_thread) + t.start() + t1 = time.time() + try: + self.read_bytes(large_csv) + except KeyboardInterrupt as e: + exc_info = e + last_duration = time.time() - t1 + finally: + # Wait for signal to arrive if it didn't already, + # to avoid getting a KeyboardInterrupt after the + # `except` block below. + select.select([sigfd], [], [sigfd], 10.0) + + except KeyboardInterrupt: + # KeyboardInterrupt didn't interrupt `read_bytes` above. + pass + + if exc_info is not None: + # We managed to get `self.read_bytes` interrupted, see if it + # was actually interrupted inside Arrow C++ or in the Python + # scaffolding. + if exc_info.__context__ is not None: + # Interrupted inside Arrow C++, we're satisfied now + break + + # Increase workload size to get a better chance + workload_size = workload_size * 3 + + if exc_info is None: + pytest.fail("Failed to get an interruption during CSV reading") + + # Interruption should have arrived timely + assert last_duration <= 2.0 + e = exc_info.__context__ + assert isinstance(e, pa.ArrowCancelled) + assert e.signum == signal.SIGINT + + @pytest.mark.threading + def test_cancellation_disabled(self): + # ARROW-12622: reader would segfault when the cancelling signal + # handler was not enabled (e.g. if disabled, or if not on the + # main thread) + t = threading.Thread( + target=lambda: self.read_bytes(b"f64\n0.1")) + t.start() + t.join() + + +class TestSerialCSVTableRead(BaseCSVTableRead): + @property + def use_threads(self): + return False + + +class TestThreadedCSVTableRead(BaseCSVTableRead): + @property + def use_threads(self): + return True + + +class BaseStreamingCSVRead(BaseTestCSV): + + def open_csv(self, csv, *args, **kwargs): + """ + Reads the CSV file into memory using pyarrow's open_csv + csv The CSV bytes + args Positional arguments to be forwarded to pyarrow's open_csv + kwargs Keyword arguments to be forwarded to pyarrow's open_csv + """ + read_options = kwargs.setdefault('read_options', ReadOptions()) + read_options.use_threads = self.use_threads + return open_csv(csv, *args, **kwargs) + + def open_bytes(self, b, **kwargs): + return self.open_csv(pa.py_buffer(b), **kwargs) + + def check_reader(self, reader, expected_schema, expected_data): + assert reader.schema == expected_schema + batches = list(reader) + assert len(batches) == len(expected_data) + for batch, expected_batch in zip(batches, expected_data): + batch.validate(full=True) + assert batch.schema == expected_schema + assert batch.to_pydict() == expected_batch + + def read_bytes(self, b, **kwargs): + return self.open_bytes(b, **kwargs).read_all() + + def test_file_object(self): + data = b"a,b\n1,2\n3,4\n" + expected_data = {'a': [1, 3], 'b': [2, 4]} + bio = io.BytesIO(data) + reader = self.open_csv(bio) + expected_schema = pa.schema([('a', pa.int64()), + ('b', pa.int64())]) + self.check_reader(reader, expected_schema, [expected_data]) + + def test_header(self): + rows = b"abc,def,gh\n" + reader = self.open_bytes(rows) + expected_schema = pa.schema([('abc', pa.null()), + ('def', pa.null()), + ('gh', pa.null())]) + self.check_reader(reader, expected_schema, []) + + def test_inference(self): + # Inference is done on first block + rows = b"a,b\n123,456\nabc,de\xff\ngh,ij\n" + expected_schema = pa.schema([('a', pa.string()), + ('b', pa.binary())]) + + read_options = ReadOptions() + read_options.block_size = len(rows) + reader = self.open_bytes(rows, read_options=read_options) + self.check_reader(reader, expected_schema, + [{'a': ['123', 'abc', 'gh'], + 'b': [b'456', b'de\xff', b'ij']}]) + + read_options.block_size = len(rows) - 1 + reader = self.open_bytes(rows, read_options=read_options) + self.check_reader(reader, expected_schema, + [{'a': ['123', 'abc'], + 'b': [b'456', b'de\xff']}, + {'a': ['gh'], + 'b': [b'ij']}]) + + def test_inference_failure(self): + # Inference on first block, then conversion failure on second block + rows = b"a,b\n123,456\nabc,de\xff\ngh,ij\n" + read_options = ReadOptions() + read_options.block_size = len(rows) - 7 + reader = self.open_bytes(rows, read_options=read_options) + expected_schema = pa.schema([('a', pa.int64()), + ('b', pa.int64())]) + assert reader.schema == expected_schema + assert reader.read_next_batch().to_pydict() == { + 'a': [123], 'b': [456] + } + # Second block + with pytest.raises(ValueError, + match="CSV conversion error to int64"): + reader.read_next_batch() + # EOF + with pytest.raises(StopIteration): + reader.read_next_batch() + + def test_invalid_csv(self): + # CSV errors on first block + rows = b"a,b\n1,2,3\n4,5\n6,7\n" + read_options = ReadOptions() + read_options.block_size = 10 + with pytest.raises(pa.ArrowInvalid, + match="Expected 2 columns, got 3"): + reader = self.open_bytes( + rows, read_options=read_options) + + # CSV errors on second block + rows = b"a,b\n1,2\n3,4,5\n6,7\n" + read_options.block_size = 8 + reader = self.open_bytes(rows, read_options=read_options) + assert reader.read_next_batch().to_pydict() == {'a': [1], 'b': [2]} + with pytest.raises(pa.ArrowInvalid, + match="Expected 2 columns, got 3"): + reader.read_next_batch() + # Cannot continue after a parse error + with pytest.raises(StopIteration): + reader.read_next_batch() + + def test_options_delimiter(self): + rows = b"a;b,c\nde,fg;eh\n" + reader = self.open_bytes(rows) + expected_schema = pa.schema([('a;b', pa.string()), + ('c', pa.string())]) + self.check_reader(reader, expected_schema, + [{'a;b': ['de'], + 'c': ['fg;eh']}]) + + opts = ParseOptions(delimiter=';') + reader = self.open_bytes(rows, parse_options=opts) + expected_schema = pa.schema([('a', pa.string()), + ('b,c', pa.string())]) + self.check_reader(reader, expected_schema, + [{'a': ['de,fg'], + 'b,c': ['eh']}]) + + def test_no_ending_newline(self): + # No \n after last line + rows = b"a,b,c\n1,2,3\n4,5,6" + reader = self.open_bytes(rows) + expected_schema = pa.schema([('a', pa.int64()), + ('b', pa.int64()), + ('c', pa.int64())]) + self.check_reader(reader, expected_schema, + [{'a': [1, 4], + 'b': [2, 5], + 'c': [3, 6]}]) + + def test_empty_file(self): + with pytest.raises(ValueError, match="Empty CSV file"): + self.open_bytes(b"") + + def test_column_options(self): + # With column_names + rows = b"1,2,3\n4,5,6" + read_options = ReadOptions() + read_options.column_names = ['d', 'e', 'f'] + reader = self.open_bytes(rows, read_options=read_options) + expected_schema = pa.schema([('d', pa.int64()), + ('e', pa.int64()), + ('f', pa.int64())]) + self.check_reader(reader, expected_schema, + [{'d': [1, 4], + 'e': [2, 5], + 'f': [3, 6]}]) + + # With include_columns + convert_options = ConvertOptions() + convert_options.include_columns = ['f', 'e'] + reader = self.open_bytes(rows, read_options=read_options, + convert_options=convert_options) + expected_schema = pa.schema([('f', pa.int64()), + ('e', pa.int64())]) + self.check_reader(reader, expected_schema, + [{'e': [2, 5], + 'f': [3, 6]}]) + + # With column_types + convert_options.column_types = {'e': pa.string()} + reader = self.open_bytes(rows, read_options=read_options, + convert_options=convert_options) + expected_schema = pa.schema([('f', pa.int64()), + ('e', pa.string())]) + self.check_reader(reader, expected_schema, + [{'e': ["2", "5"], + 'f': [3, 6]}]) + + # Missing columns in include_columns + convert_options.include_columns = ['g', 'f', 'e'] + with pytest.raises( + KeyError, + match="Column 'g' in include_columns does not exist"): + reader = self.open_bytes(rows, read_options=read_options, + convert_options=convert_options) + + convert_options.include_missing_columns = True + reader = self.open_bytes(rows, read_options=read_options, + convert_options=convert_options) + expected_schema = pa.schema([('g', pa.null()), + ('f', pa.int64()), + ('e', pa.string())]) + self.check_reader(reader, expected_schema, + [{'g': [None, None], + 'e': ["2", "5"], + 'f': [3, 6]}]) + + convert_options.column_types = {'e': pa.string(), 'g': pa.float64()} + reader = self.open_bytes(rows, read_options=read_options, + convert_options=convert_options) + expected_schema = pa.schema([('g', pa.float64()), + ('f', pa.int64()), + ('e', pa.string())]) + self.check_reader(reader, expected_schema, + [{'g': [None, None], + 'e': ["2", "5"], + 'f': [3, 6]}]) + + def test_encoding(self): + # latin-1 (invalid utf-8) + rows = b"a,b\nun,\xe9l\xe9phant" + read_options = ReadOptions() + reader = self.open_bytes(rows, read_options=read_options) + expected_schema = pa.schema([('a', pa.string()), + ('b', pa.binary())]) + self.check_reader(reader, expected_schema, + [{'a': ["un"], + 'b': [b"\xe9l\xe9phant"]}]) + + read_options.encoding = 'latin1' + reader = self.open_bytes(rows, read_options=read_options) + expected_schema = pa.schema([('a', pa.string()), + ('b', pa.string())]) + self.check_reader(reader, expected_schema, + [{'a': ["un"], + 'b': ["éléphant"]}]) + + # utf-16 + rows = (b'\xff\xfea\x00,\x00b\x00\n\x00u\x00n\x00,' + b'\x00\xe9\x00l\x00\xe9\x00p\x00h\x00a\x00n\x00t\x00') + read_options.encoding = 'utf16' + reader = self.open_bytes(rows, read_options=read_options) + expected_schema = pa.schema([('a', pa.string()), + ('b', pa.string())]) + self.check_reader(reader, expected_schema, + [{'a': ["un"], + 'b': ["éléphant"]}]) + + def test_small_random_csv(self): + csv, expected = make_random_csv(num_cols=2, num_rows=10) + reader = self.open_bytes(csv) + table = reader.read_all() + assert table.schema == expected.schema + assert table.equals(expected) + assert table.to_pydict() == expected.to_pydict() + + def test_stress_block_sizes(self): + # Test a number of small block sizes to stress block stitching + csv_base, expected = make_random_csv(num_cols=2, num_rows=500) + block_sizes = [19, 21, 23, 26, 37, 111] + csvs = [csv_base, csv_base.rstrip(b'\r\n')] + for csv in csvs: + for block_size in block_sizes: + # Need at least two lines for type inference + assert csv[:block_size].count(b'\n') >= 2 + read_options = ReadOptions(block_size=block_size) + reader = self.open_bytes( + csv, read_options=read_options) + table = reader.read_all() + assert table.schema == expected.schema + if not table.equals(expected): + # Better error output + assert table.to_pydict() == expected.to_pydict() + + def test_batch_lifetime(self): + gc.collect() + old_allocated = pa.total_allocated_bytes() + + # Memory occupation should not grow with CSV file size + def check_one_batch(reader, expected): + batch = reader.read_next_batch() + assert batch.to_pydict() == expected + + rows = b"10,11\n12,13\n14,15\n16,17\n" + read_options = ReadOptions() + read_options.column_names = ['a', 'b'] + read_options.block_size = 6 + reader = self.open_bytes(rows, read_options=read_options) + check_one_batch(reader, {'a': [10], 'b': [11]}) + allocated_after_first_batch = pa.total_allocated_bytes() + check_one_batch(reader, {'a': [12], 'b': [13]}) + assert pa.total_allocated_bytes() <= allocated_after_first_batch + check_one_batch(reader, {'a': [14], 'b': [15]}) + assert pa.total_allocated_bytes() <= allocated_after_first_batch + check_one_batch(reader, {'a': [16], 'b': [17]}) + assert pa.total_allocated_bytes() <= allocated_after_first_batch + with pytest.raises(StopIteration): + reader.read_next_batch() + assert pa.total_allocated_bytes() == old_allocated + reader = None + assert pa.total_allocated_bytes() == old_allocated + + def test_header_skip_rows(self): + super().test_header_skip_rows() + + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + # Skipping all rows immediately results in end of iteration + opts = ReadOptions() + opts.skip_rows = 4 + opts.column_names = ['ab', 'cd'] + reader = self.open_bytes(rows, read_options=opts) + with pytest.raises(StopIteration): + assert reader.read_next_batch() + + @pytest.mark.numpy + def test_skip_rows_after_names(self): + super().test_skip_rows_after_names() + + rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n" + + # Skipping all rows immediately results in end of iteration + opts = ReadOptions() + opts.skip_rows_after_names = 3 + reader = self.open_bytes(rows, read_options=opts) + with pytest.raises(StopIteration): + assert reader.read_next_batch() + + # Skipping beyond all rows immediately results in end of iteration + opts.skip_rows_after_names = 99999 + reader = self.open_bytes(rows, read_options=opts) + with pytest.raises(StopIteration): + assert reader.read_next_batch() + + +class TestSerialStreamingCSVRead(BaseStreamingCSVRead): + @property + def use_threads(self): + return False + + +@pytest.mark.threading +class TestThreadedStreamingCSVRead(BaseStreamingCSVRead): + @property + def use_threads(self): + return True + + +class BaseTestCompressedCSVRead: + + def setUp(self): + self.tmpdir = tempfile.mkdtemp(prefix='arrow-csv-test-') + + def tearDown(self): + shutil.rmtree(self.tmpdir) + + def read_csv(self, csv_path): + try: + return read_csv(csv_path) + except pa.ArrowNotImplementedError as e: + pytest.skip(str(e)) + + def test_random_csv(self): + csv, expected = make_random_csv(num_cols=2, num_rows=100) + csv_path = os.path.join(self.tmpdir, self.csv_filename) + self.write_file(csv_path, csv) + table = self.read_csv(csv_path) + table.validate(full=True) + assert table.schema == expected.schema + assert table.equals(expected) + assert table.to_pydict() == expected.to_pydict() + + +class TestGZipCSVRead(BaseTestCompressedCSVRead, unittest.TestCase): + csv_filename = "compressed.csv.gz" + + def write_file(self, path, contents): + with gzip.open(path, 'wb', 3) as f: + f.write(contents) + + def test_concatenated(self): + # ARROW-5974 + csv_path = os.path.join(self.tmpdir, self.csv_filename) + with gzip.open(csv_path, 'wb', 3) as f: + f.write(b"ab,cd\nef,gh\n") + with gzip.open(csv_path, 'ab', 3) as f: + f.write(b"ij,kl\nmn,op\n") + table = self.read_csv(csv_path) + assert table.to_pydict() == { + 'ab': ['ef', 'ij', 'mn'], + 'cd': ['gh', 'kl', 'op'], + } + + +class TestBZ2CSVRead(BaseTestCompressedCSVRead, unittest.TestCase): + csv_filename = "compressed.csv.bz2" + + def write_file(self, path, contents): + with bz2.BZ2File(path, 'w') as f: + f.write(contents) + + +def test_read_csv_does_not_close_passed_file_handles(): + # ARROW-4823 + buf = io.BytesIO(b"a,b,c\n1,2,3\n4,5,6") + read_csv(buf) + assert not buf.closed + + +def test_write_read_round_trip(): + t = pa.Table.from_arrays([[1, 2, 3], ["a", "b", "c"]], ["c1", "c2"]) + record_batch = t.to_batches(max_chunksize=4)[0] + for data in [t, record_batch]: + # Test with header + buf = io.BytesIO() + write_csv(data, buf, WriteOptions(include_header=True)) + buf.seek(0) + assert t == read_csv(buf) + + # Test without header + buf = io.BytesIO() + write_csv(data, buf, WriteOptions(include_header=False)) + buf.seek(0) + + read_options = ReadOptions(column_names=t.column_names) + assert t == read_csv(buf, read_options=read_options) + + # Test with writer + for read_options, parse_options, write_options in [ + (None, None, WriteOptions(include_header=True)), + (ReadOptions(column_names=t.column_names), None, + WriteOptions(include_header=False)), + (None, ParseOptions(delimiter='|'), + WriteOptions(include_header=True, delimiter='|')), + (ReadOptions(column_names=t.column_names), + ParseOptions(delimiter='\t'), + WriteOptions(include_header=False, delimiter='\t')), + ]: + buf = io.BytesIO() + with CSVWriter(buf, t.schema, write_options=write_options) as writer: + writer.write_table(t) + buf.seek(0) + assert t == read_csv(buf, read_options=read_options, + parse_options=parse_options) + buf = io.BytesIO() + with CSVWriter(buf, t.schema, write_options=write_options) as writer: + for batch in t.to_batches(max_chunksize=1): + writer.write_batch(batch) + buf.seek(0) + assert t == read_csv(buf, read_options=read_options, + parse_options=parse_options) + + +def test_write_quoting_style(): + t = pa.Table.from_arrays([[1, 2, None], ["a", None, "c"]], ["c1", "c2"]) + buf = io.BytesIO() + for write_options, res in [ + (WriteOptions(quoting_style='none'), b'"c1","c2"\n1,a\n2,\n,c\n'), + (WriteOptions(), b'"c1","c2"\n1,"a"\n2,\n,"c"\n'), + (WriteOptions(quoting_style='all_valid'), + b'"c1","c2"\n"1","a"\n"2",\n,"c"\n'), + ]: + with CSVWriter(buf, t.schema, write_options=write_options) as writer: + writer.write_table(t) + assert buf.getvalue() == res + buf.seek(0) + + # Test writing special characters with different quoting styles + t = pa.Table.from_arrays([[",", "\""]], ["c1"]) + buf = io.BytesIO() + for write_options, res in [ + (WriteOptions(quoting_style='needed'), b'"c1"\n","\n""""\n'), + (WriteOptions(quoting_style='none'), pa.lib.ArrowInvalid), + ]: + with CSVWriter(buf, t.schema, write_options=write_options) as writer: + try: + writer.write_table(t) + except Exception as e: + # This will trigger when we try to write a comma (,) + # without quotes, which is invalid + assert isinstance(e, res) + break + assert buf.getvalue() == res + buf.seek(0) + + +def test_read_csv_reference_cycle(): + # ARROW-13187 + def inner(): + buf = io.BytesIO(b"a,b,c\n1,2,3\n4,5,6") + table = read_csv(buf) + return weakref.ref(table) + + with util.disabled_gc(): + wr = inner() + assert wr() is None + + +@pytest.mark.parametrize("type_factory", ( + lambda: pa.decimal128(20, 1), + lambda: pa.decimal128(38, 15), + lambda: pa.decimal256(20, 1), + lambda: pa.decimal256(76, 10), +)) +def test_write_csv_decimal(tmpdir, type_factory): + type = type_factory() + table = pa.table({"col": pa.array([1, 2]).cast(type)}) + + write_csv(table, tmpdir / "out.csv") + out = read_csv(tmpdir / "out.csv") + + assert out.column('col').cast(type) == table.column('col') + + +def test_read_csv_gil_deadlock(): + # GH-38676 + # This test depends on several preconditions: + # - the CSV input is a Python file object + # - reading the CSV file produces an error + data = b"a,b,c" + + class MyBytesIO(io.BytesIO): + def read(self, *args): + time.sleep(0.001) + return super().read(*args) + + def readinto(self, *args): + time.sleep(0.001) + return super().readinto(*args) + + for i in range(20): + with pytest.raises(pa.ArrowInvalid): + read_csv(MyBytesIO(data)) diff --git a/shared/package-files/18/18b3e34f27c92aa23f3d71876e7c0c31f0af84aee359a94da4d3a0dc4583463f/column_stack.h b/shared/package-files/18/18b3e34f27c92aa23f3d71876e7c0c31f0af84aee359a94da4d3a0dc4583463f/column_stack.h new file mode 100644 index 0000000000000000000000000000000000000000..8758fa15aee8e36c8945af69fbb98165fbe64210 --- /dev/null +++ b/shared/package-files/18/18b3e34f27c92aa23f3d71876e7c0c31f0af84aee359a94da4d3a0dc4583463f/column_stack.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::column_stack(Tensor[] tensors) -> Tensor +inline at::Tensor column_stack(at::TensorList tensors) { + return at::_ops::column_stack::call(tensors); +} + +// aten::column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & column_stack_out(at::Tensor & out, at::TensorList tensors) { + return at::_ops::column_stack_out::call(tensors, out); +} +// aten::column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & column_stack_outf(at::TensorList tensors, at::Tensor & out) { + return at::_ops::column_stack_out::call(tensors, out); +} + +} diff --git a/shared/package-files/18/18b4a406131fbf52f475e9e6f0dca72a5995c70c6ededd43cb4c84e1555114d1/_embedding_bag_per_sample_weights_backward_native.h b/shared/package-files/18/18b4a406131fbf52f475e9e6f0dca72a5995c70c6ededd43cb4c84e1555114d1/_embedding_bag_per_sample_weights_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..408ddc6749d7ece8dbbb7b586afd44aa9dc48017 --- /dev/null +++ b/shared/package-files/18/18b4a406131fbf52f475e9e6f0dca72a5995c70c6ededd43cb4c84e1555114d1/_embedding_bag_per_sample_weights_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _embedding_bag_per_sample_weights_backward_out(const at::Tensor & grad, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, int64_t mode, int64_t padding_idx, at::Tensor & out); +TORCH_API at::Tensor _embedding_bag_per_sample_weights_backward_cpu(const at::Tensor & grad, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, int64_t mode, int64_t padding_idx=-1); +TORCH_API at::Tensor _embedding_bag_per_sample_weights_backward_cuda(const at::Tensor & grad, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, int64_t mode, int64_t padding_idx=-1); +} // namespace native +} // namespace at diff --git a/shared/package-files/18/18b5dbc12be2b6c4209b1b4eb1b814b780d39144676f69345feefe48db035bd2/greedy_coloring.py b/shared/package-files/18/18b5dbc12be2b6c4209b1b4eb1b814b780d39144676f69345feefe48db035bd2/greedy_coloring.py new file mode 100644 index 0000000000000000000000000000000000000000..311bc3a929f76dc2cac0b85bc02459ce0a29ffd0 --- /dev/null +++ b/shared/package-files/18/18b5dbc12be2b6c4209b1b4eb1b814b780d39144676f69345feefe48db035bd2/greedy_coloring.py @@ -0,0 +1,565 @@ +""" +Greedy graph coloring using various strategies. +""" + +import itertools +from collections import defaultdict, deque + +import networkx as nx +from networkx.utils import arbitrary_element, py_random_state + +__all__ = [ + "greedy_color", + "strategy_connected_sequential", + "strategy_connected_sequential_bfs", + "strategy_connected_sequential_dfs", + "strategy_independent_set", + "strategy_largest_first", + "strategy_random_sequential", + "strategy_saturation_largest_first", + "strategy_smallest_last", +] + + +def strategy_largest_first(G, colors): + """Returns a list of the nodes of ``G`` in decreasing order by + degree. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + """ + return sorted(G, key=G.degree, reverse=True) + + +@py_random_state(2) +def strategy_random_sequential(G, colors, seed=None): + """Returns a random permutation of the nodes of ``G`` as a list. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + """ + nodes = list(G) + seed.shuffle(nodes) + return nodes + + +def strategy_smallest_last(G, colors): + """Returns a deque of the nodes of ``G``, "smallest" last. + + Specifically, the degrees of each node are tracked in a bucket queue. + From this, the node of minimum degree is repeatedly popped from the + graph, updating its neighbors' degrees. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + This implementation of the strategy runs in $O(n + m)$ time + (ignoring polylogarithmic factors), where $n$ is the number of nodes + and $m$ is the number of edges. + + This strategy is related to :func:`strategy_independent_set`: if we + interpret each node removed as an independent set of size one, then + this strategy chooses an independent set of size one instead of a + maximal independent set. + + """ + H = G.copy() + result = deque() + + # Build initial degree list (i.e. the bucket queue data structure) + degrees = defaultdict(set) # set(), for fast random-access removals + lbound = float("inf") + for node, d in H.degree(): + degrees[d].add(node) + lbound = min(lbound, d) # Lower bound on min-degree. + + def find_min_degree(): + # Save time by starting the iterator at `lbound`, not 0. + # The value that we find will be our new `lbound`, which we set later. + return next(d for d in itertools.count(lbound) if d in degrees) + + for _ in G: + # Pop a min-degree node and add it to the list. + min_degree = find_min_degree() + u = degrees[min_degree].pop() + if not degrees[min_degree]: # Clean up the degree list. + del degrees[min_degree] + result.appendleft(u) + + # Update degrees of removed node's neighbors. + for v in H[u]: + degree = H.degree(v) + degrees[degree].remove(v) + if not degrees[degree]: # Clean up the degree list. + del degrees[degree] + degrees[degree - 1].add(v) + + # Finally, remove the node. + H.remove_node(u) + lbound = min_degree - 1 # Subtract 1 in case of tied neighbors. + + return result + + +def _maximal_independent_set(G): + """Returns a maximal independent set of nodes in ``G`` by repeatedly + choosing an independent node of minimum degree (with respect to the + subgraph of unchosen nodes). + + """ + result = set() + remaining = set(G) + while remaining: + G = G.subgraph(remaining) + v = min(remaining, key=G.degree) + result.add(v) + remaining -= set(G[v]) | {v} + return result + + +def strategy_independent_set(G, colors): + """Uses a greedy independent set removal strategy to determine the + colors. + + This function updates ``colors`` **in-place** and return ``None``, + unlike the other strategy functions in this module. + + This algorithm repeatedly finds and removes a maximal independent + set, assigning each node in the set an unused color. + + ``G`` is a NetworkX graph. + + This strategy is related to :func:`strategy_smallest_last`: in that + strategy, an independent set of size one is chosen at each step + instead of a maximal independent set. + + """ + remaining_nodes = set(G) + while len(remaining_nodes) > 0: + nodes = _maximal_independent_set(G.subgraph(remaining_nodes)) + remaining_nodes -= nodes + yield from nodes + + +def strategy_connected_sequential_bfs(G, colors): + """Returns an iterable over nodes in ``G`` in the order given by a + breadth-first traversal. + + The generated sequence has the property that for each node except + the first, at least one neighbor appeared earlier in the sequence. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + """ + return strategy_connected_sequential(G, colors, "bfs") + + +def strategy_connected_sequential_dfs(G, colors): + """Returns an iterable over nodes in ``G`` in the order given by a + depth-first traversal. + + The generated sequence has the property that for each node except + the first, at least one neighbor appeared earlier in the sequence. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + """ + return strategy_connected_sequential(G, colors, "dfs") + + +def strategy_connected_sequential(G, colors, traversal="bfs"): + """Returns an iterable over nodes in ``G`` in the order given by a + breadth-first or depth-first traversal. + + ``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``, + representing depth-first traversal or breadth-first traversal, + respectively. + + The generated sequence has the property that for each node except + the first, at least one neighbor appeared earlier in the sequence. + + ``G`` is a NetworkX graph. ``colors`` is ignored. + + """ + if traversal == "bfs": + traverse = nx.bfs_edges + elif traversal == "dfs": + traverse = nx.dfs_edges + else: + raise nx.NetworkXError( + "Please specify one of the strings 'bfs' or" + " 'dfs' for connected sequential ordering" + ) + for component in nx.connected_components(G): + source = arbitrary_element(component) + # Yield the source node, then all the nodes in the specified + # traversal order. + yield source + for _, end in traverse(G.subgraph(component), source): + yield end + + +def strategy_saturation_largest_first(G, colors): + """Iterates over all the nodes of ``G`` in "saturation order" (also + known as "DSATUR"). + + ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of + ``G`` to colors, for those nodes that have already been colored. + + """ + distinct_colors = {v: set() for v in G} + + # Add the node color assignments given in colors to the + # distinct colors set for each neighbor of that node + for node, color in colors.items(): + for neighbor in G[node]: + distinct_colors[neighbor].add(color) + + # Check that the color assignments in colors are valid + # i.e. no neighboring nodes have the same color + if len(colors) >= 2: + for node, color in colors.items(): + if color in distinct_colors[node]: + raise nx.NetworkXError("Neighboring nodes must have different colors") + + # If 0 nodes have been colored, simply choose the node of highest degree. + if not colors: + node = max(G, key=G.degree) + yield node + # Add the color 0 to the distinct colors set for each + # neighbor of that node. + for v in G[node]: + distinct_colors[v].add(0) + + while len(G) != len(colors): + # Update the distinct color sets for the neighbors. + for node, color in colors.items(): + for neighbor in G[node]: + distinct_colors[neighbor].add(color) + + # Compute the maximum saturation and the set of nodes that + # achieve that saturation. + saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors} + # Yield the node with the highest saturation, and break ties by + # degree. + node = max(saturation, key=lambda v: (saturation[v], G.degree(v))) + yield node + + +#: Dictionary mapping name of a strategy as a string to the strategy function. +STRATEGIES = { + "largest_first": strategy_largest_first, + "random_sequential": strategy_random_sequential, + "smallest_last": strategy_smallest_last, + "independent_set": strategy_independent_set, + "connected_sequential_bfs": strategy_connected_sequential_bfs, + "connected_sequential_dfs": strategy_connected_sequential_dfs, + "connected_sequential": strategy_connected_sequential, + "saturation_largest_first": strategy_saturation_largest_first, + "DSATUR": strategy_saturation_largest_first, +} + + +@nx._dispatchable +def greedy_color(G, strategy="largest_first", interchange=False): + """Color a graph using various strategies of greedy graph coloring. + + Attempts to color a graph using as few colors as possible, where no + neighbors of a node can have same color as the node itself. The + given strategy determines the order in which nodes are colored. + + The strategies are described in [1]_, and smallest-last is based on + [2]_. + + Parameters + ---------- + G : NetworkX graph + + strategy : string or function(G, colors) + A function (or a string representing a function) that provides + the coloring strategy, by returning nodes in the ordering they + should be colored. ``G`` is the graph, and ``colors`` is a + dictionary of the currently assigned colors, keyed by nodes. The + function must return an iterable over all the nodes in ``G``. + + If the strategy function is an iterator generator (that is, a + function with ``yield`` statements), keep in mind that the + ``colors`` dictionary will be updated after each ``yield``, since + this function chooses colors greedily. + + If ``strategy`` is a string, it must be one of the following, + each of which represents one of the built-in strategy functions. + + * ``'largest_first'`` + * ``'random_sequential'`` + * ``'smallest_last'`` + * ``'independent_set'`` + * ``'connected_sequential_bfs'`` + * ``'connected_sequential_dfs'`` + * ``'connected_sequential'`` (alias for the previous strategy) + * ``'saturation_largest_first'`` + * ``'DSATUR'`` (alias for the previous strategy) + + interchange: bool + Will use the color interchange algorithm described by [3]_ if set + to ``True``. + + Note that ``saturation_largest_first`` and ``independent_set`` + do not work with interchange. Furthermore, if you use + interchange with your own strategy function, you cannot rely + on the values in the ``colors`` argument. + + Returns + ------- + A dictionary with keys representing nodes and values representing + corresponding coloring. + + Examples + -------- + >>> G = nx.cycle_graph(4) + >>> d = nx.coloring.greedy_color(G, strategy="largest_first") + >>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}] + True + + Raises + ------ + NetworkXPointlessConcept + If ``strategy`` is ``saturation_largest_first`` or + ``independent_set`` and ``interchange`` is ``True``. + + References + ---------- + .. [1] Adrian Kosowski, and Krzysztof Manuszewski, + Classical Coloring of Graphs, Graph Colorings, 2-19, 2004. + ISBN 0-8218-3458-4. + .. [2] David W. Matula, and Leland L. Beck, "Smallest-last + ordering and clustering and graph coloring algorithms." *J. ACM* 30, + 3 (July 1983), 417–427. + .. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik, + Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983. + ISBN 0-486-45353-7. + + """ + if len(G) == 0: + return {} + # Determine the strategy provided by the caller. + strategy = STRATEGIES.get(strategy, strategy) + if not callable(strategy): + raise nx.NetworkXError( + f"strategy must be callable or a valid string. {strategy} not valid." + ) + # Perform some validation on the arguments before executing any + # strategy functions. + if interchange: + if strategy is strategy_independent_set: + msg = "interchange cannot be used with independent_set" + raise nx.NetworkXPointlessConcept(msg) + if strategy is strategy_saturation_largest_first: + msg = "interchange cannot be used with saturation_largest_first" + raise nx.NetworkXPointlessConcept(msg) + colors = {} + nodes = strategy(G, colors) + if interchange: + return _greedy_coloring_with_interchange(G, nodes) + for u in nodes: + # Set to keep track of colors of neighbors + nbr_colors = {colors[v] for v in G[u] if v in colors} + # Find the first unused color. + for color in itertools.count(): + if color not in nbr_colors: + break + # Assign the new color to the current node. + colors[u] = color + return colors + + +# Tools for coloring with interchanges +class _Node: + __slots__ = ["node_id", "color", "adj_list", "adj_color"] + + def __init__(self, node_id, n): + self.node_id = node_id + self.color = -1 + self.adj_list = None + self.adj_color = [None for _ in range(n)] + + def __repr__(self): + return ( + f"Node_id: {self.node_id}, Color: {self.color}, " + f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})" + ) + + def assign_color(self, adj_entry, color): + adj_entry.col_prev = None + adj_entry.col_next = self.adj_color[color] + self.adj_color[color] = adj_entry + if adj_entry.col_next is not None: + adj_entry.col_next.col_prev = adj_entry + + def clear_color(self, adj_entry, color): + if adj_entry.col_prev is None: + self.adj_color[color] = adj_entry.col_next + else: + adj_entry.col_prev.col_next = adj_entry.col_next + if adj_entry.col_next is not None: + adj_entry.col_next.col_prev = adj_entry.col_prev + + def iter_neighbors(self): + adj_node = self.adj_list + while adj_node is not None: + yield adj_node + adj_node = adj_node.next + + def iter_neighbors_color(self, color): + adj_color_node = self.adj_color[color] + while adj_color_node is not None: + yield adj_color_node.node_id + adj_color_node = adj_color_node.col_next + + +class _AdjEntry: + __slots__ = ["node_id", "next", "mate", "col_next", "col_prev"] + + def __init__(self, node_id): + self.node_id = node_id + self.next = None + self.mate = None + self.col_next = None + self.col_prev = None + + def __repr__(self): + col_next = None if self.col_next is None else self.col_next.node_id + col_prev = None if self.col_prev is None else self.col_prev.node_id + return ( + f"Node_id: {self.node_id}, Next: ({self.next}), " + f"Mate: ({self.mate.node_id}), " + f"col_next: ({col_next}), col_prev: ({col_prev})" + ) + + +def _greedy_coloring_with_interchange(G, nodes): + """Return a coloring for `original_graph` using interchange approach + + This procedure is an adaption of the algorithm described by [1]_, + and is an implementation of coloring with interchange. Please be + advised, that the datastructures used are rather complex because + they are optimized to minimize the time spent identifying + subcomponents of the graph, which are possible candidates for color + interchange. + + Parameters + ---------- + G : NetworkX graph + The graph to be colored + + nodes : list + nodes ordered using the strategy of choice + + Returns + ------- + dict : + A dictionary keyed by node to a color value + + References + ---------- + .. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik, + Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983. + ISBN 0-486-45353-7. + """ + n = len(G) + + graph = {node: _Node(node, n) for node in G} + + for node1, node2 in G.edges(): + adj_entry1 = _AdjEntry(node2) + adj_entry2 = _AdjEntry(node1) + adj_entry1.mate = adj_entry2 + adj_entry2.mate = adj_entry1 + node1_head = graph[node1].adj_list + adj_entry1.next = node1_head + graph[node1].adj_list = adj_entry1 + node2_head = graph[node2].adj_list + adj_entry2.next = node2_head + graph[node2].adj_list = adj_entry2 + + k = 0 + for node in nodes: + # Find the smallest possible, unused color + neighbors = graph[node].iter_neighbors() + col_used = {graph[adj_node.node_id].color for adj_node in neighbors} + col_used.discard(-1) + k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count())) + + # k1 is now the lowest available color + if k1 > k: + connected = True + visited = set() + col1 = -1 + col2 = -1 + while connected and col1 < k: + col1 += 1 + neighbor_cols = graph[node].iter_neighbors_color(col1) + col1_adj = list(neighbor_cols) + + col2 = col1 + while connected and col2 < k: + col2 += 1 + visited = set(col1_adj) + frontier = list(col1_adj) + i = 0 + while i < len(frontier): + search_node = frontier[i] + i += 1 + col_opp = col2 if graph[search_node].color == col1 else col1 + neighbor_cols = graph[search_node].iter_neighbors_color(col_opp) + + for neighbor in neighbor_cols: + if neighbor not in visited: + visited.add(neighbor) + frontier.append(neighbor) + + # Search if node is not adj to any col2 vertex + connected = ( + len( + visited.intersection(graph[node].iter_neighbors_color(col2)) + ) + > 0 + ) + + # If connected is false then we can swap !!! + if not connected: + # Update all the nodes in the component + for search_node in visited: + graph[search_node].color = ( + col2 if graph[search_node].color == col1 else col1 + ) + col2_adj = graph[search_node].adj_color[col2] + graph[search_node].adj_color[col2] = graph[search_node].adj_color[ + col1 + ] + graph[search_node].adj_color[col1] = col2_adj + + # Update all the neighboring nodes + for search_node in visited: + col = graph[search_node].color + col_opp = col1 if col == col2 else col2 + for adj_node in graph[search_node].iter_neighbors(): + if graph[adj_node.node_id].color != col_opp: + # Direct reference to entry + adj_mate = adj_node.mate + graph[adj_node.node_id].clear_color(adj_mate, col_opp) + graph[adj_node.node_id].assign_color(adj_mate, col) + k1 = col1 + + # We can color this node color k1 + graph[node].color = k1 + k = max(k1, k) + + # Update the neighbors of this node + for adj_node in graph[node].iter_neighbors(): + adj_mate = adj_node.mate + graph[adj_node.node_id].assign_color(adj_mate, k1) + + return {node.node_id: node.color for node in graph.values()} diff --git a/shared/package-files/18/18c8715d395075770237999a98fba25b0788af2a664cc8e1d5ea7c9076e55189/subclass_utils.cpython-311.pyc b/shared/package-files/18/18c8715d395075770237999a98fba25b0788af2a664cc8e1d5ea7c9076e55189/subclass_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0b733311c0fa63e76db6cbc6dca3a1043b3956a Binary files /dev/null and b/shared/package-files/18/18c8715d395075770237999a98fba25b0788af2a664cc8e1d5ea7c9076e55189/subclass_utils.cpython-311.pyc differ diff --git a/shared/package-files/18/18c997e01eea439f7cf5fd8a0a2d40ab9081e5ce72777c412e45684da175b9b3/view_as_native.h b/shared/package-files/18/18c997e01eea439f7cf5fd8a0a2d40ab9081e5ce72777c412e45684da175b9b3/view_as_native.h new file mode 100644 index 0000000000000000000000000000000000000000..309ad0fa4f6cc402028540157be87d5270950a90 --- /dev/null +++ b/shared/package-files/18/18c997e01eea439f7cf5fd8a0a2d40ab9081e5ce72777c412e45684da175b9b3/view_as_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor view_as(const at::Tensor & self, const at::Tensor & other); +} // namespace native +} // namespace at diff --git a/shared/package-files/18/18cba8485d6fa8a0ecfdedc927b63496916b9de5cc64b664fea202e5de90e545/dimensions.py b/shared/package-files/18/18cba8485d6fa8a0ecfdedc927b63496916b9de5cc64b664fea202e5de90e545/dimensions.py new file mode 100644 index 0000000000000000000000000000000000000000..de42912edca025a6cb53d457fd3e03d8fa30931e --- /dev/null +++ b/shared/package-files/18/18cba8485d6fa8a0ecfdedc927b63496916b9de5cc64b664fea202e5de90e545/dimensions.py @@ -0,0 +1,590 @@ +""" +Definition of physical dimensions. + +Unit systems will be constructed on top of these dimensions. + +Most of the examples in the doc use MKS system and are presented from the +computer point of view: from a human point, adding length to time is not legal +in MKS but it is in natural system; for a computer in natural system there is +no time dimension (but a velocity dimension instead) - in the basis - so the +question of adding time to length has no meaning. +""" + +from __future__ import annotations + +import collections +from functools import reduce + +from sympy.core.basic import Basic +from sympy.core.containers import (Dict, Tuple) +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.matrices.dense import Matrix +from sympy.functions.elementary.trigonometric import TrigonometricFunction +from sympy.core.expr import Expr +from sympy.core.power import Pow + + +class _QuantityMapper: + + _quantity_scale_factors_global: dict[Expr, Expr] = {} + _quantity_dimensional_equivalence_map_global: dict[Expr, Expr] = {} + _quantity_dimension_global: dict[Expr, Expr] = {} + + def __init__(self, *args, **kwargs): + self._quantity_dimension_map = {} + self._quantity_scale_factors = {} + + def set_quantity_dimension(self, quantity, dimension): + """ + Set the dimension for the quantity in a unit system. + + If this relation is valid in every unit system, use + ``quantity.set_global_dimension(dimension)`` instead. + """ + from sympy.physics.units import Quantity + dimension = sympify(dimension) + if not isinstance(dimension, Dimension): + if dimension == 1: + dimension = Dimension(1) + else: + raise ValueError("expected dimension or 1") + elif isinstance(dimension, Quantity): + dimension = self.get_quantity_dimension(dimension) + self._quantity_dimension_map[quantity] = dimension + + def set_quantity_scale_factor(self, quantity, scale_factor): + """ + Set the scale factor of a quantity relative to another quantity. + + It should be used only once per quantity to just one other quantity, + the algorithm will then be able to compute the scale factors to all + other quantities. + + In case the scale factor is valid in every unit system, please use + ``quantity.set_global_relative_scale_factor(scale_factor)`` instead. + """ + from sympy.physics.units import Quantity + from sympy.physics.units.prefixes import Prefix + scale_factor = sympify(scale_factor) + # replace all prefixes by their ratio to canonical units: + scale_factor = scale_factor.replace( + lambda x: isinstance(x, Prefix), + lambda x: x.scale_factor + ) + # replace all quantities by their ratio to canonical units: + scale_factor = scale_factor.replace( + lambda x: isinstance(x, Quantity), + lambda x: self.get_quantity_scale_factor(x) + ) + self._quantity_scale_factors[quantity] = scale_factor + + def get_quantity_dimension(self, unit): + from sympy.physics.units import Quantity + # First look-up the local dimension map, then the global one: + if unit in self._quantity_dimension_map: + return self._quantity_dimension_map[unit] + if unit in self._quantity_dimension_global: + return self._quantity_dimension_global[unit] + if unit in self._quantity_dimensional_equivalence_map_global: + dep_unit = self._quantity_dimensional_equivalence_map_global[unit] + if isinstance(dep_unit, Quantity): + return self.get_quantity_dimension(dep_unit) + else: + return Dimension(self.get_dimensional_expr(dep_unit)) + if isinstance(unit, Quantity): + return Dimension(unit.name) + else: + return Dimension(1) + + def get_quantity_scale_factor(self, unit): + if unit in self._quantity_scale_factors: + return self._quantity_scale_factors[unit] + if unit in self._quantity_scale_factors_global: + mul_factor, other_unit = self._quantity_scale_factors_global[unit] + return mul_factor*self.get_quantity_scale_factor(other_unit) + return S.One + + +class Dimension(Expr): + """ + This class represent the dimension of a physical quantities. + + The ``Dimension`` constructor takes as parameters a name and an optional + symbol. + + For example, in classical mechanics we know that time is different from + temperature and dimensions make this difference (but they do not provide + any measure of these quantities. + + >>> from sympy.physics.units import Dimension + >>> length = Dimension('length') + >>> length + Dimension(length) + >>> time = Dimension('time') + >>> time + Dimension(time) + + Dimensions can be composed using multiplication, division and + exponentiation (by a number) to give new dimensions. Addition and + subtraction is defined only when the two objects are the same dimension. + + >>> velocity = length / time + >>> velocity + Dimension(length/time) + + It is possible to use a dimension system object to get the dimensionsal + dependencies of a dimension, for example the dimension system used by the + SI units convention can be used: + + >>> from sympy.physics.units.systems.si import dimsys_SI + >>> dimsys_SI.get_dimensional_dependencies(velocity) + {Dimension(length, L): 1, Dimension(time, T): -1} + >>> length + length + Dimension(length) + >>> l2 = length**2 + >>> l2 + Dimension(length**2) + >>> dimsys_SI.get_dimensional_dependencies(l2) + {Dimension(length, L): 2} + + """ + + _op_priority = 13.0 + + # XXX: This doesn't seem to be used anywhere... + _dimensional_dependencies = {} # type: ignore + + is_commutative = True + is_number = False + # make sqrt(M**2) --> M + is_positive = True + is_real = True + + def __new__(cls, name, symbol=None): + + if isinstance(name, str): + name = Symbol(name) + else: + name = sympify(name) + + if not isinstance(name, Expr): + raise TypeError("Dimension name needs to be a valid math expression") + + if isinstance(symbol, str): + symbol = Symbol(symbol) + elif symbol is not None: + assert isinstance(symbol, Symbol) + + obj = Expr.__new__(cls, name) + + obj._name = name + obj._symbol = symbol + return obj + + @property + def name(self): + return self._name + + @property + def symbol(self): + return self._symbol + + def __str__(self): + """ + Display the string representation of the dimension. + """ + if self.symbol is None: + return "Dimension(%s)" % (self.name) + else: + return "Dimension(%s, %s)" % (self.name, self.symbol) + + def __repr__(self): + return self.__str__() + + def __neg__(self): + return self + + def __add__(self, other): + from sympy.physics.units.quantities import Quantity + other = sympify(other) + if isinstance(other, Basic): + if other.has(Quantity): + raise TypeError("cannot sum dimension and quantity") + if isinstance(other, Dimension) and self == other: + return self + return super().__add__(other) + return self + + def __radd__(self, other): + return self.__add__(other) + + def __sub__(self, other): + # there is no notion of ordering (or magnitude) among dimension, + # subtraction is equivalent to addition when the operation is legal + return self + other + + def __rsub__(self, other): + # there is no notion of ordering (or magnitude) among dimension, + # subtraction is equivalent to addition when the operation is legal + return self + other + + def __pow__(self, other): + return self._eval_power(other) + + def _eval_power(self, other): + other = sympify(other) + return Dimension(self.name**other) + + def __mul__(self, other): + from sympy.physics.units.quantities import Quantity + if isinstance(other, Basic): + if other.has(Quantity): + raise TypeError("cannot sum dimension and quantity") + if isinstance(other, Dimension): + return Dimension(self.name*other.name) + if not other.free_symbols: # other.is_number cannot be used + return self + return super().__mul__(other) + return self + + def __rmul__(self, other): + return self.__mul__(other) + + def __truediv__(self, other): + return self*Pow(other, -1) + + def __rtruediv__(self, other): + return other * pow(self, -1) + + @classmethod + def _from_dimensional_dependencies(cls, dependencies): + return reduce(lambda x, y: x * y, ( + d**e for d, e in dependencies.items() + ), 1) + + def has_integer_powers(self, dim_sys): + """ + Check if the dimension object has only integer powers. + + All the dimension powers should be integers, but rational powers may + appear in intermediate steps. This method may be used to check that the + final result is well-defined. + """ + + return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values()) + + +# Create dimensions according to the base units in MKSA. +# For other unit systems, they can be derived by transforming the base +# dimensional dependency dictionary. + + +class DimensionSystem(Basic, _QuantityMapper): + r""" + DimensionSystem represents a coherent set of dimensions. + + The constructor takes three parameters: + + - base dimensions; + - derived dimensions: these are defined in terms of the base dimensions + (for example velocity is defined from the division of length by time); + - dependency of dimensions: how the derived dimensions depend + on the base dimensions. + + Optionally either the ``derived_dims`` or the ``dimensional_dependencies`` + may be omitted. + """ + + def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}): + dimensional_dependencies = dict(dimensional_dependencies) + + def parse_dim(dim): + if isinstance(dim, str): + dim = Dimension(Symbol(dim)) + elif isinstance(dim, Dimension): + pass + elif isinstance(dim, Symbol): + dim = Dimension(dim) + else: + raise TypeError("%s wrong type" % dim) + return dim + + base_dims = [parse_dim(i) for i in base_dims] + derived_dims = [parse_dim(i) for i in derived_dims] + + for dim in base_dims: + if (dim in dimensional_dependencies + and (len(dimensional_dependencies[dim]) != 1 or + dimensional_dependencies[dim].get(dim, None) != 1)): + raise IndexError("Repeated value in base dimensions") + dimensional_dependencies[dim] = Dict({dim: 1}) + + def parse_dim_name(dim): + if isinstance(dim, Dimension): + return dim + elif isinstance(dim, str): + return Dimension(Symbol(dim)) + elif isinstance(dim, Symbol): + return Dimension(dim) + else: + raise TypeError("unrecognized type %s for %s" % (type(dim), dim)) + + for dim in dimensional_dependencies.keys(): + dim = parse_dim(dim) + if (dim not in derived_dims) and (dim not in base_dims): + derived_dims.append(dim) + + def parse_dict(d): + return Dict({parse_dim_name(i): j for i, j in d.items()}) + + # Make sure everything is a SymPy type: + dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in + dimensional_dependencies.items()} + + for dim in derived_dims: + if dim in base_dims: + raise ValueError("Dimension %s both in base and derived" % dim) + if dim not in dimensional_dependencies: + # TODO: should this raise a warning? + dimensional_dependencies[dim] = Dict({dim: 1}) + + base_dims.sort(key=default_sort_key) + derived_dims.sort(key=default_sort_key) + + base_dims = Tuple(*base_dims) + derived_dims = Tuple(*derived_dims) + dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()}) + obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies) + return obj + + @property + def base_dims(self): + return self.args[0] + + @property + def derived_dims(self): + return self.args[1] + + @property + def dimensional_dependencies(self): + return self.args[2] + + def _get_dimensional_dependencies_for_name(self, dimension): + if isinstance(dimension, str): + dimension = Dimension(Symbol(dimension)) + elif not isinstance(dimension, Dimension): + dimension = Dimension(dimension) + + if dimension.name.is_Symbol: + # Dimensions not included in the dependencies are considered + # as base dimensions: + return dict(self.dimensional_dependencies.get(dimension, {dimension: 1})) + + if dimension.name.is_number or dimension.name.is_NumberSymbol: + return {} + + get_for_name = self._get_dimensional_dependencies_for_name + + if dimension.name.is_Mul: + ret = collections.defaultdict(int) + dicts = [get_for_name(i) for i in dimension.name.args] + for d in dicts: + for k, v in d.items(): + ret[k] += v + return {k: v for (k, v) in ret.items() if v != 0} + + if dimension.name.is_Add: + dicts = [get_for_name(i) for i in dimension.name.args] + if all(d == dicts[0] for d in dicts[1:]): + return dicts[0] + raise TypeError("Only equivalent dimensions can be added or subtracted.") + + if dimension.name.is_Pow: + dim_base = get_for_name(dimension.name.base) + dim_exp = get_for_name(dimension.name.exp) + if dim_exp == {} or dimension.name.exp.is_Symbol: + return {k: v * dimension.name.exp for (k, v) in dim_base.items()} + else: + raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.") + + if dimension.name.is_Function: + args = (Dimension._from_dimensional_dependencies( + get_for_name(arg)) for arg in dimension.name.args) + result = dimension.name.func(*args) + + dicts = [get_for_name(i) for i in dimension.name.args] + + if isinstance(result, Dimension): + return self.get_dimensional_dependencies(result) + elif result.func == dimension.name.func: + if isinstance(dimension.name, TrigonometricFunction): + if dicts[0] in ({}, {Dimension('angle'): 1}): + return {} + else: + raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func)) + else: + if all(item == {} for item in dicts): + return {} + else: + raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func)) + else: + return get_for_name(result) + + raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name))) + + def get_dimensional_dependencies(self, name, mark_dimensionless=False): + dimdep = self._get_dimensional_dependencies_for_name(name) + if mark_dimensionless and dimdep == {}: + return {Dimension(1): 1} + return dict(dimdep.items()) + + def equivalent_dims(self, dim1, dim2): + deps1 = self.get_dimensional_dependencies(dim1) + deps2 = self.get_dimensional_dependencies(dim2) + return deps1 == deps2 + + def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None): + deps = dict(self.dimensional_dependencies) + if new_dim_deps: + deps.update(new_dim_deps) + + new_dim_sys = DimensionSystem( + tuple(self.base_dims) + tuple(new_base_dims), + tuple(self.derived_dims) + tuple(new_derived_dims), + deps + ) + new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map) + new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors) + return new_dim_sys + + def is_dimensionless(self, dimension): + """ + Check if the dimension object really has a dimension. + + A dimension should have at least one component with non-zero power. + """ + if dimension.name == 1: + return True + return self.get_dimensional_dependencies(dimension) == {} + + @property + def list_can_dims(self): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + List all canonical dimension names. + """ + dimset = set() + for i in self.base_dims: + dimset.update(set(self.get_dimensional_dependencies(i).keys())) + return tuple(sorted(dimset, key=str)) + + @property + def inv_can_transf_matrix(self): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + Compute the inverse transformation matrix from the base to the + canonical dimension basis. + + It corresponds to the matrix where columns are the vector of base + dimensions in canonical basis. + + This matrix will almost never be used because dimensions are always + defined with respect to the canonical basis, so no work has to be done + to get them in this basis. Nonetheless if this matrix is not square + (or not invertible) it means that we have chosen a bad basis. + """ + matrix = reduce(lambda x, y: x.row_join(y), + [self.dim_can_vector(d) for d in self.base_dims]) + return matrix + + @property + def can_transf_matrix(self): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + Return the canonical transformation matrix from the canonical to the + base dimension basis. + + It is the inverse of the matrix computed with inv_can_transf_matrix(). + """ + + #TODO: the inversion will fail if the system is inconsistent, for + # example if the matrix is not a square + return reduce(lambda x, y: x.row_join(y), + [self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)] + ).inv() + + def dim_can_vector(self, dim): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + Dimensional representation in terms of the canonical base dimensions. + """ + + vec = [] + for d in self.list_can_dims: + vec.append(self.get_dimensional_dependencies(dim).get(d, 0)) + return Matrix(vec) + + def dim_vector(self, dim): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + + Vector representation in terms of the base dimensions. + """ + return self.can_transf_matrix * Matrix(self.dim_can_vector(dim)) + + def print_dim_base(self, dim): + """ + Give the string expression of a dimension in term of the basis symbols. + """ + dims = self.dim_vector(dim) + symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims] + res = S.One + for (s, p) in zip(symbols, dims): + res *= s**p + return res + + @property + def dim(self): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + Give the dimension of the system. + + That is return the number of dimensions forming the basis. + """ + return len(self.base_dims) + + @property + def is_consistent(self): + """ + Useless method, kept for compatibility with previous versions. + + DO NOT USE. + + Check if the system is well defined. + """ + + # not enough or too many base dimensions compared to independent + # dimensions + # in vector language: the set of vectors do not form a basis + return self.inv_can_transf_matrix.is_square diff --git a/shared/package-files/18/18ce7de1e85300b021786ad70400ed8c62914d4886d3370b4a4cac7745d38d93/test_take.cpython-311.pyc b/shared/package-files/18/18ce7de1e85300b021786ad70400ed8c62914d4886d3370b4a4cac7745d38d93/test_take.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b27f3c31f55bfc7fcf6b934f38be33cc9d08e697 Binary files /dev/null and b/shared/package-files/18/18ce7de1e85300b021786ad70400ed8c62914d4886d3370b4a4cac7745d38d93/test_take.cpython-311.pyc differ diff --git a/shared/package-files/18/18d9d81470e83b772439193c414f5e9ede0a99af0f3de750e8f642c9365dadf8/freezing_patterns.py b/shared/package-files/18/18d9d81470e83b772439193c414f5e9ede0a99af0f3de750e8f642c9365dadf8/freezing_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..8b6437fc2582ab8927a54324337895612358a8ed --- /dev/null +++ b/shared/package-files/18/18d9d81470e83b772439193c414f5e9ede0a99af0f3de750e8f642c9365dadf8/freezing_patterns.py @@ -0,0 +1,236 @@ +# mypy: allow-untyped-defs +import functools + +import torch +from torch._inductor.compile_fx import fake_tensor_prop +from torch._inductor.utils import GPU_TYPES + +from ..._dynamo.utils import counters +from .. import config +from ..pattern_matcher import ( + _return_true, + CallFunction, + fwd_only, + Ignored, + init_once_fakemode, + KeywordArg, + Match, + PatternMatcherPass, + register_graph_pattern, + register_replacement, + stable_topological_sort, +) + + +aten = torch.ops.aten + +# First pass_patterns[0] are applied, then [1], then [2] +pass_patterns = [ + PatternMatcherPass(), + PatternMatcherPass(), + PatternMatcherPass(), +] + +binary_folding_pass = PatternMatcherPass() + + +def freezing_passes(gm: torch.fx.GraphModule, aot_example_inputs): + """ + Passes that are applied to the graph to freeze pass. + """ + + from ..freezing import constant_fold + + lazy_init() + # We need a few rounds of binary folding to get rid of all the + # unnecessary nodes, but may need a good method to chose the rounds number. + # works like: conv+binary+binary. + binary_folding = counters["inductor"]["binary_folding"] + fake_tensor_prop(gm, aot_example_inputs, True) + + torch._inductor.fx_passes.binary_folding.mark_mixed_dtype_allowed_computation_ops( + gm + ) + for _ in range(4): + constant_fold(gm) + # Make sure meta['val'] is properly set for all nodes + fake_tensor_prop(gm, aot_example_inputs, True) + binary_folding_pass.apply(gm.graph) # type: ignore[arg-type] + # If we don't have binary folding, we don't need to run the pass again. + # TODO: remove the need to run fake_tensor_prop on the whole model. + if counters["inductor"]["binary_folding"] == binary_folding: + break + binary_folding = counters["inductor"]["binary_folding"] + + torch._inductor.fx_passes.binary_folding.recover_original_precision_folded_computation_ops( + gm + ) + + constant_fold(gm) + fake_tensor_prop(gm, aot_example_inputs, True) + + for pattern in pass_patterns: + pattern.apply(gm.graph) # type: ignore[arg-type] + + # The CPU weight packing always assume the conv's weight is channels last, + # So make sure the layout_optimization is on when doing it. + if ( + torch._C._has_mkldnn + and config.cpp.weight_prepack + and config.layout_optimization + ): + from .mkldnn_fusion import _eliminate_duplicate_packed_nodes + + _eliminate_duplicate_packed_nodes(gm) + + stable_topological_sort(gm.graph) + gm.recompile() + gm.graph.lint() + + +@init_once_fakemode +def lazy_init(): + if torch._C._has_mkldnn and config.cpp.weight_prepack: + from .mkldnn_fusion import _mkldnn_weight_pack_init + + _mkldnn_weight_pack_init() + + from .binary_folding import binary_folding_init + + addmm_patterns_init() + binary_folding_init() + + +def register_freezing_graph_pattern(pattern, extra_check=_return_true, pass_number=0): + while pass_number > len(pass_patterns) - 1: + pass_patterns.append(PatternMatcherPass()) + return register_graph_pattern( + pattern, + extra_check=extra_check, + pass_dict=pass_patterns[pass_number], + ) + + +def register_binary_folding_pattern(pattern, extra_check=_return_true): + return register_graph_pattern( + pattern, + extra_check=extra_check, + pass_dict=binary_folding_pass, + ) + + +@functools.lru_cache(None) +def addmm_patterns_init(): + device = next( + (gpu for gpu in GPU_TYPES if getattr(torch, gpu).is_available()), "cpu" + ) + val = functools.partial(torch.empty, (10, 10), device=device, requires_grad=False) + + def check_concat_weights(match): + is_cpu = match.kwargs["inp"].meta["val"].is_cpu + if is_cpu and not config.cpp.enable_concat_linear: + return False + + weight_inputs = ["w1", "w2"] + if "w3" in match.kwargs: + weight_inputs.append("w3") + + equal_shape_inputs = [weight_inputs] + + if "b1" in match.kwargs: + bias_inputs = ["b1", "b2"] + if "b3" in match.kwargs: + bias_inputs.append("b3") + + equal_shape_inputs.append(bias_inputs) + + for equal_shape_group in equal_shape_inputs: + inps = [match.kwargs[name] for name in equal_shape_group] + + if not all( + inp.op == "get_attr" + and inp.meta["val"].shape == inps[0].meta["val"].shape + for inp in inps + ): + return False + + return True + + def matmul_fuse_pattern(inp, w1, w2, w3): + return (inp @ w1, inp @ w2, inp @ w3) + + def matmul_replacement(inp, w1, w2, w3): + cat_t = torch.cat((w1, w2, w3), dim=1) + mm = inp @ cat_t + return mm.chunk(3, dim=1) + + register_replacement( + matmul_fuse_pattern, + matmul_replacement, + [val(), val(), val(), val()], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3"), + ) + + def matmul_fuse_pattern_two(inp, w1, w2): + return (inp @ w1, inp @ w2) + + def matmul_replacement_two(inp, w1, w2): + cat_t = torch.cat((w1, w2), dim=1) + mm = inp @ cat_t + return mm.chunk(2, dim=1) + + register_replacement( + matmul_fuse_pattern_two, + matmul_replacement_two, + [val(), val(), val()], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2"), + ) + + def addmm_fuse_pattern_second(inp, w1, w2, w3, b1, b2, b3): + return ( + aten.addmm(b1, inp, w1), + aten.addmm(b2, inp, w2), + aten.addmm(b3, inp, w3), + ) + + def addmm_fuse_replacement_second(inp, w1, w2, w3, b1, b2, b3): + cat_w = torch.cat((w1, w2, w3), dim=1) + cat_b = torch.cat((b1, b2, b3)) + return aten.addmm(cat_b, inp, cat_w).chunk(3, dim=1) + + register_replacement( + addmm_fuse_pattern_second, + addmm_fuse_replacement_second, + [val() for _ in range(7)], + fwd_only, + pass_patterns[0], + extra_check=check_concat_weights, + exclusive_arg_names=("w1", "w2", "w3", "b1", "b2", "b3"), + ) + + +def same_dtype(match): + return match.output_node().args[0].meta["val"].dtype == match.kwargs["dtype"] + + +@register_graph_pattern( + CallFunction( + torch.ops.prims.convert_element_type.default, + Ignored(), + KeywordArg("dtype"), + ), + pass_dict=pass_patterns[0], + extra_check=same_dtype, +) +def unnecessary_dtype_convert(match: Match, **kwargs): + """Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding""" + graph = match.graph + node = match.output_node() + node.replace_all_uses_with(node.args[0]) # type: ignore[arg-type] + graph.erase_node(node) diff --git a/shared/package-files/18/18d9eacb499beb23cc6b7ce9184cf3da9eaec58ed5b686cfb705226a585f6044/testutil.py b/shared/package-files/18/18d9eacb499beb23cc6b7ce9184cf3da9eaec58ed5b686cfb705226a585f6044/testutil.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe664ce9e7437b97feec90f2052eb2987c57a4e --- /dev/null +++ b/shared/package-files/18/18d9eacb499beb23cc6b7ce9184cf3da9eaec58ed5b686cfb705226a585f6044/testutil.py @@ -0,0 +1,357 @@ +from sympy.combinatorics import Permutation +from sympy.combinatorics.util import _distribute_gens_by_base + +rmul = Permutation.rmul + + +def _cmp_perm_lists(first, second): + """ + Compare two lists of permutations as sets. + + Explanation + =========== + + This is used for testing purposes. Since the array form of a + permutation is currently a list, Permutation is not hashable + and cannot be put into a set. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.testutil import _cmp_perm_lists + >>> a = Permutation([0, 2, 3, 4, 1]) + >>> b = Permutation([1, 2, 0, 4, 3]) + >>> c = Permutation([3, 4, 0, 1, 2]) + >>> ls1 = [a, b, c] + >>> ls2 = [b, c, a] + >>> _cmp_perm_lists(ls1, ls2) + True + + """ + return {tuple(a) for a in first} == \ + {tuple(a) for a in second} + + +def _naive_list_centralizer(self, other, af=False): + from sympy.combinatorics.perm_groups import PermutationGroup + """ + Return a list of elements for the centralizer of a subgroup/set/element. + + Explanation + =========== + + This is a brute force implementation that goes over all elements of the + group and checks for membership in the centralizer. It is used to + test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import _naive_list_centralizer + >>> from sympy.combinatorics.named_groups import DihedralGroup + >>> D = DihedralGroup(4) + >>> _naive_list_centralizer(D, D) + [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] + + See Also + ======== + + sympy.combinatorics.perm_groups.centralizer + + """ + from sympy.combinatorics.permutations import _af_commutes_with + if hasattr(other, 'generators'): + elements = list(self.generate_dimino(af=True)) + gens = [x._array_form for x in other.generators] + commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) + centralizer_list = [] + if not af: + for element in elements: + if commutes_with_gens(element): + centralizer_list.append(Permutation._af_new(element)) + else: + for element in elements: + if commutes_with_gens(element): + centralizer_list.append(element) + return centralizer_list + elif hasattr(other, 'getitem'): + return _naive_list_centralizer(self, PermutationGroup(other), af) + elif hasattr(other, 'array_form'): + return _naive_list_centralizer(self, PermutationGroup([other]), af) + + +def _verify_bsgs(group, base, gens): + """ + Verify the correctness of a base and strong generating set. + + Explanation + =========== + + This is a naive implementation using the definition of a base and a strong + generating set relative to it. There are other procedures for + verifying a base and strong generating set, but this one will + serve for more robust testing. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import AlternatingGroup + >>> from sympy.combinatorics.testutil import _verify_bsgs + >>> A = AlternatingGroup(4) + >>> A.schreier_sims() + >>> _verify_bsgs(A, A.base, A.strong_gens) + True + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims + + """ + from sympy.combinatorics.perm_groups import PermutationGroup + strong_gens_distr = _distribute_gens_by_base(base, gens) + current_stabilizer = group + for i in range(len(base)): + candidate = PermutationGroup(strong_gens_distr[i]) + if current_stabilizer.order() != candidate.order(): + return False + current_stabilizer = current_stabilizer.stabilizer(base[i]) + if current_stabilizer.order() != 1: + return False + return True + + +def _verify_centralizer(group, arg, centr=None): + """ + Verify the centralizer of a group/set/element inside another group. + + This is used for testing ``.centralizer()`` from + ``sympy.combinatorics.perm_groups`` + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> from sympy.combinatorics.testutil import _verify_centralizer + >>> S = SymmetricGroup(5) + >>> A = AlternatingGroup(5) + >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) + >>> _verify_centralizer(S, A, centr) + True + + See Also + ======== + + _naive_list_centralizer, + sympy.combinatorics.perm_groups.PermutationGroup.centralizer, + _cmp_perm_lists + + """ + if centr is None: + centr = group.centralizer(arg) + centr_list = list(centr.generate_dimino(af=True)) + centr_list_naive = _naive_list_centralizer(group, arg, af=True) + return _cmp_perm_lists(centr_list, centr_list_naive) + + +def _verify_normal_closure(group, arg, closure=None): + from sympy.combinatorics.perm_groups import PermutationGroup + """ + Verify the normal closure of a subgroup/subset/element in a group. + + This is used to test + sympy.combinatorics.perm_groups.PermutationGroup.normal_closure + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import (SymmetricGroup, + ... AlternatingGroup) + >>> from sympy.combinatorics.testutil import _verify_normal_closure + >>> S = SymmetricGroup(3) + >>> A = AlternatingGroup(3) + >>> _verify_normal_closure(S, A, closure=A) + True + + See Also + ======== + + sympy.combinatorics.perm_groups.PermutationGroup.normal_closure + + """ + if closure is None: + closure = group.normal_closure(arg) + conjugates = set() + if hasattr(arg, 'generators'): + subgr_gens = arg.generators + elif hasattr(arg, '__getitem__'): + subgr_gens = arg + elif hasattr(arg, 'array_form'): + subgr_gens = [arg] + for el in group.generate_dimino(): + conjugates.update(gen ^ el for gen in subgr_gens) + naive_closure = PermutationGroup(list(conjugates)) + return closure.is_subgroup(naive_closure) + + +def canonicalize_naive(g, dummies, sym, *v): + """ + Canonicalize tensor formed by tensors of the different types. + + Explanation + =========== + + sym_i symmetry under exchange of two component tensors of type `i` + None no symmetry + 0 commuting + 1 anticommuting + + Parameters + ========== + + g : Permutation representing the tensor. + dummies : List of dummy indices. + msym : Symmetry of the metric. + v : A list of (base_i, gens_i, n_i, sym_i) for tensors of type `i`. + base_i, gens_i BSGS for tensors of this type + n_i number of tensors of type `i` + + Returns + ======= + + Returns 0 if the tensor is zero, else returns the array form of + the permutation representing the canonical form of the tensor. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import canonicalize_naive + >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs + >>> from sympy.combinatorics import Permutation + >>> g = Permutation([1, 3, 2, 0, 4, 5]) + >>> base2, gens2 = get_symmetric_group_sgs(2) + >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) + [0, 2, 1, 3, 4, 5] + """ + from sympy.combinatorics.perm_groups import PermutationGroup + from sympy.combinatorics.tensor_can import gens_products, dummy_sgs + from sympy.combinatorics.permutations import _af_rmul + v1 = [] + for i in range(len(v)): + base_i, gens_i, n_i, sym_i = v[i] + v1.append((base_i, gens_i, [[]]*n_i, sym_i)) + size, sbase, sgens = gens_products(*v1) + dgens = dummy_sgs(dummies, sym, size-2) + if isinstance(sym, int): + num_types = 1 + dummies = [dummies] + sym = [sym] + else: + num_types = len(sym) + dgens = [] + for i in range(num_types): + dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2)) + S = PermutationGroup(sgens) + D = PermutationGroup([Permutation(x) for x in dgens]) + dlist = list(D.generate(af=True)) + g = g.array_form + st = set() + for s in S.generate(af=True): + h = _af_rmul(g, s) + for d in dlist: + q = tuple(_af_rmul(d, h)) + st.add(q) + a = list(st) + a.sort() + prev = (0,)*size + for h in a: + if h[:-2] == prev[:-2]: + if h[-1] != prev[-1]: + return 0 + prev = h + return list(a[0]) + + +def graph_certificate(gr): + """ + Return a certificate for the graph + + Parameters + ========== + + gr : adjacency list + + Explanation + =========== + + The graph is assumed to be unoriented and without + external lines. + + Associate to each vertex of the graph a symmetric tensor with + number of indices equal to the degree of the vertex; indices + are contracted when they correspond to the same line of the graph. + The canonical form of the tensor gives a certificate for the graph. + + This is not an efficient algorithm to get the certificate of a graph. + + Examples + ======== + + >>> from sympy.combinatorics.testutil import graph_certificate + >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} + >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} + >>> c1 = graph_certificate(gr1) + >>> c2 = graph_certificate(gr2) + >>> c1 + [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] + >>> c1 == c2 + True + """ + from sympy.combinatorics.permutations import _af_invert + from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize + items = list(gr.items()) + items.sort(key=lambda x: len(x[1]), reverse=True) + pvert = [x[0] for x in items] + pvert = _af_invert(pvert) + + # the indices of the tensor are twice the number of lines of the graph + num_indices = 0 + for v, neigh in items: + num_indices += len(neigh) + # associate to each vertex its indices; for each line + # between two vertices assign the + # even index to the vertex which comes first in items, + # the odd index to the other vertex + vertices = [[] for i in items] + i = 0 + for v, neigh in items: + for v2 in neigh: + if pvert[v] < pvert[v2]: + vertices[pvert[v]].append(i) + vertices[pvert[v2]].append(i+1) + i += 2 + g = [] + for v in vertices: + g.extend(v) + assert len(g) == num_indices + g += [num_indices, num_indices + 1] + size = num_indices + 2 + assert sorted(g) == list(range(size)) + g = Permutation(g) + vlen = [0]*(len(vertices[0])+1) + for neigh in vertices: + vlen[len(neigh)] += 1 + v = [] + for i in range(len(vlen)): + n = vlen[i] + if n: + base, gens = get_symmetric_group_sgs(i) + v.append((base, gens, n, 0)) + v.reverse() + dummies = list(range(num_indices)) + can = canonicalize(g, dummies, 0, *v) + return can diff --git a/shared/package-files/18/18fa735d24cc2205c4ac7ae5f696c3311396aa789cedfc5bd94046dcdc99e8c7/base.cpython-311.pyc b/shared/package-files/18/18fa735d24cc2205c4ac7ae5f696c3311396aa789cedfc5bd94046dcdc99e8c7/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a79df461d4e7b8ec8342f7d99b2061b37f7477d4 Binary files /dev/null and b/shared/package-files/18/18fa735d24cc2205c4ac7ae5f696c3311396aa789cedfc5bd94046dcdc99e8c7/base.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f020c7c5914419cd809acc29f165377752a4226c2796c873cb925bd2b245651/sparse_mask_ops.h b/shared/package-files/1f/1f020c7c5914419cd809acc29f165377752a4226c2796c873cb925bd2b245651/sparse_mask_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1ac6d45219382d5f0f1b419d440a02e38567dfad --- /dev/null +++ b/shared/package-files/1f/1f020c7c5914419cd809acc29f165377752a4226c2796c873cb925bd2b245651/sparse_mask_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API sparse_mask { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::sparse_mask"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "sparse_mask(Tensor self, Tensor mask) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & mask); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask); +}; + +struct TORCH_API sparse_mask_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::sparse_mask"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "sparse_mask.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f09cbccf792216607230db0184b8b158c935cdabc76bd767749a0ed1a2f2017/topk_ops.h b/shared/package-files/1f/1f09cbccf792216607230db0184b8b158c935cdabc76bd767749a0ed1a2f2017/topk_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6896fe5484da691b54e750eaea57c793ba67bcb2 --- /dev/null +++ b/shared/package-files/1f/1f09cbccf792216607230db0184b8b158c935cdabc76bd767749a0ed1a2f2017/topk_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API topk_values { + using schema = ::std::tuple (const at::Tensor &, c10::SymInt, int64_t, bool, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::topk"; + static constexpr const char* overload_name = "values"; + static constexpr const char* schema_str = "topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)"; + static ::std::tuple call(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices); +}; + +struct TORCH_API topk { + using schema = ::std::tuple (const at::Tensor &, c10::SymInt, int64_t, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::topk"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)"; + static ::std::tuple call(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f0ea79d563a1c92738d97ec6d2864ef176324f73f9ebc151db2ecd3918c227e/common_op_utils.cpython-311.pyc b/shared/package-files/1f/1f0ea79d563a1c92738d97ec6d2864ef176324f73f9ebc151db2ecd3918c227e/common_op_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..917fc6828fc21a60865e134533209a4b22a7ed20 Binary files /dev/null and b/shared/package-files/1f/1f0ea79d563a1c92738d97ec6d2864ef176324f73f9ebc151db2ecd3918c227e/common_op_utils.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f0ed3e5e6f1fcbfcda49fe73efd0fe8e0597846be9e19c52f47e1825d85fe9d/privateuse1_observer.h b/shared/package-files/1f/1f0ed3e5e6f1fcbfcda49fe73efd0fe8e0597846be9e19c52f47e1825d85fe9d/privateuse1_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..48b77d3daae28661fcabb2f9483d7428c1955053 --- /dev/null +++ b/shared/package-files/1f/1f0ed3e5e6f1fcbfcda49fe73efd0fe8e0597846be9e19c52f47e1825d85fe9d/privateuse1_observer.h @@ -0,0 +1,46 @@ +#pragma once +#include + +namespace torch::profiler::impl { + +using CallBackFnPtr = void (*)( + const ProfilerConfig& config, + const std::unordered_set& scopes); + +struct PushPRIVATEUSE1CallbacksStub { + PushPRIVATEUSE1CallbacksStub() = default; + PushPRIVATEUSE1CallbacksStub(const PushPRIVATEUSE1CallbacksStub&) = delete; + PushPRIVATEUSE1CallbacksStub& operator=(const PushPRIVATEUSE1CallbacksStub&) = + delete; + PushPRIVATEUSE1CallbacksStub(PushPRIVATEUSE1CallbacksStub&&) = default; + PushPRIVATEUSE1CallbacksStub& operator=(PushPRIVATEUSE1CallbacksStub&&) = + default; + ~PushPRIVATEUSE1CallbacksStub() = default; + + template + void operator()(ArgTypes&&... args) { + return (*push_privateuse1_callbacks_fn)(std::forward(args)...); + } + + void set_privateuse1_dispatch_ptr(CallBackFnPtr fn_ptr) { + push_privateuse1_callbacks_fn = fn_ptr; + } + + private: + CallBackFnPtr push_privateuse1_callbacks_fn = nullptr; +}; + +extern TORCH_API struct PushPRIVATEUSE1CallbacksStub + pushPRIVATEUSE1CallbacksStub; + +struct RegisterPRIVATEUSE1Observer { + RegisterPRIVATEUSE1Observer( + PushPRIVATEUSE1CallbacksStub& stub, + CallBackFnPtr value) { + stub.set_privateuse1_dispatch_ptr(value); + } +}; + +#define REGISTER_PRIVATEUSE1_OBSERVER(name, fn) \ + static RegisterPRIVATEUSE1Observer name##__register(name, fn); +} // namespace torch::profiler::impl diff --git a/shared/package-files/1f/1f127a18859cddbeae01958d878e6878f5e540b01d5fd2a6bb73c1c803af961e/__init__.py b/shared/package-files/1f/1f127a18859cddbeae01958d878e6878f5e540b01d5fd2a6bb73c1c803af961e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..faac68bb632934ba730ba7c5ce3cf7fe934a58cf --- /dev/null +++ b/shared/package-files/1f/1f127a18859cddbeae01958d878e6878f5e540b01d5fd2a6bb73c1c803af961e/__init__.py @@ -0,0 +1,44 @@ +""" +:mod:`torch.distributed.optim` exposes DistributedOptimizer, which takes a list +of remote parameters (:class:`~torch.distributed.rpc.RRef`) and runs the +optimizer locally on the workers where the parameters live. The distributed +optimizer can use any of the local optimizer :ref:`optimizer-algorithms` to +apply the gradients on each worker. +""" + +import warnings + +import torch +from torch import optim + +from .apply_optimizer_in_backward import ( + _apply_optimizer_in_backward, + _get_in_backward_optimizers, +) +from .functional_adadelta import _FunctionalAdadelta +from .functional_adagrad import _FunctionalAdagrad +from .functional_adam import _FunctionalAdam +from .functional_adamax import _FunctionalAdamax +from .functional_adamw import _FunctionalAdamW +from .functional_rmsprop import _FunctionalRMSprop +from .functional_rprop import _FunctionalRprop +from .functional_sgd import _FunctionalSGD +from .named_optimizer import _NamedOptimizer +from .utils import as_functional_optim + + +# DistributedOptimizer imports torch.distributed.rpc names, so gate availability +# based on RPC being available. +if hasattr(torch._C, "_rpc_init"): + from .optimizer import DistributedOptimizer + +from .post_localSGD_optimizer import PostLocalSGDOptimizer +from .zero_redundancy_optimizer import ZeroRedundancyOptimizer + + +__all__ = [ + "as_functional_optim", + "DistributedOptimizer", + "PostLocalSGDOptimizer", + "ZeroRedundancyOptimizer", +] diff --git a/shared/package-files/1f/1f135a9505b4371e447fe966c6d681fb6101e8ee951615f1319ede909c195728/digraph.cpython-311.pyc b/shared/package-files/1f/1f135a9505b4371e447fe966c6d681fb6101e8ee951615f1319ede909c195728/digraph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71f723386a896c7552e50638af886bfb34de17c2 Binary files /dev/null and b/shared/package-files/1f/1f135a9505b4371e447fe966c6d681fb6101e8ee951615f1319ede909c195728/digraph.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f141c8a5056c8578fd07d521b52006d28eed0e71aba4b4bdcdef6aedb5e11c3/graph_utils.h b/shared/package-files/1f/1f141c8a5056c8578fd07d521b52006d28eed0e71aba4b4bdcdef6aedb5e11c3/graph_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1c5e702e5900d4bf0fb41c9cfe1aebb6d0f8f1ec --- /dev/null +++ b/shared/package-files/1f/1f141c8a5056c8578fd07d521b52006d28eed0e71aba4b4bdcdef6aedb5e11c3/graph_utils.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +#include + +namespace torch::jit { + +TORCH_API TypePtr getTensorType(const at::Tensor& t, bool complete); + +TORCH_API TypePtr inferShapeAndTypeForInput( + TypePtr input_type, + Stack::const_iterator& s_iter, + const Stack::const_iterator& s_iter_end, + bool complete); + +TORCH_API void setInputTensorTypes( + Graph& g, + const Stack& stack, + bool complete, + const std::vector& param_count_list = {}); + +} // namespace torch::jit diff --git a/shared/package-files/1f/1f150d886687fb5e2cf3f5d6c194e760a81f59b3bf615bc9f5c410b81e14339d/bilinear_compositeimplicitautograd_dispatch.h b/shared/package-files/1f/1f150d886687fb5e2cf3f5d6c194e760a81f59b3bf615bc9f5c410b81e14339d/bilinear_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..72982391a915acbcefd93a573db180385653538a --- /dev/null +++ b/shared/package-files/1f/1f150d886687fb5e2cf3f5d6c194e760a81f59b3bf615bc9f5c410b81e14339d/bilinear_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor bilinear(const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & weight, const ::std::optional & bias={}); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/1f/1f167188f79a88bbf5d12ee265a5ab3ee2f0dbcb9cc2402f6ec107b9a1699fa1/max_pool3d_ops.h b/shared/package-files/1f/1f167188f79a88bbf5d12ee265a5ab3ee2f0dbcb9cc2402f6ec107b9a1699fa1/max_pool3d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a9beb2791c57d3a1cd43a52b20926f3dc3a5c96d --- /dev/null +++ b/shared/package-files/1f/1f167188f79a88bbf5d12ee265a5ab3ee2f0dbcb9cc2402f6ec107b9a1699fa1/max_pool3d_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API max_pool3d { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::max_pool3d"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f18dce117e0cdaa54300973757689ec906060def79a91580c672507323ee435/_batch_norm_no_update_native.h b/shared/package-files/1f/1f18dce117e0cdaa54300973757689ec906060def79a91580c672507323ee435/_batch_norm_no_update_native.h new file mode 100644 index 0000000000000000000000000000000000000000..45c676ff3e0f87d816ef8c7a7cef80cb2447679e --- /dev/null +++ b/shared/package-files/1f/1f18dce117e0cdaa54300973757689ec906060def79a91580c672507323ee435/_batch_norm_no_update_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _batch_norm_no_update(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum, double eps); +TORCH_API ::std::tuple _batch_norm_no_update_out(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); +} // namespace native +} // namespace at diff --git a/shared/package-files/1f/1f2c567ff74b7c1346c7b73e6210d45487fd3323c85bc4f34e34786a05e2adad/mish_ops.h b/shared/package-files/1f/1f2c567ff74b7c1346c7b73e6210d45487fd3323c85bc4f34e34786a05e2adad/mish_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..baff7eb917c6c5ad7ecf7b37ee8ae2512ec00cbd --- /dev/null +++ b/shared/package-files/1f/1f2c567ff74b7c1346c7b73e6210d45487fd3323c85bc4f34e34786a05e2adad/mish_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API mish { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mish"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "mish(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API mish_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mish_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "mish_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API mish_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::mish"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f393973c495fa46e0e3bc0128b8b46077f582b0eec93a7a63ecd2e45109a527/random_matrix_models.cpython-311.pyc b/shared/package-files/1f/1f393973c495fa46e0e3bc0128b8b46077f582b0eec93a7a63ecd2e45109a527/random_matrix_models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0600883f08ba93cd560755d2cd92ae720eb6a4b7 Binary files /dev/null and b/shared/package-files/1f/1f393973c495fa46e0e3bc0128b8b46077f582b0eec93a7a63ecd2e45109a527/random_matrix_models.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f40839461404ba18def05e0f92f5ae2653720a209bddd9942bcb1a56cc2e511/margin_ranking_loss_ops.h b/shared/package-files/1f/1f40839461404ba18def05e0f92f5ae2653720a209bddd9942bcb1a56cc2e511/margin_ranking_loss_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..b3c1f549cef67e6c434c0607bda3981fac2f3f70 --- /dev/null +++ b/shared/package-files/1f/1f40839461404ba18def05e0f92f5ae2653720a209bddd9942bcb1a56cc2e511/margin_ranking_loss_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API margin_ranking_loss { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, double, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::margin_ranking_loss"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor"; + static at::Tensor call(const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & target, double margin, int64_t reduction); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & target, double margin, int64_t reduction); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f40c65df3feb76ad084f1011fce46f4049bf92dcbff011e318bb0c466fbe346/rocm_kernel.cpython-311.pyc b/shared/package-files/1f/1f40c65df3feb76ad084f1011fce46f4049bf92dcbff011e318bb0c466fbe346/rocm_kernel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d5b413354f2cfbebe61c249daa067689c5105f7 Binary files /dev/null and b/shared/package-files/1f/1f40c65df3feb76ad084f1011fce46f4049bf92dcbff011e318bb0c466fbe346/rocm_kernel.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f44d7c30f0c69746d384a26a3e1e7e35123f7ac4aff623eb71c6a0ff0f49bbb/sym_size_native.h b/shared/package-files/1f/1f44d7c30f0c69746d384a26a3e1e7e35123f7ac4aff623eb71c6a0ff0f49bbb/sym_size_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7a9b32bac1ed713cd4149d1cbebe181d6a5f8cb4 --- /dev/null +++ b/shared/package-files/1f/1f44d7c30f0c69746d384a26a3e1e7e35123f7ac4aff623eb71c6a0ff0f49bbb/sym_size_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API c10::SymInt sym_size(const at::Tensor & self, int64_t dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/1f/1f4ccd493605c7b86f59ea081e80d2e3bdb4da7ec978c5c86d220be278cefb1c/utils.cpython-311.pyc b/shared/package-files/1f/1f4ccd493605c7b86f59ea081e80d2e3bdb4da7ec978c5c86d220be278cefb1c/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88997c7cdf9ef283a1aeada3c33ec315a65f1f79 Binary files /dev/null and b/shared/package-files/1f/1f4ccd493605c7b86f59ea081e80d2e3bdb4da7ec978c5c86d220be278cefb1c/utils.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f4e913f22201e2bfcbce280e625a9c162d16be13f68dd299b6e02d7ecd351d6/max_pool1d_ops.h b/shared/package-files/1f/1f4e913f22201e2bfcbce280e625a9c162d16be13f68dd299b6e02d7ecd351d6/max_pool1d_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1acf33a6f3a89372b51b13d276545afdd14f0ea6 --- /dev/null +++ b/shared/package-files/1f/1f4e913f22201e2bfcbce280e625a9c162d16be13f68dd299b6e02d7ecd351d6/max_pool1d_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API max_pool1d { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::max_pool1d"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor"; + static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f5065576692ea166941002500e21d1f951debccdac934079dd0c4d3e12890ff/_values_copy.h b/shared/package-files/1f/1f5065576692ea166941002500e21d1f951debccdac934079dd0c4d3e12890ff/_values_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..8c131a69b43749795979442f006ee7b24a305f6b --- /dev/null +++ b/shared/package-files/1f/1f5065576692ea166941002500e21d1f951debccdac934079dd0c4d3e12890ff/_values_copy.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_values_copy(Tensor self) -> Tensor +inline at::Tensor _values_copy(const at::Tensor & self) { + return at::_ops::_values_copy::call(self); +} + +// aten::_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _values_copy_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::_values_copy_out::call(self, out); +} +// aten::_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _values_copy_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::_values_copy_out::call(self, out); +} + +} diff --git a/shared/package-files/1f/1f5661ce49b51b7bf60235879541d756f2ccc241416a71e4a5a741ed042db8f3/decompose_mem_bound_mm.cpython-311.pyc b/shared/package-files/1f/1f5661ce49b51b7bf60235879541d756f2ccc241416a71e4a5a741ed042db8f3/decompose_mem_bound_mm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32e31bfa0ce79bafcab9e6d1fd9dcbee540c9790 Binary files /dev/null and b/shared/package-files/1f/1f5661ce49b51b7bf60235879541d756f2ccc241416a71e4a5a741ed042db8f3/decompose_mem_bound_mm.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f5a43dd31e0534906cd2383887121435b94aee8666217e980f77f23b92a85fe/uniform.h b/shared/package-files/1f/1f5a43dd31e0534906cd2383887121435b94aee8666217e980f77f23b92a85fe/uniform.h new file mode 100644 index 0000000000000000000000000000000000000000..b143fa5e0a83ee17c3ba07f3d19fe1025d44df03 --- /dev/null +++ b/shared/package-files/1f/1f5a43dd31e0534906cd2383887121435b94aee8666217e980f77f23b92a85fe/uniform.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::uniform.out(Tensor self, float from=0, float to=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & uniform_out(at::Tensor & out, const at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt) { + return at::_ops::uniform_out::call(self, from, to, generator, out); +} +// aten::uniform.out(Tensor self, float from=0, float to=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & uniform_outf(const at::Tensor & self, double from, double to, ::std::optional generator, at::Tensor & out) { + return at::_ops::uniform_out::call(self, from, to, generator, out); +} + +// aten::uniform(Tensor self, float from=0, float to=1, *, Generator? generator=None) -> Tensor +inline at::Tensor uniform(const at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt) { + return at::_ops::uniform::call(self, from, to, generator); +} + +} diff --git a/shared/package-files/1f/1f5c7ca99426aa0460f84d3a03f7d4a049b843f5e9f1c56052c2078bb43fe6bb/_entry_points.cpython-311.pyc b/shared/package-files/1f/1f5c7ca99426aa0460f84d3a03f7d4a049b843f5e9f1c56052c2078bb43fe6bb/_entry_points.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8636bf9bde2a4307b10368c10050c8bd86a0433e Binary files /dev/null and b/shared/package-files/1f/1f5c7ca99426aa0460f84d3a03f7d4a049b843f5e9f1c56052c2078bb43fe6bb/_entry_points.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f5dcb75e3d3b2bede49e0aba78bf5dcbed3dd810ab1011c9d342fbc3f566d50/quasirandom.py b/shared/package-files/1f/1f5dcb75e3d3b2bede49e0aba78bf5dcbed3dd810ab1011c9d342fbc3f566d50/quasirandom.py new file mode 100644 index 0000000000000000000000000000000000000000..b5d4540e592f190e5e239391c40003a0bbc30146 --- /dev/null +++ b/shared/package-files/1f/1f5dcb75e3d3b2bede49e0aba78bf5dcbed3dd810ab1011c9d342fbc3f566d50/quasirandom.py @@ -0,0 +1,217 @@ +# mypy: allow-untyped-defs +from typing import Optional + +import torch + + +class SobolEngine: + r""" + The :class:`torch.quasirandom.SobolEngine` is an engine for generating + (scrambled) Sobol sequences. Sobol sequences are an example of low + discrepancy quasi-random sequences. + + This implementation of an engine for Sobol sequences is capable of + sampling sequences up to a maximum dimension of 21201. It uses direction + numbers from https://web.maths.unsw.edu.au/~fkuo/sobol/ obtained using the + search criterion D(6) up to the dimension 21201. This is the recommended + choice by the authors. + + References: + - Art B. Owen. Scrambling Sobol and Niederreiter-Xing points. + Journal of Complexity, 14(4):466-489, December 1998. + + - I. M. Sobol. The distribution of points in a cube and the accurate + evaluation of integrals. + Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, 1967. + + Args: + dimension (Int): The dimensionality of the sequence to be drawn + scramble (bool, optional): Setting this to ``True`` will produce + scrambled Sobol sequences. Scrambling is + capable of producing better Sobol + sequences. Default: ``False``. + seed (Int, optional): This is the seed for the scrambling. The seed + of the random number generator is set to this, + if specified. Otherwise, it uses a random seed. + Default: ``None`` + + Examples:: + + >>> # xdoctest: +SKIP("unseeded random state") + >>> soboleng = torch.quasirandom.SobolEngine(dimension=5) + >>> soboleng.draw(3) + tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [0.5000, 0.5000, 0.5000, 0.5000, 0.5000], + [0.7500, 0.2500, 0.2500, 0.2500, 0.7500]]) + """ + + MAXBIT = 30 + MAXDIM = 21201 + + def __init__(self, dimension, scramble=False, seed=None): + if dimension > self.MAXDIM or dimension < 1: + raise ValueError( + "Supported range of dimensionality " + f"for SobolEngine is [1, {self.MAXDIM}]" + ) + + self.seed = seed + self.scramble = scramble + self.dimension = dimension + + cpu = torch.device("cpu") + + self.sobolstate = torch.zeros( + dimension, self.MAXBIT, device=cpu, dtype=torch.long + ) + torch._sobol_engine_initialize_state_(self.sobolstate, self.dimension) + + if not self.scramble: + self.shift = torch.zeros(self.dimension, device=cpu, dtype=torch.long) + else: + self._scramble() + + self.quasi = self.shift.clone(memory_format=torch.contiguous_format) + self._first_point = (self.quasi / 2**self.MAXBIT).reshape(1, -1) + self.num_generated = 0 + + def draw( + self, + n: int = 1, + out: Optional[torch.Tensor] = None, + dtype: Optional[torch.dtype] = None, + ) -> torch.Tensor: + r""" + Function to draw a sequence of :attr:`n` points from a Sobol sequence. + Note that the samples are dependent on the previous samples. The size + of the result is :math:`(n, dimension)`. + + Args: + n (Int, optional): The length of sequence of points to draw. + Default: 1 + out (Tensor, optional): The output tensor + dtype (:class:`torch.dtype`, optional): the desired data type of the + returned tensor. + Default: ``None`` + """ + if dtype is None: + dtype = torch.get_default_dtype() + + if self.num_generated == 0: + if n == 1: + result = self._first_point.to(dtype) + else: + result, self.quasi = torch._sobol_engine_draw( + self.quasi, + n - 1, + self.sobolstate, + self.dimension, + self.num_generated, + dtype=dtype, + ) + result = torch.cat((self._first_point.to(dtype), result), dim=-2) + else: + result, self.quasi = torch._sobol_engine_draw( + self.quasi, + n, + self.sobolstate, + self.dimension, + self.num_generated - 1, + dtype=dtype, + ) + + self.num_generated += n + + if out is not None: + out.resize_as_(result).copy_(result) + return out + + return result + + def draw_base2( + self, + m: int, + out: Optional[torch.Tensor] = None, + dtype: Optional[torch.dtype] = None, + ) -> torch.Tensor: + r""" + Function to draw a sequence of :attr:`2**m` points from a Sobol sequence. + Note that the samples are dependent on the previous samples. The size + of the result is :math:`(2**m, dimension)`. + + Args: + m (Int): The (base2) exponent of the number of points to draw. + out (Tensor, optional): The output tensor + dtype (:class:`torch.dtype`, optional): the desired data type of the + returned tensor. + Default: ``None`` + """ + n = 2**m + total_n = self.num_generated + n + if not (total_n & (total_n - 1) == 0): + raise ValueError( + "The balance properties of Sobol' points require " + f"n to be a power of 2. {self.num_generated} points have been " + f"previously generated, then: n={self.num_generated}+2**{m}={total_n}. " + "If you still want to do this, please use " + "'SobolEngine.draw()' instead." + ) + return self.draw(n=n, out=out, dtype=dtype) + + def reset(self): + r""" + Function to reset the ``SobolEngine`` to base state. + """ + self.quasi.copy_(self.shift) + self.num_generated = 0 + return self + + def fast_forward(self, n): + r""" + Function to fast-forward the state of the ``SobolEngine`` by + :attr:`n` steps. This is equivalent to drawing :attr:`n` samples + without using the samples. + + Args: + n (Int): The number of steps to fast-forward by. + """ + if self.num_generated == 0: + torch._sobol_engine_ff_( + self.quasi, n - 1, self.sobolstate, self.dimension, self.num_generated + ) + else: + torch._sobol_engine_ff_( + self.quasi, n, self.sobolstate, self.dimension, self.num_generated - 1 + ) + self.num_generated += n + return self + + def _scramble(self): + g: Optional[torch.Generator] = None + if self.seed is not None: + g = torch.Generator() + g.manual_seed(self.seed) + + cpu = torch.device("cpu") + + # Generate shift vector + shift_ints = torch.randint( + 2, (self.dimension, self.MAXBIT), device=cpu, generator=g + ) + self.shift = torch.mv( + shift_ints, torch.pow(2, torch.arange(0, self.MAXBIT, device=cpu)) + ) + + # Generate lower triangular matrices (stacked across dimensions) + ltm_dims = (self.dimension, self.MAXBIT, self.MAXBIT) + ltm = torch.randint(2, ltm_dims, device=cpu, generator=g).tril() + + torch._sobol_engine_scramble_(self.sobolstate, ltm, self.dimension) + + def __repr__(self): + fmt_string = [f"dimension={self.dimension}"] + if self.scramble: + fmt_string += ["scramble=True"] + if self.seed is not None: + fmt_string += [f"seed={self.seed}"] + return self.__class__.__name__ + "(" + ", ".join(fmt_string) + ")" diff --git a/shared/package-files/1f/1f5ef44e371999fc2d2c3e17ee0ed00d82bda1594ea98c98e8f9e68cb8e3bdc3/test_codegen_julia.cpython-311.pyc b/shared/package-files/1f/1f5ef44e371999fc2d2c3e17ee0ed00d82bda1594ea98c98e8f9e68cb8e3bdc3/test_codegen_julia.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3356a9508f1d4845ab415275bb48eb1a5c6e77b0 Binary files /dev/null and b/shared/package-files/1f/1f5ef44e371999fc2d2c3e17ee0ed00d82bda1594ea98c98e8f9e68cb8e3bdc3/test_codegen_julia.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f5fc20bebef01a4b6eb2b385ec4c590c813c544dc8808dd8ecc238b3922b2f4/device_launch_parameters.h b/shared/package-files/1f/1f5fc20bebef01a4b6eb2b385ec4c590c813c544dc8808dd8ecc238b3922b2f4/device_launch_parameters.h new file mode 100644 index 0000000000000000000000000000000000000000..8f552db8faab7d21e90e06a1ea2184a5563d3bf2 --- /dev/null +++ b/shared/package-files/1f/1f5fc20bebef01a4b6eb2b385ec4c590c813c544dc8808dd8ecc238b3922b2f4/device_launch_parameters.h @@ -0,0 +1,118 @@ +/* + * Copyright 1993-2012 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__DEVICE_LAUNCH_PARAMETERS_H__) +#define __DEVICE_LAUNCH_PARAMETERS_H__ + +#include "vector_types.h" + +#if !defined(__STORAGE__) + +#if defined(__CUDACC_RTC__) +#define __STORAGE__ \ + extern const __device__ +#else /* !__CUDACC_RTC__ */ +#define __STORAGE__ \ + extern const +#endif /* __CUDACC_RTC__ */ + +#endif /* __STORAGE__ */ + +#if defined(__cplusplus) +extern "C" { +#endif /* __cplusplus */ + +uint3 __device_builtin__ __STORAGE__ threadIdx; +uint3 __device_builtin__ __STORAGE__ blockIdx; +dim3 __device_builtin__ __STORAGE__ blockDim; +dim3 __device_builtin__ __STORAGE__ gridDim; +int __device_builtin__ __STORAGE__ warpSize; + +#undef __STORAGE__ + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + +#if !defined(__cudaGet_threadIdx) + +#define __cudaGet_threadIdx() \ + threadIdx + +#endif /* __cudaGet_threadIdx */ + +#if !defined(__cudaGet_blockIdx) + +#define __cudaGet_blockIdx() \ + blockIdx + +#endif /* __cudaGet_blockIdx */ + +#if !defined(__cudaGet_blockDim) + +#define __cudaGet_blockDim() \ + blockDim + +#endif /* __cudaGet_blockDim */ + +#if !defined(__cudaGet_gridDim) + +#define __cudaGet_gridDim() \ + gridDim + +#endif /* __cudaGet_gridDim */ + +#if !defined(__cudaGet_warpSize) + +#define __cudaGet_warpSize() \ + warpSize + +#endif /* __cudaGet_warpSize */ + +#endif /* !__DEVICE_LAUNCH_PARAMETERS_H__ */ diff --git a/shared/package-files/1f/1f636095668cdc0d645d1b201b5ab162d54c4195d3253fd18853152e5f66c6f0/custom_ops.cpython-311.pyc b/shared/package-files/1f/1f636095668cdc0d645d1b201b5ab162d54c4195d3253fd18853152e5f66c6f0/custom_ops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2e344d5bdc43d35d2d8165565709a9c66ac5173 Binary files /dev/null and b/shared/package-files/1f/1f636095668cdc0d645d1b201b5ab162d54c4195d3253fd18853152e5f66c6f0/custom_ops.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f68d9683b0327f8bd1f64b05a9c2e15e97c06b67dc472aebe1f83400596f654/entry_points.txt b/shared/package-files/1f/1f68d9683b0327f8bd1f64b05a9c2e15e97c06b67dc472aebe1f83400596f654/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..377282a2e4c3dc8b924035d0dfd32d7ae50920c8 --- /dev/null +++ b/shared/package-files/1f/1f68d9683b0327f8bd1f64b05a9c2e15e97c06b67dc472aebe1f83400596f654/entry_points.txt @@ -0,0 +1,2 @@ +[networkx.backends] +nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface diff --git a/shared/package-files/1f/1f6a1801da9cfef25c3328c0d79805475039635352d69dd3e7274fc6363ff842/streams.cpython-311.pyc b/shared/package-files/1f/1f6a1801da9cfef25c3328c0d79805475039635352d69dd3e7274fc6363ff842/streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b56298fedede424aa483130bfd2638032a79fba Binary files /dev/null and b/shared/package-files/1f/1f6a1801da9cfef25c3328c0d79805475039635352d69dd3e7274fc6363ff842/streams.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f6d3bbb24196e83387c5e4e6db899771f90e99f5066d9e4a2378a4bdd033766/api.cpython-311.pyc b/shared/package-files/1f/1f6d3bbb24196e83387c5e4e6db899771f90e99f5066d9e4a2378a4bdd033766/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa3b7339601e483ad314b65afd179e989e91a2cd Binary files /dev/null and b/shared/package-files/1f/1f6d3bbb24196e83387c5e4e6db899771f90e99f5066d9e4a2378a4bdd033766/api.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f71c453b9a59d2ce4fc7dce37f2c464e7e558cdb71ca9bd3d4e9990ed8df60a/GridSamplerUtils.h b/shared/package-files/1f/1f71c453b9a59d2ce4fc7dce37f2c464e7e558cdb71ca9bd3d4e9990ed8df60a/GridSamplerUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..f783043c7961222302ed0ff2514ffbf138cafac2 --- /dev/null +++ b/shared/package-files/1f/1f71c453b9a59d2ce4fc7dce37f2c464e7e558cdb71ca9bd3d4e9990ed8df60a/GridSamplerUtils.h @@ -0,0 +1,105 @@ +#pragma once + +// See NOTE: [Tensor vs. TensorBase] +// https://github.com/pytorch/pytorch/pull/66979 +#include +#include +#include + +namespace at::native { + +namespace detail { + +enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic}; +enum class GridSamplerPadding {Zeros, Border, Reflection}; + +} // namespace detail + +using detail::GridSamplerInterpolation; +using detail::GridSamplerPadding; + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_common( + const TensorBase& input, + const TensorBase& grid +) { + auto input_opt = input.options(); + auto grid_opt = grid.options(); + + TORCH_CHECK( + input.defined(), + "grid_sampler(): expected input to not be undefined"); + TORCH_CHECK( + grid.defined(), + "grid_sampler(): expected grid to not be undefined"); + TORCH_CHECK( + input_opt.device() == grid_opt.device(), + "grid_sampler(): expected input and grid to be on same device, but input " + "is on ", input_opt.device(), " and grid is on ", grid_opt.device()); + TORCH_CHECK( + input_opt.layout() == kStrided && grid_opt.layout() == kStrided, + "grid_sampler(): expected input and grid to have torch.strided layout, but " + "input has ", input_opt.layout(), " and grid has ", grid_opt.layout()); + TORCH_CHECK( + input.size(0) == grid.size(0), + "grid_sampler(): expected grid and input to have same batch size, but got " + "input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes()); + TORCH_CHECK( + grid.size(-1) == input.dim() - 2, + "grid_sampler(): expected grid to have size ", input.dim() - 2, " in last " + "dimension, but got grid with sizes ", grid.sizes()); + + for (const auto i : c10::irange(2, input.dim())) { + TORCH_CHECK(input.size(i) > 0, + "grid_sampler(): expected input to have non-empty spatial dimensions, " + "but input has sizes ", input.sizes(), " with dimension ", i, " being " + "empty"); + } +} + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_2d( + const TensorBase& input, + const TensorBase& grid +) { + TORCH_CHECK( + input.dim() == 4 && input.dim() == grid.dim(), + "grid_sampler(): expected 4D input and grid with same number of " + "dimensions, but got input with sizes ", input.sizes(), + " and grid with sizes ", grid.sizes()); +} + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_3d( + const TensorBase& input, + const TensorBase& grid, + int64_t interpolation_mode +) { + TORCH_CHECK( + input.dim() == 5 && input.dim() == grid.dim(), + "grid_sampler(): expected 5D input and grid with same number of " + "dimensions, but got input with sizes ", input.sizes(), + " and grid with sizes ", grid.sizes()); + TORCH_CHECK( + !(input.dim() == 5 && + static_cast(interpolation_mode) == + GridSamplerInterpolation::Bicubic), + "grid_sampler(): bicubic interpolation only supports 4D input"); +} + +// See NOTE [ grid_sampler Native Functions ]. +// cudnn does not support inputs larger than 1024. +inline bool cond_cudnn_grid_sampler( + const TensorBase& input, + const TensorBase& grid +) { + return ( + at::native::cudnn_is_acceptable(input) && + at::native::cudnn_is_acceptable(grid) && + at::native::canUse32BitIndexMath(input) && + at::native::canUse32BitIndexMath(grid) && + input.dim() == 4 && + input.sym_size(1) <= 1024); +} + +} // namespace at::native diff --git a/shared/package-files/1f/1f74bba1e2c76889d99ecf64a34e013ce71248e2b63398412bbd6307cd771316/fieldfunctions.py b/shared/package-files/1f/1f74bba1e2c76889d99ecf64a34e013ce71248e2b63398412bbd6307cd771316/fieldfunctions.py new file mode 100644 index 0000000000000000000000000000000000000000..50dd74ff9e5cb4fdf469a0ea5d72d812c8f03f15 --- /dev/null +++ b/shared/package-files/1f/1f74bba1e2c76889d99ecf64a34e013ce71248e2b63398412bbd6307cd771316/fieldfunctions.py @@ -0,0 +1,313 @@ +from sympy.core.function import diff +from sympy.core.singleton import S +from sympy.integrals.integrals import integrate +from sympy.physics.vector import Vector, express +from sympy.physics.vector.frame import _check_frame +from sympy.physics.vector.vector import _check_vector + + +__all__ = ['curl', 'divergence', 'gradient', 'is_conservative', + 'is_solenoidal', 'scalar_potential', + 'scalar_potential_difference'] + + +def curl(vect, frame): + """ + Returns the curl of a vector field computed wrt the coordinate + symbols of the given frame. + + Parameters + ========== + + vect : Vector + The vector operand + + frame : ReferenceFrame + The reference frame to calculate the curl in + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import curl + >>> R = ReferenceFrame('R') + >>> v1 = R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z + >>> curl(v1, R) + 0 + >>> v2 = R[0]*R[1]*R[2]*R.x + >>> curl(v2, R) + R_x*R_y*R.y - R_x*R_z*R.z + + """ + + _check_vector(vect) + if vect == 0: + return Vector(0) + vect = express(vect, frame, variables=True) + # A mechanical approach to avoid looping overheads + vectx = vect.dot(frame.x) + vecty = vect.dot(frame.y) + vectz = vect.dot(frame.z) + outvec = Vector(0) + outvec += (diff(vectz, frame[1]) - diff(vecty, frame[2])) * frame.x + outvec += (diff(vectx, frame[2]) - diff(vectz, frame[0])) * frame.y + outvec += (diff(vecty, frame[0]) - diff(vectx, frame[1])) * frame.z + return outvec + + +def divergence(vect, frame): + """ + Returns the divergence of a vector field computed wrt the coordinate + symbols of the given frame. + + Parameters + ========== + + vect : Vector + The vector operand + + frame : ReferenceFrame + The reference frame to calculate the divergence in + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import divergence + >>> R = ReferenceFrame('R') + >>> v1 = R[0]*R[1]*R[2] * (R.x+R.y+R.z) + >>> divergence(v1, R) + R_x*R_y + R_x*R_z + R_y*R_z + >>> v2 = 2*R[1]*R[2]*R.y + >>> divergence(v2, R) + 2*R_z + + """ + + _check_vector(vect) + if vect == 0: + return S.Zero + vect = express(vect, frame, variables=True) + vectx = vect.dot(frame.x) + vecty = vect.dot(frame.y) + vectz = vect.dot(frame.z) + out = S.Zero + out += diff(vectx, frame[0]) + out += diff(vecty, frame[1]) + out += diff(vectz, frame[2]) + return out + + +def gradient(scalar, frame): + """ + Returns the vector gradient of a scalar field computed wrt the + coordinate symbols of the given frame. + + Parameters + ========== + + scalar : sympifiable + The scalar field to take the gradient of + + frame : ReferenceFrame + The frame to calculate the gradient in + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import gradient + >>> R = ReferenceFrame('R') + >>> s1 = R[0]*R[1]*R[2] + >>> gradient(s1, R) + R_y*R_z*R.x + R_x*R_z*R.y + R_x*R_y*R.z + >>> s2 = 5*R[0]**2*R[2] + >>> gradient(s2, R) + 10*R_x*R_z*R.x + 5*R_x**2*R.z + + """ + + _check_frame(frame) + outvec = Vector(0) + scalar = express(scalar, frame, variables=True) + for i, x in enumerate(frame): + outvec += diff(scalar, frame[i]) * x # noqa: PLR1736 + return outvec + + +def is_conservative(field): + """ + Checks if a field is conservative. + + Parameters + ========== + + field : Vector + The field to check for conservative property + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import is_conservative + >>> R = ReferenceFrame('R') + >>> is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) + True + >>> is_conservative(R[2] * R.y) + False + + """ + + # Field is conservative irrespective of frame + # Take the first frame in the result of the separate method of Vector + if field == Vector(0): + return True + frame = list(field.separate())[0] + return curl(field, frame).simplify() == Vector(0) + + +def is_solenoidal(field): + """ + Checks if a field is solenoidal. + + Parameters + ========== + + field : Vector + The field to check for solenoidal property + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import is_solenoidal + >>> R = ReferenceFrame('R') + >>> is_solenoidal(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) + True + >>> is_solenoidal(R[1] * R.y) + False + + """ + + # Field is solenoidal irrespective of frame + # Take the first frame in the result of the separate method in Vector + if field == Vector(0): + return True + frame = list(field.separate())[0] + return divergence(field, frame).simplify() is S.Zero + + +def scalar_potential(field, frame): + """ + Returns the scalar potential function of a field in a given frame + (without the added integration constant). + + Parameters + ========== + + field : Vector + The vector field whose scalar potential function is to be + calculated + + frame : ReferenceFrame + The frame to do the calculation in + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame + >>> from sympy.physics.vector import scalar_potential, gradient + >>> R = ReferenceFrame('R') + >>> scalar_potential(R.z, R) == R[2] + True + >>> scalar_field = 2*R[0]**2*R[1]*R[2] + >>> grad_field = gradient(scalar_field, R) + >>> scalar_potential(grad_field, R) + 2*R_x**2*R_y*R_z + + """ + + # Check whether field is conservative + if not is_conservative(field): + raise ValueError("Field is not conservative") + if field == Vector(0): + return S.Zero + # Express the field exntirely in frame + # Substitute coordinate variables also + _check_frame(frame) + field = express(field, frame, variables=True) + # Make a list of dimensions of the frame + dimensions = list(frame) + # Calculate scalar potential function + temp_function = integrate(field.dot(dimensions[0]), frame[0]) + for i, dim in enumerate(dimensions[1:]): + partial_diff = diff(temp_function, frame[i + 1]) + partial_diff = field.dot(dim) - partial_diff + temp_function += integrate(partial_diff, frame[i + 1]) + return temp_function + + +def scalar_potential_difference(field, frame, point1, point2, origin): + """ + Returns the scalar potential difference between two points in a + certain frame, wrt a given field. + + If a scalar field is provided, its values at the two points are + considered. If a conservative vector field is provided, the values + of its scalar potential function at the two points are used. + + Returns (potential at position 2) - (potential at position 1) + + Parameters + ========== + + field : Vector/sympyfiable + The field to calculate wrt + + frame : ReferenceFrame + The frame to do the calculations in + + point1 : Point + The initial Point in given frame + + position2 : Point + The second Point in the given frame + + origin : Point + The Point to use as reference point for position vector + calculation + + Examples + ======== + + >>> from sympy.physics.vector import ReferenceFrame, Point + >>> from sympy.physics.vector import scalar_potential_difference + >>> R = ReferenceFrame('R') + >>> O = Point('O') + >>> P = O.locatenew('P', R[0]*R.x + R[1]*R.y + R[2]*R.z) + >>> vectfield = 4*R[0]*R[1]*R.x + 2*R[0]**2*R.y + >>> scalar_potential_difference(vectfield, R, O, P, O) + 2*R_x**2*R_y + >>> Q = O.locatenew('O', 3*R.x + R.y + 2*R.z) + >>> scalar_potential_difference(vectfield, R, P, Q, O) + -2*R_x**2*R_y + 18 + + """ + + _check_frame(frame) + if isinstance(field, Vector): + # Get the scalar potential function + scalar_fn = scalar_potential(field, frame) + else: + # Field is a scalar + scalar_fn = field + # Express positions in required frame + position1 = express(point1.pos_from(origin), frame, variables=True) + position2 = express(point2.pos_from(origin), frame, variables=True) + # Get the two positions as substitution dicts for coordinate variables + subs_dict1 = {} + subs_dict2 = {} + for i, x in enumerate(frame): + subs_dict1[frame[i]] = x.dot(position1) + subs_dict2[frame[i]] = x.dot(position2) + return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1) diff --git a/shared/package-files/1f/1f7a670a1e3c171eef8a7cdfad0be520360b06733b0f632f35562e07a1588411/fake_quantize_per_tensor_affine_ops.h b/shared/package-files/1f/1f7a670a1e3c171eef8a7cdfad0be520360b06733b0f632f35562e07a1588411/fake_quantize_per_tensor_affine_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..aca2f1439b0a9e2cdedbd24352a26dec2b29e07b --- /dev/null +++ b/shared/package-files/1f/1f7a670a1e3c171eef8a7cdfad0be520360b06733b0f632f35562e07a1588411/fake_quantize_per_tensor_affine_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fake_quantize_per_tensor_affine { + using schema = at::Tensor (const at::Tensor &, double, int64_t, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fake_quantize_per_tensor_affine"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "fake_quantize_per_tensor_affine(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> Tensor"; + static at::Tensor call(const at::Tensor & self, double scale, int64_t zero_point, int64_t quant_min, int64_t quant_max); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double scale, int64_t zero_point, int64_t quant_min, int64_t quant_max); +}; + +struct TORCH_API fake_quantize_per_tensor_affine_tensor_qparams { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fake_quantize_per_tensor_affine"; + static constexpr const char* overload_name = "tensor_qparams"; + static constexpr const char* schema_str = "fake_quantize_per_tensor_affine.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t quant_min, int64_t quant_max); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t quant_min, int64_t quant_max); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1f81d181f3487b69e2f9ec44df520ef02049e3c4d7455a9bd5eba55f19112120/test_clip.cpython-311.pyc b/shared/package-files/1f/1f81d181f3487b69e2f9ec44df520ef02049e3c4d7455a9bd5eba55f19112120/test_clip.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b094c892a44bd70ae8f5b4c95e6164ce91eecfa6 Binary files /dev/null and b/shared/package-files/1f/1f81d181f3487b69e2f9ec44df520ef02049e3c4d7455a9bd5eba55f19112120/test_clip.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f83aa2eec5571e13b4c5b70dfc880c0bc9bfef7e117355a2d7d1af7920cd425/comparisons.cpython-311.pyc b/shared/package-files/1f/1f83aa2eec5571e13b4c5b70dfc880c0bc9bfef7e117355a2d7d1af7920cd425/comparisons.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fed183295ae10b64cfb144dbc8fe9f02a9af2562 Binary files /dev/null and b/shared/package-files/1f/1f83aa2eec5571e13b4c5b70dfc880c0bc9bfef7e117355a2d7d1af7920cd425/comparisons.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f86f93dafab7e0901b507b79010a27af8a4cb9ed2c622e2057a054662e785ca/tensor_split_native.h b/shared/package-files/1f/1f86f93dafab7e0901b507b79010a27af8a4cb9ed2c622e2057a054662e785ca/tensor_split_native.h new file mode 100644 index 0000000000000000000000000000000000000000..207ea050e6b2fe7b83c18a7c818b2e042bea2aae --- /dev/null +++ b/shared/package-files/1f/1f86f93dafab7e0901b507b79010a27af8a4cb9ed2c622e2057a054662e785ca/tensor_split_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector tensor_split_sections_symint(const at::Tensor & self, c10::SymInt sections, int64_t dim=0); +TORCH_API ::std::vector tensor_split_indices_symint(const at::Tensor & self, c10::SymIntArrayRef indices, int64_t dim=0); +TORCH_API ::std::vector tensor_split(const at::Tensor & self, const at::Tensor & tensor_indices_or_sections, int64_t dim=0); +} // namespace native +} // namespace at diff --git a/shared/package-files/1f/1f8cedfa8f63ed7718d0296253e0c11bababcb64dfef0aa9974b3556634a328a/radsimp.cpython-311.pyc b/shared/package-files/1f/1f8cedfa8f63ed7718d0296253e0c11bababcb64dfef0aa9974b3556634a328a/radsimp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d42cc9c5577e0e7e9e4d5ab9b23391a1933ac3c Binary files /dev/null and b/shared/package-files/1f/1f8cedfa8f63ed7718d0296253e0c11bababcb64dfef0aa9974b3556634a328a/radsimp.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f8ddfd40d6b47fc225fe337a51014163707a9b57524b392863f74c80f4f2aca/__init__.cpython-311.pyc b/shared/package-files/1f/1f8ddfd40d6b47fc225fe337a51014163707a9b57524b392863f74c80f4f2aca/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d7f8dc32d79a0b73307448c6d751403720e0715 Binary files /dev/null and b/shared/package-files/1f/1f8ddfd40d6b47fc225fe337a51014163707a9b57524b392863f74c80f4f2aca/__init__.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f8f330f0d18325629454f8fc0724db8d5da94f076fc4c5d3b80f2e33241f711/von_mises.cpython-311.pyc b/shared/package-files/1f/1f8f330f0d18325629454f8fc0724db8d5da94f076fc4c5d3b80f2e33241f711/von_mises.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f97e5e427c4df6f268b92220f8a97e24edf5dcf Binary files /dev/null and b/shared/package-files/1f/1f8f330f0d18325629454f8fc0724db8d5da94f076fc4c5d3b80f2e33241f711/von_mises.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f8f6c763381562dc7b49fa52a9011969f1f4cb9abb168133acb20df4f80a3f6/batch_norm_native.h b/shared/package-files/1f/1f8f6c763381562dc7b49fa52a9011969f1f4cb9abb168133acb20df4f80a3f6/batch_norm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..5f71e046985e4917651de5154166089c7b23e515 --- /dev/null +++ b/shared/package-files/1f/1f8f6c763381562dc7b49fa52a9011969f1f4cb9abb168133acb20df4f80a3f6/batch_norm_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor batch_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps, bool cudnn_enabled); +} // namespace native +} // namespace at diff --git a/shared/package-files/1f/1f912c92b590ead8f49e0d5a95126cd9bae29de7d2af303b34389a8941df22db/build_py.cpython-311.pyc b/shared/package-files/1f/1f912c92b590ead8f49e0d5a95126cd9bae29de7d2af303b34389a8941df22db/build_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f76317044b5a3ecdb1401efffc99d8bd158583 Binary files /dev/null and b/shared/package-files/1f/1f912c92b590ead8f49e0d5a95126cd9bae29de7d2af303b34389a8941df22db/build_py.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f95018ac3357fbb0e44aba28fb2cc9fe621262fabf30a262c1f8805a852d6fb/ccompiler.cpython-311.pyc b/shared/package-files/1f/1f95018ac3357fbb0e44aba28fb2cc9fe621262fabf30a262c1f8805a852d6fb/ccompiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7db7007f94826bbfd8b0c765bb285e0b726ca8e6 Binary files /dev/null and b/shared/package-files/1f/1f95018ac3357fbb0e44aba28fb2cc9fe621262fabf30a262c1f8805a852d6fb/ccompiler.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f9b30d13a1266c1f054ebf4d4ec36695027c0935d2f6ad6979c0a34cf6b4acc/conv_utils.cpython-311.pyc b/shared/package-files/1f/1f9b30d13a1266c1f054ebf4d4ec36695027c0935d2f6ad6979c0a34cf6b4acc/conv_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d8e3bdf8706db6580399dc20a5614f0f10010c0 Binary files /dev/null and b/shared/package-files/1f/1f9b30d13a1266c1f054ebf4d4ec36695027c0935d2f6ad6979c0a34cf6b4acc/conv_utils.cpython-311.pyc differ diff --git a/shared/package-files/1f/1f9df45a5a194006aeaa384bf9d78ef6a68563d5d8b4fdc01bdb8c422ae26b02/embedding_renorm_ops.h b/shared/package-files/1f/1f9df45a5a194006aeaa384bf9d78ef6a68563d5d8b4fdc01bdb8c422ae26b02/embedding_renorm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0833edb82c7bd9b37324f742b4860c90758982bd --- /dev/null +++ b/shared/package-files/1f/1f9df45a5a194006aeaa384bf9d78ef6a68563d5d8b4fdc01bdb8c422ae26b02/embedding_renorm_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API embedding_renorm_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::embedding_renorm_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); +}; + +struct TORCH_API embedding_renorm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, double, double, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::embedding_renorm"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "embedding_renorm.out(Tensor self, Tensor indices, float max_norm, float norm_type, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type, at::Tensor & out); +}; + +struct TORCH_API embedding_renorm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, double, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::embedding_renorm"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "embedding_renorm(Tensor self, Tensor indices, float max_norm, float norm_type) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & indices, double max_norm, double norm_type); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1fa1680676ab12e3bb475b1b5fc41af612b88c28eef74476a8debaffed4de948/numpy_nodes.py b/shared/package-files/1f/1fa1680676ab12e3bb475b1b5fc41af612b88c28eef74476a8debaffed4de948/numpy_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c47c87f0e1df74cd314bb70674ebff732fe500aa --- /dev/null +++ b/shared/package-files/1f/1fa1680676ab12e3bb475b1b5fc41af612b88c28eef74476a8debaffed4de948/numpy_nodes.py @@ -0,0 +1,177 @@ +from sympy.core.function import Add, ArgumentIndexError, Function +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import sympify +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.miscellaneous import Max, Min +from .ast import Token, none + + +def _logaddexp(x1, x2, *, evaluate=True): + return log(Add(exp(x1, evaluate=evaluate), exp(x2, evaluate=evaluate), evaluate=evaluate)) + + +_two = S.One*2 +_ln2 = log(_two) + + +def _lb(x, *, evaluate=True): + return log(x, evaluate=evaluate)/_ln2 + + +def _exp2(x, *, evaluate=True): + return Pow(_two, x, evaluate=evaluate) + + +def _logaddexp2(x1, x2, *, evaluate=True): + return _lb(Add(_exp2(x1, evaluate=evaluate), + _exp2(x2, evaluate=evaluate), evaluate=evaluate)) + + +class logaddexp(Function): + """ Logarithm of the sum of exponentiations of the inputs. + + Helper class for use with e.g. numpy.logaddexp + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + """ + nargs = 2 + + def __new__(cls, *args): + return Function.__new__(cls, *sorted(args, key=default_sort_key)) + + def fdiff(self, argindex=1): + """ + Returns the first derivative of this function. + """ + if argindex == 1: + wrt, other = self.args + elif argindex == 2: + other, wrt = self.args + else: + raise ArgumentIndexError(self, argindex) + return S.One/(S.One + exp(other-wrt)) + + def _eval_rewrite_as_log(self, x1, x2, **kwargs): + return _logaddexp(x1, x2) + + def _eval_evalf(self, *args, **kwargs): + return self.rewrite(log).evalf(*args, **kwargs) + + def _eval_simplify(self, *args, **kwargs): + a, b = (x.simplify(**kwargs) for x in self.args) + candidate = _logaddexp(a, b) + if candidate != _logaddexp(a, b, evaluate=False): + return candidate + else: + return logaddexp(a, b) + + +class logaddexp2(Function): + """ Logarithm of the sum of exponentiations of the inputs in base-2. + + Helper class for use with e.g. numpy.logaddexp2 + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.logaddexp2.html + """ + nargs = 2 + + def __new__(cls, *args): + return Function.__new__(cls, *sorted(args, key=default_sort_key)) + + def fdiff(self, argindex=1): + """ + Returns the first derivative of this function. + """ + if argindex == 1: + wrt, other = self.args + elif argindex == 2: + other, wrt = self.args + else: + raise ArgumentIndexError(self, argindex) + return S.One/(S.One + _exp2(other-wrt)) + + def _eval_rewrite_as_log(self, x1, x2, **kwargs): + return _logaddexp2(x1, x2) + + def _eval_evalf(self, *args, **kwargs): + return self.rewrite(log).evalf(*args, **kwargs) + + def _eval_simplify(self, *args, **kwargs): + a, b = (x.simplify(**kwargs).factor() for x in self.args) + candidate = _logaddexp2(a, b) + if candidate != _logaddexp2(a, b, evaluate=False): + return candidate + else: + return logaddexp2(a, b) + + +class amin(Token): + """ Minimum value along an axis. + + Helper class for use with e.g. numpy.amin + + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.amin.html + """ + __slots__ = _fields = ('array', 'axis') + defaults = {'axis': none} + _construct_axis = staticmethod(sympify) + + +class amax(Token): + """ Maximum value along an axis. + + Helper class for use with e.g. numpy.amax + + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.amax.html + """ + __slots__ = _fields = ('array', 'axis') + defaults = {'axis': none} + _construct_axis = staticmethod(sympify) + + +class maximum(Function): + """ Element-wise maximum of array elements. + + Helper class for use with e.g. numpy.maximum + + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.maximum.html + """ + + def _eval_rewrite_as_Max(self, *args): + return Max(*self.args) + + +class minimum(Function): + """ Element-wise minimum of array elements. + + Helper class for use with e.g. numpy.minimum + + + See Also + ======== + + https://numpy.org/doc/stable/reference/generated/numpy.minimum.html + """ + + def _eval_rewrite_as_Min(self, *args): + return Min(*self.args) diff --git a/shared/package-files/1f/1fa4d3951ee75c014968a6bb6d5d1c1697a12ea98e7cfe92da1ead01023b7848/moments_utils.h b/shared/package-files/1f/1fa4d3951ee75c014968a6bb6d5d1c1697a12ea98e7cfe92da1ead01023b7848/moments_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6f403d60ea7c09849e1ea9d48625532aa51117c3 --- /dev/null +++ b/shared/package-files/1f/1fa4d3951ee75c014968a6bb6d5d1c1697a12ea98e7cfe92da1ead01023b7848/moments_utils.h @@ -0,0 +1,202 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +template using opmath_t = at::opmath_type; + +constexpr int64_t kChunkSize = 16; + +template +void AddMoments( + int64_t m0_add, + const T& m1_add, + const T& m2_add, + int64_t& m0, + T& m1, + T& m2) { + const int64_t n = m0 + m0_add; + const T c = n == 0 ? static_cast(0) : static_cast(m0_add) / static_cast(n); + const T delta = m1_add - m1; + m1 += c * delta; + m2 += m2_add + delta * delta * c * static_cast(m0); + m0 = n; +} + +template +C10_ALWAYS_INLINE void AddMomentsVec( + int64_t m0_add, + const vec::Vectorized& m1_add, + const vec::Vectorized& m2_add, + int64_t& m0, + vec::Vectorized& m1, + vec::Vectorized& m2) { + using Vec = vec::Vectorized; + const int64_t n = m0 + m0_add; + const T c = n == 0 ? static_cast(0) : static_cast(m0_add) / static_cast(n); + const Vec c_vec(c); + const Vec delta = m1_add - m1; + m1 += c_vec * delta; + m2 += m2_add + delta * delta * c_vec * Vec(static_cast(m0)); + m0 = n; +} + +template +inline std::enable_if_t>, void> +UpdateMomentsVec( + int64_t m0, + const T* X_ptr, + const std::array>, kChunkSize>& c_vecs, + int64_t& m0_stk0, + vec::Vectorized>& m1_stk0, + vec::Vectorized>& m2_stk0) { + using Vec = vec::Vectorized>; + Vec m1_vec(0); + Vec m2_vec(0); + for (const auto j : c10::irange(m0)) { + const Vec x_vec = Vec::loadu(X_ptr + j * Vec::size()); + const Vec delta_vec = x_vec - m1_vec; + m1_vec += delta_vec * c_vecs[j]; + m2_vec += delta_vec * (x_vec - m1_vec); + } + AddMomentsVec(m0, m1_vec, m2_vec, m0_stk0, m1_stk0, m2_stk0); +} + +// each bfloat16/half vector will be converted to two float vectors, +// and accumulated successively on m1_stk0/m2_stk0. +template +inline std::enable_if_t>, void> +UpdateMomentsVec( + int64_t m0, + const T* X_ptr, + const std::array>, kChunkSize>& c_vecs, + int64_t& m0_stk0, + vec::Vectorized>& m1_stk0, + vec::Vectorized>& m2_stk0) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized>; + fVec m1_fvec0(0), m1_fvec1(0); + fVec m2_fvec0(0), m2_fvec1(0); + for (const auto j : c10::irange(m0)) { + const Vec x_bvec = Vec::loadu(X_ptr + j * Vec::size()); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + const fVec delta_fvec0 = x_fvec0 - m1_fvec0; + const fVec delta_fvec1 = x_fvec1 - m1_fvec1; + m1_fvec0 += delta_fvec0 * c_vecs[j]; + m1_fvec1 += delta_fvec1 * c_vecs[j]; + m2_fvec0 += delta_fvec0 * (x_fvec0 - m1_fvec0); + m2_fvec1 += delta_fvec1 * (x_fvec1 - m1_fvec1); + } + AddMomentsVec(m0, m1_fvec0, m2_fvec0, m0_stk0, m1_stk0, m2_stk0); + AddMomentsVec(m0, m1_fvec1, m2_fvec1, m0_stk0, m1_stk0, m2_stk0); +} + +// Compute rowwise moments by Welford algorithm and cascade sum to improve +// numerical stability. +// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance +// https://en.wikipedia.org/wiki/Pairwise_summation +template +std::pair, opmath_t> RowwiseMomentsImpl(const T* X, int64_t N, int64_t ddof = 0) { + using math_t = opmath_t; + + constexpr int64_t kVecSize = vec::Vectorized::size(); + constexpr int64_t kAccVecSize = vec::Vectorized::size(); + const int64_t n = N / kVecSize; + const int64_t m = divup(n, kChunkSize); + const int64_t depth = utils::CeilLog2(m); + + using Vec = vec::Vectorized; + const Vec kZeroVec(math_t(0)); + c10::SmallVector m0_stk(depth, 0); + c10::SmallVector m1_stk(depth, kZeroVec); + c10::SmallVector m2_stk(depth, kZeroVec); + + for (const auto i : c10::irange(m)) { + const T* X_ptr = X + i * kChunkSize * kVecSize; + const int64_t m0 = std::min(kChunkSize, n - i * kChunkSize); + static std::array c_vecs = ([]() { + std::array result; + for (const auto i : c10::irange(kChunkSize)) { + result[i] = Vec(math_t(1) / static_cast(i + 1)); + } + return result; + })(); + UpdateMomentsVec(m0, X_ptr, c_vecs, m0_stk[0], m1_stk[0], m2_stk[0]); + + int64_t mask = i + 1; + for (int64_t j = 1; j < depth && (mask & 1) == 0; ++j) { + AddMomentsVec( + m0_stk[j - 1], + m1_stk[j - 1], + m2_stk[j - 1], + m0_stk[j], + m1_stk[j], + m2_stk[j]); + m0_stk[j - 1] = 0; + m1_stk[j - 1] = kZeroVec; + m2_stk[j - 1] = kZeroVec; + mask >>= 1; + } + } + for (const auto i : c10::irange(1, depth)) { + AddMomentsVec( + m0_stk[i], m1_stk[i], m2_stk[i], m0_stk[0], m1_stk[0], m2_stk[0]); + } + + std::array m1_arr{}; + std::array m2_arr{}; + m1_stk[0].store(m1_arr.data()); + m2_stk[0].store(m2_arr.data()); + + int64_t m0 = 0; + math_t m1 = 0; + math_t m2 = 0; + for (int64_t i = n * kVecSize; i < N; ++i) { + math_t x = static_cast(X[i]); + const math_t delta = x - m1; + ++m0; + m1 += delta / static_cast(m0); + m2 += delta * (x - m1); + } + // for BFloat16, each vector in m1_arr/m2_arr holds 2*n accumulated result + int64_t m0_add = n * kVecSize / kAccVecSize; + for (const auto i : c10::irange(kAccVecSize)) { + AddMoments(m0_add, m1_arr[i], m2_arr[i], m0, m1, m2); + } + + return std::make_pair(m1, m2 / static_cast(N - ddof)); +} + +template +std::pair, opmath_t> RowwiseMoments(const T* X, int64_t N, int64_t ddof = 0) { + using Vec = vec::Vectorized; + constexpr int64_t kVecSize = Vec::size(); + const int64_t n = N / kVecSize; + const int64_t m = divup(n, kChunkSize); + const int64_t depth = utils::CeilLog2(m); + if (depth <= 4) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 8) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 16) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 32) { + return RowwiseMomentsImpl(X, N, ddof); + } else { + return RowwiseMomentsImpl(X, N, ddof); + } +} + +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/shared/package-files/1f/1fa8afc81549d24302bdb1c28f5694db3ab0078d860d0150c7a2432dc40d260d/cp1253.cpython-311.pyc b/shared/package-files/1f/1fa8afc81549d24302bdb1c28f5694db3ab0078d860d0150c7a2432dc40d260d/cp1253.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b62dad2fdafcb178ee6b890ba6ce935939a970f0 Binary files /dev/null and b/shared/package-files/1f/1fa8afc81549d24302bdb1c28f5694db3ab0078d860d0150c7a2432dc40d260d/cp1253.cpython-311.pyc differ diff --git a/shared/package-files/1f/1faab361ec1219ba5e90c697965ab4127d0825911381343c7773a6bd661cf9c2/test_set_value.cpython-311.pyc b/shared/package-files/1f/1faab361ec1219ba5e90c697965ab4127d0825911381343c7773a6bd661cf9c2/test_set_value.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e177c6a59d082821adef903b6d805d9a2b24fe82 Binary files /dev/null and b/shared/package-files/1f/1faab361ec1219ba5e90c697965ab4127d0825911381343c7773a6bd661cf9c2/test_set_value.cpython-311.pyc differ diff --git a/shared/package-files/1f/1facdc4ac393ebc73095a7d980a84e25c56de19f020da3deaf4fccd434c0f84a/__init__.cpython-311.pyc b/shared/package-files/1f/1facdc4ac393ebc73095a7d980a84e25c56de19f020da3deaf4fccd434c0f84a/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a704adddef018dc6a26e1144b2f62606b29fe4ab Binary files /dev/null and b/shared/package-files/1f/1facdc4ac393ebc73095a7d980a84e25c56de19f020da3deaf4fccd434c0f84a/__init__.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fb02e6bce93245ce43a8e772d3bb8499b11a403c3f587f7a8e196798129746d/CUDAGraphsUtils.cuh b/shared/package-files/1f/1fb02e6bce93245ce43a8e772d3bb8499b11a403c3f587f7a8e196798129746d/CUDAGraphsUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d3a5b306eeea49b47d45ae5f28944b6dfd8ac4dc --- /dev/null +++ b/shared/package-files/1f/1fb02e6bce93245ce43a8e772d3bb8499b11a403c3f587f7a8e196798129746d/CUDAGraphsUtils.cuh @@ -0,0 +1,53 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +// c10/cuda/CUDAGraphsC10Utils.h has utils used by both c10 and aten. +// This file adds utils used by aten only. + +namespace at::cuda { + +using CaptureId_t = c10::cuda::CaptureId_t; +using CaptureStatus = c10::cuda::CaptureStatus; + +// Use this version where you don't want to create a CUDA context if none exists. +inline CaptureStatus currentStreamCaptureStatus() { + // don't create a context if we don't have to + if (c10::cuda::hasPrimaryContext(c10::cuda::current_device())) { + return c10::cuda::currentStreamCaptureStatusMayInitCtx(); + } else { + return CaptureStatus::None; + } +} + +inline void assertNotCapturing(const std::string& attempt) { + auto status = currentStreamCaptureStatus(); + TORCH_CHECK(status == CaptureStatus::None, + attempt, + " during CUDA graph capture. If you need this call to be captured, " + "please file an issue. " + "Current cudaStreamCaptureStatus: ", + status); +} + +inline void errorIfCapturingCudnnBenchmark(const std::string& version_specific) { + auto status = currentStreamCaptureStatus(); + TORCH_CHECK(status == CaptureStatus::None, + "Current cudaStreamCaptureStatus: ", + status, + "\nCapturing ", + version_specific, + "is prohibited. Possible causes of this error:\n" + "1. No warmup iterations occurred before capture.\n" + "2. The convolutions you're trying to capture use dynamic shapes, " + "in which case capturing them is generally prohibited."); +} + +} // namespace at::cuda diff --git a/shared/package-files/1f/1fb1c78c08a40985ca435978e5d44a19458dd658140d0ddfb2b76bd10a7701e8/__init__.cpython-311.pyc b/shared/package-files/1f/1fb1c78c08a40985ca435978e5d44a19458dd658140d0ddfb2b76bd10a7701e8/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c776d0f0b02884db5bd5327aff71e6b3b9edcbec Binary files /dev/null and b/shared/package-files/1f/1fb1c78c08a40985ca435978e5d44a19458dd658140d0ddfb2b76bd10a7701e8/__init__.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fb3045f5db9f5a56b58cb20b165f6eadb8210f48917e888e75277b0ab1879cd/filesystem.h b/shared/package-files/1f/1fb3045f5db9f5a56b58cb20b165f6eadb8210f48917e888e75277b0ab1879cd/filesystem.h new file mode 100644 index 0000000000000000000000000000000000000000..d4f62f86a7482b5ab38cc118c249cfc4911c0fad --- /dev/null +++ b/shared/package-files/1f/1fb3045f5db9f5a56b58cb20b165f6eadb8210f48917e888e75277b0ab1879cd/filesystem.h @@ -0,0 +1,723 @@ +// 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. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/filesystem/type_fwd.h" +#include "arrow/io/interfaces.h" +#include "arrow/type_fwd.h" +#include "arrow/util/compare.h" +#include "arrow/util/macros.h" +#include "arrow/util/type_fwd.h" +#include "arrow/util/visibility.h" +#include "arrow/util/windows_fixup.h" + +namespace arrow { +namespace fs { + +using arrow::util::Uri; + +// A system clock time point expressed as a 64-bit (or more) number of +// nanoseconds since the epoch. +using TimePoint = + std::chrono::time_point; + +ARROW_EXPORT std::string ToString(FileType); + +ARROW_EXPORT std::ostream& operator<<(std::ostream& os, FileType); + +static const int64_t kNoSize = -1; +static const TimePoint kNoTime = TimePoint(TimePoint::duration(-1)); + +/// \brief FileSystem entry info +struct ARROW_EXPORT FileInfo : public util::EqualityComparable { + FileInfo() = default; + FileInfo(FileInfo&&) = default; + FileInfo& operator=(FileInfo&&) = default; + FileInfo(const FileInfo&) = default; + FileInfo& operator=(const FileInfo&) = default; + + explicit FileInfo(std::string path, FileType type = FileType::Unknown) + : path_(std::move(path)), type_(type) {} + + /// The file type + FileType type() const { return type_; } + void set_type(FileType type) { type_ = type; } + + /// The full file path in the filesystem + const std::string& path() const { return path_; } + void set_path(std::string path) { path_ = std::move(path); } + + /// The file base name (component after the last directory separator) + std::string base_name() const; + + // The directory base name (component before the file base name). + std::string dir_name() const; + + /// The size in bytes, if available + /// + /// Only regular files are guaranteed to have a size. + int64_t size() const { return size_; } + void set_size(int64_t size) { size_ = size; } + + /// The file extension (excluding the dot) + std::string extension() const; + + /// The time of last modification, if available + TimePoint mtime() const { return mtime_; } + void set_mtime(TimePoint mtime) { mtime_ = mtime; } + + bool IsFile() const { return type_ == FileType::File; } + bool IsDirectory() const { return type_ == FileType::Directory; } + + bool Equals(const FileInfo& other) const { + return type() == other.type() && path() == other.path() && size() == other.size() && + mtime() == other.mtime(); + } + + std::string ToString() const; + + /// Function object implementing less-than comparison and hashing by + /// path, to support sorting infos, using them as keys, and other + /// interactions with the STL. + struct ByPath { + bool operator()(const FileInfo& l, const FileInfo& r) const { + return l.path() < r.path(); + } + + size_t operator()(const FileInfo& i) const { + return std::hash{}(i.path()); + } + }; + + protected: + std::string path_; + FileType type_ = FileType::Unknown; + int64_t size_ = kNoSize; + TimePoint mtime_ = kNoTime; +}; + +ARROW_EXPORT std::ostream& operator<<(std::ostream& os, const FileInfo&); + +/// \brief File selector for filesystem APIs +struct ARROW_EXPORT FileSelector { + /// The directory in which to select files. + /// If the path exists but doesn't point to a directory, this should be an error. + std::string base_dir; + /// The behavior if `base_dir` isn't found in the filesystem. If false, + /// an error is returned. If true, an empty selection is returned. + bool allow_not_found; + /// Whether to recurse into subdirectories. + bool recursive; + /// The maximum number of subdirectories to recurse into. + int32_t max_recursion; + + FileSelector() : allow_not_found(false), recursive(false), max_recursion(INT32_MAX) {} +}; + +/// \brief FileSystem, path pair +struct ARROW_EXPORT FileLocator { + std::shared_ptr filesystem; + std::string path; +}; + +using FileInfoVector = std::vector; +using FileInfoGenerator = std::function()>; + +} // namespace fs + +template <> +struct IterationTraits { + static fs::FileInfoVector End() { return {}; } + static bool IsEnd(const fs::FileInfoVector& val) { return val.empty(); } +}; + +namespace fs { + +/// \brief Abstract file system API +class ARROW_EXPORT FileSystem + /// \cond false + : public std::enable_shared_from_this +/// \endcond +{ // NOLINT + public: + virtual ~FileSystem(); + + virtual std::string type_name() const = 0; + + /// EXPERIMENTAL: The IOContext associated with this filesystem. + const io::IOContext& io_context() const { return io_context_; } + + /// Normalize path for the given filesystem + /// + /// The default implementation of this method is a no-op, but subclasses + /// may allow normalizing irregular path forms (such as Windows local paths). + virtual Result NormalizePath(std::string path); + + /// \brief Ensure a URI (or path) is compatible with the given filesystem and return the + /// path + /// + /// \param uri_string A URI representing a resource in the given filesystem. + /// + /// This method will check to ensure the given filesystem is compatible with the + /// URI. This can be useful when the user provides both a URI and a filesystem or + /// when a user provides multiple URIs that should be compatible with the same + /// filesystem. + /// + /// uri_string can be an absolute path instead of a URI. In that case it will ensure + /// the filesystem (if supplied) is the local filesystem (or some custom filesystem that + /// is capable of reading local paths) and will normalize the path's file separators. + /// + /// Note, this method only checks to ensure the URI scheme is valid. It will not detect + /// inconsistencies like a mismatching region or endpoint override. + /// + /// \return The path inside the filesystem that is indicated by the URI. + virtual Result PathFromUri(const std::string& uri_string) const; + + /// \brief Make a URI from which FileSystemFromUri produces an equivalent filesystem + /// \param path The path component to use in the resulting URI + /// \return A URI string, or an error if an equivalent URI cannot be produced + virtual Result MakeUri(std::string path) const; + + virtual bool Equals(const FileSystem& other) const = 0; + + virtual bool Equals(const std::shared_ptr& other) const { + return Equals(*other); + } + + /// Get info for the given target. + /// + /// Any symlink is automatically dereferenced, recursively. + /// A nonexistent or unreachable file returns an Ok status and + /// has a FileType of value NotFound. An error status indicates + /// a truly exceptional condition (low-level I/O error, etc.). + virtual Result GetFileInfo(const std::string& path) = 0; + /// Same, for many targets at once. + virtual Result GetFileInfo(const std::vector& paths); + /// Same, according to a selector. + /// + /// The selector's base directory will not be part of the results, even if + /// it exists. + /// If it doesn't exist, see `FileSelector::allow_not_found`. + virtual Result GetFileInfo(const FileSelector& select) = 0; + + /// Async version of GetFileInfo + virtual Future GetFileInfoAsync(const std::vector& paths); + + /// Streaming async version of GetFileInfo + /// + /// The returned generator is not async-reentrant, i.e. you need to wait for + /// the returned future to complete before calling the generator again. + virtual FileInfoGenerator GetFileInfoGenerator(const FileSelector& select); + + /// Create a directory and subdirectories. + /// + /// This function succeeds if the directory already exists. + virtual Status CreateDir(const std::string& path, bool recursive) = 0; + Status CreateDir(const std::string& path) { return CreateDir(path, true); } + + /// Delete a directory and its contents, recursively. + virtual Status DeleteDir(const std::string& path) = 0; + + /// Delete a directory's contents, recursively. + /// + /// Like DeleteDir, but doesn't delete the directory itself. + /// Passing an empty path ("" or "/") is disallowed, see DeleteRootDirContents. + virtual Status DeleteDirContents(const std::string& path, bool missing_dir_ok) = 0; + Status DeleteDirContents(const std::string& path) { + return DeleteDirContents(path, false); + } + + /// Async version of DeleteDirContents. + virtual Future<> DeleteDirContentsAsync(const std::string& path, bool missing_dir_ok); + + /// Async version of DeleteDirContents. + /// + /// This overload allows missing directories. + Future<> DeleteDirContentsAsync(const std::string& path); + + /// EXPERIMENTAL: Delete the root directory's contents, recursively. + /// + /// Implementations may decide to raise an error if this operation is + /// too dangerous. + // NOTE: may decide to remove this if it's deemed not useful + virtual Status DeleteRootDirContents() = 0; + + /// Delete a file. + virtual Status DeleteFile(const std::string& path) = 0; + /// Delete many files. + /// + /// The default implementation issues individual delete operations in sequence. + virtual Status DeleteFiles(const std::vector& paths); + + /// Move / rename a file or directory. + /// + /// If the destination exists: + /// - if it is a non-empty directory, an error is returned + /// - otherwise, if it has the same type as the source, it is replaced + /// - otherwise, behavior is unspecified (implementation-dependent). + virtual Status Move(const std::string& src, const std::string& dest) = 0; + + /// Copy a file. + /// + /// If the destination exists and is a directory, an error is returned. + /// Otherwise, it is replaced. + virtual Status CopyFile(const std::string& src, const std::string& dest) = 0; + + /// Open an input stream for sequential reading. + virtual Result> OpenInputStream( + const std::string& path) = 0; + + /// Open an input stream for sequential reading. + /// + /// This override assumes the given FileInfo validly represents the file's + /// characteristics, and may optimize access depending on them (for example + /// avoid querying the file size or its existence). + virtual Result> OpenInputStream(const FileInfo& info); + + /// Open an input file for random access reading. + virtual Result> OpenInputFile( + const std::string& path) = 0; + + /// Open an input file for random access reading. + /// + /// This override assumes the given FileInfo validly represents the file's + /// characteristics, and may optimize access depending on them (for example + /// avoid querying the file size or its existence). + virtual Result> OpenInputFile( + const FileInfo& info); + + /// Async version of OpenInputStream + virtual Future> OpenInputStreamAsync( + const std::string& path); + + /// Async version of OpenInputStream + virtual Future> OpenInputStreamAsync( + const FileInfo& info); + + /// Async version of OpenInputFile + virtual Future> OpenInputFileAsync( + const std::string& path); + + /// Async version of OpenInputFile + virtual Future> OpenInputFileAsync( + const FileInfo& info); + + /// Open an output stream for sequential writing. + /// + /// If the target already exists, existing data is truncated. + virtual Result> OpenOutputStream( + const std::string& path, + const std::shared_ptr& metadata) = 0; + Result> OpenOutputStream(const std::string& path); + + /// Open an output stream for appending. + /// + /// If the target doesn't exist, a new empty file is created. + /// + /// Note: some filesystem implementations do not support efficient appending + /// to an existing file, in which case this method will return NotImplemented. + /// Consider writing to multiple files (using e.g. the dataset layer) instead. + virtual Result> OpenAppendStream( + const std::string& path, + const std::shared_ptr& metadata) = 0; + Result> OpenAppendStream(const std::string& path); + + protected: + explicit FileSystem(io::IOContext io_context = io::default_io_context()) + : io_context_(std::move(io_context)) {} + + io::IOContext io_context_; + // Whether metadata operations (such as GetFileInfo or OpenInputStream) + // are cheap enough that the default async variants don't bother with + // a thread pool. + bool default_async_is_sync_ = true; +}; + +struct FileSystemFactory { + std::function>( + const Uri& uri, const io::IOContext& io_context, std::string* out_path)> + function; + std::string_view file; + int line; + + bool operator==(const FileSystemFactory& other) const { + // In the case where libarrow is linked statically both to the executable and to a + // dynamically loaded filesystem implementation library, the library contains a + // duplicate definition of the registry and duplicate definitions of any + // FileSystemRegistrars which are statically linked to libarrow. When retrieving + // factories from the filesystem implementation library, we use the file and line + // of the registrar's definition to determine equivalence of the duplicate factories. + return file == other.file && line == other.line; + } +}; + +/// \brief A FileSystem implementation that delegates to another +/// implementation after prepending a fixed base path. +/// +/// This is useful to expose a logical view of a subtree of a filesystem, +/// for example a directory in a LocalFileSystem. +/// This works on abstract paths, i.e. paths using forward slashes and +/// and a single root "/". Windows paths are not guaranteed to work. +/// This makes no security guarantee. For example, symlinks may allow to +/// "escape" the subtree and access other parts of the underlying filesystem. +class ARROW_EXPORT SubTreeFileSystem : public FileSystem { + public: + // This constructor may abort if base_path is invalid. + explicit SubTreeFileSystem(const std::string& base_path, + std::shared_ptr base_fs); + ~SubTreeFileSystem() override; + + std::string type_name() const override { return "subtree"; } + std::string base_path() const { return base_path_; } + std::shared_ptr base_fs() const { return base_fs_; } + + Result NormalizePath(std::string path) override; + Result PathFromUri(const std::string& uri_string) const override; + + bool Equals(const FileSystem& other) const override; + + /// \cond FALSE + using FileSystem::CreateDir; + using FileSystem::DeleteDirContents; + using FileSystem::GetFileInfo; + using FileSystem::OpenAppendStream; + using FileSystem::OpenOutputStream; + /// \endcond + + Result GetFileInfo(const std::string& path) override; + Result GetFileInfo(const FileSelector& select) override; + + FileInfoGenerator GetFileInfoGenerator(const FileSelector& select) override; + + Status CreateDir(const std::string& path, bool recursive) override; + + Status DeleteDir(const std::string& path) override; + Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override; + Status DeleteRootDirContents() override; + + Status DeleteFile(const std::string& path) override; + + Status Move(const std::string& src, const std::string& dest) override; + + Status CopyFile(const std::string& src, const std::string& dest) override; + + Result> OpenInputStream( + const std::string& path) override; + Result> OpenInputStream(const FileInfo& info) override; + Result> OpenInputFile( + const std::string& path) override; + Result> OpenInputFile( + const FileInfo& info) override; + + Future> OpenInputStreamAsync( + const std::string& path) override; + Future> OpenInputStreamAsync( + const FileInfo& info) override; + Future> OpenInputFileAsync( + const std::string& path) override; + Future> OpenInputFileAsync( + const FileInfo& info) override; + + Result> OpenOutputStream( + const std::string& path, + const std::shared_ptr& metadata) override; + Result> OpenAppendStream( + const std::string& path, + const std::shared_ptr& metadata) override; + + protected: + SubTreeFileSystem() = default; + + const std::string base_path_; + std::shared_ptr base_fs_; + + Result PrependBase(const std::string& s) const; + Result PrependBaseNonEmpty(const std::string& s) const; + Result StripBase(const std::string& s) const; + Status FixInfo(FileInfo* info) const; + + static Result NormalizeBasePath( + std::string base_path, const std::shared_ptr& base_fs); +}; + +/// \brief A FileSystem implementation that delegates to another +/// implementation but inserts latencies at various points. +class ARROW_EXPORT SlowFileSystem : public FileSystem { + public: + SlowFileSystem(std::shared_ptr base_fs, + std::shared_ptr latencies); + SlowFileSystem(std::shared_ptr base_fs, double average_latency); + SlowFileSystem(std::shared_ptr base_fs, double average_latency, + int32_t seed); + + std::string type_name() const override { return "slow"; } + bool Equals(const FileSystem& other) const override; + Result PathFromUri(const std::string& uri_string) const override; + + /// \cond FALSE + using FileSystem::CreateDir; + using FileSystem::DeleteDirContents; + using FileSystem::GetFileInfo; + using FileSystem::OpenAppendStream; + using FileSystem::OpenOutputStream; + /// \endcond + + Result GetFileInfo(const std::string& path) override; + Result GetFileInfo(const FileSelector& select) override; + + Status CreateDir(const std::string& path, bool recursive) override; + + Status DeleteDir(const std::string& path) override; + Status DeleteDirContents(const std::string& path, bool missing_dir_ok) override; + Status DeleteRootDirContents() override; + + Status DeleteFile(const std::string& path) override; + + Status Move(const std::string& src, const std::string& dest) override; + + Status CopyFile(const std::string& src, const std::string& dest) override; + + Result> OpenInputStream( + const std::string& path) override; + Result> OpenInputStream(const FileInfo& info) override; + Result> OpenInputFile( + const std::string& path) override; + Result> OpenInputFile( + const FileInfo& info) override; + Result> OpenOutputStream( + const std::string& path, + const std::shared_ptr& metadata) override; + Result> OpenAppendStream( + const std::string& path, + const std::shared_ptr& metadata) override; + + protected: + std::shared_ptr base_fs_; + std::shared_ptr latencies_; +}; + +/// \brief Ensure all registered filesystem implementations are finalized. +/// +/// Individual finalizers may wait for concurrent calls to finish so as to avoid +/// race conditions. After this function has been called, all filesystem APIs +/// will fail with an error. +/// +/// The user is responsible for synchronization of calls to this function. +void EnsureFinalized(); + +/// \defgroup filesystem-factories Functions for creating FileSystem instances +/// +/// @{ + +/// \brief Create a new FileSystem by URI +/// +/// Recognized schemes are "file", "mock", "hdfs", "viewfs", "s3", +/// "gs" and "gcs". +/// +/// Support for other schemes can be added using RegisterFileSystemFactory. +/// +/// \param[in] uri a URI-based path, ex: file:///some/local/path +/// \param[out] out_path (optional) Path inside the filesystem. +/// \return out_fs FileSystem instance. +ARROW_EXPORT +Result> FileSystemFromUri(const std::string& uri, + std::string* out_path = NULLPTR); + +/// \brief Create a new FileSystem by URI with a custom IO context +/// +/// Recognized schemes are "file", "mock", "hdfs", "viewfs", "s3", +/// "gs" and "gcs". +/// +/// Support for other schemes can be added using RegisterFileSystemFactory. +/// +/// \param[in] uri a URI-based path, ex: file:///some/local/path +/// \param[in] io_context an IOContext which will be associated with the filesystem +/// \param[out] out_path (optional) Path inside the filesystem. +/// \return out_fs FileSystem instance. +ARROW_EXPORT +Result> FileSystemFromUri(const std::string& uri, + const io::IOContext& io_context, + std::string* out_path = NULLPTR); + +/// \brief Create a new FileSystem by URI +/// +/// Support for other schemes can be added using RegisterFileSystemFactory. +/// +/// Same as FileSystemFromUri, but in addition also recognize non-URIs +/// and treat them as local filesystem paths. Only absolute local filesystem +/// paths are allowed. +ARROW_EXPORT +Result> FileSystemFromUriOrPath( + const std::string& uri, std::string* out_path = NULLPTR); + +/// \brief Create a new FileSystem by URI with a custom IO context +/// +/// Support for other schemes can be added using RegisterFileSystemFactory. +/// +/// Same as FileSystemFromUri, but in addition also recognize non-URIs +/// and treat them as local filesystem paths. Only absolute local filesystem +/// paths are allowed. +ARROW_EXPORT +Result> FileSystemFromUriOrPath( + const std::string& uri, const io::IOContext& io_context, + std::string* out_path = NULLPTR); + +/// @} + +/// \defgroup filesystem-factory-registration Helpers for FileSystem registration +/// +/// @{ + +/// \brief Register a FileSystem factory +/// +/// Support for custom URI schemes can be added by registering a factory +/// for the corresponding FileSystem. +/// +/// \param[in] scheme a Uri scheme which the factory will handle. +/// If a factory has already been registered for a scheme, +/// the new factory will be ignored. +/// \param[in] factory a function which can produce a FileSystem for Uris which match +/// scheme. +/// \param[in] finalizer a function which must be called to finalize the factory before +/// the process exits, or nullptr if no finalization is necessary. +/// \return raises KeyError if a name collision occurs. +ARROW_EXPORT Status RegisterFileSystemFactory(std::string scheme, + FileSystemFactory factory, + std::function finalizer = {}); + +/// \brief Register FileSystem factories from a shared library +/// +/// FileSystem implementations may be housed in separate shared libraries and only +/// registered when the shared library is explicitly loaded. FileSystemRegistrar is +/// provided to simplify definition of such libraries: each instance at namespace scope +/// in the library will register a factory for a scheme. Any library which uses +/// FileSystemRegistrars and which must be dynamically loaded should be loaded using +/// LoadFileSystemFactories(), which will additionally merge registries are if necessary +/// (static linkage to arrow can produce isolated registries). +ARROW_EXPORT Status LoadFileSystemFactories(const char* libpath); + +struct ARROW_EXPORT FileSystemRegistrar { + /// \brief Register a FileSystem factory at load time + /// + /// Support for custom URI schemes can be added by registering a factory for the + /// corresponding FileSystem. An instance of this helper can be defined at namespace + /// scope to cause the factory to be registered at load time. + /// + /// Global constructors will finish execution before main() starts if the registrar is + /// linked into the same binary as main(), or before dlopen()/LoadLibrary() returns if + /// the library in which the registrar is defined is dynamically loaded. + /// + /// \code + /// FileSystemRegistrar kSlowFileSystemModule{ + /// "slowfile", + /// [](const Uri& uri, const io::IOContext& io_context, std::string* out_path) + /// ->Result> { + /// auto local_uri = "file" + uri.ToString().substr(uri.scheme().size()); + /// ARROW_ASSIGN_OR_RAISE(auto base_fs, + /// FileSystemFromUri(local_uri, io_context, out_path)); + /// double average_latency = 1; + /// int32_t seed = 0xDEADBEEF; + /// ARROW_ASSIGN_OR_RAISE(auto params, uri.query_item()); + /// for (const auto& [key, value] : params) { + /// if (key == "average_latency") { + /// average_latency = std::stod(value); + /// } + /// if (key == "seed") { + /// seed = std::stoi(value, nullptr, /*base=*/16); + /// } + /// } + /// return std::make_shared(base_fs, average_latency, seed); + /// })); + /// \endcode + /// + /// \param[in] scheme a Uri scheme which the factory will handle. + /// If a factory has already been registered for a scheme, the + /// new factory will be ignored. + /// \param[in] factory a function which can produce a FileSystem for Uris which match + /// scheme. + /// \param[in] finalizer a function which must be called to finalize the factory before + /// the process exits, or nullptr if no finalization is necessary. + FileSystemRegistrar(std::string scheme, FileSystemFactory factory, + std::function finalizer = {}); +}; + +#define ARROW_REGISTER_FILESYSTEM(scheme, factory_function, finalizer) \ + ::arrow::fs::FileSystemRegistrar { \ + scheme, ::arrow::fs::FileSystemFactory{factory_function, __FILE__, __LINE__}, \ + finalizer \ + } + +/// @} + +namespace internal { +ARROW_EXPORT void* GetFileSystemRegistry(); +} // namespace internal + +/// \brief Copy files, including from one FileSystem to another +/// +/// If a source and destination are resident in the same FileSystem FileSystem::CopyFile +/// will be used, otherwise the file will be opened as a stream in both FileSystems and +/// chunks copied from the source to the destination. No directories will be created. +ARROW_EXPORT +Status CopyFiles(const std::vector& sources, + const std::vector& destinations, + const io::IOContext& io_context = io::default_io_context(), + int64_t chunk_size = 1024 * 1024, bool use_threads = true); + +/// \brief Copy selected files, including from one FileSystem to another +/// +/// Directories will be created under the destination base directory as needed. +ARROW_EXPORT +Status CopyFiles(const std::shared_ptr& source_fs, + const FileSelector& source_sel, + const std::shared_ptr& destination_fs, + const std::string& destination_base_dir, + const io::IOContext& io_context = io::default_io_context(), + int64_t chunk_size = 1024 * 1024, bool use_threads = true); + +struct FileSystemGlobalOptions { + /// Path to a single PEM file holding all TLS CA certificates + /// + /// If empty, the underlying TLS library's defaults will be used. + std::string tls_ca_file_path; + + /// Path to a directory holding TLS CA certificates in individual PEM files + /// named along the OpenSSL "hashed" format. + /// + /// If empty, the underlying TLS library's defaults will be used. + std::string tls_ca_dir_path; +}; + +/// EXPERIMENTAL: optional global initialization routine +/// +/// This is for environments (such as manylinux) where the path +/// to TLS CA certificates needs to be configured at runtime. +ARROW_EXPORT +Status Initialize(const FileSystemGlobalOptions& options); + +} // namespace fs +} // namespace arrow diff --git a/shared/package-files/1f/1fb3c07819fd97faeea3eac7447877817fa366e78d0127eddc8c5f018850ad07/_test_string_default_native.h b/shared/package-files/1f/1fb3c07819fd97faeea3eac7447877817fa366e78d0127eddc8c5f018850ad07/_test_string_default_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7c126e63c5490124df60c782bb8b6ea1d6fb26f8 --- /dev/null +++ b/shared/package-files/1f/1fb3c07819fd97faeea3eac7447877817fa366e78d0127eddc8c5f018850ad07/_test_string_default_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _test_string_default(const at::Tensor & dummy, c10::string_view a="\"'\\", c10::string_view b="\"'\\"); +} // namespace native +} // namespace at diff --git a/shared/package-files/1f/1fb485c695959c5e2f82917de5a77e168e711e122f2a1b5926e1818342764809/test_power.py b/shared/package-files/1f/1fb485c695959c5e2f82917de5a77e168e711e122f2a1b5926e1818342764809/test_power.py new file mode 100644 index 0000000000000000000000000000000000000000..80ae48c525c20da6153deffbc9feadef81acf527 --- /dev/null +++ b/shared/package-files/1f/1fb485c695959c5e2f82917de5a77e168e711e122f2a1b5926e1818342764809/test_power.py @@ -0,0 +1,670 @@ +from sympy.core import ( + Basic, Rational, Symbol, S, Float, Integer, Mul, Number, Pow, + Expr, I, nan, pi, symbols, oo, zoo, N) +from sympy.core.parameters import global_parameters +from sympy.core.tests.test_evalf import NS +from sympy.core.function import expand_multinomial +from sympy.functions.elementary.miscellaneous import sqrt, cbrt +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.special.error_functions import erf +from sympy.functions.elementary.trigonometric import ( + sin, cos, tan, sec, csc, atan) +from sympy.functions.elementary.hyperbolic import cosh, sinh, tanh +from sympy.polys import Poly +from sympy.series.order import O +from sympy.sets import FiniteSet +from sympy.core.power import power +from sympy.core.intfunc import integer_nthroot +from sympy.testing.pytest import warns, _both_exp_pow +from sympy.utilities.exceptions import SymPyDeprecationWarning +from sympy.abc import a, b, c, x, y +from sympy.core.numbers import all_close + +def test_rational(): + a = Rational(1, 5) + + r = sqrt(5)/5 + assert sqrt(a) == r + assert 2*sqrt(a) == 2*r + + r = a*a**S.Half + assert a**Rational(3, 2) == r + assert 2*a**Rational(3, 2) == 2*r + + r = a**5*a**Rational(2, 3) + assert a**Rational(17, 3) == r + assert 2 * a**Rational(17, 3) == 2*r + + +def test_large_rational(): + e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3) + assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3)) + + +def test_negative_real(): + def feq(a, b): + return abs(a - b) < 1E-10 + + assert feq(S.One / Float(-0.5), -Integer(2)) + + +def test_expand(): + assert (2**(-1 - x)).expand() == S.Half*2**(-x) + + +def test_issue_3449(): + #test if powers are simplified correctly + #see also issue 3995 + assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3) + assert ( + (x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5) + + a = Symbol('a', real=True) + b = Symbol('b', real=True) + assert (a**2)**b == (abs(a)**b)**2 + assert sqrt(1/a) != 1/sqrt(a) # e.g. for a = -1 + assert (a**3)**Rational(1, 3) != a + assert (x**a)**b != x**(a*b) # e.g. x = -1, a=2, b=1/2 + assert (x**.5)**b == x**(.5*b) + assert (x**.5)**.5 == x**.25 + assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I + + k = Symbol('k', integer=True) + m = Symbol('m', integer=True) + assert (x**k)**m == x**(k*m) + assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3) + + assert (x**.5)**2 == x**1.0 + assert (x**2)**k == (x**k)**2 == x**(2*k) + + a = Symbol('a', positive=True) + assert (a**3)**Rational(2, 5) == a**Rational(6, 5) + assert (a**2)**b == (a**b)**2 + assert (a**Rational(2, 3))**x == a**(x*Rational(2, 3)) != (a**x)**Rational(2, 3) + + +def test_issue_3866(): + assert --sqrt(sqrt(5) - 1) == sqrt(sqrt(5) - 1) + + +def test_negative_one(): + x = Symbol('x', complex=True) + y = Symbol('y', complex=True) + assert 1/x**y == x**(-y) + + +def test_issue_4362(): + neg = Symbol('neg', negative=True) + nonneg = Symbol('nonneg', nonnegative=True) + any = Symbol('any') + num, den = sqrt(1/neg).as_numer_denom() + assert num == sqrt(-1) + assert den == sqrt(-neg) + num, den = sqrt(1/nonneg).as_numer_denom() + assert num == 1 + assert den == sqrt(nonneg) + num, den = sqrt(1/any).as_numer_denom() + assert num == sqrt(1/any) + assert den == 1 + + def eqn(num, den, pow): + return (num/den)**pow + npos = 1 + nneg = -1 + dpos = 2 - sqrt(3) + dneg = 1 - sqrt(3) + assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0 + # pos or neg integer + eq = eqn(npos, dpos, 2) + assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) + eq = eqn(npos, dneg, 2) + assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) + eq = eqn(nneg, dpos, 2) + assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2) + eq = eqn(nneg, dneg, 2) + assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2) + eq = eqn(npos, dpos, -2) + assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) + eq = eqn(npos, dneg, -2) + assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) + eq = eqn(nneg, dpos, -2) + assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1) + eq = eqn(nneg, dneg, -2) + assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1) + # pos or neg rational + pow = S.Half + eq = eqn(npos, dpos, pow) + assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) + eq = eqn(npos, dneg, pow) + assert eq.is_Pow is False and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) + eq = eqn(nneg, dpos, pow) + assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow) + eq = eqn(nneg, dneg, pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) + eq = eqn(npos, dpos, -pow) + assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow) + eq = eqn(npos, dneg, -pow) + assert eq.is_Pow is False and eq.as_numer_denom() == (-(-npos)**pow*(-dneg)**pow, npos) + eq = eqn(nneg, dpos, -pow) + assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow) + eq = eqn(nneg, dneg, -pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) + # unknown exponent + pow = 2*any + eq = eqn(npos, dpos, pow) + assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow) + eq = eqn(npos, dneg, pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow) + eq = eqn(nneg, dpos, pow) + assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow) + eq = eqn(nneg, dneg, pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow) + eq = eqn(npos, dpos, -pow) + assert eq.as_numer_denom() == (dpos**pow, npos**pow) + eq = eqn(npos, dneg, -pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow) + eq = eqn(nneg, dpos, -pow) + assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow) + eq = eqn(nneg, dneg, -pow) + assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow) + + assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3) + notp = Symbol('notp', positive=False) # not positive does not imply real + b = ((1 + x/notp)**-2) + assert (b**(-y)).as_numer_denom() == (1, b**y) + assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2) + nonp = Symbol('nonp', nonpositive=True) + assert (((1 + x/nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp - + x)**2, nonp**2) + + n = Symbol('n', negative=True) + assert (x**n).as_numer_denom() == (1, x**-n) + assert sqrt(1/n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n)) + n = Symbol('0 or neg', nonpositive=True) + # if x and n are split up without negating each term and n is negative + # then the answer might be wrong; if n is 0 it won't matter since + # 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also + # zero (in which case the negative sign doesn't matter): + # 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I + assert (1/sqrt(x/n)).as_numer_denom() == (sqrt(-n), sqrt(-x)) + c = Symbol('c', complex=True) + e = sqrt(1/c) + assert e.as_numer_denom() == (e, 1) + i = Symbol('i', integer=True) + assert ((1 + x/y)**i).as_numer_denom() == ((x + y)**i, y**i) + + +def test_Pow_Expr_args(): + bases = [Basic(), Poly(x, x), FiniteSet(x)] + for base in bases: + # The cache can mess with the stacklevel test + with warns(SymPyDeprecationWarning, test_stacklevel=False): + Pow(base, S.One) + + +def test_Pow_signs(): + """Cf. issues 4595 and 5250""" + n = Symbol('n', even=True) + assert (3 - y)**2 != (y - 3)**2 + assert (3 - y)**n != (y - 3)**n + assert (-3 + y - x)**2 != (3 - y + x)**2 + assert (y - 3)**3 != -(3 - y)**3 + + +def test_power_with_noncommutative_mul_as_base(): + x = Symbol('x', commutative=False) + y = Symbol('y', commutative=False) + assert not (x*y)**3 == x**3*y**3 + assert (2*x*y)**3 == 8*(x*y)**3 + + +@_both_exp_pow +def test_power_rewrite_exp(): + assert (I**I).rewrite(exp) == exp(-pi/2) + + expr = (2 + 3*I)**(4 + 5*I) + assert expr.rewrite(exp) == exp((4 + 5*I)*(log(sqrt(13)) + I*atan(Rational(3, 2)))) + assert expr.rewrite(exp).expand() == \ + 169*exp(5*I*log(13)/2)*exp(4*I*atan(Rational(3, 2)))*exp(-5*atan(Rational(3, 2))) + + assert ((6 + 7*I)**5).rewrite(exp) == 7225*sqrt(85)*exp(5*I*atan(Rational(7, 6))) + + expr = 5**(6 + 7*I) + assert expr.rewrite(exp) == exp((6 + 7*I)*log(5)) + assert expr.rewrite(exp).expand() == 15625*exp(7*I*log(5)) + + assert Pow(123, 789, evaluate=False).rewrite(exp) == 123**789 + assert (1**I).rewrite(exp) == 1**I + assert (0**I).rewrite(exp) == 0**I + + expr = (-2)**(2 + 5*I) + assert expr.rewrite(exp) == exp((2 + 5*I)*(log(2) + I*pi)) + assert expr.rewrite(exp).expand() == 4*exp(-5*pi)*exp(5*I*log(2)) + + assert ((-2)**S(-5)).rewrite(exp) == (-2)**S(-5) + + x, y = symbols('x y') + assert (x**y).rewrite(exp) == exp(y*log(x)) + if global_parameters.exp_is_pow: + assert (7**x).rewrite(exp) == Pow(S.Exp1, x*log(7), evaluate=False) + else: + assert (7**x).rewrite(exp) == exp(x*log(7), evaluate=False) + assert ((2 + 3*I)**x).rewrite(exp) == exp(x*(log(sqrt(13)) + I*atan(Rational(3, 2)))) + assert (y**(5 + 6*I)).rewrite(exp) == exp(log(y)*(5 + 6*I)) + + assert all((1/func(x)).rewrite(exp) == 1/(func(x).rewrite(exp)) for func in + (sin, cos, tan, sec, csc, sinh, cosh, tanh)) + + +def test_zero(): + assert 0**x != 0 + assert 0**(2*x) == 0**x + assert 0**(1.0*x) == 0**x + assert 0**(2.0*x) == 0**x + assert (0**(2 - x)).as_base_exp() == (0, 2 - x) + assert 0**(x - 2) != S.Infinity**(2 - x) + assert 0**(2*x*y) == 0**(x*y) + assert 0**(-2*x*y) == S.ComplexInfinity**(x*y) + assert Float(0)**2 is not S.Zero + assert Float(0)**2 == 0.0 + assert Float(0)**-2 is zoo + assert Float(0)**oo is S.Zero + + #Test issue 19572 + assert 0 ** -oo is zoo + assert power(0, -oo) is zoo + assert Float(0)**-oo is zoo + +def test_pow_as_base_exp(): + assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x) + assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2) + p = S.Half**x + assert p.base, p.exp == p.as_base_exp() == (S(2), -x) + p = (S(3)/2)**x + assert p.base, p.exp == p.as_base_exp() == (3*S.Half, x) + p = (S(2)/3)**x + assert p.as_base_exp() == (S(2)/3, x) + assert p.base, p.exp == (S(2)/3, x) + # issue 8344: + assert Pow(1, 2, evaluate=False).as_base_exp() == (S.One, S(2)) + + +def test_nseries(): + assert sqrt(I*x - 1)._eval_nseries(x, 4, None, 1) == I + x/2 + I*x**2/8 - x**3/16 + O(x**4) + assert sqrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -I - x/2 - I*x**2/8 + x**3/16 + O(x**4) + assert cbrt(I*x - 1)._eval_nseries(x, 4, None, 1) == (-1)**(S(1)/3) - (-1)**(S(5)/6)*x/3 + \ + (-1)**(S(1)/3)*x**2/9 + 5*(-1)**(S(5)/6)*x**3/81 + O(x**4) + assert cbrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -(-1)**(S(2)/3) - (-1)**(S(1)/6)*x/3 - \ + (-1)**(S(2)/3)*x**2/9 + 5*(-1)**(S(1)/6)*x**3/81 + O(x**4) + assert (1 / (exp(-1/x) + 1/x))._eval_nseries(x, 2, None) == x + O(x**2) + # test issue 23752 + assert sqrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, 1) == -sqrt(3)*I + sqrt(3)*I*x/6 - \ + sqrt(3)*I*x**2*(-S(1)/72 + I/6) - sqrt(3)*I*x**3*(-S(1)/432 + I/36) + O(x**4) + assert sqrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, -1) == -sqrt(3)*I + sqrt(3)*I*x/6 - \ + sqrt(3)*I*x**2*(-S(1)/72 + I/6) - sqrt(3)*I*x**3*(-S(1)/432 + I/36) + O(x**4) + assert cbrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, 1) == -(-1)**(S(2)/3)*3**(S(1)/3) + \ + (-1)**(S(2)/3)*3**(S(1)/3)*x/9 - (-1)**(S(2)/3)*3**(S(1)/3)*x**2*(-S(1)/81 + I/9) - \ + (-1)**(S(2)/3)*3**(S(1)/3)*x**3*(-S(5)/2187 + 2*I/81) + O(x**4) + assert cbrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, -1) == -(-1)**(S(2)/3)*3**(S(1)/3) + \ + (-1)**(S(2)/3)*3**(S(1)/3)*x/9 - (-1)**(S(2)/3)*3**(S(1)/3)*x**2*(-S(1)/81 + I/9) - \ + (-1)**(S(2)/3)*3**(S(1)/3)*x**3*(-S(5)/2187 + 2*I/81) + O(x**4) + + +def test_issue_6100_12942_4473(): + assert x**1.0 != x + assert x != x**1.0 + assert True != x**1.0 + assert x**1.0 is not True + assert x is not True + assert x*y != (x*y)**1.0 + # Pow != Symbol + assert (x**1.0)**1.0 != x + assert (x**1.0)**2.0 != x**2 + b = Expr() + assert Pow(b, 1.0, evaluate=False) != b + # if the following gets distributed as a Mul (x**1.0*y**1.0 then + # __eq__ methods could be added to Symbol and Pow to detect the + # power-of-1.0 case. + assert ((x*y)**1.0).func is Pow + + +def test_issue_6208(): + from sympy.functions.elementary.miscellaneous import root + assert sqrt(33**(I*9/10)) == -33**(I*9/20) + assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3 + assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9 + assert sqrt(exp(3*I)) == exp(3*I/2) + assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I) + assert sqrt(exp(5*I)) == -exp(5*I/2) + assert root(exp(5*I), 3).exp == Rational(1, 3) + + +def test_issue_6990(): + assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \ + sqrt(a)*x**2*(1/(2*a) - b**2/(8*a**2)) + sqrt(a) + b*x/(2*sqrt(a)) + + +def test_issue_6068(): + assert sqrt(sin(x)).series(x, 0, 7) == \ + sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ + x**Rational(13, 2)/24192 + O(x**7) + assert sqrt(sin(x)).series(x, 0, 9) == \ + sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \ + x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9) + assert sqrt(sin(x**3)).series(x, 0, 19) == \ + x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19) + assert sqrt(sin(x**3)).series(x, 0, 20) == \ + x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \ + x**Rational(39, 2)/24192 + O(x**20) + + +def test_issue_6782(): + assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7) + assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3) + + +def test_issue_6653(): + assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2/2 + O(x**3) + + +def test_issue_6429(): + f = (c**2 + x)**(0.5) + assert f.series(x, x0=0, n=1) == (c**2)**0.5 + O(x) + assert f.taylor_term(0, x) == (c**2)**0.5 + assert f.taylor_term(1, x) == 0.5*x*(c**2)**(-0.5) + assert f.taylor_term(2, x) == -0.125*x**2*(c**2)**(-1.5) + + +def test_issue_7638(): + f = pi/log(sqrt(2)) + assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f) + # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the + # sign will be +/-1; for the previous "small arg" case, it didn't matter + # that this could not be proved + assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**Rational(1, 3) + + assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3) + r = symbols('r', real=True) + assert sqrt(r**2) == abs(r) + assert cbrt(r**3) != r + assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**Rational(5, 4) + p = symbols('p', positive=True) + assert cbrt(p**2) == p**Rational(2, 3) + assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I' + assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2) # or 1/sqrt(1 + I) + e = 1/(1 - sqrt(2)) + assert sqrt(e) == I/sqrt(-1 + sqrt(2)) + assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2)) + assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half, + Rational(3, 2) + I/2] + assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3) + assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3) + + for q in 1+I, 1-I: + assert sqrt(q**2) == q + for q in -1+I, -1-I: + assert sqrt(q**2) == -q + + assert sqrt((p + r*I)**2) != p + r*I + e = (1 + I/5) + assert sqrt(e**5) == e**(5*S.Half) + assert sqrt(e**6) == e**3 + assert sqrt((1 + I*r)**6) != (1 + I*r)**3 + + +def test_issue_8582(): + assert 1**oo is nan + assert 1**(-oo) is nan + assert 1**zoo is nan + assert 1**(oo + I) is nan + assert 1**(1 + I*oo) is nan + assert 1**(oo + I*oo) is nan + + +def test_issue_8650(): + n = Symbol('n', integer=True, nonnegative=True) + assert (n**n).is_positive is True + x = 5*n + 5 + assert (x**(5*(n + 1))).is_positive is True + + +def test_issue_13914(): + b = Symbol('b') + assert (-1)**zoo is nan + assert 2**zoo is nan + assert (S.Half)**(1 + zoo) is nan + assert I**(zoo + I) is nan + assert b**(I + zoo) is nan + + +def test_better_sqrt(): + n = Symbol('n', integer=True, nonnegative=True) + assert sqrt(3 + 4*I) == 2 + I + assert sqrt(3 - 4*I) == 2 - I + assert sqrt(-3 - 4*I) == 1 - 2*I + assert sqrt(-3 + 4*I) == 1 + 2*I + assert sqrt(32 + 24*I) == 6 + 2*I + assert sqrt(32 - 24*I) == 6 - 2*I + assert sqrt(-32 - 24*I) == 2 - 6*I + assert sqrt(-32 + 24*I) == 2 + 6*I + + # triple (3, 4, 5): + # parity of 3 matches parity of 5 and + # den, 4, is a square + assert sqrt((3 + 4*I)/4) == 1 + I/2 + # triple (8, 15, 17) + # parity of 8 doesn't match parity of 17 but + # den/2, 8/2, is a square + assert sqrt((8 + 15*I)/8) == (5 + 3*I)/4 + # handle the denominator + assert sqrt((3 - 4*I)/25) == (2 - I)/5 + assert sqrt((3 - 4*I)/26) == (2 - I)/sqrt(26) + # mul + # issue #12739 + assert sqrt((3 + 4*I)/(3 - 4*I)) == (3 + 4*I)/5 + assert sqrt(2/(3 + 4*I)) == sqrt(2)/5*(2 - I) + assert sqrt(n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(2 - I) + assert sqrt(-2/(3 + 4*I)) == sqrt(2)/5*(1 + 2*I) + assert sqrt(-n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(1 + 2*I) + # power + assert sqrt(1/(3 + I*4)) == (2 - I)/5 + assert sqrt(1/(3 - I)) == sqrt(10)*sqrt(3 + I)/10 + # symbolic + i = symbols('i', imaginary=True) + assert sqrt(3/i) == Mul(sqrt(3), 1/sqrt(i), evaluate=False) + # multiples of 1/2; don't make this too automatic + assert sqrt(3 + 4*I)**3 == (2 + I)**3 + assert Pow(3 + 4*I, Rational(3, 2)) == 2 + 11*I + assert Pow(6 + 8*I, Rational(3, 2)) == 2*sqrt(2)*(2 + 11*I) + n, d = (3 + 4*I), (3 - 4*I)**3 + a = n/d + assert a.args == (1/d, n) + eq = sqrt(a) + assert eq.args == (a, S.Half) + assert expand_multinomial(eq) == sqrt((-117 + 44*I)*(3 + 4*I))/125 + assert eq.expand() == (7 - 24*I)/125 + + # issue 12775 + # pos im part + assert sqrt(2*I) == (1 + I) + assert sqrt(2*9*I) == Mul(3, 1 + I, evaluate=False) + assert Pow(2*I, 3*S.Half) == (1 + I)**3 + # neg im part + assert sqrt(-I/2) == Mul(S.Half, 1 - I, evaluate=False) + # fractional im part + assert Pow(Rational(-9, 2)*I, Rational(3, 2)) == 27*(1 - I)**3/8 + + +def test_issue_2993(): + assert str((2.3*x - 4)**0.3) == '(2.3*x - 4)**0.3' + assert str((2.3*x + 4)**0.3) == '(2.3*x + 4)**0.3' + assert str((-2.3*x + 4)**0.3) == '(4 - 2.3*x)**0.3' + assert str((-2.3*x - 4)**0.3) == '(-2.3*x - 4)**0.3' + assert str((2.3*x - 2)**0.3) == '(2.3*x - 2)**0.3' + assert str((-2.3*x - 2)**0.3) == '(-2.3*x - 2)**0.3' + assert str((-2.3*x + 2)**0.3) == '(2 - 2.3*x)**0.3' + assert str((2.3*x + 2)**0.3) == '(2.3*x + 2)**0.3' + assert str((2.3*x - 4)**Rational(1, 3)) == '(2.3*x - 4)**(1/3)' + eq = (2.3*x + 4) + assert str(eq**2) == '(2.3*x + 4)**2' + assert (1/eq).args == (eq, -1) # don't change trivial power + # issue 17735 + q=.5*exp(x) - .5*exp(-x) + 0.1 + assert int((q**2).subs(x, 1)) == 1 + # issue 17756 + y = Symbol('y') + assert len(sqrt(x/(x + y)**2 + Float('0.008', 30)).subs(y, pi.n(25)).atoms(Float)) == 2 + # issue 17756 + a, b, c, d, e, f, g = symbols('a:g') + expr = sqrt(1 + a*(c**4 + g*d - 2*g*e - f*(-g + d))**2/ + (c**3*b**2*(d - 3*e + 2*f)**2))/2 + r = [ + (a, N('0.0170992456333788667034850458615', 30)), + (b, N('0.0966594956075474769169134801223', 30)), + (c, N('0.390911862903463913632151616184', 30)), + (d, N('0.152812084558656566271750185933', 30)), + (e, N('0.137562344465103337106561623432', 30)), + (f, N('0.174259178881496659302933610355', 30)), + (g, N('0.220745448491223779615401870086', 30))] + tru = expr.n(30, subs=dict(r)) + seq = expr.subs(r) + # although `tru` is the right way to evaluate + # expr with numerical values, `seq` will have + # significant loss of precision if extraction of + # the largest coefficient of a power's base's terms + # is done improperly + assert seq == tru + +def test_issue_17450(): + assert (erf(cosh(1)**7)**I).is_real is None + assert (erf(cosh(1)**7)**I).is_imaginary is False + assert (Pow(exp(1+sqrt(2)), ((1-sqrt(2))*I*pi), evaluate=False)).is_real is None + assert ((-10)**(10*I*pi/3)).is_real is False + assert ((-5)**(4*I*pi)).is_real is False + + +def test_issue_18190(): + assert sqrt(1 / tan(1 + I)) == 1 / sqrt(tan(1 + I)) + + +def test_issue_14815(): + x = Symbol('x', real=True) + assert sqrt(x).is_extended_negative is False + x = Symbol('x', real=False) + assert sqrt(x).is_extended_negative is None + x = Symbol('x', complex=True) + assert sqrt(x).is_extended_negative is False + x = Symbol('x', extended_real=True) + assert sqrt(x).is_extended_negative is False + assert sqrt(zoo, evaluate=False).is_extended_negative is False + assert sqrt(nan, evaluate=False).is_extended_negative is None + + +def test_issue_18509(): + x = Symbol('x', prime=True) + assert x**oo is oo + assert (1/x)**oo is S.Zero + assert (-1/x)**oo is S.Zero + assert (-x)**oo is zoo + assert (-oo)**(-1 + I) is S.Zero + assert (-oo)**(1 + I) is zoo + assert (oo)**(-1 + I) is S.Zero + assert (oo)**(1 + I) is zoo + + +def test_issue_18762(): + e, p = symbols('e p') + g0 = sqrt(1 + e**2 - 2*e*cos(p)) + assert len(g0.series(e, 1, 3).args) == 4 + + +def test_issue_21860(): + e = 3*2**Rational(66666666667,200000000000)*3**Rational(16666666667,50000000000)*x**Rational(66666666667, 200000000000) + ans = Mul(Rational(3, 2), + Pow(Integer(2), Rational(33333333333, 100000000000)), + Pow(Integer(3), Rational(26666666667, 40000000000))) + assert e.xreplace({x: Rational(3,8)}) == ans + + +def test_issue_21647(): + e = log((Integer(567)/500)**(811*(Integer(567)/500)**x/100)) + ans = log(Mul(Rational(64701150190720499096094005280169087619821081527, + 76293945312500000000000000000000000000000000000), + Pow(Integer(2), Rational(396204892125479941, 781250000000000000)), + Pow(Integer(3), Rational(385045107874520059, 390625000000000000)), + Pow(Integer(5), Rational(407364676376439823, 1562500000000000000)), + Pow(Integer(7), Rational(385045107874520059, 1562500000000000000)))) + assert e.xreplace({x: 6}) == ans + + +def test_issue_21762(): + e = (x**2 + 6)**(Integer(33333333333333333)/50000000000000000) + ans = Mul(Rational(5, 4), + Pow(Integer(2), Rational(16666666666666667, 25000000000000000)), + Pow(Integer(5), Rational(8333333333333333, 25000000000000000))) + assert e.xreplace({x: S.Half}) == ans + + +def test_issue_14704(): + a = 144**144 + x, xexact = integer_nthroot(a,a) + assert x == 1 and xexact is False + + +def test_rational_powers_larger_than_one(): + assert Rational(2, 3)**Rational(3, 2) == 2*sqrt(6)/9 + assert Rational(1, 6)**Rational(9, 4) == 6**Rational(3, 4)/216 + assert Rational(3, 7)**Rational(7, 3) == 9*3**Rational(1, 3)*7**Rational(2, 3)/343 + + +def test_power_dispatcher(): + + class NewBase(Expr): + pass + class NewPow(NewBase, Pow): + pass + a, b = Symbol('a'), NewBase() + + @power.register(Expr, NewBase) + @power.register(NewBase, Expr) + @power.register(NewBase, NewBase) + def _(a, b): + return NewPow(a, b) + + # Pow called as fallback + assert power(2, 3) == 8*S.One + assert power(a, 2) == Pow(a, 2) + assert power(a, a) == Pow(a, a) + + # NewPow called by dispatch + assert power(a, b) == NewPow(a, b) + assert power(b, a) == NewPow(b, a) + assert power(b, b) == NewPow(b, b) + + +def test_powers_of_I(): + assert [sqrt(I)**i for i in range(13)] == [ + 1, sqrt(I), I, sqrt(I)**3, -1, -sqrt(I), -I, -sqrt(I)**3, + 1, sqrt(I), I, sqrt(I)**3, -1] + assert sqrt(I)**(S(9)/2) == -I**(S(1)/4) + + +def test_issue_23918(): + b = S(2)/3 + assert (b**x).as_base_exp() == (b, x) + + +def test_issue_26546(): + x = Symbol('x', real=True) + assert x.is_extended_real is True + assert sqrt(x+I).is_extended_real is False + assert Pow(x+I, S.Half).is_extended_real is False + assert Pow(x+I, Rational(1,2)).is_extended_real is False + assert Pow(x+I, Rational(1,13)).is_extended_real is False + assert Pow(x+I, Rational(2,3)).is_extended_real is None + + +def test_issue_25165(): + e1 = (1/sqrt(( - x + 1)**2 + (x - 0.23)**4)).series(x, 0, 2) + e2 = 0.998603724830355 + 1.02004923189934*x + O(x**2) + assert all_close(e1, e2) diff --git a/shared/package-files/1f/1fb96df9e728d98195b0838d9d65a975bb339a79117f53097ce0340b882385e2/bn_relu.cpython-311.pyc b/shared/package-files/1f/1fb96df9e728d98195b0838d9d65a975bb339a79117f53097ce0340b882385e2/bn_relu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad566fcf2ae8aba1054b9269d5ba7b8e62a60c08 Binary files /dev/null and b/shared/package-files/1f/1fb96df9e728d98195b0838d9d65a975bb339a79117f53097ce0340b882385e2/bn_relu.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fbd151ff03969ee1f1bfe4228ba8328671bd65ded921807bc8095e7054ddb5b/file_check.h b/shared/package-files/1f/1fbd151ff03969ee1f1bfe4228ba8328671bd65ded921807bc8095e7054ddb5b/file_check.h new file mode 100644 index 0000000000000000000000000000000000000000..fd09fcc6ad30b476e373e2a7c96f5c266d9bd04f --- /dev/null +++ b/shared/package-files/1f/1fbd151ff03969ee1f1bfe4228ba8328671bd65ded921807bc8095e7054ddb5b/file_check.h @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include + +namespace torch::jit { + +struct Graph; + +namespace testing { + +struct FileCheckImpl; + +struct FileCheck { + public: + TORCH_API explicit FileCheck(); + TORCH_API ~FileCheck(); + + // Run FileCheck against test string + TORCH_API void run(const std::string& test_string); + + // Run FileCheck against dump of graph IR + TORCH_API void run(const Graph& graph); + + // Parsing input checks string and run against test string / dump of graph IR + TORCH_API void run( + const std::string& input_checks_string, + const std::string& test_string); + TORCH_API void run( + const std::string& input_checks_string, + const Graph& graph); + + // Checks that the string occurs, starting at the end of the most recent match + TORCH_API FileCheck* check(const std::string& str); + + // Checks that the string does not occur between the previous match and next + // match. Consecutive check_nots test against the same previous match and next + // match + TORCH_API FileCheck* check_not(const std::string& str); + + // Checks that the string occurs on the same line as the previous match + TORCH_API FileCheck* check_same(const std::string& str); + + // Checks that the string occurs on the line immediately following the + // previous match + TORCH_API FileCheck* check_next(const std::string& str); + + // Checks that the string occurs count number of times, starting at the end + // of the previous match. If exactly is true, checks that there are exactly + // count many matches + TORCH_API FileCheck* check_count( + const std::string& str, + size_t count, + bool exactly = false); + + // A series of consecutive check_dags get turned into a group of checks + // which can appear in any order relative to each other. The checks begin + // at the end of the previous match, and the match for the check_dag group + // is the minimum match of all individual checks to the maximum match of all + // individual checks. + TORCH_API FileCheck* check_dag(const std::string& str); + + // Checks that source token is highlighted in str (usually an error message). + TORCH_API FileCheck* check_source_highlighted(const std::string& str); + + // Checks that the regex matched string occurs, starting at the end of the + // most recent match + TORCH_API FileCheck* check_regex(const std::string& str); + + // reset checks + TORCH_API void reset(); + + private: + bool has_run = false; + std::unique_ptr fcImpl; +}; +} // namespace testing +} // namespace torch::jit diff --git a/shared/package-files/1f/1fbd23b5e17cc470c017b9d35b6e9984800d0adbd974d4d87d2bce9c9988c11a/piecewise.cpython-311.pyc b/shared/package-files/1f/1fbd23b5e17cc470c017b9d35b6e9984800d0adbd974d4d87d2bce9c9988c11a/piecewise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e413b0aa40bc78c5e9163e544c630a05880c2096 Binary files /dev/null and b/shared/package-files/1f/1fbd23b5e17cc470c017b9d35b6e9984800d0adbd974d4d87d2bce9c9988c11a/piecewise.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fc039011c3234ea820faf2ef762a285a962240b16814a6136d84b8a8d1b9784/_einsum_strategy.py b/shared/package-files/1f/1fc039011c3234ea820faf2ef762a285a962240b16814a6136d84b8a8d1b9784/_einsum_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..5953721d219c86825901f4f0226bdc51ccdee7bf --- /dev/null +++ b/shared/package-files/1f/1fc039011c3234ea820faf2ef762a285a962240b16814a6136d84b8a8d1b9784/_einsum_strategy.py @@ -0,0 +1,173 @@ +import itertools +from dataclasses import dataclass + +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor._dtensor_spec import DTensorSpec +from torch.distributed.tensor._op_schema import OpStrategy, PlacementStrategy +from torch.distributed.tensor.placement_types import ( + Partial, + Placement, + Replicate, + Shard, +) + + +@dataclass +class EinsumDims: + contracting_dims: list[str] + batch_dims: list[str] + lhs_out_only_dims: list[str] + rhs_out_only_dims: list[str] + + @classmethod + def parse_equation(cls, equation: str) -> tuple[list[str], str]: + # parse einop equation and extract arg specs + """ + Parse the einsum equation str to input dim chars and output dim char + """ + inputs, outputs = equation.split("->") + input_dims, output_dims = inputs.split(","), outputs.split(",") + + # NOTE: only support at most two inputs, and single output + # extend to support more inputs if needed in future + assert len(input_dims) <= 2, "Only support at most two inputs" + assert len(output_dims) == 1, "Only support single output" + output_dim = output_dims[0] + return input_dims, output_dim + + @classmethod + def parse_dims(cls, input_dims: list[str], output_dim: str) -> "EinsumDims": + """ + Parse the dims and extract the contracting, batch, and free dimensions + for the left and right hand sides. + """ + dim_char_set: set[str] = set() + for input_dim in input_dims: + dim_char_set.update(input_dim) + + # get a determinisitc order of all dim chars + all_dim_chars = sorted(dim_char_set) + + # parse input and output dimensions + lhs_out_only_dims, rhs_out_only_dims = [], [] + batch_dims, contracting_dims = [], [] + + for dim_char in all_dim_chars: + if dim_char not in output_dim: + contracting_dims.append(dim_char) + else: + is_batch_dim = True + for input_dim in input_dims: + is_batch_dim = is_batch_dim and dim_char in input_dim + + if is_batch_dim: + batch_dims.append(dim_char) + else: + assert len(input_dims) == 2, ( + "free dimension only supported for two inputs!" + ) + lhs, rhs = input_dims + if dim_char in lhs: + lhs_out_only_dims.append(dim_char) + elif dim_char in rhs: + rhs_out_only_dims.append(dim_char) + else: + raise RuntimeError("Invalid dimension character") + + return cls( + contracting_dims=contracting_dims, + batch_dims=batch_dims, + lhs_out_only_dims=lhs_out_only_dims, + rhs_out_only_dims=rhs_out_only_dims, + ) + + +def gen_einsum_strategies( + equation: str, + mesh: DeviceMesh, + *, + linearity: bool = False, +) -> OpStrategy: + """ + Generate a strategy list for the ops that follow einsum style notation. + """ + # parse einop equation and extract dims + input_dims, output_dim = EinsumDims.parse_equation(equation) + edims = EinsumDims.parse_dims(input_dims, output_dim) + + all_mesh_dim_strategies = [] + + # generate strategies for each mesh dim + for mesh_dim in range(mesh.ndim): + mesh_dim_strategies = [] + + # placement list stores placements of [output, input1, input2, ...] + # first we always have replicate all for inputs and output + placement_list: list[Placement] = [Replicate()] * (len(input_dims) + 1) + mesh_dim_strategies.append(placement_list) + + # split batch dim + for batch_dim in edims.batch_dims: + output_batch_dim = output_dim.index(batch_dim) + placement_list = [Shard(output_batch_dim)] + for input_dim in input_dims: + input_batch_dim = input_dim.index(batch_dim) + placement_list.append(Shard(input_batch_dim)) + + mesh_dim_strategies.append(placement_list) + + # split contracting dim + for contracting_dim in edims.contracting_dims: + placement_list = [Partial()] + for input_dim in input_dims: + input_contracting_dim = input_dim.index(contracting_dim) + placement_list.append(Shard(input_contracting_dim)) + + mesh_dim_strategies.append(placement_list) + + # split lhs free dim + for lhs_dim in edims.lhs_out_only_dims: + lhs_free_dim = output_dim.index(lhs_dim) + # this means split the lhs input and output + # i.e. S(0), R -> S(0) + lhs_placement_list: list[Placement] = [ + Shard(lhs_free_dim), + Shard(lhs_free_dim), + Replicate(), + ] + mesh_dim_strategies.append(lhs_placement_list) + + # split rhs free dim + for rhs_dim in edims.rhs_out_only_dims: + rhs_free_dim = output_dim.index(rhs_dim) + rhs_placement_list: list[Placement] = [ + Shard(rhs_free_dim), + Replicate(), + Shard(rhs_free_dim), + ] + mesh_dim_strategies.append(rhs_placement_list) + + # linearity strategy + if linearity: + linearity_placement_list: list[Placement] = [Partial()] + for input_dim in input_dims: + linearity_placement_list.append(Partial()) + mesh_dim_strategies.append(linearity_placement_list) + + all_mesh_dim_strategies.append(mesh_dim_strategies) + + # generate strategies for entire mesh + strategy_combs = itertools.product(*all_mesh_dim_strategies) + + # TODO: filter out invalid strategies, at this point we generate + # all possible strategies without considering the whether the tensor + # dim could be sharded or not, we would need to filter out invalid + # strategies base on the actual tensor shape + # (i.e. for Shard, tensor dim size must > mesh size) + all_strategies = [] + for strategy_comb in strategy_combs: + spec_list = [DTensorSpec(mesh, tuple(specs)) for specs in zip(*strategy_comb)] + strat = PlacementStrategy(output_specs=spec_list[0], input_specs=spec_list[1:]) + all_strategies.append(strat) + + return OpStrategy(all_strategies) diff --git a/shared/package-files/1f/1fc1260d9ae5c42f75a0733cff52514e8958ac4b0c66f5bb1675b7084a414b69/test_construction.cpython-311.pyc b/shared/package-files/1f/1fc1260d9ae5c42f75a0733cff52514e8958ac4b0c66f5bb1675b7084a414b69/test_construction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..828a74d537083e3591007b09dc55b95f7be2bd0d Binary files /dev/null and b/shared/package-files/1f/1fc1260d9ae5c42f75a0733cff52514e8958ac4b0c66f5bb1675b7084a414b69/test_construction.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fc46b999874932b9dc9ae3b1448a90ce5a6de9122d9673b182e160787af9843/cartesian.cpython-311.pyc b/shared/package-files/1f/1fc46b999874932b9dc9ae3b1448a90ce5a6de9122d9673b182e160787af9843/cartesian.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cc879ceec3ffda8ce5d361d2f3147e5985d2d53 Binary files /dev/null and b/shared/package-files/1f/1fc46b999874932b9dc9ae3b1448a90ce5a6de9122d9673b182e160787af9843/cartesian.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fc6c48ff5406d317d88569356825d2169d20cf588fe55bc974c34a8d54292f9/rewrite.cpython-311.pyc b/shared/package-files/1f/1fc6c48ff5406d317d88569356825d2169d20cf588fe55bc974c34a8d54292f9/rewrite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c90624eb823390795f0f6dbc5972e9d89f13354f Binary files /dev/null and b/shared/package-files/1f/1fc6c48ff5406d317d88569356825d2169d20cf588fe55bc974c34a8d54292f9/rewrite.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fc74a737952075c148846b545bdd965bcd39a48aeb5872405f90c9ffbcae73c/test_pyprojecttoml.cpython-311.pyc b/shared/package-files/1f/1fc74a737952075c148846b545bdd965bcd39a48aeb5872405f90c9ffbcae73c/test_pyprojecttoml.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f46dcb11ad7c47dda65a7e3510fafba32ed0870 Binary files /dev/null and b/shared/package-files/1f/1fc74a737952075c148846b545bdd965bcd39a48aeb5872405f90c9ffbcae73c/test_pyprojecttoml.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fc9974c3cf2078dd4bc257f73afb6a6714adfec2e9d099d47cf923e766d3490/dropout.py b/shared/package-files/1f/1fc9974c3cf2078dd4bc257f73afb6a6714adfec2e9d099d47cf923e766d3490/dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..c04f66f7a25a8fc2243a04713fef96b55ebc127d --- /dev/null +++ b/shared/package-files/1f/1fc9974c3cf2078dd4bc257f73afb6a6714adfec2e9d099d47cf923e766d3490/dropout.py @@ -0,0 +1,305 @@ +import torch.nn.functional as F +from torch import Tensor + +from .module import Module + + +__all__ = [ + "Dropout", + "Dropout1d", + "Dropout2d", + "Dropout3d", + "AlphaDropout", + "FeatureAlphaDropout", +] + + +class _DropoutNd(Module): + __constants__ = ["p", "inplace"] + p: float + inplace: bool + + def __init__(self, p: float = 0.5, inplace: bool = False) -> None: + super().__init__() + if p < 0 or p > 1: + raise ValueError( + f"dropout probability has to be between 0 and 1, but got {p}" + ) + self.p = p + self.inplace = inplace + + def extra_repr(self) -> str: + return f"p={self.p}, inplace={self.inplace}" + + +class Dropout(_DropoutNd): + r"""During training, randomly zeroes some of the elements of the input tensor with probability :attr:`p`. + + The zeroed elements are chosen independently for each forward call and are sampled from a Bernoulli distribution. + + Each channel will be zeroed out independently on every forward call. + + This has proven to be an effective technique for regularization and + preventing the co-adaptation of neurons as described in the paper + `Improving neural networks by preventing co-adaptation of feature + detectors`_ . + + Furthermore, the outputs are scaled by a factor of :math:`\frac{1}{1-p}` during + training. This means that during evaluation the module simply computes an + identity function. + + Args: + p: probability of an element to be zeroed. Default: 0.5 + inplace: If set to ``True``, will do this operation in-place. Default: ``False`` + + Shape: + - Input: :math:`(*)`. Input can be of any shape + - Output: :math:`(*)`. Output is of the same shape as input + + Examples:: + + >>> m = nn.Dropout(p=0.2) + >>> input = torch.randn(20, 16) + >>> output = m(input) + + .. _Improving neural networks by preventing co-adaptation of feature + detectors: https://arxiv.org/abs/1207.0580 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.dropout(input, self.p, self.training, self.inplace) + + +class Dropout1d(_DropoutNd): + r"""Randomly zero out entire channels. + + A channel is a 1D feature map, + e.g., the :math:`j`-th channel of the :math:`i`-th sample in the + batched input is a 1D tensor :math:`\text{input}[i, j]`. + + Each channel will be zeroed out independently on every forward call with + probability :attr:`p` using samples from a Bernoulli distribution. + + Usually the input comes from :class:`nn.Conv1d` modules. + + As described in the paper + `Efficient Object Localization Using Convolutional Networks`_ , + if adjacent pixels within feature maps are strongly correlated + (as is normally the case in early convolution layers) then i.i.d. dropout + will not regularize the activations and will otherwise just result + in an effective learning rate decrease. + + In this case, :func:`nn.Dropout1d` will help promote independence between + feature maps and should be used instead. + + Args: + p (float, optional): probability of an element to be zero-ed. + inplace (bool, optional): If set to ``True``, will do this operation + in-place + + Shape: + - Input: :math:`(N, C, L)` or :math:`(C, L)`. + - Output: :math:`(N, C, L)` or :math:`(C, L)` (same shape as input). + + Examples:: + + >>> m = nn.Dropout1d(p=0.2) + >>> input = torch.randn(20, 16, 32) + >>> output = m(input) + + .. _Efficient Object Localization Using Convolutional Networks: + https://arxiv.org/abs/1411.4280 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.dropout1d(input, self.p, self.training, self.inplace) + + +class Dropout2d(_DropoutNd): + r"""Randomly zero out entire channels. + + A channel is a 2D feature map, + e.g., the :math:`j`-th channel of the :math:`i`-th sample in the + batched input is a 2D tensor :math:`\text{input}[i, j]`. + + Each channel will be zeroed out independently on every forward call with + probability :attr:`p` using samples from a Bernoulli distribution. + + Usually the input comes from :class:`nn.Conv2d` modules. + + As described in the paper + `Efficient Object Localization Using Convolutional Networks`_ , + if adjacent pixels within feature maps are strongly correlated + (as is normally the case in early convolution layers) then i.i.d. dropout + will not regularize the activations and will otherwise just result + in an effective learning rate decrease. + + In this case, :func:`nn.Dropout2d` will help promote independence between + feature maps and should be used instead. + + Args: + p (float, optional): probability of an element to be zero-ed. + inplace (bool, optional): If set to ``True``, will do this operation + in-place + + .. warning :: + Due to historical reasons, this class will perform 1D channel-wise dropout + for 3D inputs (as done by :class:`nn.Dropout1d`). Thus, it currently does NOT + support inputs without a batch dimension of shape :math:`(C, H, W)`. This + behavior will change in a future release to interpret 3D inputs as no-batch-dim + inputs. To maintain the old behavior, switch to :class:`nn.Dropout1d`. + + Shape: + - Input: :math:`(N, C, H, W)` or :math:`(N, C, L)`. + - Output: :math:`(N, C, H, W)` or :math:`(N, C, L)` (same shape as input). + + Examples:: + + >>> m = nn.Dropout2d(p=0.2) + >>> input = torch.randn(20, 16, 32, 32) + >>> output = m(input) + + .. _Efficient Object Localization Using Convolutional Networks: + https://arxiv.org/abs/1411.4280 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.dropout2d(input, self.p, self.training, self.inplace) + + +class Dropout3d(_DropoutNd): + r"""Randomly zero out entire channels. + + A channel is a 3D feature map, + e.g., the :math:`j`-th channel of the :math:`i`-th sample in the + batched input is a 3D tensor :math:`\text{input}[i, j]`. + + Each channel will be zeroed out independently on every forward call with + probability :attr:`p` using samples from a Bernoulli distribution. + + Usually the input comes from :class:`nn.Conv3d` modules. + + As described in the paper + `Efficient Object Localization Using Convolutional Networks`_ , + if adjacent pixels within feature maps are strongly correlated + (as is normally the case in early convolution layers) then i.i.d. dropout + will not regularize the activations and will otherwise just result + in an effective learning rate decrease. + + In this case, :func:`nn.Dropout3d` will help promote independence between + feature maps and should be used instead. + + Args: + p (float, optional): probability of an element to be zeroed. + inplace (bool, optional): If set to ``True``, will do this operation + in-place + + Shape: + - Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`. + - Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input). + + Examples:: + + >>> m = nn.Dropout3d(p=0.2) + >>> input = torch.randn(20, 16, 4, 32, 32) + >>> output = m(input) + + .. _Efficient Object Localization Using Convolutional Networks: + https://arxiv.org/abs/1411.4280 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.dropout3d(input, self.p, self.training, self.inplace) + + +class AlphaDropout(_DropoutNd): + r"""Applies Alpha Dropout over the input. + + Alpha Dropout is a type of Dropout that maintains the self-normalizing + property. + For an input with zero mean and unit standard deviation, the output of + Alpha Dropout maintains the original mean and standard deviation of the + input. + Alpha Dropout goes hand-in-hand with SELU activation function, which ensures + that the outputs have zero mean and unit standard deviation. + + During training, it randomly masks some of the elements of the input + tensor with probability *p* using samples from a bernoulli distribution. + The elements to masked are randomized on every forward call, and scaled + and shifted to maintain zero mean and unit standard deviation. + + During evaluation the module simply computes an identity function. + + More details can be found in the paper `Self-Normalizing Neural Networks`_ . + + Args: + p (float): probability of an element to be dropped. Default: 0.5 + inplace (bool, optional): If set to ``True``, will do this operation + in-place + + Shape: + - Input: :math:`(*)`. Input can be of any shape + - Output: :math:`(*)`. Output is of the same shape as input + + Examples:: + + >>> m = nn.AlphaDropout(p=0.2) + >>> input = torch.randn(20, 16) + >>> output = m(input) + + .. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.alpha_dropout(input, self.p, self.training) + + +class FeatureAlphaDropout(_DropoutNd): + r"""Randomly masks out entire channels. + + A channel is a feature map, + e.g. the :math:`j`-th channel of the :math:`i`-th sample in the batch input + is a tensor :math:`\text{input}[i, j]` of the input tensor). Instead of + setting activations to zero, as in regular Dropout, the activations are set + to the negative saturation value of the SELU activation function. More details + can be found in the paper `Self-Normalizing Neural Networks`_ . + + Each element will be masked independently for each sample on every forward + call with probability :attr:`p` using samples from a Bernoulli distribution. + The elements to be masked are randomized on every forward call, and scaled + and shifted to maintain zero mean and unit variance. + + Usually the input comes from :class:`nn.AlphaDropout` modules. + + As described in the paper + `Efficient Object Localization Using Convolutional Networks`_ , + if adjacent pixels within feature maps are strongly correlated + (as is normally the case in early convolution layers) then i.i.d. dropout + will not regularize the activations and will otherwise just result + in an effective learning rate decrease. + + In this case, :func:`nn.AlphaDropout` will help promote independence between + feature maps and should be used instead. + + Args: + p (float, optional): probability of an element to be zeroed. Default: 0.5 + inplace (bool, optional): If set to ``True``, will do this operation + in-place + + Shape: + - Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`. + - Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input). + + Examples:: + + >>> m = nn.FeatureAlphaDropout(p=0.2) + >>> input = torch.randn(20, 16, 4, 32, 32) + >>> output = m(input) + + .. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515 + .. _Efficient Object Localization Using Convolutional Networks: + https://arxiv.org/abs/1411.4280 + """ + + def forward(self, input: Tensor) -> Tensor: + return F.feature_alpha_dropout(input, self.p, self.training) diff --git a/shared/package-files/1f/1fd71ee35429f0115920634541b847031ffad296f78e2d1882b4b029bc09478f/promoted_prim_ops.h b/shared/package-files/1f/1fd71ee35429f0115920634541b847031ffad296f78e2d1882b4b029bc09478f/promoted_prim_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..71baa74f95ae5a0b1c03e6f3d09fad8355a36a9c --- /dev/null +++ b/shared/package-files/1f/1fd71ee35429f0115920634541b847031ffad296f78e2d1882b4b029bc09478f/promoted_prim_ops.h @@ -0,0 +1,61 @@ +#pragma once +#include +#include + +namespace torch::jit { + +void tupleIndex(Stack& stack); + +void raiseException(Stack& stack); + +void is(Stack& stack); + +void unInitialized(Stack& stack); + +void isNot(Stack& stack); + +void aten_format(Stack& stack); + +void size(Stack& stack); + +void sym_size(Stack& stack); + +void sym_size_int(Stack& stack); + +void sym_stride_int(Stack& stack); + +void sym_numel(Stack& stack); + +void sym_storage_offset(Stack& stack); + +void sym_stride(Stack& stack); + +void device(Stack& stack); + +void device_with_index(Stack& stack); + +void dtype(Stack& stack); + +void layout(Stack& stack); + +void toPrimDType(Stack& stack); + +void dim(Stack& stack); + +void _not(Stack& stack); + +void boolTensor(Stack& stack); + +void toList(Stack& stack); + +void numToTensorScalar(Stack& stack); + +void isCuda(Stack& stack); + +void numToTensorBool(Stack& stack); + +void dictIndex(Stack& stack); + +void raiseExceptionWithMessage(Stack& stack); + +} // namespace torch::jit diff --git a/shared/package-files/1f/1fd775ef659081b02800297bccd01c54ccaa7da8188f1981f15e6065bbc20395/_semi_structured_conversions.cpython-311.pyc b/shared/package-files/1f/1fd775ef659081b02800297bccd01c54ccaa7da8188f1981f15e6065bbc20395/_semi_structured_conversions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af63bbe34339f8cb006970017a926e1858b6cb40 Binary files /dev/null and b/shared/package-files/1f/1fd775ef659081b02800297bccd01c54ccaa7da8188f1981f15e6065bbc20395/_semi_structured_conversions.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fdbcf68c43b541904b64c48e51c89f543970a62b36cf17bd29700b1835b3ff0/hip_runtime_api.h b/shared/package-files/1f/1fdbcf68c43b541904b64c48e51c89f543970a62b36cf17bd29700b1835b3ff0/hip_runtime_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0323d77d51175987517094539f06c2819235546a --- /dev/null +++ b/shared/package-files/1f/1fdbcf68c43b541904b64c48e51c89f543970a62b36cf17bd29700b1835b3ff0/hip_runtime_api.h @@ -0,0 +1,9261 @@ +/* +Copyright (c) 2015 - 2023 Advanced Micro Devices, Inc. All rights reserved. + +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. +*/ + +/** + * @file hip_runtime_api.h + * + * @brief Defines the API signatures for HIP runtime. + * This file can be compiled with a standard compiler. + */ + +#ifndef HIP_INCLUDE_HIP_HIP_RUNTIME_API_H +#define HIP_INCLUDE_HIP_HIP_RUNTIME_API_H + +#include // for getDeviceProp +#include +#include + +enum { + HIP_SUCCESS = 0, + HIP_ERROR_INVALID_VALUE, + HIP_ERROR_NOT_INITIALIZED, + HIP_ERROR_LAUNCH_OUT_OF_RESOURCES +}; +// hack to get these to show up in Doxygen: +/** + * @defgroup GlobalDefs Global enum and defines + * @{ + * + */ +/** + * hipDeviceArch_t + * + */ +typedef struct { + // 32-bit Atomics + unsigned hasGlobalInt32Atomics : 1; ///< 32-bit integer atomics for global memory. + unsigned hasGlobalFloatAtomicExch : 1; ///< 32-bit float atomic exch for global memory. + unsigned hasSharedInt32Atomics : 1; ///< 32-bit integer atomics for shared memory. + unsigned hasSharedFloatAtomicExch : 1; ///< 32-bit float atomic exch for shared memory. + unsigned hasFloatAtomicAdd : 1; ///< 32-bit float atomic add in global and shared memory. + + // 64-bit Atomics + unsigned hasGlobalInt64Atomics : 1; ///< 64-bit integer atomics for global memory. + unsigned hasSharedInt64Atomics : 1; ///< 64-bit integer atomics for shared memory. + + // Doubles + unsigned hasDoubles : 1; ///< Double-precision floating point. + + // Warp cross-lane operations + unsigned hasWarpVote : 1; ///< Warp vote instructions (__any, __all). + unsigned hasWarpBallot : 1; ///< Warp ballot instructions (__ballot). + unsigned hasWarpShuffle : 1; ///< Warp shuffle operations. (__shfl_*). + unsigned hasFunnelShift : 1; ///< Funnel two words into one with shift&mask caps. + + // Sync + unsigned hasThreadFenceSystem : 1; ///< __threadfence_system. + unsigned hasSyncThreadsExt : 1; ///< __syncthreads_count, syncthreads_and, syncthreads_or. + + // Misc + unsigned hasSurfaceFuncs : 1; ///< Surface functions. + unsigned has3dGrid : 1; ///< Grid and group dims are 3D (rather than 2D). + unsigned hasDynamicParallelism : 1; ///< Dynamic parallelism. +} hipDeviceArch_t; + +typedef struct hipUUID_t { + char bytes[16]; +} hipUUID; + +//--- +// Common headers for both NVCC and HCC paths: + +#define hipGetDeviceProperties hipGetDevicePropertiesR0600 +#define hipDeviceProp_t hipDeviceProp_tR0600 +#define hipChooseDevice hipChooseDeviceR0600 + +/** + * hipDeviceProp + * + */ +typedef struct hipDeviceProp_t { + char name[256]; ///< Device name. + hipUUID uuid; ///< UUID of a device + char luid[8]; ///< 8-byte unique identifier. Only valid on windows + unsigned int luidDeviceNodeMask; ///< LUID node mask + size_t totalGlobalMem; ///< Size of global memory region (in bytes). + size_t sharedMemPerBlock; ///< Size of shared memory per block (in bytes). + int regsPerBlock; ///< Registers per block. + int warpSize; ///< Warp size. + size_t memPitch; ///< Maximum pitch in bytes allowed by memory copies + ///< pitched memory + int maxThreadsPerBlock; ///< Max work items per work group or workgroup max size. + int maxThreadsDim[3]; ///< Max number of threads in each dimension (XYZ) of a block. + int maxGridSize[3]; ///< Max grid dimensions (XYZ). + int clockRate; ///< Max clock frequency of the multiProcessors in khz. + size_t totalConstMem; ///< Size of shared constant memory region on the device + ///< (in bytes). + int major; ///< Major compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + int minor; ///< Minor compute capability. On HCC, this is an approximation and features may + ///< differ from CUDA CC. See the arch feature flags for portable ways to query + ///< feature caps. + size_t textureAlignment; ///< Alignment requirement for textures + size_t texturePitchAlignment; ///< Pitch alignment requirement for texture references bound to + int deviceOverlap; ///< Deprecated. Use asyncEngineCount instead + int multiProcessorCount; ///< Number of multi-processors (compute units). + int kernelExecTimeoutEnabled; ///< Run time limit for kernels executed on the device + int integrated; ///< APU vs dGPU + int canMapHostMemory; ///< Check whether HIP can map host memory + int computeMode; ///< Compute mode. + int maxTexture1D; ///< Maximum number of elements in 1D images + int maxTexture1DMipmap; ///< Maximum 1D mipmap texture size + int maxTexture1DLinear; ///< Maximum size for 1D textures bound to linear memory + int maxTexture2D[2]; ///< Maximum dimensions (width, height) of 2D images, in image elements + int maxTexture2DMipmap[2]; ///< Maximum number of elements in 2D array mipmap of images + int maxTexture2DLinear[3]; ///< Maximum 2D tex dimensions if tex are bound to pitched memory + int maxTexture2DGather[2]; ///< Maximum 2D tex dimensions if gather has to be performed + int maxTexture3D[3]; ///< Maximum dimensions (width, height, depth) of 3D images, in image + ///< elements + int maxTexture3DAlt[3]; ///< Maximum alternate 3D texture dims + int maxTextureCubemap; ///< Maximum cubemap texture dims + int maxTexture1DLayered[2]; ///< Maximum number of elements in 1D array images + int maxTexture2DLayered[3]; ///< Maximum number of elements in 2D array images + int maxTextureCubemapLayered[2]; ///< Maximum cubemaps layered texture dims + int maxSurface1D; ///< Maximum 1D surface size + int maxSurface2D[2]; ///< Maximum 2D surface size + int maxSurface3D[3]; ///< Maximum 3D surface size + int maxSurface1DLayered[2]; ///< Maximum 1D layered surface size + int maxSurface2DLayered[3]; ///< Maximum 2D layared surface size + int maxSurfaceCubemap; ///< Maximum cubemap surface size + int maxSurfaceCubemapLayered[2]; ///< Maximum cubemap layered surface size + size_t surfaceAlignment; ///< Alignment requirement for surface + int concurrentKernels; ///< Device can possibly execute multiple kernels concurrently. + int ECCEnabled; ///< Device has ECC support enabled + int pciBusID; ///< PCI Bus ID. + int pciDeviceID; ///< PCI Device ID. + int pciDomainID; ///< PCI Domain ID + int tccDriver; ///< 1:If device is Tesla device using TCC driver, else 0 + int asyncEngineCount; ///< Number of async engines + int unifiedAddressing; ///< Does device and host share unified address space + int memoryClockRate; ///< Max global memory clock frequency in khz. + int memoryBusWidth; ///< Global memory bus width in bits. + int l2CacheSize; ///< L2 cache size. + int persistingL2CacheMaxSize; ///< Device's max L2 persisting lines in bytes + int maxThreadsPerMultiProcessor; ///< Maximum resident threads per multi-processor. + int streamPrioritiesSupported; ///< Device supports stream priority + int globalL1CacheSupported; ///< Indicates globals are cached in L1 + int localL1CacheSupported; ///< Locals are cahced in L1 + size_t sharedMemPerMultiprocessor; ///< Amount of shared memory available per multiprocessor. + int regsPerMultiprocessor; ///< registers available per multiprocessor + int managedMemory; ///< Device supports allocating managed memory on this system + int isMultiGpuBoard; ///< 1 if device is on a multi-GPU board, 0 if not. + int multiGpuBoardGroupID; ///< Unique identifier for a group of devices on same multiboard GPU + int hostNativeAtomicSupported; ///< Link between host and device supports native atomics + int singleToDoublePrecisionPerfRatio; ///< Deprecated. CUDA only. + int pageableMemoryAccess; ///< Device supports coherently accessing pageable memory + ///< without calling hipHostRegister on it + int concurrentManagedAccess; ///< Device can coherently access managed memory concurrently with + ///< the CPU + int computePreemptionSupported; ///< Is compute preemption supported on the device + int canUseHostPointerForRegisteredMem; ///< Device can access host registered memory with same + ///< address as the host + int cooperativeLaunch; ///< HIP device supports cooperative launch + int cooperativeMultiDeviceLaunch; ///< HIP device supports cooperative launch on multiple + ///< devices + size_t + sharedMemPerBlockOptin; ///< Per device m ax shared mem per block usable by special opt in + int pageableMemoryAccessUsesHostPageTables; ///< Device accesses pageable memory via the host's + ///< page tables + int directManagedMemAccessFromHost; ///< Host can directly access managed memory on the device + ///< without migration + int maxBlocksPerMultiProcessor; ///< Max number of blocks on CU + int accessPolicyMaxWindowSize; ///< Max value of access policy window + size_t reservedSharedMemPerBlock; ///< Shared memory reserved by driver per block + int hostRegisterSupported; ///< Device supports hipHostRegister + int sparseHipArraySupported; ///< Indicates if device supports sparse hip arrays + int hostRegisterReadOnlySupported; ///< Device supports using the hipHostRegisterReadOnly flag + ///< with hipHostRegistger + int timelineSemaphoreInteropSupported; ///< Indicates external timeline semaphore support + int memoryPoolsSupported; ///< Indicates if device supports hipMallocAsync and hipMemPool APIs + int gpuDirectRDMASupported; ///< Indicates device support of RDMA APIs + unsigned int gpuDirectRDMAFlushWritesOptions; ///< Bitmask to be interpreted according to + ///< hipFlushGPUDirectRDMAWritesOptions + int gpuDirectRDMAWritesOrdering; ///< value of hipGPUDirectRDMAWritesOrdering + unsigned int + memoryPoolSupportedHandleTypes; ///< Bitmask of handle types support with mempool based IPC + int deferredMappingHipArraySupported; ///< Device supports deferred mapping HIP arrays and HIP + ///< mipmapped arrays + int ipcEventSupported; ///< Device supports IPC events + int clusterLaunch; ///< Device supports cluster launch + int unifiedFunctionPointers; ///< Indicates device supports unified function pointers + int reserved[63]; ///< CUDA Reserved. + + int hipReserved[32]; ///< Reserved for adding new entries for HIP/CUDA. + + /* HIP Only struct members */ + char gcnArchName[256]; ///< AMD GCN Arch Name. HIP Only. + size_t maxSharedMemoryPerMultiProcessor; ///< Maximum Shared Memory Per CU. HIP Only. + int clockInstructionRate; ///< Frequency in khz of the timer used by the device-side "clock*" + ///< instructions. New for HIP. + hipDeviceArch_t arch; ///< Architectural feature flags. New for HIP. + unsigned int* hdpMemFlushCntl; ///< Addres of HDP_MEM_COHERENCY_FLUSH_CNTL register + unsigned int* hdpRegFlushCntl; ///< Addres of HDP_REG_COHERENCY_FLUSH_CNTL register + int cooperativeMultiDeviceUnmatchedFunc; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched functions + int cooperativeMultiDeviceUnmatchedGridDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched grid dimensions + int cooperativeMultiDeviceUnmatchedBlockDim; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched block dimensions + int cooperativeMultiDeviceUnmatchedSharedMem; ///< HIP device supports cooperative launch on + ///< multiple + /// devices with unmatched shared memories + int isLargeBar; ///< 1: if it is a large PCI bar device, else 0 + int asicRevision; ///< Revision of the GPU in this device +} hipDeviceProp_t; + + /** + * hipMemoryType (for pointer attributes) + * + * @note hipMemoryType enum values are combination of cudaMemoryType and cuMemoryType and AMD specific enum values. + * + */ +typedef enum hipMemoryType { + hipMemoryTypeUnregistered = 0, ///< Unregistered memory + hipMemoryTypeHost = 1, ///< Memory is physically located on host + hipMemoryTypeDevice = 2, ///< Memory is physically located on device. (see deviceId for + ///< specific device) + hipMemoryTypeManaged = 3, ///< Managed memory, automaticallly managed by the unified + ///< memory system + ///< place holder for new values. + hipMemoryTypeArray = 10, ///< Array memory, physically located on device. (see deviceId for + ///< specific device) + hipMemoryTypeUnified = 11 ///< unified address space + +} hipMemoryType; + +/** + * Pointer attributes + */ +typedef struct hipPointerAttribute_t { + enum hipMemoryType type; + int device; + void* devicePointer; + void* hostPointer; + int isManaged; + unsigned allocationFlags; /* flags specified when memory was allocated*/ + /* peers? */ +} hipPointerAttribute_t; + +// Ignoring error-code return values from hip APIs is discouraged. On C++17, +// we can make that yield a warning +#if __cplusplus >= 201703L +#define __HIP_NODISCARD [[nodiscard]] +#else +#define __HIP_NODISCARD +#endif + +/** + * HIP error type + * + */ +// Developer note - when updating these, update the hipErrorName and hipErrorString functions in +// NVCC and HCC paths Also update the hipCUDAErrorTohipError function in NVCC path. + +typedef enum __HIP_NODISCARD hipError_t { + hipSuccess = 0, ///< Successful completion. + hipErrorInvalidValue = 1, ///< One or more of the parameters passed to the API call is NULL + ///< or not in an acceptable range. + hipErrorOutOfMemory = 2, ///< out of memory range. + // Deprecated + hipErrorMemoryAllocation = 2, ///< Memory allocation error. + hipErrorNotInitialized = 3, ///< Invalid not initialized + // Deprecated + hipErrorInitializationError = 3, + hipErrorDeinitialized = 4, ///< Deinitialized + hipErrorProfilerDisabled = 5, + hipErrorProfilerNotInitialized = 6, + hipErrorProfilerAlreadyStarted = 7, + hipErrorProfilerAlreadyStopped = 8, + hipErrorInvalidConfiguration = 9, ///< Invalide configuration + hipErrorInvalidPitchValue = 12, ///< Invalid pitch value + hipErrorInvalidSymbol = 13, ///< Invalid symbol + hipErrorInvalidDevicePointer = 17, ///< Invalid Device Pointer + hipErrorInvalidMemcpyDirection = 21, ///< Invalid memory copy direction + hipErrorInsufficientDriver = 35, + hipErrorMissingConfiguration = 52, + hipErrorPriorLaunchFailure = 53, + hipErrorInvalidDeviceFunction = 98, ///< Invalid device function + hipErrorNoDevice = 100, ///< Call to hipGetDeviceCount returned 0 devices + hipErrorInvalidDevice = 101, ///< DeviceID must be in range from 0 to compute-devices. + hipErrorInvalidImage = 200, ///< Invalid image + hipErrorInvalidContext = 201, ///< Produced when input context is invalid. + hipErrorContextAlreadyCurrent = 202, + hipErrorMapFailed = 205, + // Deprecated + hipErrorMapBufferObjectFailed = 205, ///< Produced when the IPC memory attach failed from ROCr. + hipErrorUnmapFailed = 206, + hipErrorArrayIsMapped = 207, + hipErrorAlreadyMapped = 208, + hipErrorNoBinaryForGpu = 209, + hipErrorAlreadyAcquired = 210, + hipErrorNotMapped = 211, + hipErrorNotMappedAsArray = 212, + hipErrorNotMappedAsPointer = 213, + hipErrorECCNotCorrectable = 214, + hipErrorUnsupportedLimit = 215, ///< Unsupported limit + hipErrorContextAlreadyInUse = 216, ///< The context is already in use + hipErrorPeerAccessUnsupported = 217, + hipErrorInvalidKernelFile = 218, ///< In CUDA DRV, it is CUDA_ERROR_INVALID_PTX + hipErrorInvalidGraphicsContext = 219, + hipErrorInvalidSource = 300, ///< Invalid source. + hipErrorFileNotFound = 301, ///< the file is not found. + hipErrorSharedObjectSymbolNotFound = 302, + hipErrorSharedObjectInitFailed = 303, ///< Failed to initialize shared object. + hipErrorOperatingSystem = 304, ///< Not the correct operating system + hipErrorInvalidHandle = 400, ///< Invalide handle + // Deprecated + hipErrorInvalidResourceHandle = 400, ///< Resource handle (hipEvent_t or hipStream_t) invalid. + hipErrorIllegalState = 401, ///< Resource required is not in a valid state to perform operation. + hipErrorNotFound = 500, ///< Not found + hipErrorNotReady = 600, ///< Indicates that asynchronous operations enqueued earlier are not + ///< ready. This is not actually an error, but is used to distinguish + ///< from hipSuccess (which indicates completion). APIs that return + ///< this error include hipEventQuery and hipStreamQuery. + hipErrorIllegalAddress = 700, + hipErrorLaunchOutOfResources = 701, ///< Out of resources error. + hipErrorLaunchTimeOut = 702, ///< Timeout for the launch. + hipErrorPeerAccessAlreadyEnabled = 704, ///< Peer access was already enabled from the current + ///< device. + hipErrorPeerAccessNotEnabled = 705, ///< Peer access was never enabled from the current device. + hipErrorSetOnActiveProcess = 708, ///< The process is active. + hipErrorContextIsDestroyed = 709, ///< The context is already destroyed + hipErrorAssert = 710, ///< Produced when the kernel calls assert. + hipErrorHostMemoryAlreadyRegistered = 712, ///< Produced when trying to lock a page-locked + ///< memory. + hipErrorHostMemoryNotRegistered = 713, ///< Produced when trying to unlock a non-page-locked + ///< memory. + hipErrorLaunchFailure = 719, ///< An exception occurred on the device while executing a kernel. + hipErrorCooperativeLaunchTooLarge = 720, ///< This error indicates that the number of blocks + ///< launched per grid for a kernel that was launched + ///< via cooperative launch APIs exceeds the maximum + ///< number of allowed blocks for the current device. + hipErrorNotSupported = 801, ///< Produced when the hip API is not supported/implemented + hipErrorStreamCaptureUnsupported = 900, ///< The operation is not permitted when the stream + ///< is capturing. + hipErrorStreamCaptureInvalidated = 901, ///< The current capture sequence on the stream + ///< has been invalidated due to a previous error. + hipErrorStreamCaptureMerge = 902, ///< The operation would have resulted in a merge of + ///< two independent capture sequences. + hipErrorStreamCaptureUnmatched = 903, ///< The capture was not initiated in this stream. + hipErrorStreamCaptureUnjoined = 904, ///< The capture sequence contains a fork that was not + ///< joined to the primary stream. + hipErrorStreamCaptureIsolation = 905, ///< A dependency would have been created which crosses + ///< the capture sequence boundary. Only implicit + ///< in-stream ordering dependencies are allowed + ///< to cross the boundary + hipErrorStreamCaptureImplicit = 906, ///< The operation would have resulted in a disallowed + ///< implicit dependency on a current capture sequence + ///< from hipStreamLegacy. + hipErrorCapturedEvent = 907, ///< The operation is not permitted on an event which was last + ///< recorded in a capturing stream. + hipErrorStreamCaptureWrongThread = 908, ///< A stream capture sequence not initiated with + ///< the hipStreamCaptureModeRelaxed argument to + ///< hipStreamBeginCapture was passed to + ///< hipStreamEndCapture in a different thread. + hipErrorGraphExecUpdateFailure = 910, ///< This error indicates that the graph update + ///< not performed because it included changes which + ///< violated constraintsspecific to instantiated graph + ///< update. + hipErrorUnknown = 999, ///< Unknown error. + // HSA Runtime Error Codes start here. + hipErrorRuntimeMemory = 1052, ///< HSA runtime memory call returned error. Typically not seen + ///< in production systems. + hipErrorRuntimeOther = 1053, ///< HSA runtime call other than memory returned error. Typically + ///< not seen in production systems. + hipErrorTbd ///< Marker that more error codes are needed. +} hipError_t; + +#undef __HIP_NODISCARD + +/** + * hipDeviceAttribute_t + * hipDeviceAttributeUnused number: 5 + */ +typedef enum hipDeviceAttribute_t { + hipDeviceAttributeCudaCompatibleBegin = 0, + + hipDeviceAttributeEccEnabled = hipDeviceAttributeCudaCompatibleBegin, ///< Whether ECC support is enabled. + hipDeviceAttributeAccessPolicyMaxWindowSize, ///< Cuda only. The maximum size of the window policy in bytes. + hipDeviceAttributeAsyncEngineCount, ///< Asynchronous engines number. + hipDeviceAttributeCanMapHostMemory, ///< Whether host memory can be mapped into device address space + hipDeviceAttributeCanUseHostPointerForRegisteredMem,///< Device can access host registered memory + ///< at the same virtual address as the CPU + hipDeviceAttributeClockRate, ///< Peak clock frequency in kilohertz. + hipDeviceAttributeComputeMode, ///< Compute mode that device is currently in. + hipDeviceAttributeComputePreemptionSupported, ///< Device supports Compute Preemption. + hipDeviceAttributeConcurrentKernels, ///< Device can possibly execute multiple kernels concurrently. + hipDeviceAttributeConcurrentManagedAccess, ///< Device can coherently access managed memory concurrently with the CPU + hipDeviceAttributeCooperativeLaunch, ///< Support cooperative launch + hipDeviceAttributeCooperativeMultiDeviceLaunch, ///< Support cooperative launch on multiple devices + hipDeviceAttributeDeviceOverlap, ///< Device can concurrently copy memory and execute a kernel. + ///< Deprecated. Use instead asyncEngineCount. + hipDeviceAttributeDirectManagedMemAccessFromHost, ///< Host can directly access managed memory on + ///< the device without migration + hipDeviceAttributeGlobalL1CacheSupported, ///< Device supports caching globals in L1 + hipDeviceAttributeHostNativeAtomicSupported, ///< Link between the device and the host supports native atomic operations + hipDeviceAttributeIntegrated, ///< Device is integrated GPU + hipDeviceAttributeIsMultiGpuBoard, ///< Multiple GPU devices. + hipDeviceAttributeKernelExecTimeout, ///< Run time limit for kernels executed on the device + hipDeviceAttributeL2CacheSize, ///< Size of L2 cache in bytes. 0 if the device doesn't have L2 cache. + hipDeviceAttributeLocalL1CacheSupported, ///< caching locals in L1 is supported + hipDeviceAttributeLuid, ///< 8-byte locally unique identifier in 8 bytes. Undefined on TCC and non-Windows platforms + hipDeviceAttributeLuidDeviceNodeMask, ///< Luid device node mask. Undefined on TCC and non-Windows platforms + hipDeviceAttributeComputeCapabilityMajor, ///< Major compute capability version number. + hipDeviceAttributeManagedMemory, ///< Device supports allocating managed memory on this system + hipDeviceAttributeMaxBlocksPerMultiProcessor, ///< Max block size per multiprocessor + hipDeviceAttributeMaxBlockDimX, ///< Max block size in width. + hipDeviceAttributeMaxBlockDimY, ///< Max block size in height. + hipDeviceAttributeMaxBlockDimZ, ///< Max block size in depth. + hipDeviceAttributeMaxGridDimX, ///< Max grid size in width. + hipDeviceAttributeMaxGridDimY, ///< Max grid size in height. + hipDeviceAttributeMaxGridDimZ, ///< Max grid size in depth. + hipDeviceAttributeMaxSurface1D, ///< Maximum size of 1D surface. + hipDeviceAttributeMaxSurface1DLayered, ///< Cuda only. Maximum dimensions of 1D layered surface. + hipDeviceAttributeMaxSurface2D, ///< Maximum dimension (width, height) of 2D surface. + hipDeviceAttributeMaxSurface2DLayered, ///< Cuda only. Maximum dimensions of 2D layered surface. + hipDeviceAttributeMaxSurface3D, ///< Maximum dimension (width, height, depth) of 3D surface. + hipDeviceAttributeMaxSurfaceCubemap, ///< Cuda only. Maximum dimensions of Cubemap surface. + hipDeviceAttributeMaxSurfaceCubemapLayered, ///< Cuda only. Maximum dimension of Cubemap layered surface. + hipDeviceAttributeMaxTexture1DWidth, ///< Maximum size of 1D texture. + hipDeviceAttributeMaxTexture1DLayered, ///< Maximum dimensions of 1D layered texture. + hipDeviceAttributeMaxTexture1DLinear, ///< Maximum number of elements allocatable in a 1D linear texture. + ///< Use cudaDeviceGetTexture1DLinearMaxWidth() instead on Cuda. + hipDeviceAttributeMaxTexture1DMipmap, ///< Maximum size of 1D mipmapped texture. + hipDeviceAttributeMaxTexture2DWidth, ///< Maximum dimension width of 2D texture. + hipDeviceAttributeMaxTexture2DHeight, ///< Maximum dimension hight of 2D texture. + hipDeviceAttributeMaxTexture2DGather, ///< Maximum dimensions of 2D texture if gather operations performed. + hipDeviceAttributeMaxTexture2DLayered, ///< Maximum dimensions of 2D layered texture. + hipDeviceAttributeMaxTexture2DLinear, ///< Maximum dimensions (width, height, pitch) of 2D textures bound to pitched memory. + hipDeviceAttributeMaxTexture2DMipmap, ///< Maximum dimensions of 2D mipmapped texture. + hipDeviceAttributeMaxTexture3DWidth, ///< Maximum dimension width of 3D texture. + hipDeviceAttributeMaxTexture3DHeight, ///< Maximum dimension height of 3D texture. + hipDeviceAttributeMaxTexture3DDepth, ///< Maximum dimension depth of 3D texture. + hipDeviceAttributeMaxTexture3DAlt, ///< Maximum dimensions of alternate 3D texture. + hipDeviceAttributeMaxTextureCubemap, ///< Maximum dimensions of Cubemap texture + hipDeviceAttributeMaxTextureCubemapLayered, ///< Maximum dimensions of Cubemap layered texture. + hipDeviceAttributeMaxThreadsDim, ///< Maximum dimension of a block + hipDeviceAttributeMaxThreadsPerBlock, ///< Maximum number of threads per block. + hipDeviceAttributeMaxThreadsPerMultiProcessor, ///< Maximum resident threads per multiprocessor. + hipDeviceAttributeMaxPitch, ///< Maximum pitch in bytes allowed by memory copies + hipDeviceAttributeMemoryBusWidth, ///< Global memory bus width in bits. + hipDeviceAttributeMemoryClockRate, ///< Peak memory clock frequency in kilohertz. + hipDeviceAttributeComputeCapabilityMinor, ///< Minor compute capability version number. + hipDeviceAttributeMultiGpuBoardGroupID, ///< Unique ID of device group on the same multi-GPU board + hipDeviceAttributeMultiprocessorCount, ///< Number of multiprocessors on the device. + hipDeviceAttributeUnused1, ///< Previously hipDeviceAttributeName + hipDeviceAttributePageableMemoryAccess, ///< Device supports coherently accessing pageable memory + ///< without calling hipHostRegister on it + hipDeviceAttributePageableMemoryAccessUsesHostPageTables, ///< Device accesses pageable memory via the host's page tables + hipDeviceAttributePciBusId, ///< PCI Bus ID. + hipDeviceAttributePciDeviceId, ///< PCI Device ID. + hipDeviceAttributePciDomainID, ///< PCI Domain ID. + hipDeviceAttributePersistingL2CacheMaxSize, ///< Maximum l2 persisting lines capacity in bytes + hipDeviceAttributeMaxRegistersPerBlock, ///< 32-bit registers available to a thread block. This number is shared + ///< by all thread blocks simultaneously resident on a multiprocessor. + hipDeviceAttributeMaxRegistersPerMultiprocessor, ///< 32-bit registers available per block. + hipDeviceAttributeReservedSharedMemPerBlock, ///< Shared memory reserved by CUDA driver per block. + hipDeviceAttributeMaxSharedMemoryPerBlock, ///< Maximum shared memory available per block in bytes. + hipDeviceAttributeSharedMemPerBlockOptin, ///< Maximum shared memory per block usable by special opt in. + hipDeviceAttributeSharedMemPerMultiprocessor, ///< Shared memory available per multiprocessor. + hipDeviceAttributeSingleToDoublePrecisionPerfRatio, ///< Cuda only. Performance ratio of single precision to double precision. + hipDeviceAttributeStreamPrioritiesSupported, ///< Whether to support stream priorities. + hipDeviceAttributeSurfaceAlignment, ///< Alignment requirement for surfaces + hipDeviceAttributeTccDriver, ///< Cuda only. Whether device is a Tesla device using TCC driver + hipDeviceAttributeTextureAlignment, ///< Alignment requirement for textures + hipDeviceAttributeTexturePitchAlignment, ///< Pitch alignment requirement for 2D texture references bound to pitched memory; + hipDeviceAttributeTotalConstantMemory, ///< Constant memory size in bytes. + hipDeviceAttributeTotalGlobalMem, ///< Global memory available on devicice. + hipDeviceAttributeUnifiedAddressing, ///< Cuda only. An unified address space shared with the host. + hipDeviceAttributeUnused2, ///< Previously hipDeviceAttributeUuid + hipDeviceAttributeWarpSize, ///< Warp size in threads. + hipDeviceAttributeMemoryPoolsSupported, ///< Device supports HIP Stream Ordered Memory Allocator + hipDeviceAttributeVirtualMemoryManagementSupported, ///< Device supports HIP virtual memory management + hipDeviceAttributeHostRegisterSupported, ///< Can device support host memory registration via hipHostRegister + hipDeviceAttributeMemoryPoolSupportedHandleTypes, ///< Supported handle mask for HIP Stream Ordered Memory Allocator + + hipDeviceAttributeCudaCompatibleEnd = 9999, + hipDeviceAttributeAmdSpecificBegin = 10000, + + hipDeviceAttributeClockInstructionRate = hipDeviceAttributeAmdSpecificBegin, ///< Frequency in khz of the timer used by the device-side "clock*" + hipDeviceAttributeUnused3, ///< Previously hipDeviceAttributeArch + hipDeviceAttributeMaxSharedMemoryPerMultiprocessor, ///< Maximum Shared Memory PerMultiprocessor. + hipDeviceAttributeUnused4, ///< Previously hipDeviceAttributeGcnArch + hipDeviceAttributeUnused5, ///< Previously hipDeviceAttributeGcnArchName + hipDeviceAttributeHdpMemFlushCntl, ///< Address of the HDP_MEM_COHERENCY_FLUSH_CNTL register + hipDeviceAttributeHdpRegFlushCntl, ///< Address of the HDP_REG_COHERENCY_FLUSH_CNTL register + hipDeviceAttributeCooperativeMultiDeviceUnmatchedFunc, ///< Supports cooperative launch on multiple + ///< devices with unmatched functions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedGridDim, ///< Supports cooperative launch on multiple + ///< devices with unmatched grid dimensions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedBlockDim, ///< Supports cooperative launch on multiple + ///< devices with unmatched block dimensions + hipDeviceAttributeCooperativeMultiDeviceUnmatchedSharedMem, ///< Supports cooperative launch on multiple + ///< devices with unmatched shared memories + hipDeviceAttributeIsLargeBar, ///< Whether it is LargeBar + hipDeviceAttributeAsicRevision, ///< Revision of the GPU in this device + hipDeviceAttributeCanUseStreamWaitValue, ///< '1' if Device supports hipStreamWaitValue32() and + ///< hipStreamWaitValue64(), '0' otherwise. + hipDeviceAttributeImageSupport, ///< '1' if Device supports image, '0' otherwise. + hipDeviceAttributePhysicalMultiProcessorCount, ///< All available physical compute + ///< units for the device + hipDeviceAttributeFineGrainSupport, ///< '1' if Device supports fine grain, '0' otherwise + hipDeviceAttributeWallClockRate, ///< Constant frequency of wall clock in kilohertz. + + hipDeviceAttributeAmdSpecificEnd = 19999, + hipDeviceAttributeVendorSpecificBegin = 20000, + // Extended attributes for vendors +} hipDeviceAttribute_t; + +typedef enum hipDriverProcAddressQueryResult { + HIP_GET_PROC_ADDRESS_SUCCESS = 0, + HIP_GET_PROC_ADDRESS_SYMBOL_NOT_FOUND = 1, + HIP_GET_PROC_ADDRESS_VERSION_NOT_SUFFICIENT = 2 +} hipDriverProcAddressQueryResult; + +enum hipComputeMode { + hipComputeModeDefault = 0, + hipComputeModeExclusive = 1, + hipComputeModeProhibited = 2, + hipComputeModeExclusiveProcess = 3 +}; + +enum hipFlushGPUDirectRDMAWritesOptions { + hipFlushGPUDirectRDMAWritesOptionHost = 1 << 0, + hipFlushGPUDirectRDMAWritesOptionMemOps = 1 << 1 +}; + +enum hipGPUDirectRDMAWritesOrdering { + hipGPUDirectRDMAWritesOrderingNone = 0, + hipGPUDirectRDMAWritesOrderingOwner = 100, + hipGPUDirectRDMAWritesOrderingAllDevices = 200 +}; + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) + +#include +#include +#ifndef GENERIC_GRID_LAUNCH +#define GENERIC_GRID_LAUNCH 1 +#endif +#include +#include +#include +#include +#if defined(_MSC_VER) +#define DEPRECATED(msg) __declspec(deprecated(msg)) +#else // !defined(_MSC_VER) +#define DEPRECATED(msg) __attribute__ ((deprecated(msg))) +#endif // !defined(_MSC_VER) +#define DEPRECATED_MSG "This API is marked as deprecated and may not be supported in future releases. For more details please refer https://github.com/ROCm/HIP/blob/develop/docs/reference/deprecated_api_list.md" +#define HIP_LAUNCH_PARAM_BUFFER_POINTER ((void*)0x01) +#define HIP_LAUNCH_PARAM_BUFFER_SIZE ((void*)0x02) +#define HIP_LAUNCH_PARAM_END ((void*)0x03) +#ifdef __cplusplus + #define __dparm(x) \ + = x +#else + #define __dparm(x) +#endif +#ifdef __GNUC__ +#pragma GCC visibility push (default) +#endif +#ifdef __cplusplus +namespace hip_impl { +hipError_t hip_init(); +} // namespace hip_impl +#endif +// Structure definitions: +#ifdef __cplusplus +extern "C" { +#endif +//--- +// API-visible structures +typedef struct ihipCtx_t* hipCtx_t; +// Note many APIs also use integer deviceIds as an alternative to the device pointer: +typedef int hipDevice_t; +typedef enum hipDeviceP2PAttr { + hipDevP2PAttrPerformanceRank = 0, + hipDevP2PAttrAccessSupported, + hipDevP2PAttrNativeAtomicSupported, + hipDevP2PAttrHipArrayAccessSupported +} hipDeviceP2PAttr; +typedef struct ihipStream_t* hipStream_t; +#define hipIpcMemLazyEnablePeerAccess 0x01 +#define HIP_IPC_HANDLE_SIZE 64 +typedef struct hipIpcMemHandle_st { + char reserved[HIP_IPC_HANDLE_SIZE]; +} hipIpcMemHandle_t; +typedef struct hipIpcEventHandle_st { + char reserved[HIP_IPC_HANDLE_SIZE]; +} hipIpcEventHandle_t; +typedef struct ihipModule_t* hipModule_t; +typedef struct ihipModuleSymbol_t* hipFunction_t; +/** + * HIP memory pool + */ +typedef struct ihipMemPoolHandle_t* hipMemPool_t; + +typedef struct hipFuncAttributes { + int binaryVersion; + int cacheModeCA; + size_t constSizeBytes; + size_t localSizeBytes; + int maxDynamicSharedSizeBytes; + int maxThreadsPerBlock; + int numRegs; + int preferredShmemCarveout; + int ptxVersion; + size_t sharedSizeBytes; +} hipFuncAttributes; +typedef struct ihipEvent_t* hipEvent_t; + +/** + * hipLimit + * + * @note In HIP device limit-related APIs, any input limit value other than those defined in the + * enum is treated as "UnsupportedLimit" by default. + */ +enum hipLimit_t { + hipLimitStackSize = 0x0, ///< Limit of stack size in bytes on the current device, per + ///< thread. The size is in units of 256 dwords, up to the + ///< limit of (128K - 16) + hipLimitPrintfFifoSize = 0x01, ///< Size limit in bytes of fifo used by printf call on the + ///< device. Currently not supported + hipLimitMallocHeapSize = 0x02, ///< Limit of heap size in bytes on the current device, should + ///< be less than the global memory size on the device + hipLimitRange ///< Supported limit range +}; +/** + * Flags that can be used with hipStreamCreateWithFlags. + */ +//Flags that can be used with hipStreamCreateWithFlags. +/** Default stream creation flags. These are used with hipStreamCreate().*/ +#define hipStreamDefault 0x00 + +/** Stream does not implicitly synchronize with null stream.*/ +#define hipStreamNonBlocking 0x01 + +//Flags that can be used with hipEventCreateWithFlags. +/** Default flags.*/ +#define hipEventDefault 0x0 + +/** Waiting will yield CPU. Power-friendly and usage-friendly but may increase latency.*/ +#define hipEventBlockingSync 0x1 + +/** Disable event's capability to record timing information. May improve performance.*/ +#define hipEventDisableTiming 0x2 + +/** Event can support IPC. hipEventDisableTiming also must be set.*/ +#define hipEventInterprocess 0x4 + +/** Disable performing a system scope sequentially consistent memory fence when the event + * transitions from recording to recorded. This can be used for events that are only being + * used to measure timing, and do not require the event inspection operations + * (see ::hipEventSynchronize, ::hipEventQuery, and ::hipEventElapsedTime) to synchronize-with + * the work on which the recorded event (see ::hipEventRecord) is waiting. + * On some AMD GPU devices this can improve the accuracy of timing measurements by avoiding the + * cost of cache writeback and invalidation, and the performance impact of those actions on the + * execution of following work. */ +#define hipEventDisableSystemFence 0x20000000 + +/** Use a device-scope release when recording this event. This flag is useful to obtain more + * precise timings of commands between events. The flag is a no-op on CUDA platforms.*/ +#define hipEventReleaseToDevice 0x40000000 + +/** Use a system-scope release when recording this event. This flag is useful to make + * non-coherent host memory visible to the host. The flag is a no-op on CUDA platforms.*/ +#define hipEventReleaseToSystem 0x80000000 + +//Flags that can be used with hipHostMalloc. +/** Default pinned memory allocation on the host.*/ +#define hipHostMallocDefault 0x0 + +/** Memory is considered allocated by all contexts.*/ +#define hipHostMallocPortable 0x1 + +/** Map the allocation into the address space for the current device. The device pointer + * can be obtained with #hipHostGetDevicePointer.*/ +#define hipHostMallocMapped 0x2 + +/** Allocates the memory as write-combined. On some system configurations, write-combined allocation + * may be transferred faster across the PCI Express bus, however, could have low read efficiency by + * most CPUs. It's a good option for data tranfer from host to device via mapped pinned memory.*/ +#define hipHostMallocWriteCombined 0x4 + +/** +* Host memory allocation will follow numa policy set by user. +* @note This numa allocation flag is applicable on Linux, under development on Windows. +*/ +#define hipHostMallocNumaUser 0x20000000 + +/** Allocate coherent memory. Overrides HIP_COHERENT_HOST_ALLOC for specific allocation.*/ +#define hipHostMallocCoherent 0x40000000 + +/** Allocate non-coherent memory. Overrides HIP_COHERENT_HOST_ALLOC for specific allocation.*/ +#define hipHostMallocNonCoherent 0x80000000 + +/** Memory can be accessed by any stream on any device*/ +#define hipMemAttachGlobal 0x01 + +/** Memory cannot be accessed by any stream on any device.*/ +#define hipMemAttachHost 0x02 + +/** Memory can only be accessed by a single stream on the associated device.*/ +#define hipMemAttachSingle 0x04 + +#define hipDeviceMallocDefault 0x0 + +/** Memory is allocated in fine grained region of device.*/ +#define hipDeviceMallocFinegrained 0x1 + +/** Memory represents a HSA signal.*/ +#define hipMallocSignalMemory 0x2 + +/** Memory allocated will be uncached. */ +#define hipDeviceMallocUncached 0x3 + +/** Memory allocated will be contiguous. */ +#define hipDeviceMallocContiguous 0x4 + +//Flags that can be used with hipHostRegister. +/** Memory is Mapped and Portable.*/ +#define hipHostRegisterDefault 0x0 + +/** Memory is considered registered by all contexts.*/ +#define hipHostRegisterPortable 0x1 + +/** Map the allocation into the address space for the current device. The device pointer + * can be obtained with #hipHostGetDevicePointer.*/ +#define hipHostRegisterMapped 0x2 + +/** Not supported.*/ +#define hipHostRegisterIoMemory 0x4 + +/** This flag is ignored On AMD devices.*/ +#define hipHostRegisterReadOnly 0x08 + +/** Coarse Grained host memory lock.*/ +#define hipExtHostRegisterCoarseGrained 0x8 + +/** Automatically select between Spin and Yield.*/ +#define hipDeviceScheduleAuto 0x0 + +/** Dedicate a CPU core to spin-wait. Provides lowest latency, but burns a CPU core and may + * consume more power.*/ +#define hipDeviceScheduleSpin 0x1 + +/** Yield the CPU to the operating system when waiting. May increase latency, but lowers power + * and is friendlier to other threads in the system.*/ +#define hipDeviceScheduleYield 0x2 +#define hipDeviceScheduleBlockingSync 0x4 +#define hipDeviceScheduleMask 0x7 +#define hipDeviceMapHost 0x8 +#define hipDeviceLmemResizeToMax 0x10 +/** Default HIP array allocation flag.*/ +#define hipArrayDefault 0x00 +#define hipArrayLayered 0x01 +#define hipArraySurfaceLoadStore 0x02 +#define hipArrayCubemap 0x04 +#define hipArrayTextureGather 0x08 +#define hipOccupancyDefault 0x00 +#define hipOccupancyDisableCachingOverride 0x01 +#define hipCooperativeLaunchMultiDeviceNoPreSync 0x01 +#define hipCooperativeLaunchMultiDeviceNoPostSync 0x02 +#define hipCpuDeviceId ((int)-1) +#define hipInvalidDeviceId ((int)-2) +//Flags that can be used with hipExtLaunch Set of APIs. +/** AnyOrderLaunch of kernels.*/ +#define hipExtAnyOrderLaunch 0x01 +// Flags to be used with hipStreamWaitValue32 and hipStreamWaitValue64. +#define hipStreamWaitValueGte 0x0 +#define hipStreamWaitValueEq 0x1 +#define hipStreamWaitValueAnd 0x2 +#define hipStreamWaitValueNor 0x3 +// Stream per thread +/** Implicit stream per application thread.*/ +#define hipStreamPerThread ((hipStream_t)2) + +#define hipStreamLegacy ((hipStream_t)1) + +// Indicates that the external memory object is a dedicated resource +#define hipExternalMemoryDedicated 0x1 +/** + * HIP Memory Advise values + * + * @note This memory advise enumeration is used on Linux, not Windows. + */ +typedef enum hipMemoryAdvise { + hipMemAdviseSetReadMostly = 1, ///< Data will mostly be read and only occassionally + ///< be written to + hipMemAdviseUnsetReadMostly = 2, ///< Undo the effect of hipMemAdviseSetReadMostly + hipMemAdviseSetPreferredLocation = 3, ///< Set the preferred location for the data as + ///< the specified device + hipMemAdviseUnsetPreferredLocation = 4, ///< Clear the preferred location for the data + hipMemAdviseSetAccessedBy = 5, ///< Data will be accessed by the specified device + ///< so prevent page faults as much as possible + hipMemAdviseUnsetAccessedBy = 6, ///< Let HIP to decide on the page faulting policy + ///< for the specified device + hipMemAdviseSetCoarseGrain = 100, ///< The default memory model is fine-grain. That allows + ///< coherent operations between host and device, while + ///< executing kernels. The coarse-grain can be used + ///< for data that only needs to be coherent at dispatch + ///< boundaries for better performance + hipMemAdviseUnsetCoarseGrain = 101 ///< Restores cache coherency policy back to fine-grain +} hipMemoryAdvise; +/** + * HIP Coherency Mode + */ +typedef enum hipMemRangeCoherencyMode { + hipMemRangeCoherencyModeFineGrain = 0, ///< Updates to memory with this attribute can be + ///< done coherently from all devices + hipMemRangeCoherencyModeCoarseGrain = 1, ///< Writes to memory with this attribute can be + ///< performed by a single device at a time + hipMemRangeCoherencyModeIndeterminate = 2 ///< Memory region queried contains subregions with + ///< both hipMemRangeCoherencyModeFineGrain and + ///< hipMemRangeCoherencyModeCoarseGrain attributes +} hipMemRangeCoherencyMode; +/** + * HIP range attributes + */ +typedef enum hipMemRangeAttribute { + hipMemRangeAttributeReadMostly = 1, ///< Whether the range will mostly be read and + ///< only occassionally be written to + hipMemRangeAttributePreferredLocation = 2, ///< The preferred location of the range + hipMemRangeAttributeAccessedBy = 3, ///< Memory range has hipMemAdviseSetAccessedBy + ///< set for the specified device + hipMemRangeAttributeLastPrefetchLocation = 4,///< The last location to where the range was + ///< prefetched + hipMemRangeAttributeCoherencyMode = 100, ///< Returns coherency mode + ///< @ref hipMemRangeCoherencyMode for the range +} hipMemRangeAttribute; + +/** + * HIP memory pool attributes + */ +typedef enum hipMemPoolAttr +{ + /** + * (value type = int) + * Allow @p hipMemAllocAsync to use memory asynchronously freed + * in another streams as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * hip events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + */ + hipMemPoolReuseFollowEventDependencies = 0x1, + /** + * (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + */ + hipMemPoolReuseAllowOpportunistic = 0x2, + /** + * (value type = int) + * Allow @p hipMemAllocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by cuFreeAsync (default enabled). + */ + hipMemPoolReuseAllowInternalDependencies = 0x3, + /** + * (value type = uint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + */ + hipMemPoolAttrReleaseThreshold = 0x4, + /** + * (value type = uint64_t) + * Amount of backing memory currently allocated for the mempool. + */ + hipMemPoolAttrReservedMemCurrent = 0x5, + /** + * (value type = uint64_t) + * High watermark of backing memory allocated for the mempool since the + * last time it was reset. High watermark can only be reset to zero. + */ + hipMemPoolAttrReservedMemHigh = 0x6, + /** + * (value type = uint64_t) + * Amount of memory from the pool that is currently in use by the application. + */ + hipMemPoolAttrUsedMemCurrent = 0x7, + /** + * (value type = uint64_t) + * High watermark of the amount of memory from the pool that was in use by the application since + * the last time it was reset. High watermark can only be reset to zero. + */ + hipMemPoolAttrUsedMemHigh = 0x8 +} hipMemPoolAttr; +/** + * Specifies the type of location + */ + typedef enum hipMemLocationType { + hipMemLocationTypeInvalid = 0, + hipMemLocationTypeDevice = 1 ///< Device location, thus it's HIP device ID +} hipMemLocationType; +/** + * Specifies a memory location. + * + * To specify a gpu, set type = @p hipMemLocationTypeDevice and set id = the gpu's device ID + */ +typedef struct hipMemLocation { + hipMemLocationType type; ///< Specifies the location type, which describes the meaning of id + int id; ///< Identifier for the provided location type @p hipMemLocationType +} hipMemLocation; +/** + * Specifies the memory protection flags for mapping + * + */ +typedef enum hipMemAccessFlags { + hipMemAccessFlagsProtNone = 0, ///< Default, make the address range not accessible + hipMemAccessFlagsProtRead = 1, ///< Set the address range read accessible + hipMemAccessFlagsProtReadWrite = 3 ///< Set the address range read-write accessible +} hipMemAccessFlags; +/** + * Memory access descriptor + */ +typedef struct hipMemAccessDesc { + hipMemLocation location; ///< Location on which the accessibility has to change + hipMemAccessFlags flags; ///< Accessibility flags to set +} hipMemAccessDesc; +/** + * Defines the allocation types + */ +typedef enum hipMemAllocationType { + hipMemAllocationTypeInvalid = 0x0, + /** This allocation type is 'pinned', i.e. cannot migrate from its current + * location while the application is actively using it + */ + hipMemAllocationTypePinned = 0x1, + hipMemAllocationTypeMax = 0x7FFFFFFF +} hipMemAllocationType; +/** + * Flags for specifying handle types for memory pool allocations + * + */ +typedef enum hipMemAllocationHandleType { + hipMemHandleTypeNone = 0x0, ///< Does not allow any export mechanism + hipMemHandleTypePosixFileDescriptor = 0x1, ///< Allows a file descriptor for exporting. Permitted only on POSIX systems + hipMemHandleTypeWin32 = 0x2, ///< Allows a Win32 NT handle for exporting. (HANDLE) + hipMemHandleTypeWin32Kmt = 0x4 ///< Allows a Win32 KMT handle for exporting. (D3DKMT_HANDLE) +} hipMemAllocationHandleType; +/** + * Specifies the properties of allocations made from the pool. + */ +typedef struct hipMemPoolProps { + hipMemAllocationType allocType; ///< Allocation type. Currently must be specified as @p hipMemAllocationTypePinned + hipMemAllocationHandleType handleTypes; ///< Handle types that will be supported by allocations from the pool + hipMemLocation location; ///< Location where allocations should reside + /** + * Windows-specific LPSECURITYATTRIBUTES required when @p hipMemHandleTypeWin32 is specified + */ + void* win32SecurityAttributes; + size_t maxSize; ///< Maximum pool size. When set to 0, defaults to a system dependent value + unsigned char reserved[56]; ///< Reserved for future use, must be 0 +} hipMemPoolProps; +/** + * Opaque data structure for exporting a pool allocation + */ +typedef struct hipMemPoolPtrExportData { + unsigned char reserved[64]; +} hipMemPoolPtrExportData; + +/** + * hipJitOption + */ +typedef enum hipJitOption { + hipJitOptionMaxRegisters = 0, + hipJitOptionThreadsPerBlock, + hipJitOptionWallTime, + hipJitOptionInfoLogBuffer, + hipJitOptionInfoLogBufferSizeBytes, + hipJitOptionErrorLogBuffer, + hipJitOptionErrorLogBufferSizeBytes, + hipJitOptionOptimizationLevel, + hipJitOptionTargetFromContext, + hipJitOptionTarget, + hipJitOptionFallbackStrategy, + hipJitOptionGenerateDebugInfo, + hipJitOptionLogVerbose, + hipJitOptionGenerateLineInfo, + hipJitOptionCacheMode, + hipJitOptionSm3xOpt, + hipJitOptionFastCompile, + hipJitOptionNumOptions +} hipJitOption; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipFuncAttribute { + hipFuncAttributeMaxDynamicSharedMemorySize = 8, + hipFuncAttributePreferredSharedMemoryCarveout = 9, + hipFuncAttributeMax +} hipFuncAttribute; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipFuncCache_t { + hipFuncCachePreferNone, ///< no preference for shared memory or L1 (default) + hipFuncCachePreferShared, ///< prefer larger shared memory and smaller L1 cache + hipFuncCachePreferL1, ///< prefer larger L1 cache and smaller shared memory + hipFuncCachePreferEqual, ///< prefer equal size L1 cache and shared memory +} hipFuncCache_t; +/** + * @warning On AMD devices and some Nvidia devices, these hints and controls are ignored. + */ +typedef enum hipSharedMemConfig { + hipSharedMemBankSizeDefault, ///< The compiler selects a device-specific value for the banking. + hipSharedMemBankSizeFourByte, ///< Shared mem is banked at 4-bytes intervals and performs best + ///< when adjacent threads access data 4 bytes apart. + hipSharedMemBankSizeEightByte ///< Shared mem is banked at 8-byte intervals and performs best + ///< when adjacent threads access data 4 bytes apart. +} hipSharedMemConfig; +/** + * Struct for data in 3D + */ +typedef struct dim3 { + uint32_t x; ///< x + uint32_t y; ///< y + uint32_t z; ///< z +#ifdef __cplusplus + constexpr __host__ __device__ dim3(uint32_t _x = 1, uint32_t _y = 1, uint32_t _z = 1) : x(_x), y(_y), z(_z){}; +#endif +} dim3; +/** + * struct hipLaunchParams_t + */ +typedef struct hipLaunchParams_t { + void* func; ///< Device function symbol + dim3 gridDim; ///< Grid dimentions + dim3 blockDim; ///< Block dimentions + void **args; ///< Arguments + size_t sharedMem; ///< Shared memory + hipStream_t stream; ///< Stream identifier +} hipLaunchParams; +/** + * struct hipFunctionLaunchParams_t + */ +typedef struct hipFunctionLaunchParams_t { + hipFunction_t function; ///< Kernel to launch + unsigned int gridDimX; ///< Width(X) of grid in blocks + unsigned int gridDimY; ///< Height(Y) of grid in blocks + unsigned int gridDimZ; ///< Depth(Z) of grid in blocks + unsigned int blockDimX; ///< X dimension of each thread block + unsigned int blockDimY; ///< Y dimension of each thread block + unsigned int blockDimZ; ///< Z dimension of each thread block + unsigned int sharedMemBytes; ///< Shared memory + hipStream_t hStream; ///< Stream identifier + void **kernelParams; ///< Kernel parameters +} hipFunctionLaunchParams; +typedef enum hipExternalMemoryHandleType_enum { + hipExternalMemoryHandleTypeOpaqueFd = 1, + hipExternalMemoryHandleTypeOpaqueWin32 = 2, + hipExternalMemoryHandleTypeOpaqueWin32Kmt = 3, + hipExternalMemoryHandleTypeD3D12Heap = 4, + hipExternalMemoryHandleTypeD3D12Resource = 5, + hipExternalMemoryHandleTypeD3D11Resource = 6, + hipExternalMemoryHandleTypeD3D11ResourceKmt = 7, + hipExternalMemoryHandleTypeNvSciBuf = 8 +} hipExternalMemoryHandleType; +typedef struct hipExternalMemoryHandleDesc_st { + hipExternalMemoryHandleType type; + union { + int fd; + struct { + void *handle; + const void *name; + } win32; + const void *nvSciBufObject; + } handle; + unsigned long long size; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalMemoryHandleDesc; +typedef struct hipExternalMemoryBufferDesc_st { + unsigned long long offset; + unsigned long long size; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalMemoryBufferDesc; +typedef struct hipExternalMemoryMipmappedArrayDesc_st { + unsigned long long offset; + hipChannelFormatDesc formatDesc; + hipExtent extent; + unsigned int flags; + unsigned int numLevels; +} hipExternalMemoryMipmappedArrayDesc; +typedef void* hipExternalMemory_t; +typedef enum hipExternalSemaphoreHandleType_enum { + hipExternalSemaphoreHandleTypeOpaqueFd = 1, + hipExternalSemaphoreHandleTypeOpaqueWin32 = 2, + hipExternalSemaphoreHandleTypeOpaqueWin32Kmt = 3, + hipExternalSemaphoreHandleTypeD3D12Fence = 4, + hipExternalSemaphoreHandleTypeD3D11Fence = 5, + hipExternalSemaphoreHandleTypeNvSciSync = 6, + hipExternalSemaphoreHandleTypeKeyedMutex = 7, + hipExternalSemaphoreHandleTypeKeyedMutexKmt = 8, + hipExternalSemaphoreHandleTypeTimelineSemaphoreFd = 9, + hipExternalSemaphoreHandleTypeTimelineSemaphoreWin32 = 10 +} hipExternalSemaphoreHandleType; +typedef struct hipExternalSemaphoreHandleDesc_st { + hipExternalSemaphoreHandleType type; + union { + int fd; + struct { + void* handle; + const void* name; + } win32; + const void* NvSciSyncObj; + } handle; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreHandleDesc; +typedef void* hipExternalSemaphore_t; +typedef struct hipExternalSemaphoreSignalParams_st { + struct { + struct { + unsigned long long value; + } fence; + union { + void *fence; + unsigned long long reserved; + } nvSciSync; + struct { + unsigned long long key; + } keyedMutex; + unsigned int reserved[12]; + } params; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreSignalParams; +/** + * External semaphore wait parameters, compatible with driver type + */ +typedef struct hipExternalSemaphoreWaitParams_st { + struct { + struct { + unsigned long long value; + } fence; + union { + void *fence; + unsigned long long reserved; + } nvSciSync; + struct { + unsigned long long key; + unsigned int timeoutMs; + } keyedMutex; + unsigned int reserved[10]; + } params; + unsigned int flags; + unsigned int reserved[16]; +} hipExternalSemaphoreWaitParams; + +#if __HIP_HAS_GET_PCH +/** + * Internal use only. This API may change in the future + * Pre-Compiled header for online compilation + */ + void __hipGetPCH(const char** pch, unsigned int*size); +#endif + +/** + * HIP Access falgs for Interop resources. + */ +typedef enum hipGraphicsRegisterFlags { + hipGraphicsRegisterFlagsNone = 0, + hipGraphicsRegisterFlagsReadOnly = 1, ///< HIP will not write to this registered resource + hipGraphicsRegisterFlagsWriteDiscard = + 2, ///< HIP will only write and will not read from this registered resource + hipGraphicsRegisterFlagsSurfaceLoadStore = 4, ///< HIP will bind this resource to a surface + hipGraphicsRegisterFlagsTextureGather = + 8 ///< HIP will perform texture gather operations on this registered resource +} hipGraphicsRegisterFlags; + +typedef struct _hipGraphicsResource hipGraphicsResource; + +typedef hipGraphicsResource* hipGraphicsResource_t; + +/** + * An opaque value that represents a hip graph + */ +typedef struct ihipGraph* hipGraph_t; +/** + * An opaque value that represents a hip graph node + */ +typedef struct hipGraphNode* hipGraphNode_t; +/** + * An opaque value that represents a hip graph Exec + */ +typedef struct hipGraphExec* hipGraphExec_t; + +/** + * An opaque value that represents a user obj + */ +typedef struct hipUserObject* hipUserObject_t; + + +/** + * hipGraphNodeType + */ +typedef enum hipGraphNodeType { + hipGraphNodeTypeKernel = 0, ///< GPU kernel node + hipGraphNodeTypeMemcpy = 1, ///< Memcpy node + hipGraphNodeTypeMemset = 2, ///< Memset node + hipGraphNodeTypeHost = 3, ///< Host (executable) node + hipGraphNodeTypeGraph = 4, ///< Node which executes an embedded graph + hipGraphNodeTypeEmpty = 5, ///< Empty (no-op) node + hipGraphNodeTypeWaitEvent = 6, ///< External event wait node + hipGraphNodeTypeEventRecord = 7, ///< External event record node + hipGraphNodeTypeExtSemaphoreSignal = 8, ///< External Semaphore signal node + hipGraphNodeTypeExtSemaphoreWait = 9, ///< External Semaphore wait node + hipGraphNodeTypeMemAlloc = 10, ///< Memory alloc node + hipGraphNodeTypeMemFree = 11, ///< Memory free node + hipGraphNodeTypeMemcpyFromSymbol = 12, ///< MemcpyFromSymbol node + hipGraphNodeTypeMemcpyToSymbol = 13, ///< MemcpyToSymbol node + hipGraphNodeTypeCount +} hipGraphNodeType; + +typedef void (*hipHostFn_t)(void* userData); +typedef struct hipHostNodeParams { + hipHostFn_t fn; + void* userData; +} hipHostNodeParams; +typedef struct hipKernelNodeParams { + dim3 blockDim; + void** extra; + void* func; + dim3 gridDim; + void** kernelParams; + unsigned int sharedMemBytes; +} hipKernelNodeParams; +typedef struct hipMemsetParams { + void* dst; + unsigned int elementSize; + size_t height; + size_t pitch; + unsigned int value; + size_t width; +} hipMemsetParams; + +typedef struct hipMemAllocNodeParams { + hipMemPoolProps poolProps; ///< Pool properties, which contain where + ///< the location should reside + const hipMemAccessDesc* accessDescs;///< The number of memory access descriptors. + ///< Must not be bigger than the number of GPUs + size_t accessDescCount; ///< The number of access descriptors + size_t bytesize; ///< The size of the requested allocation in bytes + void* dptr; ///< Returned device address of the allocation +} hipMemAllocNodeParams; + + +typedef enum hipAccessProperty { + hipAccessPropertyNormal = 0, + hipAccessPropertyStreaming = 1, + hipAccessPropertyPersisting = 2, +} hipAccessProperty; +typedef struct hipAccessPolicyWindow { + void* base_ptr; + hipAccessProperty hitProp; + float hitRatio; + hipAccessProperty missProp; + size_t num_bytes; +} hipAccessPolicyWindow; + +/** + * Launch Attribute ID + */ +typedef enum hipLaunchAttributeID { + hipLaunchAttributeAccessPolicyWindow = 1, /**< Valid for Streams, graph nodes, launches*/ + hipLaunchAttributeCooperative = 2, /**< Valid for graph nodes, launches */ + hipLaunchAttributePriority = 8, /**< Valid for graph node, streams, launches */ +} hipLaunchAttributeID; + +/** + * Launch Attribute Value + */ +typedef union hipLaunchAttributeValue { + hipAccessPolicyWindow accessPolicyWindow; /**< Value of launch attribute:: + hipLaunchAttributePolicyWindow. */ + int cooperative; /**< Value of launch attribute ::hipLaunchAttributeCooperative */ + int priority; /**< Value of launch attribute :: hipLaunchAttributePriority. Execution + priority of kernel. */ +} hipLaunchAttributeValue; + +/** + * Kernel node attributeID + */ +#define hipKernelNodeAttrID hipLaunchAttributeID +#define hipKernelNodeAttributeAccessPolicyWindow hipLaunchAttributeAccessPolicyWindow +#define hipKernelNodeAttributeCooperative hipLaunchAttributeCooperative +#define hipKernelNodeAttributePriority hipLaunchAttributePriority + +/** + * Kernel node attribute value + */ +#define hipKernelNodeAttrValue hipLaunchAttributeValue + +/** + * Memset node params + */ +typedef struct HIP_MEMSET_NODE_PARAMS { + hipDeviceptr_t dst; ///< Destination pointer on device + size_t pitch; ///< Destination device pointer pitch. Unused if height equals 1 + unsigned int value; ///< Value of memset to be set + unsigned int elementSize; ///< Element in bytes. Must be 1, 2, or 4. + size_t width; ///< Width of a row + size_t height; ///< Number of rows +} HIP_MEMSET_NODE_PARAMS; + +/** + * Graph execution update result + */ +typedef enum hipGraphExecUpdateResult { + hipGraphExecUpdateSuccess = 0x0, ///< The update succeeded + hipGraphExecUpdateError = 0x1, ///< The update failed for an unexpected reason which is described + ///< in the return value of the function + hipGraphExecUpdateErrorTopologyChanged = 0x2, ///< The update failed because the topology changed + hipGraphExecUpdateErrorNodeTypeChanged = 0x3, ///< The update failed because a node type changed + hipGraphExecUpdateErrorFunctionChanged = + 0x4, ///< The update failed because the function of a kernel node changed + hipGraphExecUpdateErrorParametersChanged = + 0x5, ///< The update failed because the parameters changed in a way that is not supported + hipGraphExecUpdateErrorNotSupported = + 0x6, ///< The update failed because something about the node is not supported + hipGraphExecUpdateErrorUnsupportedFunctionChange = 0x7 +} hipGraphExecUpdateResult; + +typedef enum hipStreamCaptureMode { + hipStreamCaptureModeGlobal = 0, + hipStreamCaptureModeThreadLocal, + hipStreamCaptureModeRelaxed +} hipStreamCaptureMode; +typedef enum hipStreamCaptureStatus { + hipStreamCaptureStatusNone = 0, ///< Stream is not capturing + hipStreamCaptureStatusActive, ///< Stream is actively capturing + hipStreamCaptureStatusInvalidated ///< Stream is part of a capture sequence that has been + ///< invalidated, but not terminated +} hipStreamCaptureStatus; + +typedef enum hipStreamUpdateCaptureDependenciesFlags { + hipStreamAddCaptureDependencies = 0, ///< Add new nodes to the dependency set + hipStreamSetCaptureDependencies, ///< Replace the dependency set with the new nodes +} hipStreamUpdateCaptureDependenciesFlags; + +typedef enum hipGraphMemAttributeType { + hipGraphMemAttrUsedMemCurrent = 0, ///< Amount of memory, in bytes, currently associated with graphs + hipGraphMemAttrUsedMemHigh, ///< High watermark of memory, in bytes, associated with graphs since the last time. + hipGraphMemAttrReservedMemCurrent, ///< Amount of memory, in bytes, currently allocated for graphs. + hipGraphMemAttrReservedMemHigh, ///< High watermark of memory, in bytes, currently allocated for graphs +}hipGraphMemAttributeType; +typedef enum hipUserObjectFlags { + hipUserObjectNoDestructorSync = 0x1, ///< Destructor execution is not synchronized. +} hipUserObjectFlags; + +typedef enum hipUserObjectRetainFlags { + hipGraphUserObjectMove = 0x1, ///< Add new reference or retain. +} hipUserObjectRetainFlags; + +typedef enum hipGraphInstantiateFlags { + hipGraphInstantiateFlagAutoFreeOnLaunch = + 1, ///< Automatically free memory allocated in a graph before relaunching. + hipGraphInstantiateFlagUpload = + 2, ///< Automatically upload the graph after instantiaton. + hipGraphInstantiateFlagDeviceLaunch = + 4, ///< Instantiate the graph to be launchable from the device. + hipGraphInstantiateFlagUseNodePriority = + 8, ///< Run the graph using the per-node priority attributes rather than the priority of the stream it is launched into. +} hipGraphInstantiateFlags; + +enum hipGraphDebugDotFlags { + hipGraphDebugDotFlagsVerbose = 1 + << 0, /**< Output all debug data as if every debug flag is enabled */ + hipGraphDebugDotFlagsKernelNodeParams = 1 << 2, /**< Adds hipKernelNodeParams to output */ + hipGraphDebugDotFlagsMemcpyNodeParams = 1 << 3, /**< Adds hipMemcpy3DParms to output */ + hipGraphDebugDotFlagsMemsetNodeParams = 1 << 4, /**< Adds hipMemsetParams to output */ + hipGraphDebugDotFlagsHostNodeParams = 1 << 5, /**< Adds hipHostNodeParams to output */ + hipGraphDebugDotFlagsEventNodeParams = 1 + << 6, /**< Adds hipEvent_t handle from record and wait nodes to output */ + hipGraphDebugDotFlagsExtSemasSignalNodeParams = 1 + << 7, /**< Adds hipExternalSemaphoreSignalNodeParams values to output */ + hipGraphDebugDotFlagsExtSemasWaitNodeParams = 1 + << 8, /**< Adds hipExternalSemaphoreWaitNodeParams to output */ + hipGraphDebugDotFlagsKernelNodeAttributes = 1 + << 9, /**< Adds hipKernelNodeAttrID values to output */ + hipGraphDebugDotFlagsHandles = 1 + << 10 /**< Adds node handles and every kernel function handle to output */ +}; + +/** +* hipGraphInstantiateWithParams results +*/ +typedef enum hipGraphInstantiateResult { + hipGraphInstantiateSuccess = 0, /**< Instantiation Success */ + hipGraphInstantiateError = 1, /**< Instantiation failed for an + unexpected reason which is described in the return value of the function */ + hipGraphInstantiateInvalidStructure = 2, /**< Instantiation failed due + to invalid structure, such as cycles */ + hipGraphInstantiateNodeOperationNotSupported = 3, /**< Instantiation for device launch failed + because the graph contained an unsupported operation */ + hipGraphInstantiateMultipleDevicesNotSupported = 4, /**< Instantiation for device launch failed + due to the nodes belonging to different contexts */ +}hipGraphInstantiateResult; + +/** + * Graph Instantiation parameters +*/ +typedef struct hipGraphInstantiateParams { + hipGraphNode_t errNode_out; /**< The node which caused instantiation to fail, if any*/ + unsigned long long flags; /**< Instantiation flags */ + hipGraphInstantiateResult result_out; /**< Whether instantiation was successful. + If it failed, the reason why */ + hipStream_t uploadStream; /**< Upload stream */ +} hipGraphInstantiateParams; + + +/** + * Memory allocation properties + */ +typedef struct hipMemAllocationProp { + hipMemAllocationType type; ///< Memory allocation type + hipMemAllocationHandleType requestedHandleType; ///< Requested handle type + hipMemLocation location; ///< Memory location + void* win32HandleMetaData; ///< Metadata for Win32 handles + struct { + unsigned char compressionType; ///< Compression type + unsigned char gpuDirectRDMACapable; ///< RDMA capable + unsigned short usage; ///< Usage + } allocFlags; +} hipMemAllocationProp; + +/** + * External semaphore signal node parameters + */ +typedef struct hipExternalSemaphoreSignalNodeParams { + ///< Array containing external semaphore handles. + hipExternalSemaphore_t* extSemArray; + ///< Array containing parameters of external signal semaphore. + const hipExternalSemaphoreSignalParams* paramsArray; + ///< Total number of handles and parameters contained in extSemArray and paramsArray. + unsigned int numExtSems; +} hipExternalSemaphoreSignalNodeParams; + +/** + * External semaphore wait node parameters + */ +typedef struct hipExternalSemaphoreWaitNodeParams { + ///< Array containing external semaphore handles. + hipExternalSemaphore_t* extSemArray; + ///< Array containing parameters of external wait semaphore. + const hipExternalSemaphoreWaitParams* paramsArray; + ///< Total number of handles and parameters contained in extSemArray and paramsArray. + unsigned int numExtSems; +} hipExternalSemaphoreWaitNodeParams; + +/** + * Generic handle for memory allocation + */ +typedef struct ihipMemGenericAllocationHandle* hipMemGenericAllocationHandle_t; + +/** + * Flags for granularity + */ +typedef enum hipMemAllocationGranularity_flags { + hipMemAllocationGranularityMinimum = 0x0, ///< Minimum granularity + hipMemAllocationGranularityRecommended = 0x1 ///< Recommended granularity for performance +} hipMemAllocationGranularity_flags; + +/** + * Memory handle type + */ +typedef enum hipMemHandleType { + hipMemHandleTypeGeneric = 0x0 ///< Generic handle type +} hipMemHandleType; + +/** + * Memory operation types + */ +typedef enum hipMemOperationType { + hipMemOperationTypeMap = 0x1, ///< Map operation + hipMemOperationTypeUnmap = 0x2 ///< Unmap operation +} hipMemOperationType; + +/** + * Subresource types for sparse arrays + */ +typedef enum hipArraySparseSubresourceType { + hipArraySparseSubresourceTypeSparseLevel = 0x0, ///< Sparse level + hipArraySparseSubresourceTypeMiptail = 0x1 ///< Miptail +} hipArraySparseSubresourceType; + +/** + * Map info for arrays + */ +typedef struct hipArrayMapInfo { + hipResourceType resourceType; ///< Resource type + union { + hipMipmappedArray mipmap; + hipArray_t array; + } resource; + hipArraySparseSubresourceType subresourceType; ///< Sparse subresource type + union { + struct { + unsigned int level; ///< For mipmapped arrays must be a valid mipmap level. For arrays must be zero + unsigned int layer; ///< For layered arrays must be a valid layer index. Otherwise, must be zero + unsigned int offsetX; ///< X offset in elements + unsigned int offsetY; ///< Y offset in elements + unsigned int offsetZ; ///< Z offset in elements + unsigned int extentWidth; ///< Width in elements + unsigned int extentHeight; ///< Height in elements + unsigned int extentDepth; ///< Depth in elements + } sparseLevel; + struct { + unsigned int layer; ///< For layered arrays must be a valid layer index. Otherwise, must be zero + unsigned long long offset; ///< Offset within mip tail + unsigned long long size; ///< Extent in bytes + } miptail; + } subresource; + hipMemOperationType memOperationType; ///< Memory operation type + hipMemHandleType memHandleType; ///< Memory handle type + union { + hipMemGenericAllocationHandle_t memHandle; + } memHandle; + unsigned long long offset; ///< Offset within the memory + unsigned int deviceBitMask; ///< Device ordinal bit mask + unsigned int flags; ///< flags for future use, must be zero now. + unsigned int reserved[2]; ///< Reserved for future use, must be zero now. +} hipArrayMapInfo; + +/** + * Memcpy node params + */ +typedef struct hipMemcpyNodeParams { + int flags; ///< Must be zero. + int reserved[3]; ///< Must be zero. + hipMemcpy3DParms copyParams; ///< Params set for the memory copy. +} hipMemcpyNodeParams; + +/** + * Child graph node params + */ +typedef struct hipChildGraphNodeParams { + hipGraph_t graph; ///< Either the child graph to clone into the node, or + ///< a handle to the graph possesed by the node used during query +} hipChildGraphNodeParams; + +/** + * Event record node params + */ +typedef struct hipEventWaitNodeParams { + hipEvent_t event; ///< Event to wait on +} hipEventWaitNodeParams; + +/** + * Event record node params + */ +typedef struct hipEventRecordNodeParams { + hipEvent_t event; ///< The event to be recorded when node executes +} hipEventRecordNodeParams; + +/** + * Memory free node params + */ +typedef struct hipMemFreeNodeParams { + void *dptr; ///< the pointer to be freed +} hipMemFreeNodeParams; + +/** + * Params for different graph nodes + */ +typedef struct hipGraphNodeParams { + hipGraphNodeType type; + int reserved0[3]; + union { + long long reserved1[29]; + hipKernelNodeParams kernel; + hipMemcpyNodeParams memcpy; + hipMemsetParams memset; + hipHostNodeParams host; + hipChildGraphNodeParams graph; + hipEventWaitNodeParams eventWait; + hipEventRecordNodeParams eventRecord; + hipExternalSemaphoreSignalNodeParams extSemSignal; + hipExternalSemaphoreWaitNodeParams extSemWait; + hipMemAllocNodeParams alloc; + hipMemFreeNodeParams free; + }; + + long long reserved2; +} hipGraphNodeParams; + +/** + * This port activates when the kernel has finished executing. + */ +#define hipGraphKernelNodePortDefault 0 + +/** + * This port activates when all blocks of the kernel have begun execution. + */ +#define hipGraphKernelNodePortLaunchCompletion 2 + +/** + * This port activates when all blocks of the kernel have performed + * hipTriggerProgrammaticLaunchCompletion() or have terminated. + * It must be used with edge type hipGraphDependencyTypeProgrammatic. + */ +#define hipGraphKernelNodePortProgrammatic 1 + +typedef enum hipGraphDependencyType { + hipGraphDependencyTypeDefault = 0, + hipGraphDependencyTypeProgrammatic = 1 +}hipGraphDependencyType; + +typedef struct hipGraphEdgeData { + unsigned char + from_port; ///< This indicates when the dependency is triggered from the upstream node on the + ///< edge. The meaning is specfic to the node type. A value of 0 in all cases + ///< means full completion of the upstream node, with memory visibility to the + ///< downstream node or portion thereof (indicated by to_port). Only kernel nodes + ///< define non-zero ports. A kernel node can use the following output port types: + ///< hipGraphKernelNodePortDefault, hipGraphKernelNodePortProgrammatic, or + ///< hipGraphKernelNodePortLaunchCompletion. + unsigned char reserved[5]; ///< These bytes are unused and must be zeroed + unsigned char + to_port; ///< Currently no node types define non-zero ports. This field must be set to zero. + unsigned char type; ///< This should be populated with a value from hipGraphDependencyType +} hipGraphEdgeData; + +// Doxygen end group GlobalDefs +/** +* @} +*/ +/** + * @defgroup API HIP API + * @{ + * + * Defines the HIP API. See the individual sections for more information. + */ +/** + * @defgroup Driver Initialization and Version + * @{ + * This section describes the initializtion and version functions of HIP runtime API. + * + */ +/** + * @brief Explicitly initializes the HIP runtime. + * + * @param [in] flags Initialization flag, should be zero. + * + * Most HIP APIs implicitly initialize the HIP runtime. + * This API provides control over the timing of the initialization. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +// TODO-ctx - more description on error codes. +hipError_t hipInit(unsigned int flags); + +/** + * @brief Returns the approximate HIP driver version. + * + * @param [out] driverVersion driver version + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning The HIP feature set does not correspond to an exact CUDA SDK driver revision. + * This function always set *driverVersion to 4 as an approximation though HIP supports + * some features which were introduced in later CUDA SDK revisions. + * HIP apps code should not rely on the driver revision number here and should + * use arch feature flags to test device capabilities or conditional compilation. + * + * @see hipRuntimeGetVersion + */ +hipError_t hipDriverGetVersion(int* driverVersion); +/** + * @brief Returns the approximate HIP Runtime version. + * + * @param [out] runtimeVersion HIP runtime version + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning The version definition of HIP runtime is different from CUDA. + * On AMD platform, the function returns HIP runtime version, + * while on NVIDIA platform, it returns CUDA runtime version. + * And there is no mapping/correlation between HIP version and CUDA version. + * + * @see hipDriverGetVersion + */ +hipError_t hipRuntimeGetVersion(int* runtimeVersion); +/** + * @brief Returns a handle to a compute device + * @param [out] device Handle of device + * @param [in] ordinal Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGet(hipDevice_t* device, int ordinal); + +/** + * @brief Returns the compute capability of the device + * @param [out] major Major compute capability version number + * @param [out] minor Minor compute capability version number + * @param [in] device Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceComputeCapability(int* major, int* minor, hipDevice_t device); +/** + * @brief Returns an identifer string for the device. + * @param [out] name String of the device name + * @param [in] len Maximum length of string to store in device name + * @param [in] device Device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetName(char* name, int len, hipDevice_t device); +/** + * @brief Returns an UUID for the device.[BETA] + * @param [out] uuid UUID for the device + * @param [in] device device ordinal + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorDeinitialized + */ +hipError_t hipDeviceGetUuid(hipUUID* uuid, hipDevice_t device); +/** + * @brief Returns a value for attribute of link between two devices + * @param [out] value Pointer of the value for the attrubute + * @param [in] attr enum of hipDeviceP2PAttr to query + * @param [in] srcDevice The source device of the link + * @param [in] dstDevice The destination device of the link + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetP2PAttribute(int* value, hipDeviceP2PAttr attr, + int srcDevice, int dstDevice); +/** + * @brief Returns a PCI Bus Id string for the device, overloaded to take int device ID. + * @param [out] pciBusId The string of PCI Bus Id format for the device + * @param [in] len Maximum length of string + * @param [in] device The device ordinal + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceGetPCIBusId(char* pciBusId, int len, int device); +/** + * @brief Returns a handle to a compute device. + * @param [out] device The handle of the device + * @param [in] pciBusId The string of PCI Bus Id for the device + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipDeviceGetByPCIBusId(int* device, const char* pciBusId); +/** + * @brief Returns the total amount of memory on the device. + * @param [out] bytes The size of memory in bytes, on the device + * @param [in] device The ordinal of the device + * + * @returns #hipSuccess, #hipErrorInvalidDevice + */ +hipError_t hipDeviceTotalMem(size_t* bytes, hipDevice_t device); +// doxygen end initialization +/** + * @} + */ +/** + * @defgroup Device Device Management + * @{ + * This section describes the device management functions of HIP runtime API. + */ +/** + * @brief Waits on all active streams on current device + * + * When this command is invoked, the host thread gets blocked until all the commands associated + * with streams associated with the device. HIP does not support multiple blocking modes (yet!). + * + * @returns #hipSuccess + * + * @see hipSetDevice, hipDeviceReset + */ +hipError_t hipDeviceSynchronize(void); +/** + * @brief The state of current device is discarded and updated to a fresh state. + * + * Calling this function deletes all streams created, memory allocated, kernels running, events + * created. Make sure that no other thread is using the device or streams, memory, kernels, events + * associated with the current device. + * + * @returns #hipSuccess + * + * @see hipDeviceSynchronize + */ +hipError_t hipDeviceReset(void); +/** + * @brief Set default device to be used for subsequent hip API calls from this thread. + * + * @param[in] deviceId Valid device in range 0...hipGetDeviceCount(). + * + * Sets @p device as the default device for the calling host thread. Valid device id's are 0... + * (hipGetDeviceCount()-1). + * + * Many HIP APIs implicitly use the "default device" : + * + * - Any device memory subsequently allocated from this host thread (using hipMalloc) will be + * allocated on device. + * - Any streams or events created from this host thread will be associated with device. + * - Any kernels launched from this host thread (using hipLaunchKernel) will be executed on device + * (unless a specific stream is specified, in which case the device associated with that stream will + * be used). + * + * This function may be called from any host thread. Multiple host threads may use the same device. + * This function does no synchronization with the previous or new device, and has very little + * runtime overhead. Applications can use hipSetDevice to quickly switch the default device before + * making a HIP runtime call which uses the default device. + * + * The default device is stored in thread-local-storage for each thread. + * Thread-pool implementations may inherit the default device of the previous thread. A good + * practice is to always call hipSetDevice at the start of HIP coding sequency to establish a known + * standard device. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorNoDevice + * + * @see #hipGetDevice, #hipGetDeviceCount + */ +hipError_t hipSetDevice(int deviceId); +/** + * @brief Set a list of devices that can be used. + * + * @param[in] device_arr List of devices to try + * @param[in] len Number of devices in specified list + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see #hipGetDevice, #hipGetDeviceCount. #hipSetDevice. #hipGetDeviceProperties. #hipSetDeviceFlags. #hipChooseDevice + * + * */ +hipError_t hipSetValidDevices(int* device_arr, int len); +/** + * @brief Return the default device id for the calling host thread. + * + * @param [out] deviceId *device is written with the default device + * + * HIP maintains an default device for each thread using thread-local-storage. + * This device is used implicitly for HIP runtime APIs called by this thread. + * hipGetDevice returns in * @p device the default device for the calling host thread. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see hipSetDevice, hipGetDevicesizeBytes + */ +hipError_t hipGetDevice(int* deviceId); +/** + * @brief Return number of compute-capable devices. + * + * @param [out] count Returns number of compute-capable devices. + * + * @returns #hipSuccess, #hipErrorNoDevice + * + * + * Returns in @p *count the number of devices that have ability to run compute commands. If there + * are no such devices, then @ref hipGetDeviceCount will return #hipErrorNoDevice. If 1 or more + * devices can be found, then hipGetDeviceCount returns #hipSuccess. + */ +hipError_t hipGetDeviceCount(int* count); +/** + * @brief Query for a specific device attribute. + * + * @param [out] pi pointer to value to return + * @param [in] attr attribute to query + * @param [in] deviceId which device to query for information + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipDeviceGetAttribute(int* pi, hipDeviceAttribute_t attr, int deviceId); +/** + * @brief Returns the default memory pool of the specified device + * + * @param [out] mem_pool Default memory pool to return + * @param [in] device Device index for query the default memory pool + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetDefaultMemPool(hipMemPool_t* mem_pool, int device); +/** + * @brief Sets the current memory pool of a device + * + * The memory pool must be local to the specified device. + * @p hipMallocAsync allocates from the current mempool of the provided stream's device. + * By default, a device's current memory pool is its default memory pool. + * + * @note Use @p hipMallocFromPoolAsync for asynchronous memory allocations from a device + * different than the one the stream runs on. + * + * @param [in] device Device index for the update + * @param [in] mem_pool Memory pool for update as the current on the specified device + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceSetMemPool(int device, hipMemPool_t mem_pool); +/** + * @brief Gets the current memory pool for the specified device + * + * Returns the last pool provided to @p hipDeviceSetMemPool for this device + * or the device's default memory pool if @p hipDeviceSetMemPool has never been called. + * By default the current mempool is the default mempool for a device, + * otherwise the returned pool must have been set with @p hipDeviceSetMemPool. + * + * @param [out] mem_pool Current memory pool on the specified device + * @param [in] device Device index to query the current memory pool + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipDeviceGetDefaultMemPool, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetMemPool(hipMemPool_t* mem_pool, int device); +/** + * @brief Returns device properties. + * + * @param [out] prop written with device properties + * @param [in] deviceId which device to query for information + * + * @return #hipSuccess, #hipErrorInvalidDevice + * @bug HCC always returns 0 for maxThreadsPerMultiProcessor + * @bug HCC always returns 0 for regsPerBlock + * @bug HCC always returns 0 for l2CacheSize + * + * Populates hipGetDeviceProperties with information for the specified device. + */ +hipError_t hipGetDeviceProperties(hipDeviceProp_t* prop, int deviceId); +/** + * @brief Set L1/Shared cache partition. + * + * @param [in] cacheConfig Cache configuration + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorNotSupported + * + * Note: AMD devices do not support reconfigurable cache. This API is not implemented + * on AMD platform. If the function is called, it will return hipErrorNotSupported. + * + */ +hipError_t hipDeviceSetCacheConfig(hipFuncCache_t cacheConfig); +/** + * @brief Get Cache configuration for a specific Device + * + * @param [out] cacheConfig Pointer of cache configuration + * + * @returns #hipSuccess, #hipErrorNotInitialized + * Note: AMD devices do not support reconfigurable cache. This hint is ignored + * on these architectures. + * + */ +hipError_t hipDeviceGetCacheConfig(hipFuncCache_t* cacheConfig); +/** + * @brief Gets resource limits of current device + * + * The function queries the size of limit value, as required by the input enum value hipLimit_t, + * which can be either #hipLimitStackSize, or #hipLimitMallocHeapSize. Any other input as + * default, the function will return #hipErrorUnsupportedLimit. + * + * @param [out] pValue Returns the size of the limit in bytes + * @param [in] limit The limit to query + * + * @returns #hipSuccess, #hipErrorUnsupportedLimit, #hipErrorInvalidValue + * + */ +hipError_t hipDeviceGetLimit(size_t* pValue, enum hipLimit_t limit); +/** + * @brief Sets resource limits of current device. + * + * As the input enum limit, + * #hipLimitStackSize sets the limit value of the stack size on the current GPU device, per thread. + * The limit size can get via hipDeviceGetLimit. The size is in units of 256 dwords, up to the limit + * (128K - 16). + * + * #hipLimitMallocHeapSize sets the limit value of the heap used by the malloc()/free() + * calls. For limit size, use the #hipDeviceGetLimit API. + * + * Any other input as default, the funtion will return hipErrorUnsupportedLimit. + * + * @param [in] limit Enum of hipLimit_t to set + * @param [in] value The size of limit value in bytes + * + * @returns #hipSuccess, #hipErrorUnsupportedLimit, #hipErrorInvalidValue + * + */ +hipError_t hipDeviceSetLimit ( enum hipLimit_t limit, size_t value ); +/** + * @brief Returns bank width of shared memory for current device + * + * @param [out] pConfig The pointer of the bank width for shared memory + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipDeviceGetSharedMemConfig(hipSharedMemConfig* pConfig); +/** + * @brief Gets the flags set for current device + * + * @param [out] flags Pointer of the flags + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + */ +hipError_t hipGetDeviceFlags(unsigned int* flags); +/** + * @brief The bank width of shared memory on current device is set + * + * @param [in] config Configuration for the bank width of shared memory + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipDeviceSetSharedMemConfig(hipSharedMemConfig config); +/** + * @brief The current device behavior is changed according the flags passed. + * + * @param [in] flags Flag to set on the current device + * + * The schedule flags impact how HIP waits for the completion of a command running on a device. + * hipDeviceScheduleSpin : HIP runtime will actively spin in the thread which submitted the + * work until the command completes. This offers the lowest latency, but will consume a CPU core + * and may increase power. hipDeviceScheduleYield : The HIP runtime will yield the CPU to + * system so that other tasks can use it. This may increase latency to detect the completion but + * will consume less power and is friendlier to other tasks in the system. + * hipDeviceScheduleBlockingSync : On ROCm platform, this is a synonym for hipDeviceScheduleYield. + * hipDeviceScheduleAuto : Use a hueristic to select between Spin and Yield modes. If the + * number of HIP contexts is greater than the number of logical processors in the system, use Spin + * scheduling. Else use Yield scheduling. + * + * + * hipDeviceMapHost : Allow mapping host memory. On ROCM, this is always allowed and + * the flag is ignored. hipDeviceLmemResizeToMax : @warning ROCm silently ignores this flag. + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorSetOnActiveProcess + * + * + */ +hipError_t hipSetDeviceFlags(unsigned flags); +/** + * @brief Device which matches hipDeviceProp_t is returned + * + * @param [out] device Pointer of the device + * @param [in] prop Pointer of the properties + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipChooseDevice(int* device, const hipDeviceProp_t* prop); +/** + * @brief Returns the link type and hop count between two devices + * + * @param [in] device1 Ordinal for device1 + * @param [in] device2 Ordinal for device2 + * @param [out] linktype Returns the link type (See hsa_amd_link_info_type_t) between the two devices + * @param [out] hopcount Returns the hop count between the two devices + * + * Queries and returns the HSA link type and the hop count between the two specified devices. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipExtGetLinkTypeAndHopCount(int device1, int device2, uint32_t* linktype, uint32_t* hopcount); +// TODO: implement IPC apis +/** + * @brief Gets an interprocess memory handle for an existing device memory + * allocation + * + * Takes a pointer to the base of an existing device memory allocation created + * with hipMalloc and exports it for use in another process. This is a + * lightweight operation and may be called multiple times on an allocation + * without adverse effects. + * + * If a region of memory is freed with hipFree and a subsequent call + * to hipMalloc returns memory with the same device address, + * hipIpcGetMemHandle will return a unique handle for the + * new memory. + * + * @param handle - Pointer to user allocated hipIpcMemHandle to return + * the handle in. + * @param devPtr - Base pointer to previously allocated device memory + * + * @returns #hipSuccess, #hipErrorInvalidHandle, #hipErrorOutOfMemory, #hipErrorMapFailed + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcGetMemHandle(hipIpcMemHandle_t* handle, void* devPtr); +/** + * @brief Opens an interprocess memory handle exported from another process + * and returns a device pointer usable in the local process. + * + * Maps memory exported from another process with hipIpcGetMemHandle into + * the current device address space. For contexts on different devices + * hipIpcOpenMemHandle can attempt to enable peer access between the + * devices as if the user called hipDeviceEnablePeerAccess. This behavior is + * controlled by the hipIpcMemLazyEnablePeerAccess flag. + * hipDeviceCanAccessPeer can determine if a mapping is possible. + * + * Contexts that may open hipIpcMemHandles are restricted in the following way. + * hipIpcMemHandles from each device in a given process may only be opened + * by one context per device per other process. + * + * Memory returned from hipIpcOpenMemHandle must be freed with + * hipIpcCloseMemHandle. + * + * Calling hipFree on an exported memory region before calling + * hipIpcCloseMemHandle in the importing context will result in undefined + * behavior. + * + * @param devPtr - Returned device pointer + * @param handle - hipIpcMemHandle to open + * @param flags - Flags for this operation. Must be specified as hipIpcMemLazyEnablePeerAccess + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, + * #hipErrorInvalidDevicePointer + * + * @note During multiple processes, using the same memory handle opened by the current context, + * there is no guarantee that the same device poiter will be returned in @p *devPtr. + * This is diffrent from CUDA. + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcOpenMemHandle(void** devPtr, hipIpcMemHandle_t handle, unsigned int flags); +/** + * @brief Close memory mapped with hipIpcOpenMemHandle + * + * Unmaps memory returnd by hipIpcOpenMemHandle. The original allocation + * in the exporting process as well as imported mappings in other processes + * will be unaffected. + * + * Any resources used to enable peer access will be freed if this is the + * last mapping using them. + * + * @param devPtr - Device pointer returned by hipIpcOpenMemHandle + * + * @returns #hipSuccess, #hipErrorMapFailed, #hipErrorInvalidHandle + * + * @note This IPC memory related feature API on Windows may behave differently from Linux. + * + */ +hipError_t hipIpcCloseMemHandle(void* devPtr); + +/** + * @brief Gets an opaque interprocess handle for an event. + * + * This opaque handle may be copied into other processes and opened with hipIpcOpenEventHandle. + * Then hipEventRecord, hipEventSynchronize, hipStreamWaitEvent and hipEventQuery may be used in + * either process. Operations on the imported event after the exported event has been freed with hipEventDestroy + * will result in undefined behavior. + * + * @param[out] handle Pointer to hipIpcEventHandle to return the opaque event handle + * @param[in] event Event allocated with hipEventInterprocess and hipEventDisableTiming flags + * + * @returns #hipSuccess, #hipErrorInvalidConfiguration, #hipErrorInvalidValue + * + * @note This IPC event related feature API is currently applicable on Linux. + * + */ +hipError_t hipIpcGetEventHandle(hipIpcEventHandle_t* handle, hipEvent_t event); + +/** + * @brief Opens an interprocess event handles. + * + * Opens an interprocess event handle exported from another process with hipIpcGetEventHandle. The returned + * hipEvent_t behaves like a locally created event with the hipEventDisableTiming flag specified. This event + * need be freed with hipEventDestroy. Operations on the imported event after the exported event has been freed + * with hipEventDestroy will result in undefined behavior. If the function is called within the same process where + * handle is returned by hipIpcGetEventHandle, it will return hipErrorInvalidContext. + * + * @param[out] event Pointer to hipEvent_t to return the event + * @param[in] handle The opaque interprocess handle to open + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext + * + * @note This IPC event related feature API is currently applicable on Linux. + * + */ +hipError_t hipIpcOpenEventHandle(hipEvent_t* event, hipIpcEventHandle_t handle); + +// end doxygen Device +/** + * @} + */ +/** + * + * @defgroup Execution Execution Control + * @{ + * This section describes the execution control functions of HIP runtime API. + * + */ +/** + * @brief Set attribute for a specific function + * + * @param [in] func Pointer of the function + * @param [in] attr Attribute to set + * @param [in] value Value to set + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipFuncSetAttribute(const void* func, hipFuncAttribute attr, int value); +/** + * @brief Set Cache configuration for a specific function + * + * @param [in] func Pointer of the function. + * @param [in] config Configuration to set. + * + * @returns #hipSuccess, #hipErrorNotInitialized + * Note: AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is ignored + * on those architectures. + * + */ +hipError_t hipFuncSetCacheConfig(const void* func, hipFuncCache_t config); +/** + * @brief Set shared memory configuation for a specific function + * + * @param [in] func Pointer of the function + * @param [in] config Configuration + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + * + * Note: AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + */ +hipError_t hipFuncSetSharedMemConfig(const void* func, hipSharedMemConfig config); +//doxygen end execution +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Error Error Handling + * @{ + * This section describes the error handling functions of HIP runtime API. + */ +/** + * @brief Return last error returned by any HIP runtime API call and resets the stored error code to + * #hipSuccess + * + * @returns return code from last HIP called from the active host thread + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread, and then resets the saved error to #hipSuccess. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipGetLastError(void); + +/** + * @brief Return last error returned by any HIP runtime API call and resets the stored error code to + * #hipSuccess + * + * @returns return code from last HIP called from the active host thread + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread, and then resets the saved error to #hipSuccess. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipExtGetLastError(void); + +/** + * @brief Return last error returned by any HIP runtime API call. + * + * @return #hipSuccess + * + * Returns the last error that has been returned by any of the runtime calls in the same host + * thread. Unlike hipGetLastError, this function does not reset the saved error code. + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipPeekAtLastError(void); +/** + * @brief Return hip error as text string form. + * + * @param hip_error Error code to convert to name. + * @return const char pointer to the NULL-terminated error name + * + * @see hipGetErrorString, hipGetLastError, hipPeakAtLastError, hipError_t + */ +const char* hipGetErrorName(hipError_t hip_error); +/** + * @brief Return handy text string message to explain the error which occurred + * + * @param hipError Error code to convert to string. + * @return const char pointer to the NULL-terminated error string + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +const char* hipGetErrorString(hipError_t hipError); +/** + * @brief Return hip error as text string form. + * + * @param [in] hipError Error code to convert to string. + * @param [out] errorString char pointer to the NULL-terminated error string + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipDrvGetErrorName(hipError_t hipError, const char** errorString); +/** + * @brief Return handy text string message to explain the error which occurred + * + * @param [in] hipError Error code to convert to string. + * @param [out] errorString char pointer to the NULL-terminated error string + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipGetErrorName, hipGetLastError, hipPeakAtLastError, hipError_t + */ +hipError_t hipDrvGetErrorString(hipError_t hipError, const char** errorString); +// end doxygen Error +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Stream Stream Management + * @{ + * This section describes the stream management functions of HIP runtime API. + * The following Stream APIs are not (yet) supported in HIP: + * - hipStreamAttachMemAsync is a nop + */ + +/** + * @brief Create an asynchronous stream. + * + * @param[in, out] stream Valid pointer to hipStream_t. This function writes the memory with the + * newly created stream. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream. @p stream returns an opaque handle that can be used to + * reference the newly created stream in subsequent hipStream* commands. The stream is allocated on + * the heap and will remain allocated even if the handle goes out-of-scope. To release the memory + * used by the stream, application must call hipStreamDestroy. + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreate(hipStream_t* stream); +/** + * @brief Create an asynchronous stream. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] flags to control stream creation. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream. @p stream returns an opaque handle that can be used to + * reference the newly created stream in subsequent hipStream* commands. The stream is allocated on + * the heap and will remain allocated even if the handle goes out-of-scope. To release the memory + * used by the stream, application must call hipStreamDestroy. Flags controls behavior of the + * stream. See #hipStreamDefault, #hipStreamNonBlocking. + * + * + * @see hipStreamCreate, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreateWithFlags(hipStream_t* stream, unsigned int flags); +/** + * @brief Create an asynchronous stream with the specified priority. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] flags to control stream creation. + * @param[in ] priority of the stream. Lower numbers represent higher priorities. + * @return #hipSuccess, #hipErrorInvalidValue + * + * Create a new asynchronous stream with the specified priority. @p stream returns an opaque handle + * that can be used to reference the newly created stream in subsequent hipStream* commands. The + * stream is allocated on the heap and will remain allocated even if the handle goes out-of-scope. + * To release the memory used by the stream, application must call hipStreamDestroy. Flags controls + * behavior of the stream. See #hipStreamDefault, #hipStreamNonBlocking. + * + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipStreamCreateWithPriority(hipStream_t* stream, unsigned int flags, int priority); +/** + * @brief Returns numerical values that correspond to the least and greatest stream priority. + * + * @param[in, out] leastPriority pointer in which value corresponding to least priority is returned. + * @param[in, out] greatestPriority pointer in which value corresponding to greatest priority is returned. + * @returns #hipSuccess + * + * Returns in *leastPriority and *greatestPriority the numerical values that correspond to the least + * and greatest stream priority respectively. Stream priorities follow a convention where lower numbers + * imply greater priorities. The range of meaningful stream priorities is given by + * [*greatestPriority, *leastPriority]. If the user attempts to create a stream with a priority value + * that is outside the meaningful range as specified by this API, the priority is automatically + * clamped to within the valid range. + */ +hipError_t hipDeviceGetStreamPriorityRange(int* leastPriority, int* greatestPriority); +/** + * @brief Destroys the specified stream. + * + * @param[in] stream stream identifier. + * @return #hipSuccess #hipErrorInvalidHandle + * + * Destroys the specified stream. + * + * If commands are still executing on the specified stream, some may complete execution before the + * queue is deleted. + * + * The queue may be destroyed while some commands are still inflight, or may wait for all commands + * queued to the stream before destroying it. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamQuery, + * hipStreamWaitEvent, hipStreamSynchronize + */ +hipError_t hipStreamDestroy(hipStream_t stream); +/** + * @brief Return #hipSuccess if all of the operations in the specified @p stream have completed, or + * #hipErrorNotReady if not. + * + * @param[in] stream stream to query + * + * @return #hipSuccess, #hipErrorNotReady, #hipErrorInvalidHandle + * + * This is thread-safe and returns a snapshot of the current state of the queue. However, if other + * host threads are sending work to the stream, the status may change immediately after the function + * is called. It is typically used for debug. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamWaitEvent, + * hipStreamSynchronize, hipStreamDestroy + */ +hipError_t hipStreamQuery(hipStream_t stream); +/** + * @brief Wait for all commands in stream to complete. + * + * @param[in] stream stream identifier. + * + * @return #hipSuccess, #hipErrorInvalidHandle + * + * This command is host-synchronous : the host will block until the specified stream is empty. + * + * This command follows standard null-stream semantics. Specifically, specifying the null stream + * will cause the command to wait for other streams on the same device to complete all pending + * operations. + * + * This command honors the hipDeviceLaunchBlocking flag, which controls whether the wait is active + * or blocking. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamWaitEvent, + * hipStreamDestroy + * + */ +hipError_t hipStreamSynchronize(hipStream_t stream); +/** + * @brief Make the specified compute stream wait for an event + * + * @param[in] stream stream to make wait. + * @param[in] event event to wait on + * @param[in] flags control operation [must be 0] + * + * @return #hipSuccess, #hipErrorInvalidHandle + * + * This function inserts a wait operation into the specified stream. + * All future work submitted to @p stream will wait until @p event reports completion before + * beginning execution. + * + * This function only waits for commands in the current stream to complete. Notably, this function + * does not implicitly wait for commands in the default stream to complete, even if the specified + * stream is created with hipStreamNonBlocking = 0. + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamCreateWithPriority, hipStreamSynchronize, hipStreamDestroy + */ +hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags __dparm(0)); +/** + * @brief Return flags associated with this stream. + * + * @param[in] stream stream to be queried + * @param[in,out] flags Pointer to an unsigned integer in which the stream's flags are returned + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidHandle + * + * @returns #hipSuccess #hipErrorInvalidValue #hipErrorInvalidHandle + * + * Return flags associated with this stream in *@p flags. + * + * @see hipStreamCreateWithFlags + */ +hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int* flags); +/** + * @brief Query the priority of a stream. + * + * @param[in] stream stream to be queried + * @param[in,out] priority Pointer to an unsigned integer in which the stream's priority is returned + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidHandle + * + * @returns #hipSuccess #hipErrorInvalidValue #hipErrorInvalidHandle + * + * Query the priority of a stream. The priority is returned in in priority. + * + * @see hipStreamCreateWithFlags + */ +hipError_t hipStreamGetPriority(hipStream_t stream, int* priority); +/** + * @brief Get the device assocaited with the stream + * + * @param[in] stream stream to be queried + * @param[out] device device associated with the stream + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorContextIsDestroyed, #hipErrorInvalidHandle, + * #hipErrorNotInitialized, #hipErrorDeinitialized, #hipErrorInvalidContext + * + * @see hipStreamCreate, hipStreamDestroy, hipDeviceGetStreamPriorityRange + */ +hipError_t hipStreamGetDevice(hipStream_t stream, hipDevice_t* device); +/** + * @brief Create an asynchronous stream with the specified CU mask. + * + * @param[in, out] stream Pointer to new stream + * @param[in ] cuMaskSize Size of CU mask bit array passed in. + * @param[in ] cuMask Bit-vector representing the CU mask. Each active bit represents using one CU. + * The first 32 bits represent the first 32 CUs, and so on. If its size is greater than physical + * CU number (i.e., multiProcessorCount member of hipDeviceProp_t), the extra elements are ignored. + * It is user's responsibility to make sure the input is meaningful. + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorInvalidValue + * + * Create a new asynchronous stream with the specified CU mask. @p stream returns an opaque handle + * that can be used to reference the newly created stream in subsequent hipStream* commands. The + * stream is allocated on the heap and will remain allocated even if the handle goes out-of-scope. + * To release the memory used by the stream, application must call hipStreamDestroy. + * + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipExtStreamCreateWithCUMask(hipStream_t* stream, uint32_t cuMaskSize, const uint32_t* cuMask); +/** + * @brief Get CU mask associated with an asynchronous stream + * + * @param[in] stream stream to be queried + * @param[in] cuMaskSize number of the block of memories (uint32_t *) allocated by user + * @param[out] cuMask Pointer to a pre-allocated block of memories (uint32_t *) in which + * the stream's CU mask is returned. The CU mask is returned in a chunck of 32 bits where + * each active bit represents one active CU + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorInvalidValue + * + * @see hipStreamCreate, hipStreamSynchronize, hipStreamWaitEvent, hipStreamDestroy + */ +hipError_t hipExtStreamGetCUMask(hipStream_t stream, uint32_t cuMaskSize, uint32_t* cuMask); +/** + * Stream CallBack struct + */ +typedef void (*hipStreamCallback_t)(hipStream_t stream, hipError_t status, void* userData); +/** + * @brief Adds a callback to be called on the host after all currently enqueued + * items in the stream have completed. For each + * hipStreamAddCallback call, a callback will be executed exactly once. + * The callback will block later work in the stream until it is finished. + * @param[in] stream - Stream to add callback to + * @param[in] callback - The function to call once preceding stream operations are complete + * @param[in] userData - User specified data to be passed to the callback function + * @param[in] flags - Reserved for future use, must be 0 + * @return #hipSuccess, #hipErrorInvalidHandle, #hipErrorNotSupported + * + * @see hipStreamCreate, hipStreamCreateWithFlags, hipStreamQuery, hipStreamSynchronize, + * hipStreamWaitEvent, hipStreamDestroy, hipStreamCreateWithPriority + * + */ +hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData, + unsigned int flags); +// end doxygen Stream +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup StreamM Stream Memory Operations + * @{ + * This section describes Stream Memory Wait and Write functions of HIP runtime API. + */ +/** + * @brief Enqueues a wait command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to memory object allocated using 'hipMallocSignalMemory' flag + * @param [in] value - Value to be used in compare operation + * @param [in] flags - Defines the compare operation, supported values are hipStreamWaitValueGte + * hipStreamWaitValueEq, hipStreamWaitValueAnd and hipStreamWaitValueNor + * @param [in] mask - Mask to be applied on value at memory before it is compared with value, + * default value is set to enable every bit + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a wait command to the stream, all operations enqueued on this stream after this, will + * not execute until the defined wait condition is true. + * + * hipStreamWaitValueGte: waits until *ptr&mask >= value + * hipStreamWaitValueEq : waits until *ptr&mask == value + * hipStreamWaitValueAnd: waits until ((*ptr&mask) & value) != 0 + * hipStreamWaitValueNor: waits until ~((*ptr&mask) | (value&mask)) != 0 + * + * @note when using 'hipStreamWaitValueNor', mask is applied on both 'value' and '*ptr'. + * + * @note Support for hipStreamWaitValue32 can be queried using 'hipDeviceGetAttribute()' and + * 'hipDeviceAttributeCanUseStreamWaitValue' flag. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWaitValue64, hipStreamWriteValue64, + * hipStreamWriteValue32, hipDeviceGetAttribute + */ +hipError_t hipStreamWaitValue32(hipStream_t stream, void* ptr, uint32_t value, unsigned int flags, + uint32_t mask __dparm(0xFFFFFFFF)); +/** + * @brief Enqueues a wait command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to memory object allocated using 'hipMallocSignalMemory' flag + * @param [in] value - Value to be used in compare operation + * @param [in] flags - Defines the compare operation, supported values are hipStreamWaitValueGte + * hipStreamWaitValueEq, hipStreamWaitValueAnd and hipStreamWaitValueNor. + * @param [in] mask - Mask to be applied on value at memory before it is compared with value + * default value is set to enable every bit + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a wait command to the stream, all operations enqueued on this stream after this, will + * not execute until the defined wait condition is true. + * + * hipStreamWaitValueGte: waits until *ptr&mask >= value + * hipStreamWaitValueEq : waits until *ptr&mask == value + * hipStreamWaitValueAnd: waits until ((*ptr&mask) & value) != 0 + * hipStreamWaitValueNor: waits until ~((*ptr&mask) | (value&mask)) != 0 + * + * @note when using 'hipStreamWaitValueNor', mask is applied on both 'value' and '*ptr'. + * + * @note Support for hipStreamWaitValue64 can be queried using 'hipDeviceGetAttribute()' and + * 'hipDeviceAttributeCanUseStreamWaitValue' flag. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWaitValue32, hipStreamWriteValue64, + * hipStreamWriteValue32, hipDeviceGetAttribute + */ +hipError_t hipStreamWaitValue64(hipStream_t stream, void* ptr, uint64_t value, unsigned int flags, + uint64_t mask __dparm(0xFFFFFFFFFFFFFFFF)); +/** + * @brief Enqueues a write command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to a GPU accessible memory object + * @param [in] value - Value to be written + * @param [in] flags - reserved, ignored for now, will be used in future releases + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a write command to the stream, write operation is performed after all earlier commands + * on this stream have completed the execution. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWriteValue32, hipStreamWaitValue32, + * hipStreamWaitValue64 + */ +hipError_t hipStreamWriteValue32(hipStream_t stream, void* ptr, uint32_t value, unsigned int flags); +/** + * @brief Enqueues a write command to the stream.[BETA] + * + * @param [in] stream - Stream identifier + * @param [in] ptr - Pointer to a GPU accessible memory object + * @param [in] value - Value to be written + * @param [in] flags - reserved, ignored for now, will be used in future releases + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * Enqueues a write command to the stream, write operation is performed after all earlier commands + * on this stream have completed the execution. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipExtMallocWithFlags, hipFree, hipStreamWriteValue32, hipStreamWaitValue32, + * hipStreamWaitValue64 + */ +hipError_t hipStreamWriteValue64(hipStream_t stream, void* ptr, uint64_t value, unsigned int flags); +// end doxygen Stream Memory Operations +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Event Event Management + * @{ + * This section describes the event management functions of HIP runtime API. + */ +/** + * @brief Create an event with the specified flags + * + * @param[in,out] event Returns the newly created event. + * @param[in] flags Flags to control event behavior. Valid values are #hipEventDefault, + #hipEventBlockingSync, #hipEventDisableTiming, #hipEventInterprocess + * #hipEventDefault : Default flag. The event will use active synchronization and will support + timing. Blocking synchronization provides lowest possible latency at the expense of dedicating a + CPU to poll on the event. + * #hipEventBlockingSync : The event will use blocking synchronization : if hipEventSynchronize is + called on this event, the thread will block until the event completes. This can increase latency + for the synchroniation but can result in lower power and more resources for other CPU threads. + * #hipEventDisableTiming : Disable recording of timing information. Events created with this flag + would not record profiling data and provide best performance if used for synchronization. + * #hipEventInterprocess : The event can be used as an interprocess event. hipEventDisableTiming + flag also must be set when hipEventInterprocess flag is set. + * #hipEventDisableSystemFence : Disable acquire and release system scope fence. This may + improve performance but device memory may not be visible to the host and other devices + if this flag is set. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + #hipErrorLaunchFailure, #hipErrorOutOfMemory + * + * @see hipEventCreate, hipEventSynchronize, hipEventDestroy, hipEventElapsedTime + */ +hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags); +/** + * Create an event + * + * @param[in,out] event Returns the newly created event. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorLaunchFailure, #hipErrorOutOfMemory + * + * @see hipEventCreateWithFlags, hipEventRecord, hipEventQuery, hipEventSynchronize, + * hipEventDestroy, hipEventElapsedTime + */ +hipError_t hipEventCreate(hipEvent_t* event); +/** + * @brief Record an event in the specified stream. + * + * @param[in] event event to record. + * @param[in] stream stream in which to record event. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorInvalidHandle, #hipErrorLaunchFailure + * + * hipEventQuery() or hipEventSynchronize() must be used to determine when the event + * transitions from "recording" (after hipEventRecord() is called) to "recorded" + * (when timestamps are set, if requested). + * + * Events which are recorded in a non-NULL stream will transition to + * from recording to "recorded" state when they reach the head of + * the specified stream, after all previous + * commands in that stream have completed executing. + * + * If hipEventRecord() has been previously called on this event, then this call will overwrite any + * existing state in event. + * + * If this function is called on an event that is currently being recorded, results are undefined + * - either outstanding recording may save state into the event, and the order is not guaranteed. + * + * @note: If this function is not called before use hipEventQuery() or hipEventSynchronize(), + * #hipSuccess is returned, meaning no pending event in the stream. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventSynchronize, + * hipEventDestroy, hipEventElapsedTime + * + */ +#ifdef __cplusplus +hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream = NULL); +#else +hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream); +#endif +/** + * @brief Destroy the specified event. + * + * @param[in] event Event to destroy. + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorLaunchFailure + * + * Releases memory associated with the event. If the event is recording but has not completed + * recording when hipEventDestroy() is called, the function will return immediately and the + * completion_future resources will be released later, when the hipDevice is synchronized. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventSynchronize, hipEventRecord, + * hipEventElapsedTime + * + * @returns #hipSuccess + */ +hipError_t hipEventDestroy(hipEvent_t event); +/** + * @brief Wait for an event to complete. + * + * This function will block until the event is ready, waiting for all previous work in the stream + * specified when event was recorded with hipEventRecord(). + * + * If hipEventRecord() has not been called on @p event, this function returns #hipSuccess when no + * event is captured. + * + * + * @param[in] event Event on which to wait. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, + * #hipErrorInvalidHandle, #hipErrorLaunchFailure + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventDestroy, hipEventRecord, + * hipEventElapsedTime + */ +hipError_t hipEventSynchronize(hipEvent_t event); +/** + * @brief Return the elapsed time between two events. + * + * @param[out] ms : Return time between start and stop in ms. + * @param[in] start : Start event. + * @param[in] stop : Stop event. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotReady, #hipErrorInvalidHandle, + * #hipErrorNotInitialized, #hipErrorLaunchFailure + * + * Computes the elapsed time between two events. Time is computed in ms, with + * a resolution of approximately 1 us. + * + * Events which are recorded in a NULL stream will block until all commands + * on all other streams complete execution, and then record the timestamp. + * + * Events which are recorded in a non-NULL stream will record their timestamp + * when they reach the head of the specified stream, after all previous + * commands in that stream have completed executing. Thus the time that + * the event recorded may be significantly after the host calls hipEventRecord(). + * + * If hipEventRecord() has not been called on either event, then #hipErrorInvalidHandle is + * returned. If hipEventRecord() has been called on both events, but the timestamp has not yet been + * recorded on one or both events (that is, hipEventQuery() would return #hipErrorNotReady on at + * least one of the events), then #hipErrorNotReady is returned. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventQuery, hipEventDestroy, hipEventRecord, + * hipEventSynchronize + */ +hipError_t hipEventElapsedTime(float* ms, hipEvent_t start, hipEvent_t stop); +/** + * @brief Query event status + * + * @param[in] event Event to query. + * @returns #hipSuccess, #hipErrorNotReady, #hipErrorInvalidHandle, #hipErrorInvalidValue, + * #hipErrorNotInitialized, #hipErrorLaunchFailure + * + * Query the status of the specified event. This function will return #hipSuccess if all + * commands in the appropriate stream (specified to hipEventRecord()) have completed. If any execution + * has not completed, then #hipErrorNotReady is returned. + * + * @note: This API returns #hipSuccess, if hipEventRecord() is not called before this API. + * + * @see hipEventCreate, hipEventCreateWithFlags, hipEventRecord, hipEventDestroy, + * hipEventSynchronize, hipEventElapsedTime + */ +hipError_t hipEventQuery(hipEvent_t event); +// end doxygen Events +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Memory Memory Management + * @{ + * This section describes the memory management functions of HIP runtime API. + * The following CUDA APIs are not currently supported: + * - cudaMalloc3D + * - cudaMalloc3DArray + * - TODO - more 2D, 3D, array APIs here. + * + * + */ + +/** + * @brief Sets information on the specified pointer.[BETA] + * + * @param [in] value Sets pointer attribute value + * @param [in] attribute Attribute to set + * @param [in] ptr Pointer to set attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipPointerSetAttribute(const void* value, hipPointer_attribute attribute, + hipDeviceptr_t ptr); + + +/** + * @brief Returns attributes for the specified pointer + * + * @param [out] attributes attributes for the specified pointer + * @param [in] ptr pointer to get attributes for + * + * The output parameter 'attributes' has a member named 'type' that describes what memory the + * pointer is associated with, such as device memory, host memory, managed memory, and others. + * Otherwise, the API cannot handle the pointer and returns #hipErrorInvalidValue. + * + * @note The unrecognized memory type is unsupported to keep the HIP functionality backward + * compatibility due to #hipMemoryType enum values. + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @note The current behavior of this HIP API corresponds to the CUDA API before version 11.0. + * + * @see hipPointerGetAttribute + */ +hipError_t hipPointerGetAttributes(hipPointerAttribute_t* attributes, const void* ptr); +/** + * @brief Returns information about the specified pointer.[BETA] + * + * @param [in, out] data Returned pointer attribute value + * @param [in] attribute Attribute to query for + * @param [in] ptr Pointer to get attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipPointerGetAttributes + */ +hipError_t hipPointerGetAttribute(void* data, hipPointer_attribute attribute, + hipDeviceptr_t ptr); +/** + * @brief Returns information about the specified pointer.[BETA] + * + * @param [in] numAttributes number of attributes to query for + * @param [in] attributes attributes to query for + * @param [in, out] data a two-dimensional containing pointers to memory locations + * where the result of each attribute query will be written to + * @param [in] ptr pointer to get attributes for + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @see hipPointerGetAttribute + */ +hipError_t hipDrvPointerGetAttributes(unsigned int numAttributes, hipPointer_attribute* attributes, + void** data, hipDeviceptr_t ptr); +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup External External Resource Interoperability + * @{ + * @ingroup API + * + * This section describes the external resource interoperability functions of HIP runtime API. + * + */ +/** + * @brief Imports an external semaphore. + * + * @param[out] extSem_out External semaphores to be waited on + * @param[in] semHandleDesc Semaphore import handle descriptor + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipImportExternalSemaphore(hipExternalSemaphore_t* extSem_out, + const hipExternalSemaphoreHandleDesc* semHandleDesc); +/** + * @brief Signals a set of external semaphore objects. + * + * @param[in] extSemArray External semaphores to be waited on + * @param[in] paramsArray Array of semaphore parameters + * @param[in] numExtSems Number of semaphores to wait on + * @param[in] stream Stream to enqueue the wait operations in + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipSignalExternalSemaphoresAsync(const hipExternalSemaphore_t* extSemArray, + const hipExternalSemaphoreSignalParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); +/** + * @brief Waits on a set of external semaphore objects + * + * @param[in] extSemArray External semaphores to be waited on + * @param[in] paramsArray Array of semaphore parameters + * @param[in] numExtSems Number of semaphores to wait on + * @param[in] stream Stream to enqueue the wait operations in + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipWaitExternalSemaphoresAsync(const hipExternalSemaphore_t* extSemArray, + const hipExternalSemaphoreWaitParams* paramsArray, + unsigned int numExtSems, hipStream_t stream); +/** + * @brief Destroys an external semaphore object and releases any references to the underlying resource. Any outstanding signals or waits must have completed before the semaphore is destroyed. + * + * @param[in] extSem handle to an external memory object + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see + */ +hipError_t hipDestroyExternalSemaphore(hipExternalSemaphore_t extSem); + +/** +* @brief Imports an external memory object. +* +* @param[out] extMem_out Returned handle to an external memory object +* @param[in] memHandleDesc Memory import handle descriptor +* +* @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipImportExternalMemory(hipExternalMemory_t* extMem_out, const hipExternalMemoryHandleDesc* memHandleDesc); +/** +* @brief Maps a buffer onto an imported memory object. +* +* @param[out] devPtr Returned device pointer to buffer +* @param[in] extMem Handle to external memory object +* @param[in] bufferDesc Buffer descriptor +* +* @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipExternalMemoryGetMappedBuffer(void **devPtr, hipExternalMemory_t extMem, const hipExternalMemoryBufferDesc *bufferDesc); +/** +* @brief Destroys an external memory object. +* +* @param[in] extMem External memory object to be destroyed +* +* @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue +* +* @see +*/ +hipError_t hipDestroyExternalMemory(hipExternalMemory_t extMem); +/** + * @brief Maps a mipmapped array onto an external memory object. + * + * @param[out] mipmap mipmapped array to return + * @param[in] extMem external memory object handle + * @param[in] mipmapDesc external mipmapped array descriptor + * + * Returned mipmapped array must be freed using hipFreeMipmappedArray. + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidResourceHandle + * + * @see hipImportExternalMemory, hipDestroyExternalMemory, hipExternalMemoryGetMappedBuffer, hipFreeMipmappedArray + */ +hipError_t hipExternalMemoryGetMappedMipmappedArray(hipMipmappedArray_t* mipmap, hipExternalMemory_t extMem, + const hipExternalMemoryMipmappedArrayDesc* mipmapDesc); + // end of external resource + /** + * @} + */ +/** + * @brief Allocate memory on the default accelerator + * + * @param[out] ptr Pointer to the allocated memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory, #hipErrorInvalidValue (bad context, null *ptr) + * + * @see hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, hipMalloc3DArray, + * hipHostFree, hipHostMalloc + */ +hipError_t hipMalloc(void** ptr, size_t size); +/** + * @brief Allocate memory on the default accelerator + * + * @param[out] ptr Pointer to the allocated memory + * @param[in] sizeBytes Requested memory size + * @param[in] flags Type of memory allocation + * + * If requested memory size is 0, no memory is allocated, *ptr returns nullptr, and #hipSuccess + * is returned. + * + * The memory allocation flag should be either #hipDeviceMallocDefault, + * #hipDeviceMallocFinegrained, #hipDeviceMallocUncached, or #hipMallocSignalMemory. + * If the flag is any other value, the API returns #hipErrorInvalidValue. + * + * @return #hipSuccess, #hipErrorOutOfMemory, #hipErrorInvalidValue (bad context, null *ptr) + * + * @see hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, hipMalloc3DArray, + * hipHostFree, hipHostMalloc + */ +hipError_t hipExtMallocWithFlags(void** ptr, size_t sizeBytes, unsigned int flags); +/** + * @brief Allocate pinned host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipMallocHost(void** ptr, size_t size); +/** + * @brief Allocate pinned host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipMemAllocHost(void** ptr, size_t size); +/** + * @brief Allocates device accessible page locked (pinned) host memory + * + * This API allocates pinned host memory which is mapped into the address space of all GPUs + * in the system, the memory can be accessed directly by the GPU device, and can be read or + * written with much higher bandwidth than pageable memory obtained with functions such as + * malloc(). + * + * Using the pinned host memory, applications can implement faster data transfers for HostToDevice + * and DeviceToHost. The runtime tracks the hipHostMalloc allocations and can avoid some of the + * setup required for regular unpinned memory. + * + * When the memory accesses are infrequent, zero-copy memory can be a good choice, for coherent + * allocation. GPU can directly access the host memory over the CPU/GPU interconnect, without need + * to copy the data. + * + * Currently the allocation granularity is 4KB for the API. + * + * Developers need to choose proper allocation flag with consideration of synchronization. + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size in bytes + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * @param[in] flags Type of host memory allocation + * + * If no input for flags, it will be the default pinned memory allocation on the host. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipSetDeviceFlags, hipHostFree + */ +hipError_t hipHostMalloc(void** ptr, size_t size, unsigned int flags); +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup MemoryM Managed Memory + * + * @ingroup Memory + * @{ + * This section describes the managed memory management functions of HIP runtime API. + * + * @note The managed memory management APIs are implemented on Linux, under developement + * on Windows. + * + */ +/** + * @brief Allocates memory that will be automatically managed by HIP. + * + * This API is used for managed memory, allows data be shared and accessible to both CPU and + * GPU using a single pointer. + * + * The API returns the allocation pointer, managed by HMM, can be used further to execute kernels + * on device and fetch data between the host and device as needed. + * + * @note It is recommend to do the capability check before call this API. + * + * @param [out] dev_ptr - pointer to allocated device memory + * @param [in] size - requested allocation size in bytes, it should be granularity of 4KB + * @param [in] flags - must be either hipMemAttachGlobal or hipMemAttachHost + * (defaults to hipMemAttachGlobal) + * + * @returns #hipSuccess, #hipErrorMemoryAllocation, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipMallocManaged(void** dev_ptr, + size_t size, + unsigned int flags __dparm(hipMemAttachGlobal)); +/** + * @brief Prefetches memory to the specified destination device using HIP. + * + * @param [in] dev_ptr pointer to be prefetched + * @param [in] count size in bytes for prefetching + * @param [in] device destination device to prefetch to + * @param [in] stream stream to enqueue prefetch operation + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPrefetchAsync(const void* dev_ptr, + size_t count, + int device, + hipStream_t stream __dparm(0)); +/** + * @brief Advise about the usage of a given memory range to HIP. + * + * @param [in] dev_ptr pointer to memory to set the advice for + * @param [in] count size in bytes of the memory range, it should be CPU page size alligned. + * @param [in] advice advice to be applied for the specified memory range + * @param [in] device device to apply the advice for + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * This HIP API advises about the usage to be applied on unified memory allocation in the + * range starting from the pointer address devPtr, with the size of count bytes. + * The memory range must refer to managed memory allocated via the API hipMallocManaged, and the + * range will be handled with proper round down and round up respectively in the driver to + * be aligned to CPU page size, the same way as corresponding CUDA API behaves in CUDA version 8.0 + * and afterwards. + * + * @note This API is implemented on Linux and is under development on Windows. + */ +hipError_t hipMemAdvise(const void* dev_ptr, + size_t count, + hipMemoryAdvise advice, + int device); +/** + * @brief Query an attribute of a given memory range in HIP. + * + * @param [in,out] data a pointer to a memory location where the result of each + * attribute query will be written to + * @param [in] data_size the size of data + * @param [in] attribute the attribute to query + * @param [in] dev_ptr start of the range to query + * @param [in] count size of the range to query + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRangeGetAttribute(void* data, + size_t data_size, + hipMemRangeAttribute attribute, + const void* dev_ptr, + size_t count); +/** + * @brief Query attributes of a given memory range in HIP. + * + * @param [in,out] data a two-dimensional array containing pointers to memory locations + * where the result of each attribute query will be written to + * @param [in] data_sizes an array, containing the sizes of each result + * @param [in] attributes the attribute to query + * @param [in] num_attributes an array of attributes to query (numAttributes and the number + * of attributes in this array should match) + * @param [in] dev_ptr start of the range to query + * @param [in] count size of the range to query + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRangeGetAttributes(void** data, + size_t* data_sizes, + hipMemRangeAttribute* attributes, + size_t num_attributes, + const void* dev_ptr, + size_t count); +/** + * @brief Attach memory to a stream asynchronously in HIP. + * + * @param [in] stream - stream in which to enqueue the attach operation + * @param [in] dev_ptr - pointer to memory (must be a pointer to managed memory or + * to a valid host-accessible region of system-allocated memory) + * @param [in] length - length of memory (defaults to zero) + * @param [in] flags - must be one of hipMemAttachGlobal, hipMemAttachHost or + * hipMemAttachSingle (defaults to hipMemAttachSingle) + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipStreamAttachMemAsync(hipStream_t stream, + void* dev_ptr, + size_t length __dparm(0), + unsigned int flags __dparm(hipMemAttachSingle)); +// end doxygen Managed Memory +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup StreamO Stream Ordered Memory Allocator + * @{ + * @ingroup Memory + * This section describes Stream Ordered Memory Allocator functions of HIP runtime API. + * + * The asynchronous allocator allows the user to allocate and free in stream order. + * All asynchronous accesses of the allocation must happen between the stream executions of + * the allocation and the free. If the memory is accessed outside of the promised stream order, + * a use before allocation / use after free error will cause undefined behavior. + * + * The allocator is free to reallocate the memory as long as it can guarantee that compliant memory + * accesses will not overlap temporally. The allocator may refer to internal stream ordering as well + * as inter-stream dependencies (such as HIP events and null stream dependencies) when establishing + * the temporal guarantee. The allocator may also insert inter-stream dependencies to establish + * the temporal guarantee. Whether or not a device supports the integrated stream ordered memory + * allocator may be queried by calling @p hipDeviceGetAttribute with the device attribute + * @p hipDeviceAttributeMemoryPoolsSupported + * + * @note APIs in this section are implemented on Linux, under development on Windows. + */ + +/** + * @brief Allocates memory with stream ordered semantics + * + * Inserts a memory allocation operation into @p stream. + * A pointer to the allocated memory is returned immediately in *dptr. + * The allocation must not be accessed until the allocation operation completes. + * The allocation comes from the memory pool associated with the stream's device. + * + * @note The default memory pool of a device contains device memory from that device. + * @note Basic stream ordering allows future work submitted into the same stream to use the + * allocation. Stream query, stream synchronize, and HIP events can be used to guarantee that + * the allocation operation completes before work submitted in a separate stream runs. + * @note During stream capture, this function results in the creation of an allocation node. + * In this case, the allocation is owned by the graph instead of the memory pool. The memory + * pool's properties are used to set the node's creation parameters. + * + * @param [out] dev_ptr Returned device pointer of memory allocation + * @param [in] size Number of bytes to allocate + * @param [in] stream The stream establishing the stream ordering contract and + * the memory pool to allocate from + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @see hipMallocFromPoolAsync, hipFreeAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMallocAsync(void** dev_ptr, size_t size, hipStream_t stream); +/** + * @brief Frees memory with stream ordered semantics + * + * Inserts a free operation into @p stream. + * The allocation must not be used after stream execution reaches the free. + * After this API returns, accessing the memory from any subsequent work launched on the GPU + * or querying its pointer attributes results in undefined behavior. + * + * @note During stream capture, this function results in the creation of a free node and + * must therefore be passed the address of a graph allocation. + * + * @param [in] dev_ptr Pointer to device memory to free + * @param [in] stream The stream, where the destruciton will occur according to the execution order + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipMemPoolTrimTo, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipFreeAsync(void* dev_ptr, hipStream_t stream); +/** + * @brief Releases freed memory back to the OS + * + * Releases memory back to the OS until the pool contains fewer than @p min_bytes_to_keep + * reserved bytes, or there is no more memory that the allocator can safely release. + * The allocator cannot release OS allocations that back outstanding asynchronous allocations. + * The OS allocations may happen at different granularity from the user allocations. + * + * @note: Allocations that have not been freed count as outstanding. + * @note: Allocations that have been asynchronously freed but whose completion has + * not been observed on the host (eg. by a synchronize) can count as outstanding. + * + * @param[in] mem_pool The memory pool to trim allocations + * @param[in] min_bytes_to_hold If the pool has less than min_bytes_to_hold reserved, + * then the TrimTo operation is a no-op. Otherwise the memory pool will contain + * at least min_bytes_to_hold bytes reserved after the operation. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolTrimTo(hipMemPool_t mem_pool, size_t min_bytes_to_hold); +/** + * @brief Sets attributes of a memory pool + * + * Supported attributes are: + * - @p hipMemPoolAttrReleaseThreshold: (value type = cuuint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + * - @p hipMemPoolReuseFollowEventDependencies: (value type = int) + * Allow @p hipMallocAsync to use memory asynchronously freed + * in another stream as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * HIP events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + * - @p hipMemPoolReuseAllowOpportunistic: (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + * - @p hipMemPoolReuseAllowInternalDependencies: (value type = int) + * Allow @p hipMallocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by @p hipFreeAsync (default enabled). + * + * @param [in] mem_pool The memory pool to modify + * @param [in] attr The attribute to modify + * @param [in] value Pointer to the value to assign + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolSetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); +/** + * @brief Gets attributes of a memory pool + * + * Supported attributes are: + * - @p hipMemPoolAttrReleaseThreshold: (value type = cuuint64_t) + * Amount of reserved memory in bytes to hold onto before trying + * to release memory back to the OS. When more than the release + * threshold bytes of memory are held by the memory pool, the + * allocator will try to release memory back to the OS on the + * next call to stream, event or context synchronize. (default 0) + * - @p hipMemPoolReuseFollowEventDependencies: (value type = int) + * Allow @p hipMallocAsync to use memory asynchronously freed + * in another stream as long as a stream ordering dependency + * of the allocating stream on the free action exists. + * HIP events and null stream interactions can create the required + * stream ordered dependencies. (default enabled) + * - @p hipMemPoolReuseAllowOpportunistic: (value type = int) + * Allow reuse of already completed frees when there is no dependency + * between the free and allocation. (default enabled) + * - @p hipMemPoolReuseAllowInternalDependencies: (value type = int) + * Allow @p hipMallocAsync to insert new stream dependencies + * in order to establish the stream ordering required to reuse + * a piece of memory released by @p hipFreeAsync (default enabled). + * + * @param [in] mem_pool The memory pool to get attributes of + * @param [in] attr The attribute to get + * @param [in] value Retrieved value + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolGetAttribute(hipMemPool_t mem_pool, hipMemPoolAttr attr, void* value); +/** + * @brief Controls visibility of the specified pool between devices + * + * @param [in] mem_pool Memory pool for acccess change + * @param [in] desc_list Array of access descriptors. Each descriptor instructs the access to enable for a single gpu + * @param [in] count Number of descriptors in the map array. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolSetAccess(hipMemPool_t mem_pool, const hipMemAccessDesc* desc_list, size_t count); +/** + * @brief Returns the accessibility of a pool from a device + * + * Returns the accessibility of the pool's memory from the specified location. + * + * @param [out] flags Accessibility of the memory pool from the specified location/device + * @param [in] mem_pool Memory pool being queried + * @param [in] location Location/device for memory pool access + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolGetAccess(hipMemAccessFlags* flags, hipMemPool_t mem_pool, hipMemLocation* location); +/** + * @brief Creates a memory pool + * + * Creates a HIP memory pool and returns the handle in @p mem_pool. The @p pool_props determines + * the properties of the pool such as the backing device and IPC capabilities. + * + * By default, the memory pool will be accessible from the device it is allocated on. + * + * @param [out] mem_pool Contains createed memory pool + * @param [in] pool_props Memory pool properties + * + * @note Specifying hipMemHandleTypeNone creates a memory pool that will not support IPC. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolDestroy, + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolCreate(hipMemPool_t* mem_pool, const hipMemPoolProps* pool_props); +/** + * @brief Destroys the specified memory pool + * + * If any pointers obtained from this pool haven't been freed or + * the pool has free operations that haven't completed + * when @p hipMemPoolDestroy is invoked, the function will return immediately and the + * resources associated with the pool will be released automatically + * once there are no more outstanding allocations. + * + * Destroying the current mempool of a device sets the default mempool of + * that device as the current mempool for that device. + * + * @param [in] mem_pool Memory pool for destruction + * + * @note A device's default memory pool cannot be destroyed. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipMallocFromPoolAsync, hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolCreate + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolDestroy(hipMemPool_t mem_pool); +/** + * @brief Allocates memory from a specified pool with stream ordered semantics. + * + * Inserts an allocation operation into @p stream. + * A pointer to the allocated memory is returned immediately in @p dev_ptr. + * The allocation must not be accessed until the allocation operation completes. + * The allocation comes from the specified memory pool. + * + * @note The specified memory pool may be from a device different than that of the specified @p stream. + * + * Basic stream ordering allows future work submitted into the same stream to use the allocation. + * Stream query, stream synchronize, and HIP events can be used to guarantee that the allocation + * operation completes before work submitted in a separate stream runs. + * + * @note During stream capture, this function results in the creation of an allocation node. In this case, + * the allocation is owned by the graph instead of the memory pool. The memory pool's properties + * are used to set the node's creation parameters. + * + * @param [out] dev_ptr Returned device pointer + * @param [in] size Number of bytes to allocate + * @param [in] mem_pool The pool to allocate from + * @param [in] stream The stream establishing the stream ordering semantic + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @see hipMallocAsync, hipFreeAsync, hipMemPoolGetAttribute, hipMemPoolCreate + * hipMemPoolTrimTo, hipDeviceSetMemPool, hipMemPoolSetAttribute, hipMemPoolSetAccess, hipMemPoolGetAccess, + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMallocFromPoolAsync(void** dev_ptr, size_t size, hipMemPool_t mem_pool, hipStream_t stream); +/** + * @brief Exports a memory pool to the requested handle type. + * + * Given an IPC capable mempool, create an OS handle to share the pool with another process. + * A recipient process can convert the shareable handle into a mempool with @p hipMemPoolImportFromShareableHandle. + * Individual pointers can then be shared with the @p hipMemPoolExportPointer and @p hipMemPoolImportPointer APIs. + * The implementation of what the shareable handle is and how it can be transferred is defined by the requested + * handle type. + * + * @note: To create an IPC capable mempool, create a mempool with a @p hipMemAllocationHandleType other + * than @p hipMemHandleTypeNone. + * + * @param [out] shared_handle Pointer to the location in which to store the requested handle + * @param [in] mem_pool Pool to export + * @param [in] handle_type The type of handle to create + * @param [in] flags Must be 0 + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolImportFromShareableHandle + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolExportToShareableHandle( + void* shared_handle, + hipMemPool_t mem_pool, + hipMemAllocationHandleType handle_type, + unsigned int flags); +/** + * @brief Imports a memory pool from a shared handle. + * + * Specific allocations can be imported from the imported pool with @p hipMemPoolImportPointer. + * + * @note Imported memory pools do not support creating new allocations. + * As such imported memory pools may not be used in @p hipDeviceSetMemPool + * or @p hipMallocFromPoolAsync calls. + * + * @param [out] mem_pool Returned memory pool + * @param [in] shared_handle OS handle of the pool to open + * @param [in] handle_type The type of handle being imported + * @param [in] flags Must be 0 + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolExportToShareableHandle + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolImportFromShareableHandle( + hipMemPool_t* mem_pool, + void* shared_handle, + hipMemAllocationHandleType handle_type, + unsigned int flags); +/** + * @brief Export data to share a memory pool allocation between processes. + * + * Constructs @p export_data for sharing a specific allocation from an already shared memory pool. + * The recipient process can import the allocation with the @p hipMemPoolImportPointer api. + * The data is not a handle and may be shared through any IPC mechanism. + * + * @param[out] export_data Returned export data + * @param[in] dev_ptr Pointer to memory being exported + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipMemPoolImportPointer + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolExportPointer(hipMemPoolPtrExportData* export_data, void* dev_ptr); +/** + * @brief Import a memory pool allocation from another process. + * + * Returns in @p dev_ptr a pointer to the imported memory. + * The imported memory must not be accessed before the allocation operation completes + * in the exporting process. The imported memory must be freed from all importing processes before + * being freed in the exporting process. The pointer may be freed with @p hipFree + * or @p hipFreeAsync. If @p hipFreeAsync is used, the free must be completed + * on the importing process before the free operation on the exporting process. + * + * @note The @p hipFreeAsync api may be used in the exporting process before + * the @p hipFreeAsync operation completes in its stream as long as the + * @p hipFreeAsync in the exporting process specifies a stream with + * a stream dependency on the importing process's @p hipFreeAsync. + * + * @param [out] dev_ptr Pointer to imported memory + * @param [in] mem_pool Memory pool from which to import a pointer + * @param [in] export_data Data specifying the memory to import + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized, #hipErrorOutOfMemory + * + * @see hipMemPoolExportPointer + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemPoolImportPointer( + void** dev_ptr, + hipMemPool_t mem_pool, + hipMemPoolPtrExportData* export_data); +// Doxygen end of ordered memory allocator +/** + * @} + */ + +/** + * @brief Allocate device accessible page locked host memory [Deprecated] + * + * @param[out] ptr Pointer to the allocated host pinned memory + * @param[in] size Requested memory size in bytes + * @param[in] flags Type of host memory allocation + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @warning This API is deprecated, use hipHostMalloc() instead + */ +DEPRECATED("use hipHostMalloc instead") +hipError_t hipHostAlloc(void** ptr, size_t size, unsigned int flags); +/** + * @brief Get Device pointer from Host Pointer allocated through hipHostMalloc + * + * @param[out] devPtr Device Pointer mapped to passed host pointer + * @param[in] hstPtr Host Pointer allocated through hipHostMalloc + * @param[in] flags Flags to be passed for extension + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorOutOfMemory + * + * @see hipSetDeviceFlags, hipHostMalloc + */ +hipError_t hipHostGetDevicePointer(void** devPtr, void* hstPtr, unsigned int flags); +/** + * @brief Return flags associated with host pointer + * + * @param[out] flagsPtr Memory location to store flags + * @param[in] hostPtr Host Pointer allocated through hipHostMalloc + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipHostMalloc + */ +hipError_t hipHostGetFlags(unsigned int* flagsPtr, void* hostPtr); +/** + * @brief Register host memory so it can be accessed from the current device. + * + * @param[out] hostPtr Pointer to host memory to be registered. + * @param[in] sizeBytes Size of the host memory + * @param[in] flags See below. + * + * Flags: + * - #hipHostRegisterDefault Memory is Mapped and Portable + * - #hipHostRegisterPortable Memory is considered registered by all contexts. HIP only supports + * one context so this is always assumed true. + * - #hipHostRegisterMapped Map the allocation into the address space for the current device. + * The device pointer can be obtained with #hipHostGetDevicePointer. + * + * + * After registering the memory, use #hipHostGetDevicePointer to obtain the mapped device pointer. + * On many systems, the mapped device pointer will have a different value than the mapped host + * pointer. Applications must use the device pointer in device code, and the host pointer in device + * code. + * + * On some systems, registered memory is pinned. On some systems, registered memory may not be + * actually be pinned but uses OS or hardware facilities to all GPU access to the host memory. + * + * Developers are strongly encouraged to register memory blocks which are aligned to the host + * cache-line size. (typically 64-bytes but can be obtains from the CPUID instruction). + * + * If registering non-aligned pointers, the application must take care when register pointers from + * the same cache line on different devices. HIP's coarse-grained synchronization model does not + * guarantee correct results if different devices write to different parts of the same cache block - + * typically one of the writes will "win" and overwrite data from the other registered memory + * region. + * + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipHostUnregister, hipHostGetFlags, hipHostGetDevicePointer + */ +hipError_t hipHostRegister(void* hostPtr, size_t sizeBytes, unsigned int flags); +/** + * @brief Un-register host pointer + * + * @param[in] hostPtr Host pointer previously registered with #hipHostRegister + * @return Error code + * + * @see hipHostRegister + */ +hipError_t hipHostUnregister(void* hostPtr); +/** + * Allocates at least width (in bytes) * height bytes of linear memory + * Padding may occur to ensure alighnment requirements are met for the given row + * The change in width size due to padding will be returned in *pitch. + * Currently the alignment is set to 128 bytes + * + * @param[out] ptr Pointer to the allocated device memory + * @param[out] pitch Pitch for allocation (in bytes) + * @param[in] width Requested pitched allocation width (in bytes) + * @param[in] height Requested pitched allocation height + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * + * @return Error code + * + * @see hipMalloc, hipFree, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipMallocPitch(void** ptr, size_t* pitch, size_t width, size_t height); +/** + * Allocates at least width (in bytes) * height bytes of linear memory + * Padding may occur to ensure alighnment requirements are met for the given row + * The change in width size due to padding will be returned in *pitch. + * Currently the alignment is set to 128 bytes + * + * @param[out] dptr Pointer to the allocated device memory + * @param[out] pitch Pitch for allocation (in bytes) + * @param[in] widthInBytes Requested pitched allocation width (in bytes) + * @param[in] height Requested pitched allocation height + * @param[in] elementSizeBytes The size of element bytes, should be 4, 8 or 16 + * + * If size is 0, no memory is allocated, *ptr returns nullptr, and hipSuccess is returned. + * The intended usage of pitch is as a separate parameter of the allocation, used to compute addresses within the 2D array. + * Given the row and column of an array element of type T, the address is computed as: + * T* pElement = (T*)((char*)BaseAddress + Row * Pitch) + Column; + * + * @return Error code + * + * @see hipMalloc, hipFree, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipMemAllocPitch(hipDeviceptr_t* dptr, size_t* pitch, size_t widthInBytes, size_t height, + unsigned int elementSizeBytes); +/** + * @brief Free memory allocated by the hcc hip memory allocation API. + * This API performs an implicit hipDeviceSynchronize() call. + * If pointer is NULL, the hip runtime is initialized and hipSuccess is returned. + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess + * @return #hipErrorInvalidDevicePointer (if pointer is invalid, including host pointers allocated + * with hipHostMalloc) + * + * @see hipMalloc, hipMallocPitch, hipMallocArray, hipFreeArray, hipHostFree, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipFree(void* ptr); +/** + * @brief Free memory allocated by the hcc hip host memory allocation API [Deprecated] + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess, + * #hipErrorInvalidValue (if pointer is invalid, including device pointers allocated + * with hipMalloc) + * + * @warning This API is deprecated, use hipHostFree() instead + */ +DEPRECATED("use hipHostFree instead") +hipError_t hipFreeHost(void* ptr); +/** + * @brief Free memory allocated by the hcc hip host memory allocation API + * This API performs an implicit hipDeviceSynchronize() call. + * If pointer is NULL, the hip runtime is initialized and hipSuccess is returned. + * + * @param[in] ptr Pointer to memory to be freed + * @return #hipSuccess, + * #hipErrorInvalidValue (if pointer is invalid, including device pointers allocated with + * hipMalloc) + * + * @see hipMalloc, hipMallocPitch, hipFree, hipMallocArray, hipFreeArray, hipMalloc3D, + * hipMalloc3DArray, hipHostMalloc + */ +hipError_t hipHostFree(void* ptr); +/** + * @brief Copy data from src to dst. + * + * It supports memory from host to device, + * device to host, device to device and host to host + * The src and dst must not overlap. + * + * For hipMemcpy, the copy is always performed by the current device (set by hipSetDevice). + * For multi-gpu or peer-to-peer configurations, it is recommended to set the current device to the + * device where the src data is physically located. For optimal peer-to-peer copies, the copy device + * must be able to access the src and dst pointers (by calling hipDeviceEnablePeerAccess with copy + * agent as the current device and src/dest as the peerDevice argument. if this is not done, the + * hipMemcpy will still work, but will perform the copy using a staging buffer on the host. + * Calling hipMemcpy with dst and src pointers that do not match the hipMemcpyKind results in + * undefined behavior. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Kind of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpy(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind); +/** + * @brief Memory copy on the stream. + * It allows single or multiple devices to do memory copy on single or multiple streams. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Kind of transfer + * @param[in] stream Valid stream + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + * @see hipMemcpy, hipStreamCreate, hipStreamSynchronize, hipStreamDestroy, hipSetDevice, hipLaunchKernelGGL + * + */ +hipError_t hipMemcpyWithStream(void* dst, const void* src, size_t sizeBytes, + hipMemcpyKind kind, hipStream_t stream); +/** + * @brief Copy data from Host to Device + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoD(hipDeviceptr_t dst, void* src, size_t sizeBytes); +/** + * @brief Copy data from Device to Host + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoH(void* dst, hipDeviceptr_t src, size_t sizeBytes); +/** + * @brief Copy data from Device to Device + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoD(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes); +/** + * @brief Copies from one 1D array to device memory. + * + * @param[out] dstDevice Destination device pointer + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoD(hipDeviceptr_t dstDevice, hipArray_t srcArray, size_t srcOffset, + size_t ByteCount); +/** + * @brief Copies from device memory to a 1D array. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcDevice Source device pointer + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoA(hipArray_t dstArray, size_t dstOffset, hipDeviceptr_t srcDevice, + size_t ByteCount); + +/** + * @brief Copies from one 1D array to another. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoA(hipArray_t dstArray, size_t dstOffset, hipArray_t srcArray, + size_t srcOffset, size_t ByteCount); +/** + * @brief Copy data from Host to Device asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoDAsync(hipDeviceptr_t dst, void* src, size_t sizeBytes, hipStream_t stream); +/** + * @brief Copy data from Device to Host asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoHAsync(void* dst, hipDeviceptr_t src, size_t sizeBytes, hipStream_t stream); +/** + * @brief Copy data from Device to Device asynchronously + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyDtoDAsync(hipDeviceptr_t dst, hipDeviceptr_t src, size_t sizeBytes, + hipStream_t stream); +/** + * @brief Copies from one 1D array to host memory. + * + * @param[out] dstHost Destination pointer + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] ByteCount Size of memory copy in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyAtoHAsync(void* dstHost, hipArray_t srcArray, size_t srcOffset, + size_t ByteCount, hipStream_t stream); +/** + * @brief Copies from host memory to a 1D array. + * + * @param[out] dstArray Destination array + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcHost Source host pointer + * @param[in] ByteCount Size of memory copy in bytes + * @param[in] stream Stream identifier + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, hipMemAllocHost, + * hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, hipMemcpyAtoA, + * hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, hipMemcpyDtoA, hipMemcpyDtoD, + * hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, hipMemcpyHtoA, hipMemcpyHtoAAsync, + * hipMemcpyHtoDAsync, hipMemFree, hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, + * hipMemHostAlloc, hipMemHostGetDevicePointer + */ +hipError_t hipMemcpyHtoAAsync(hipArray_t dstArray, size_t dstOffset, const void* srcHost, + size_t ByteCount, hipStream_t stream); +/** + * @brief Returns a global pointer from a module. + * Returns in *dptr and *bytes the pointer and size of the global of name name located in module hmod. + * If no variable of that name exists, it returns hipErrorNotFound. Both parameters dptr and bytes are optional. + * If one of them is NULL, it is ignored and hipSuccess is returned. + * + * @param[out] dptr Returns global device pointer + * @param[out] bytes Returns global size in bytes + * @param[in] hmod Module to retrieve global from + * @param[in] name Name of global to retrieve + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotFound, #hipErrorInvalidContext + * + */ +hipError_t hipModuleGetGlobal(hipDeviceptr_t* dptr, size_t* bytes, + hipModule_t hmod, const char* name); + +/** + * @brief Gets device pointer associated with symbol on the device. + * + * @param[out] devPtr pointer to the device associated the symbole + * @param[in] symbol pointer to the symbole of the device + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetSymbolAddress(void** devPtr, const void* symbol); + + + +/** + * @brief Gets the size of the given symbol on the device. + * + * @param[in] symbol pointer to the device symbole + * @param[out] size pointer to the size + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetSymbolSize(size_t* size, const void* symbol); + +/** + * @brief Gets the pointer of requested HIP driver function. + * + * @param[in] symbol The Symbol name of the driver function to request. + * @param[out] pfn Output pointer to the requested driver function. + * @param[in] hipVersion The HIP version for the requested driver function symbol. + * HIP version is defined as 100*version_major + version_minor. For example, in HIP 6.1, the + * hipversion is 601, for the symbol function "hipGetDeviceProperties", the specified hipVersion 601 + * is greater or equal to the version 600, the symbol function will be handle properly as backend + * compatible function. + * + * @param[in] flags Currently only default flag is suppported. + * @param[out] symbolStatus Optional enumeration for returned status of searching for symbol driver + * function based on the input hipVersion. + * + * Returns hipSuccess if the returned pfn is addressed to the pointer of found driver function. + * + * @return #hipSuccess, #hipErrorInvalidValue. + */ +hipError_t hipGetProcAddress(const char* symbol, void** pfn, int hipVersion, uint64_t flags, + hipDriverProcAddressQueryResult* symbolStatus); + +/** + * @brief Copies data to the given symbol on the device. + * Symbol HIP APIs allow a kernel to define a device-side data symbol which can be accessed on + * the host side. The symbol can be in __constant or device space. + * Note that the symbol name needs to be encased in the HIP_SYMBOL macro. + * This also applies to hipMemcpyFromSymbol, hipGetSymbolAddress, and hipGetSymbolSize. + * For detailed usage, see the + * memcpyToSymbol example + * in the HIP Porting Guide. + * + * + * @param[out] symbol pointer to the device symbole + * @param[in] src pointer to the source address + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from start of symbole + * @param[in] kind type of memory transfer + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyToSymbol(const void* symbol, const void* src, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)); + +/** + * @brief Copies data to the given symbol on the device asynchronously. + * + * @param[out] symbol pointer to the device symbole + * @param[in] src pointer to the source address + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from start of symbole + * @param[in] kind type of memory transfer + * @param[in] stream stream identifier + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyToSymbolAsync(const void* symbol, const void* src, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)); + +/** + * @brief Copies data from the given symbol on the device. + * + * @param[out] dst Returns pointer to destinition memory address + * @param[in] symbol Pointer to the symbole address on the device + * @param[in] sizeBytes Size in bytes to copy + * @param[in] offset Offset in bytes from the start of symbole + * @param[in] kind Type of memory transfer + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyFromSymbol(void* dst, const void* symbol, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)); + +/** + * @brief Copies data from the given symbol on the device asynchronously. + * + * @param[out] dst Returns pointer to destinition memory address + * @param[in] symbol pointer to the symbole address on the device + * @param[in] sizeBytes size in bytes to copy + * @param[in] offset offset in bytes from the start of symbole + * @param[in] kind type of memory transfer + * @param[in] stream stream identifier + * + * @return #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipMemcpyFromSymbolAsync(void* dst, const void* symbol, + size_t sizeBytes, size_t offset, + hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Copy data from src to dst asynchronously. + * + * @warning If host or dest are not pinned, the memory copy will be performed synchronously. For + * best performance, use hipHostMalloc to allocate host memory that is transferred asynchronously. + * + * @warning on HCC hipMemcpyAsync does not support overlapped H2D and D2H copies. + * For hipMemcpy, the copy is always performed by the device associated with the specified stream. + * + * For multi-gpu or peer-to-peer configurations, it is recommended to use a stream which is a + * attached to the device where the src data is physically located. For optimal peer-to-peer copies, + * the copy device must be able to access the src and dst pointers (by calling + * hipDeviceEnablePeerAccess with copy agent as the current device and src/dest as the peerDevice + * argument. if this is not done, the hipMemcpy will still work, but will perform the copy using a + * staging buffer on the host. + * + * @param[out] dst Data being copy to + * @param[in] src Data being copy from + * @param[in] sizeBytes Data size in bytes + * @param[in] kind Type of memory transfer + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpy2DFromArray, hipMemcpyArrayToArray, hipMemcpy2DArrayToArray, hipMemcpyToSymbol, + * hipMemcpyFromSymbol, hipMemcpy2DAsync, hipMemcpyToArrayAsync, hipMemcpy2DToArrayAsync, + * hipMemcpyFromArrayAsync, hipMemcpy2DFromArrayAsync, hipMemcpyToSymbolAsync, + * hipMemcpyFromSymbolAsync + */ +hipError_t hipMemcpyAsync(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * @param[out] dst Data being filled + * @param[in] value Value to be set + * @param[in] sizeBytes Data size in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemset(void* dst, int value, size_t sizeBytes); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD8(hipDeviceptr_t dest, unsigned char value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * byte value value. + * + * hipMemsetD8Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD8Async(hipDeviceptr_t dest, unsigned char value, size_t count, hipStream_t stream __dparm(0)); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * short value value. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD16(hipDeviceptr_t dest, unsigned short value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dest with the constant + * short value value. + * + * hipMemsetD16Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dest Data ptr to be filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD16Async(hipDeviceptr_t dest, unsigned short value, size_t count, hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dest with the constant integer + * value for specified number of times. + * + * @param[out] dest Data being filled + * @param[in] value Constant value to be set + * @param[in] count Number of values to be set + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + */ +hipError_t hipMemsetD32(hipDeviceptr_t dest, int value, size_t count); +/** + * @brief Fills the first sizeBytes bytes of the memory area pointed to by dev with the constant + * byte value value. + * + * hipMemsetAsync() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dst Pointer to device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] sizeBytes Size in bytes to set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemsetAsync(void* dst, int value, size_t sizeBytes, hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dev with the constant integer + * value for specified number of times. + * + * hipMemsetD32Async() is asynchronous with respect to the host, so the call may return before the + * memset is complete. The operation can optionally be associated to a stream by passing a non-zero + * stream argument. If stream is non-zero, the operation may overlap with operations in other + * streams. + * + * @param[out] dst Pointer to device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] count Number of values to be set + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemsetD32Async(hipDeviceptr_t dst, int value, size_t count, + hipStream_t stream __dparm(0)); +/** + * @brief Fills the memory area pointed to by dst with the constant value. + * + * @param[out] dst Pointer to device memory + * @param[in] pitch Data size in bytes + * @param[in] value Constant value to be set + * @param[in] width + * @param[in] height + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset2D(void* dst, size_t pitch, int value, size_t width, size_t height); +/** + * @brief Fills asynchronously the memory area pointed to by dst with the constant value. + * + * @param[in] dst Pointer to 2D device memory + * @param[in] pitch Pitch size in bytes + * @param[in] value Value to be set for each byte of specified memory + * @param[in] width Width of matrix set columns in bytes + * @param[in] height Height of matrix set rows in bytes + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset2DAsync(void* dst, size_t pitch, int value, size_t width, size_t height,hipStream_t stream __dparm(0)); +/** + * @brief Fills synchronously the memory area pointed to by pitchedDevPtr with the constant value. + * + * @param[in] pitchedDevPtr Pointer to pitched device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] extent Size parameters for width field in bytes in device memory + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset3D(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent ); +/** + * @brief Fills asynchronously the memory area pointed to by pitchedDevPtr with the constant value. + * + * @param[in] pitchedDevPtr Pointer to pitched device memory + * @param[in] value Value to set for each byte of specified memory + * @param[in] extent Size parameters for width field in bytes in device memory + * @param[in] stream Stream identifier + * @return #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipMemset3DAsync(hipPitchedPtr pitchedDevPtr, int value, hipExtent extent ,hipStream_t stream __dparm(0)); +/** + * @brief Query memory info. + * + * On ROCM, this function gets the actual free memory left on the current device, so supports + * the cases while running multi-workload (such as multiple processes, multiple threads, and + * multiple GPUs). + * + * @warning On Windows, the free memory only accounts for memory allocated by this process and may + * be optimistic. + * + * @param[out] free Returns free memory on the current device in bytes + * @param[out] total Returns total allocatable memory on the current device in bytes + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + **/ +hipError_t hipMemGetInfo(size_t* free, size_t* total); + +/** + * @brief Get allocated memory size via memory pointer. + * + * This function gets the allocated shared virtual memory size from memory pointer. + * + * @param[in] ptr Pointer to allocated memory + * @param[out] size Returns the allocated memory size in bytes + * + * @return #hipSuccess, #hipErrorInvalidValue + * + **/ +hipError_t hipMemPtrGetInfo(void* ptr, size_t* size); +/** + * @brief Allocate an array on the device. + * + * @param[out] array Pointer to allocated array in device memory + * @param[in] desc Requested channel format + * @param[in] width Requested array allocation width + * @param[in] height Requested array allocation height + * @param[in] flags Requested properties of allocated array + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipMalloc, hipMallocPitch, hipFree, hipFreeArray, hipHostMalloc, hipHostFree + */ +hipError_t hipMallocArray(hipArray_t* array, const hipChannelFormatDesc* desc, size_t width, + size_t height __dparm(0), unsigned int flags __dparm(hipArrayDefault)); +/** + * @brief Create an array memory pointer on the device. + * + * @param[out] pHandle Pointer to the array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArrayCreate(hipArray_t* pHandle, const HIP_ARRAY_DESCRIPTOR* pAllocateArray); + /** + * @brief Destroy an array memory pointer on the device. + * + * @param[in] array Pointer to the array memory + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @see hipArrayCreate, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArrayDestroy(hipArray_t array); +/** + * @brief Create a 3D array memory pointer on the device. + * + * @param[out] array Pointer to the 3D array memory + * @param[in] pAllocateArray Requested array desciptor + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocArray, hipArrayDestroy, hipFreeArray + */ +hipError_t hipArray3DCreate(hipArray_t* array, const HIP_ARRAY3D_DESCRIPTOR* pAllocateArray); +/** + * @brief Create a 3D memory pointer on the device. + * + * @param[out] pitchedDevPtr Pointer to the 3D memory + * @param[in] extent Requested extent + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @see hipMallocPitch, hipMemGetInfo, hipFree + */ +hipError_t hipMalloc3D(hipPitchedPtr* pitchedDevPtr, hipExtent extent); +/** + * @brief Frees an array on the device. + * + * @param[in] array Pointer to array to free + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorNotInitialized + * + * @see hipMalloc, hipMallocPitch, hipFree, hipMallocArray, hipHostMalloc, hipHostFree + */ +hipError_t hipFreeArray(hipArray_t array); +/** + * @brief Allocate an array on the device. + * + * @param[out] array Pointer to allocated array in device memory + * @param[in] desc Requested channel format + * @param[in] extent Requested array allocation width, height and depth + * @param[in] flags Requested properties of allocated array + * @return #hipSuccess, #hipErrorOutOfMemory + * + * @see hipMalloc, hipMallocPitch, hipFree, hipFreeArray, hipHostMalloc, hipHostFree + */ +hipError_t hipMalloc3DArray(hipArray_t* array, const struct hipChannelFormatDesc* desc, + struct hipExtent extent, unsigned int flags); +/** + * @brief Gets info about the specified array + * + * @param[out] desc - Returned array type + * @param[out] extent - Returned array shape. 2D arrays will have depth of zero + * @param[out] flags - Returned array flags + * @param[in] array - The HIP array to get info for + * + * @return #hipSuccess, #hipErrorInvalidValue #hipErrorInvalidHandle + * + * @see hipArrayGetDescriptor, hipArray3DGetDescriptor + */ +hipError_t hipArrayGetInfo(hipChannelFormatDesc* desc, hipExtent* extent, unsigned int* flags, + hipArray_t array); +/** + * @brief Gets a 1D or 2D array descriptor + * + * @param[out] pArrayDescriptor - Returned array descriptor + * @param[in] array - Array to get descriptor of + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue #hipErrorInvalidHandle + * + * @see hipArray3DCreate, hipArray3DGetDescriptor, hipArrayCreate, hipArrayDestroy, hipMemAlloc, + * hipMemAllocHost, hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, + * hipMemcpy3D, hipMemcpy3DAsync, hipMemcpyAtoA, hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, + * hipMemcpyDtoA, hipMemcpyDtoD, hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, + * hipMemcpyHtoA, hipMemcpyHtoAAsync, hipMemcpyHtoD, hipMemcpyHtoDAsync, hipMemFree, + * hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, hipMemHostAlloc, + * hipMemHostGetDevicePointer, hipMemsetD8, hipMemsetD16, hipMemsetD32, hipArrayGetInfo + */ +hipError_t hipArrayGetDescriptor(HIP_ARRAY_DESCRIPTOR* pArrayDescriptor, hipArray_t array); +/** + * @brief Gets a 3D array descriptor + * + * @param[out] pArrayDescriptor - Returned 3D array descriptor + * @param[in] array - 3D array to get descriptor of + * + * @return #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidValue #hipErrorInvalidHandle, #hipErrorContextIsDestroyed + * + * @see hipArray3DCreate, hipArrayCreate, hipArrayDestroy, hipArrayGetDescriptor, hipMemAlloc, + * hipMemAllocHost, hipMemAllocPitch, hipMemcpy2D, hipMemcpy2DAsync, hipMemcpy2DUnaligned, + * hipMemcpy3D, hipMemcpy3DAsync, hipMemcpyAtoA, hipMemcpyAtoD, hipMemcpyAtoH, hipMemcpyAtoHAsync, + * hipMemcpyDtoA, hipMemcpyDtoD, hipMemcpyDtoDAsync, hipMemcpyDtoH, hipMemcpyDtoHAsync, + * hipMemcpyHtoA, hipMemcpyHtoAAsync, hipMemcpyHtoD, hipMemcpyHtoDAsync, hipMemFree, + * hipMemFreeHost, hipMemGetAddressRange, hipMemGetInfo, hipMemHostAlloc, + * hipMemHostGetDevicePointer, hipMemsetD8, hipMemsetD16, hipMemsetD32, hipArrayGetInfo + */ +hipError_t hipArray3DGetDescriptor(HIP_ARRAY3D_DESCRIPTOR* pArrayDescriptor, hipArray_t array); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2D(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind); +/** + * @brief Copies memory for 2D arrays. + * @param[in] pCopy Parameters for the memory copy + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpyToSymbol, hipMemcpyAsync +*/ +hipError_t hipMemcpyParam2D(const hip_Memcpy2D* pCopy); +/** + * @brief Copies memory for 2D arrays. + * @param[in] pCopy Parameters for the memory copy + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2D, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, + * hipMemcpyToSymbol, hipMemcpyAsync +*/ +hipError_t hipMemcpyParam2DAsync(const hip_Memcpy2D* pCopy, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2DToArray, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DAsync(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, + size_t height, hipMemcpyKind kind, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DToArray(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] spitch Pitch of source memory + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Accelerator view which the copy is being enqueued + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DToArrayAsync(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t spitch, size_t width, size_t height, hipMemcpyKind kind, + hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffsetDst Destination starting X offset + * @param[in] hOffsetDst Destination starting Y offset + * @param[in] src Source memory address + * @param[in] wOffsetSrc Source starting X offset + * @param[in] hOffsetSrc Source starting Y offset (columns in bytes) + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpyToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DArrayToArray(hipArray_t dst, size_t wOffsetDst, size_t hOffsetDst, + hipArray_const_t src, size_t wOffsetSrc, size_t hOffsetSrc, + size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] wOffset Destination starting X offset + * @param[in] hOffset Destination starting Y offset + * @param[in] src Source memory address + * @param[in] count size in bytes to copy + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + * @warning This API is deprecated. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipMemcpyToArray(hipArray_t dst, size_t wOffset, size_t hOffset, const void* src, + size_t count, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] srcArray Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] count Size in bytes to copy + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + * @warning This API is deprecated. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipMemcpyFromArray(void* dst, hipArray_const_t srcArray, size_t wOffset, size_t hOffset, + size_t count, hipMemcpyKind kind); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DFromArray( void* dst, size_t dpitch, hipArray_const_t src, size_t wOffset, size_t hOffset, size_t width, size_t height, hipMemcpyKind kind); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] dst Destination memory address + * @param[in] dpitch Pitch of destination memory + * @param[in] src Source memory address + * @param[in] wOffset Source starting X offset + * @param[in] hOffset Source starting Y offset + * @param[in] width Width of matrix transfer (columns in bytes) + * @param[in] height Height of matrix transfer (rows) + * @param[in] kind Type of transfer + * @param[in] stream Accelerator view which the copy is being enqueued + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy2DFromArrayAsync( void* dst, size_t dpitch, hipArray_const_t src, size_t wOffset, size_t hOffset, size_t width, size_t height, hipMemcpyKind kind, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] dst Destination memory address + * @param[in] srcArray Source array + * @param[in] srcOffset Offset in bytes of source array + * @param[in] count Size of memory copy in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpyAtoH(void* dst, hipArray_t srcArray, size_t srcOffset, size_t count); +/** + * @brief Copies data between host and device. + * + * @param[in] dstArray Destination memory address + * @param[in] dstOffset Offset in bytes of destination array + * @param[in] srcHost Source host pointer + * @param[in] count Size of memory copy in bytes + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpyHtoA(hipArray_t dstArray, size_t dstOffset, const void* srcHost, size_t count); +/** + * @brief Copies data between host and device. + * + * @param[in] p 3D memory copy parameters + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy3D(const struct hipMemcpy3DParms* p); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] p 3D memory copy parameters + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipMemcpy3DAsync(const struct hipMemcpy3DParms* p, hipStream_t stream __dparm(0)); +/** + * @brief Copies data between host and device. + * + * @param[in] pCopy 3D memory copy parameters + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipDrvMemcpy3D(const HIP_MEMCPY3D* pCopy); +/** + * @brief Copies data between host and device asynchronously. + * + * @param[in] pCopy 3D memory copy parameters + * @param[in] stream Stream to use + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidPitchValue, + * #hipErrorInvalidDevicePointer, #hipErrorInvalidMemcpyDirection + * + * @see hipMemcpy, hipMemcpy2DToArray, hipMemcpy2D, hipMemcpyFromArray, hipMemcpyToSymbol, + * hipMemcpyAsync + */ +hipError_t hipDrvMemcpy3DAsync(const HIP_MEMCPY3D* pCopy, hipStream_t stream); +// doxygen end Memory +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup PeerToPeer PeerToPeer Device Memory Access + * @{ + * @warning PeerToPeer support is experimental. + * This section describes the PeerToPeer device memory access functions of HIP runtime API. + */ +/** + * @brief Determine if a device can access a peer's memory. + * + * @param [out] canAccessPeer Returns the peer access capability (0 or 1) + * @param [in] deviceId - device from where memory may be accessed. + * @param [in] peerDeviceId - device where memory is physically located + * + * Returns "1" in @p canAccessPeer if the specified @p device is capable + * of directly accessing memory physically located on peerDevice , or "0" if not. + * + * Returns "0" in @p canAccessPeer if deviceId == peerDeviceId, and both are valid devices : a + * device is not a peer of itself. + * + * @returns #hipSuccess, + * @returns #hipErrorInvalidDevice if deviceId or peerDeviceId are not valid devices + */ +hipError_t hipDeviceCanAccessPeer(int* canAccessPeer, int deviceId, int peerDeviceId); +/** + * @brief Enable direct access from current device's virtual address space to memory allocations + * physically located on a peer device. + * + * Memory which already allocated on peer device will be mapped into the address space of the + * current device. In addition, all future memory allocations on peerDeviceId will be mapped into + * the address space of the current device when the memory is allocated. The peer memory remains + * accessible from the current device until a call to hipDeviceDisablePeerAccess or hipDeviceReset. + * + * + * @param [in] peerDeviceId Peer device to enable direct access to from the current device + * @param [in] flags Reserved for future use, must be zero + * + * Returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, + * @returns #hipErrorPeerAccessAlreadyEnabled if peer access is already enabled for this device. + */ +hipError_t hipDeviceEnablePeerAccess(int peerDeviceId, unsigned int flags); +/** + * @brief Disable direct access from current device's virtual address space to memory allocations + * physically located on a peer device. + * + * Returns hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been + * enabled from the current device. + * + * @param [in] peerDeviceId Peer device to disable direct access to + * + * @returns #hipSuccess, #hipErrorPeerAccessNotEnabled + */ +hipError_t hipDeviceDisablePeerAccess(int peerDeviceId); +/** + * @brief Get information on memory allocations. + * + * @param [out] pbase - BAse pointer address + * @param [out] psize - Size of allocation + * @param [in] dptr- Device Pointer + * + * @returns #hipSuccess, #hipErrorNotFound + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + */ +hipError_t hipMemGetAddressRange(hipDeviceptr_t* pbase, size_t* psize, hipDeviceptr_t dptr); +#ifndef USE_PEER_NON_UNIFIED +#define USE_PEER_NON_UNIFIED 1 +#endif +#if USE_PEER_NON_UNIFIED == 1 +/** + * @brief Copies memory from one device to memory on another device. + * + * @param [out] dst - Destination device pointer. + * @param [in] dstDeviceId - Destination device + * @param [in] src - Source device pointer + * @param [in] srcDeviceId - Source device + * @param [in] sizeBytes - Size of memory copy in bytes + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice + */ +hipError_t hipMemcpyPeer(void* dst, int dstDeviceId, const void* src, int srcDeviceId, + size_t sizeBytes); +/** + * @brief Copies memory from one device to memory on another device. + * + * @param [out] dst - Destination device pointer. + * @param [in] dstDeviceId - Destination device + * @param [in] src - Source device pointer + * @param [in] srcDevice - Source device + * @param [in] sizeBytes - Size of memory copy in bytes + * @param [in] stream - Stream identifier + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDevice + */ +hipError_t hipMemcpyPeerAsync(void* dst, int dstDeviceId, const void* src, int srcDevice, + size_t sizeBytes, hipStream_t stream __dparm(0)); +#endif +// doxygen end PeerToPeer +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Context Context Management [Deprecated] + * @{ + * This section describes the context management functions of HIP runtime API. + * + * @warning + * + * On the AMD platform, context management APIs are deprecated as there are better alternate + * interfaces, such as using hipSetDevice and stream APIs to achieve the required functionality. + * + * On the NVIDIA platform, CUDA supports the driver API that defines "Context" and "Devices" as + * separate entities. Each context contains a single device, which can theoretically have multiple + * contexts. HIP initially added limited support for these APIs to facilitate easy porting from + * existing driver codes. + * + * These APIs are only for equivalent driver APIs on the NVIDIA platform. + * + */ + +/** + * @brief Create a context and set it as current/default context + * + * @param [out] ctx Context to create + * @param [in] flags Context creation flags + * @param [in] device device handle + * + * @return #hipSuccess + * + * @see hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxPushCurrent, + * hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxCreate(hipCtx_t* ctx, unsigned int flags, hipDevice_t device); +/** + * @brief Destroy a HIP context. + * + * @param [in] ctx Context to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @see hipCtxCreate, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent,hipCtxSetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxDestroy(hipCtx_t ctx); +/** + * @brief Pop the current/default context and return the popped context. + * + * @param [out] ctx The current context to pop + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxSetCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxPopCurrent(hipCtx_t* ctx); +/** + * @brief Push the context to be set as current/ default context + * + * @param [in] ctx The current context to push + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxPushCurrent(hipCtx_t ctx); +/** + * @brief Set the passed context as current/default + * + * @param [in] ctx The context to set as current + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize , hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetCurrent(hipCtx_t ctx); +/** + * @brief Get the handle of the current/ default context + * + * @param [out] ctx The context to get as current + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetCurrent(hipCtx_t* ctx); +/** + * @brief Get the handle of the device associated with current/default context + * + * @param [out] device The device from the current context + * + * @returns #hipSuccess, #hipErrorInvalidContext + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetDevice(hipDevice_t* device); +/** + * @brief Returns the approximate HIP api version. + * + * @param [in] ctx Context to check + * @param [out] apiVersion API version to get + * + * @return #hipSuccess + * + * @warning The HIP feature set does not correspond to an exact CUDA SDK api revision. + * This function always set *apiVersion to 4 as an approximation though HIP supports + * some features which were introduced in later CUDA SDK revisions. + * HIP apps code should not rely on the api revision number here and should + * use arch feature flags to test device capabilities or conditional compilation. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetDevice, hipCtxGetFlags, hipCtxPopCurrent, + * hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetApiVersion(hipCtx_t ctx, int* apiVersion); +/** + * @brief Get Cache configuration for a specific function + * + * @param [out] cacheConfig Cache configuration + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetCacheConfig(hipFuncCache_t* cacheConfig); +/** + * @brief Set L1/Shared cache partition. + * + * @param [in] cacheConfig Cache configuration to set + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support reconfigurable cache. This hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetCacheConfig(hipFuncCache_t cacheConfig); +/** + * @brief Set Shared memory bank configuration. + * + * @param [in] config Shared memory configuration to set + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSetSharedMemConfig(hipSharedMemConfig config); +/** + * @brief Get Shared memory bank configuration. + * + * @param [out] pConfig Pointer of shared memory configuration + * + * @return #hipSuccess + * + * @warning AMD devices and some Nvidia GPUS do not support shared cache banking, and the hint is + * ignored on those architectures. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetSharedMemConfig(hipSharedMemConfig* pConfig); +/** + * @brief Blocks until the default context has completed all preceding requested tasks. + * + * @return #hipSuccess + * + * @warning This function waits for all streams on the default context to complete execution, and + * then returns. + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxSynchronize(void); +/** + * @brief Return flags used for creating default context. + * + * @param [out] flags Pointer of flags + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxPopCurrent, hipCtxGetCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxGetFlags(unsigned int* flags); +/** + * @brief Enables direct access to memory allocations in a peer context. + * + * Memory which already allocated on peer device will be mapped into the address space of the + * current device. In addition, all future memory allocations on peerDeviceId will be mapped into + * the address space of the current device when the memory is allocated. The peer memory remains + * accessible from the current device until a call to hipDeviceDisablePeerAccess or hipDeviceReset. + * + * + * @param [in] peerCtx Peer context + * @param [in] flags flags, need to set as 0 + * + * @returns #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue, + * #hipErrorPeerAccessAlreadyEnabled + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning PeerToPeer support is experimental. + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxEnablePeerAccess(hipCtx_t peerCtx, unsigned int flags); +/** + * @brief Disable direct access from current context's virtual address space to memory allocations + * physically located on a peer context.Disables direct access to memory allocations in a peer + * context and unregisters any registered allocations. + * + * Returns #hipErrorPeerAccessNotEnabled if direct access to memory on peerDevice has not yet been + * enabled from the current device. + * + * @param [in] peerCtx Peer context to be disabled + * + * @returns #hipSuccess, #hipErrorPeerAccessNotEnabled + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning PeerToPeer support is experimental. + * + * @warning This API is deprecated on the AMD platform, only for equivalent cuCtx driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipCtxDisablePeerAccess(hipCtx_t peerCtx); + +/** + * @brief Get the state of the primary context. + * + * @param [in] dev Device to get primary context flags for + * @param [out] flags Pointer to store flags + * @param [out] active Pointer to store context state; 0 = inactive, 1 = active + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the + * NVIDIA platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxGetState(hipDevice_t dev, unsigned int* flags, int* active); +/** + * @brief Release the primary context on the GPU. + * + * @param [in] dev Device which primary context is released + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * @warning This function return #hipSuccess though doesn't release the primaryCtx by design on + * HIP/HCC path. + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxRelease(hipDevice_t dev); +/** + * @brief Retain the primary context on the GPU. + * + * @param [out] pctx Returned context handle of the new context + * @param [in] dev Device which primary context is released + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxRetain(hipCtx_t* pctx, hipDevice_t dev); +/** + * @brief Resets the primary context on the GPU. + * + * @param [in] dev Device which primary context is reset + * + * @returns #hipSuccess + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxReset(hipDevice_t dev); +/** + * @brief Set flags for the primary context. + * + * @param [in] dev Device for which the primary context flags are set + * @param [in] flags New flags for the device + * + * @returns #hipSuccess, #hipErrorContextAlreadyInUse + * + * @see hipCtxCreate, hipCtxDestroy, hipCtxGetFlags, hipCtxPopCurrent, hipCtxGetCurrent, + * hipCtxSetCurrent, hipCtxPushCurrent, hipCtxSetCacheConfig, hipCtxSynchronize, hipCtxGetDevice + * + * @warning This API is deprecated on the AMD platform, only for equivalent driver API on the NVIDIA + * platform. + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipDevicePrimaryCtxSetFlags(hipDevice_t dev, unsigned int flags); +// doxygen end Context Management +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * + * @defgroup Module Module Management + * @{ + * @ingroup API + * This section describes the module management functions of HIP runtime API. + * + */ +/** + * @brief Loads code object from file into a module the currrent context. + * + * @param [in] fname Filename of code object to load + + * @param [out] module Module + * + * @warning File/memory resources allocated in this function are released only in hipModuleUnload. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorFileNotFound, + * #hipErrorOutOfMemory, #hipErrorSharedObjectInitFailed, #hipErrorNotInitialized + * + */ +hipError_t hipModuleLoad(hipModule_t* module, const char* fname); +/** + * @brief Frees the module + * + * @param [in] module Module to free + * + * @returns #hipSuccess, #hipErrorInvalidResourceHandle + * + * The module is freed, and the code objects associated with it are destroyed. + */ +hipError_t hipModuleUnload(hipModule_t module); +/** + * @brief Function with kname will be extracted if present in module + * + * @param [in] module Module to get function from + * @param [in] kname Pointer to the name of function + * @param [out] function Pointer to function handle + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidContext, #hipErrorNotInitialized, + * #hipErrorNotFound, + */ +hipError_t hipModuleGetFunction(hipFunction_t* function, hipModule_t module, const char* kname); +/** + * @brief Find out attributes for a given function. + * + * @param [out] attr Attributes of funtion + * @param [in] func Pointer to the function handle + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + */ +hipError_t hipFuncGetAttributes(struct hipFuncAttributes* attr, const void* func); +/** + * @brief Find out a specific attribute for a given function. + * + * @param [out] value Pointer to the value + * @param [in] attrib Attributes of the given funtion + * @param [in] hfunc Function to get attributes from + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + */ +hipError_t hipFuncGetAttribute(int* value, hipFunction_attribute attrib, hipFunction_t hfunc); +/** + * @brief Gets pointer to device entry function that matches entry function symbolPtr. + * + * @param [out] functionPtr Device entry function + * @param [in] symbolPtr Pointer to device entry function to search for + * + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction + * + */ +hipError_t hipGetFuncBySymbol(hipFunction_t* functionPtr, const void* symbolPtr); +/** + * @brief returns the handle of the texture reference with the name from the module. + * + * @param [in] hmod Module + * @param [in] name Pointer of name of texture reference + * @param [out] texRef Pointer of texture reference + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorNotFound, #hipErrorInvalidValue + */ +hipError_t hipModuleGetTexRef(textureReference** texRef, hipModule_t hmod, const char* name); +/** + * @brief builds module from code object which resides in host memory. Image is pointer to that + * location. + * + * @param [in] image The pointer to the location of data + * @param [out] module Retuned module + * + * @returns hipSuccess, hipErrorNotInitialized, hipErrorOutOfMemory, hipErrorNotInitialized + */ +hipError_t hipModuleLoadData(hipModule_t* module, const void* image); +/** + * @brief builds module from code object which resides in host memory. Image is pointer to that + * location. Options are not used. hipModuleLoadData is called. + * + * @param [in] image The pointer to the location of data + * @param [out] module Retuned module + * @param [in] numOptions Number of options + * @param [in] options Options for JIT + * @param [in] optionValues Option values for JIT + * + * @returns hipSuccess, hipErrorNotInitialized, hipErrorOutOfMemory, hipErrorNotInitialized + */ +hipError_t hipModuleLoadDataEx(hipModule_t* module, const void* image, unsigned int numOptions, + hipJitOption* options, void** optionValues); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelparams or extra + * + * @param [in] f Kernel to launch. + * @param [in] gridDimX X grid dimension specified as multiple of blockDimX. + * @param [in] gridDimY Y grid dimension specified as multiple of blockDimY. + * @param [in] gridDimZ Z grid dimension specified as multiple of blockDimZ. + * @param [in] blockDimX X block dimensions specified in work-items + * @param [in] blockDimY Y grid dimension specified in work-items + * @param [in] blockDimZ Z grid dimension specified in work-items + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * @param [in] kernelParams Kernel parameters to launch + * @param [in] extra Pointer to kernel arguments. These are passed directly to the kernel and + * must be in the memory layout and alignment expected by the kernel. + * All passed arguments must be naturally aligned according to their type. The memory address of each + * argument should be a multiple of its size in bytes. Please refer to hip_porting_driver_api.md + * for sample usage. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. So gridDim.x * blockDim.x, gridDim.y * blockDim.y + * and gridDim.z * blockDim.z are always less than 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + */ +hipError_t hipModuleLaunchKernel(hipFunction_t f, unsigned int gridDimX, unsigned int gridDimY, + unsigned int gridDimZ, unsigned int blockDimX, + unsigned int blockDimY, unsigned int blockDimZ, + unsigned int sharedMemBytes, hipStream_t stream, + void** kernelParams, void** extra); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelParams, where thread blocks can cooperate and synchronize as they execute + * + * @param [in] f Kernel to launch. + * @param [in] gridDimX X grid dimension specified as multiple of blockDimX. + * @param [in] gridDimY Y grid dimension specified as multiple of blockDimY. + * @param [in] gridDimZ Z grid dimension specified as multiple of blockDimZ. + * @param [in] blockDimX X block dimension specified in work-items. + * @param [in] blockDimY Y block dimension specified in work-items. + * @param [in] blockDimZ Z block dimension specified in work-items. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, + * in which case the default stream is used with associated synchronization rules. + * @param [in] kernelParams A list of kernel arguments. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidHandle, #hipErrorInvalidImage, #hipErrorInvalidValue, + * #hipErrorInvalidConfiguration, #hipErrorLaunchFailure, #hipErrorLaunchOutOfResources, + * #hipErrorLaunchTimeOut, #hipErrorCooperativeLaunchTooLarge, #hipErrorSharedObjectInitFailed + */ +hipError_t hipModuleLaunchCooperativeKernel(hipFunction_t f, unsigned int gridDimX, + unsigned int gridDimY, unsigned int gridDimZ, + unsigned int blockDimX, unsigned int blockDimY, + unsigned int blockDimZ, unsigned int sharedMemBytes, + hipStream_t stream, void** kernelParams); +/** + * @brief Launches kernels on multiple devices where thread blocks can cooperate and + * synchronize as they execute. + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorDeinitialized, #hipErrorNotInitialized, #hipErrorInvalidContext, + * #hipErrorInvalidHandle, #hipErrorInvalidImage, #hipErrorInvalidValue, + * #hipErrorInvalidConfiguration, #hipErrorInvalidResourceHandle, #hipErrorLaunchFailure, + * #hipErrorLaunchOutOfResources, #hipErrorLaunchTimeOut, #hipErrorCooperativeLaunchTooLarge, + * #hipErrorSharedObjectInitFailed + */ +hipError_t hipModuleLaunchCooperativeKernelMultiDevice(hipFunctionLaunchParams* launchParamsList, + unsigned int numDevices, + unsigned int flags); +/** + * @brief launches kernel f with launch parameters and shared memory on stream with arguments passed + * to kernelparams or extra, where thread blocks can cooperate and synchronize as they execute + * + * @param [in] f Kernel to launch. + * @param [in] gridDim Grid dimensions specified as multiple of blockDim. + * @param [in] blockDimX Block dimensions specified in work-items + * @param [in] kernelParams A list of kernel arguments + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, #hipErrorCooperativeLaunchTooLarge + */ +hipError_t hipLaunchCooperativeKernel(const void* f, dim3 gridDim, dim3 blockDimX, + void** kernelParams, unsigned int sharedMemBytes, + hipStream_t stream); +/** + * @brief Launches kernels on multiple devices where thread blocks can cooperate and + * synchronize as they execute. + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue, + * #hipErrorCooperativeLaunchTooLarge + */ +hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +/** + * @brief Launches kernels on multiple devices and guarantees all specified kernels are dispatched + * on respective streams before enqueuing any other work on the specified streams from any other threads + * + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + */ +hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, + int numDevices, unsigned int flags); +// doxygen end Module +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Occupancy Occupancy + * @{ + * This section describes the occupancy functions of HIP runtime API. + * + */ +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +//TODO - Match CUoccupancyB2DSize +hipError_t hipModuleOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + hipFunction_t f, size_t dynSharedMemPerBlk, + int blockSizeLimit); +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * @param [in] flags Extra flags for occupancy calculation (only default supported) + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +//TODO - Match CUoccupancyB2DSize +hipError_t hipModuleOccupancyMaxPotentialBlockSizeWithFlags(int* gridSize, int* blockSize, + hipFunction_t f, size_t dynSharedMemPerBlk, + int blockSizeLimit, unsigned int flags); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function (hipFunction) for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipModuleOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function(hipFunction_t) for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @param [in] flags Extra flags for occupancy calculation (only default supported) + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, hipFunction_t f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, const void* f, int blockSize, size_t dynSharedMemPerBlk); +/** + * @brief Returns occupancy for a device function. + * + * @param [out] numBlocks Returned occupancy + * @param [in] f Kernel function for which occupancy is calulated + * @param [in] blockSize Block size the kernel is intended to be launched with + * @param [in] dynSharedMemPerBlk Dynamic shared memory usage (in bytes) intended for each block + * @param [in] flags Extra flags for occupancy calculation (currently ignored) + * @returns #hipSuccess, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, const void* f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags __dparm(hipOccupancyDefault)); +/** + * @brief determine the grid and block sizes to achieves maximum occupancy for a kernel + * + * @param [out] gridSize minimum grid size for maximum potential occupancy + * @param [out] blockSize block size for maximum potential occupancy + * @param [in] f kernel function for which occupancy is calulated + * @param [in] dynSharedMemPerBlk dynamic shared memory usage (in bytes) intended for each block + * @param [in] blockSizeLimit the maximum block size for the kernel, use 0 for no limit + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + const void* f, size_t dynSharedMemPerBlk, + int blockSizeLimit); +// doxygen end Occupancy +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Profiler Profiler Control[Deprecated] + * @{ + * This section describes the profiler control functions of HIP runtime API. + * + * @warning The cudaProfilerInitialize API format for "configFile" is not supported. + * + */ +// TODO - expand descriptions: +/** + * @brief Start recording of profiling information + * When using this API, start the profiler with profiling disabled. (--startdisabled) + * @returns #hipErrorNotSupported + * @warning : hipProfilerStart API is deprecated, use roctracer/rocTX instead. + */ +DEPRECATED("use roctracer/rocTX instead") +hipError_t hipProfilerStart(); +/** + * @brief Stop recording of profiling information. + * When using this API, start the profiler with profiling disabled. (--startdisabled) + * @returns #hipErrorNotSupported + * @warning hipProfilerStart API is deprecated, use roctracer/rocTX instead. + */ +DEPRECATED("use roctracer/rocTX instead") +hipError_t hipProfilerStop(); +// doxygen end profiler +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Clang Launch API to support the triple-chevron syntax + * @{ + * This section describes the API to support the triple-chevron syntax. + */ +/** + * @brief Configure a kernel launch. + * + * @param [in] gridDim grid dimension specified as multiple of blockDim. + * @param [in] blockDim block dimensions specified in work-items + * @param [in] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t hipConfigureCall(dim3 gridDim, dim3 blockDim, size_t sharedMem __dparm(0), hipStream_t stream __dparm(0)); +/** + * @brief Set a kernel argument. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + * @param [in] arg Pointer the argument in host memory. + * @param [in] size Size of the argument. + * @param [in] offset Offset of the argument on the argument stack. + * + */ +hipError_t hipSetupArgument(const void* arg, size_t size, size_t offset); +/** + * @brief Launch a kernel. + * + * @param [in] func Kernel to launch. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t hipLaunchByPtr(const void* func); +/** + * @brief Push configuration of a kernel launch. + * + * @param [in] gridDim grid dimension specified as multiple of blockDim. + * @param [in] blockDim block dimensions specified in work-items + * @param [in] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t __hipPushCallConfiguration(dim3 gridDim, + dim3 blockDim, + size_t sharedMem __dparm(0), + hipStream_t stream __dparm(0)); +/** + * @brief Pop configuration of a kernel launch. + * + * @param [out] gridDim grid dimension specified as multiple of blockDim. + * @param [out] blockDim block dimensions specified in work-items + * @param [out] sharedMem Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [out] stream Stream where the kernel should be dispatched. May be 0, in which case the + * default stream is used with associated synchronization rules. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * Please note, HIP does not support kernel launch with total work items defined in dimension with + * size gridDim x blockDim >= 2^32. + * + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue + * + */ +hipError_t __hipPopCallConfiguration(dim3 *gridDim, + dim3 *blockDim, + size_t *sharedMem, + hipStream_t *stream); +/** + * @brief C compliant kernel launch API + * + * @param [in] function_address - kernel stub function pointer. + * @param [in] numBlocks - number of blocks + * @param [in] dimBlocks - dimension of a block + * @param [in] args - kernel arguments + * @param [in] sharedMemBytes - Amount of dynamic shared memory to allocate for this kernel. The + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream - Stream where the kernel should be dispatched. May be 0, in which case th + * default stream is used with associated synchronization rules. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipLaunchKernel(const void* function_address, + dim3 numBlocks, + dim3 dimBlocks, + void** args, + size_t sharedMemBytes __dparm(0), + hipStream_t stream __dparm(0)); + +/** + * @brief Enqueues a host function call in a stream. + * + * @param [in] stream - The stream to enqueue work in. + * @param [in] fn - The function to call once enqueued preceeding operations are complete. + * @param [in] userData - User-specified data to be passed to the function. + * + * @returns #hipSuccess, #hipErrorInvalidResourceHandle, #hipErrorInvalidValue, + * #hipErrorNotSupported + * + * The host function to call in this API will be executed after the preceding operations in + * the stream are complete. The function is a blocking operation that blocks operations in the + * stream that follow it, until the function is returned. + * Event synchronization and internal callback functions make sure enqueued operations will + * execute in order, in the stream. + * + * The host function must not make any HIP API calls. The host function is non-reentrant. It must + * not perform sychronization with any operation that may depend on other processing execution + * but is not enqueued to run earlier in the stream. + * + * Host functions that are enqueued respectively in different non-blocking streams can run concurrently. + * + * @warning This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipLaunchHostFunc(hipStream_t stream, hipHostFn_t fn, void* userData); + +/** + * Copies memory for 2D arrays. + * + * @param pCopy - Parameters for the memory copy + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipDrvMemcpy2DUnaligned(const hip_Memcpy2D* pCopy); +//TODO: Move this to hip_ext.h +/** + * @brief Launches kernel from the pointer address, with arguments and shared memory on stream. + * + * @param [in] function_address pointer to the Kernel to launch. + * @param [in] numBlocks number of blocks. + * @param [in] dimBlocks dimension of a block. + * @param [in] args pointer to kernel arguments. + * @param [in] sharedMemBytes Amount of dynamic shared memory to allocate for this kernel. + * HIP-Clang compiler provides support for extern shared declarations. + * @param [in] stream Stream where the kernel should be dispatched. + * May be 0, in which case the default stream is used with associated synchronization rules. + * @param [in] startEvent If non-null, specified event will be updated to track the start time of + * the kernel launch. The event must be created before calling this API. + * @param [in] stopEvent If non-null, specified event will be updated to track the stop time of + * the kernel launch. The event must be created before calling this API. + * @param [in] flags The value of hipExtAnyOrderLaunch, signifies if kernel can be + * launched in any order. + * @returns #hipSuccess, #hipErrorNotInitialized, #hipErrorInvalidValue. + * + */ +hipError_t hipExtLaunchKernel(const void* function_address, dim3 numBlocks, dim3 dimBlocks, + void** args, size_t sharedMemBytes, hipStream_t stream, + hipEvent_t startEvent, hipEvent_t stopEvent, int flags); +// doxygen end Clang launch +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Texture Texture Management + * @{ + * This section describes the texture management functions of HIP runtime API. + */ + +/** + * @brief Creates a texture object. + * + * @param [out] pTexObject pointer to the texture object to create + * @param [in] pResDesc pointer to resource descriptor + * @param [in] pTexDesc pointer to texture descriptor + * @param [in] pResViewDesc pointer to resource view descriptor + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported, #hipErrorOutOfMemory + * + * @note 3D liner filter isn't supported on GFX90A boards, on which the API @p hipCreateTextureObject will + * return hipErrorNotSupported. + * + */ +hipError_t hipCreateTextureObject( + hipTextureObject_t* pTexObject, + const hipResourceDesc* pResDesc, + const hipTextureDesc* pTexDesc, + const struct hipResourceViewDesc* pResViewDesc); + +/** + * @brief Destroys a texture object. + * + * @param [in] textureObject texture object to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipDestroyTextureObject(hipTextureObject_t textureObject); + +/** + * @brief Gets the channel descriptor in an array. + * + * @param [in] desc pointer to channel format descriptor + * @param [out] array memory array on the device + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetChannelDesc( + hipChannelFormatDesc* desc, + hipArray_const_t array); + +/** + * @brief Gets resource descriptor for the texture object. + * + * @param [out] pResDesc pointer to resource descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectResourceDesc( + hipResourceDesc* pResDesc, + hipTextureObject_t textureObject); + +/** + * @brief Gets resource view descriptor for the texture object. + * + * @param [out] pResViewDesc pointer to resource view descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectResourceViewDesc( + struct hipResourceViewDesc* pResViewDesc, + hipTextureObject_t textureObject); + +/** + * @brief Gets texture descriptor for the texture object. + * + * @param [out] pTexDesc pointer to texture descriptor + * @param [in] textureObject texture object + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGetTextureObjectTextureDesc( + hipTextureDesc* pTexDesc, + hipTextureObject_t textureObject); + +/** + * @brief Creates a texture object. + * + * @param [out] pTexObject pointer to texture object to create + * @param [in] pResDesc pointer to resource descriptor + * @param [in] pTexDesc pointer to texture descriptor + * @param [in] pResViewDesc pointer to resource view descriptor + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectCreate( + hipTextureObject_t* pTexObject, + const HIP_RESOURCE_DESC* pResDesc, + const HIP_TEXTURE_DESC* pTexDesc, + const HIP_RESOURCE_VIEW_DESC* pResViewDesc); + +/** + * @brief Destroys a texture object. + * + * @param [in] texObject texture object to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectDestroy( + hipTextureObject_t texObject); + +/** + * @brief Gets resource descriptor of a texture object. + * + * @param [out] pResDesc pointer to resource descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetResourceDesc( + HIP_RESOURCE_DESC* pResDesc, + hipTextureObject_t texObject); + +/** + * @brief Gets resource view descriptor of a texture object. + * + * @param [out] pResViewDesc pointer to resource view descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetResourceViewDesc( + HIP_RESOURCE_VIEW_DESC* pResViewDesc, + hipTextureObject_t texObject); + +/** + * @brief Gets texture descriptor of a texture object. + * + * @param [out] pTexDesc pointer to texture descriptor + * @param [in] texObject texture object + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + */ +hipError_t hipTexObjectGetTextureDesc( + HIP_TEXTURE_DESC* pTexDesc, + hipTextureObject_t texObject); + +/** + * @brief Allocate a mipmapped array on the device. + * + * @param[out] mipmappedArray - Pointer to allocated mipmapped array in device memory + * @param[in] desc - Requested channel format + * @param[in] extent - Requested allocation size (width field in elements) + * @param[in] numLevels - Number of mipmap levels to allocate + * @param[in] flags - Flags for extensions + * + * @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMallocMipmappedArray( + hipMipmappedArray_t *mipmappedArray, + const struct hipChannelFormatDesc* desc, + struct hipExtent extent, + unsigned int numLevels, + unsigned int flags __dparm(0)); + +/** + * @brief Frees a mipmapped array on the device. + * + * @param[in] mipmappedArray - Pointer to mipmapped array to free + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipFreeMipmappedArray(hipMipmappedArray_t mipmappedArray); + +/** + * @brief Gets a mipmap level of a HIP mipmapped array. + * + * @param[out] levelArray - Returned mipmap level HIP array + * @param[in] mipmappedArray - HIP mipmapped array + * @param[in] level - Mipmap level + * + * @return #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipGetMipmappedArrayLevel( + hipArray_t *levelArray, + hipMipmappedArray_const_t mipmappedArray, + unsigned int level); + +/** + * @brief Create a mipmapped array. + * + * @param [out] pHandle pointer to mipmapped array + * @param [in] pMipmappedArrayDesc mipmapped array descriptor + * @param [in] numMipmapLevels mipmap level + * + * @returns #hipSuccess, #hipErrorNotSupported, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + */ +hipError_t hipMipmappedArrayCreate( + hipMipmappedArray_t* pHandle, + HIP_ARRAY3D_DESCRIPTOR* pMipmappedArrayDesc, + unsigned int numMipmapLevels); + +/** + * @brief Destroy a mipmapped array. + * + * @param [out] hMipmappedArray pointer to mipmapped array to destroy + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMipmappedArrayDestroy(hipMipmappedArray_t hMipmappedArray); + +/** + * @brief Get a mipmapped array on a mipmapped level. + * + * @param [in] pLevelArray Pointer of array + * @param [out] hMipMappedArray Pointer of mipmapped array on the requested mipmap level + * @param [out] level Mipmap level + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note This API is implemented on Windows, under development on Linux. + * + */ +hipError_t hipMipmappedArrayGetLevel( + hipArray_t* pLevelArray, + hipMipmappedArray_t hMipMappedArray, + unsigned int level); + +/** + * + * @addtogroup TextureD Texture Management [Deprecated] + * @{ + * @ingroup Texture + * This section describes the deprecated texture management functions of HIP runtime API. + */ + +/** + * @brief Binds a mipmapped array to a texture. + * + * @param [in] tex pointer to the texture reference to bind + * @param [in] mipmappedArray memory mipmapped array on the device + * @param [in] desc opointer to the channel format + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTextureToMipmappedArray( + const textureReference* tex, + hipMipmappedArray_const_t mipmappedArray, + const hipChannelFormatDesc* desc); + +/** + * @brief Gets the texture reference related with the symbol. + * + * @param [out] texref texture reference + * @param [in] symbol pointer to the symbol related with the texture for the reference + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipGetTextureReference( + const textureReference** texref, + const void* symbol); + +/** + * @brief Gets the border color used by a texture reference. + * + * @param [out] pBorderColor Returned Type and Value of RGBA color. + * @param [in] texRef Texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetBorderColor(float* pBorderColor, const textureReference* texRef); + +/** + * @brief Gets the array bound to a texture reference. + + * + * @param [in] pArray Returned array. + * @param [in] texRef texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetArray(hipArray_t* pArray, const textureReference* texRef); + +/** + * @brief Sets address mode for a texture reference. + * + * @param [in] texRef texture reference. + * @param [in] dim Dimension of the texture. + * @param [in] am Value of the texture address mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddressMode( + textureReference* texRef, + int dim, + enum hipTextureAddressMode am); +/** + * @brief Binds an array as a texture reference. + * + * @param [in] tex Pointer texture reference. + * @param [in] array Array to bind. + * @param [in] flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetArray( + textureReference* tex, + hipArray_const_t array, + unsigned int flags); +/** + * @brief Set filter mode for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fm Value of texture filter mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFilterMode( + textureReference* texRef, + enum hipTextureFilterMode fm); +/** + * @brief Set flags for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] Flags Value of flags. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFlags( + textureReference* texRef, + unsigned int Flags); +/** + * @brief Set format for a texture reference. + * + * @param [in] texRef Pointer texture reference. + * @param [in] fmt Value of format. + * @param [in] NumPackedComponents Number of components per array. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetFormat( + textureReference* texRef, + hipArray_Format fmt, + int NumPackedComponents); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] size Size of memory in bites. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTexture( + size_t* offset, + const textureReference* tex, + const void* devPtr, + const hipChannelFormatDesc* desc, + size_t size __dparm(UINT_MAX)); +/** + * @brief Binds a 2D memory area to a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Pointer of channel format descriptor. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTexture2D( + size_t* offset, + const textureReference* tex, + const void* devPtr, + const hipChannelFormatDesc* desc, + size_t width, + size_t height, + size_t pitch); +/** + * @brief Binds a memory area to a texture. + * + * @param [in] tex Pointer of texture reference. + * @param [in] array Array to bind. + * @param [in] desc Pointer of channel format descriptor. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipBindTextureToArray( + const textureReference* tex, + hipArray_const_t array, + const hipChannelFormatDesc* desc); +/** + * @brief Get the offset of the alignment in a texture. + * + * @param [in] offset Offset in bytes. + * @param [in] texref Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipGetTextureAlignmentOffset( + size_t* offset, + const textureReference* texref); +/** + * @brief Unbinds a texture. + * + * @param [in] tex Texture to unbind. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipUnbindTexture(const textureReference* tex); +/** + * @brief Gets the address for a texture reference. + * + * @param [out] dev_ptr Pointer of device address. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetAddress( + hipDeviceptr_t* dev_ptr, + const textureReference* texRef); +/** + * @brief Gets the address mode for a texture reference. + * + * @param [out] pam Pointer of address mode. + * @param [in] texRef Pointer of texture reference. + * @param [in] dim Dimension. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetAddressMode( + enum hipTextureAddressMode* pam, + const textureReference* texRef, + int dim); +/** + * @brief Gets filter mode for a texture reference. + * + * @param [out] pfm Pointer of filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFilterMode( + enum hipTextureFilterMode* pfm, + const textureReference* texRef); +/** + * @brief Gets flags for a texture reference. + * + * @param [out] pFlags Pointer of flags. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFlags( + unsigned int* pFlags, + const textureReference* texRef); +/** + * @brief Gets texture format for a texture reference. + * + * @param [out] pFormat Pointer of the format. + * @param [out] pNumChannels Pointer of number of channels. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetFormat( + hipArray_Format* pFormat, + int* pNumChannels, + const textureReference* texRef); +/** + * @brief Gets the maximum anisotropy for a texture reference. + * + * @param [out] pmaxAnsio Pointer of the maximum anisotropy. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMaxAnisotropy( + int* pmaxAnsio, + const textureReference* texRef); +/** + * @brief Gets the mipmap filter mode for a texture reference. + * + * @param [out] pfm Pointer of the mipmap filter mode. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapFilterMode( + enum hipTextureFilterMode* pfm, + const textureReference* texRef); +/** + * @brief Gets the mipmap level bias for a texture reference. + * + * @param [out] pbias Pointer of the mipmap level bias. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapLevelBias( + float* pbias, + const textureReference* texRef); +/** + * @brief Gets the minimum and maximum mipmap level clamps for a texture reference. + * + * @param [out] pminMipmapLevelClamp Pointer of the minimum mipmap level clamp. + * @param [out] pmaxMipmapLevelClamp Pointer of the maximum mipmap level clamp. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipmapLevelClamp( + float* pminMipmapLevelClamp, + float* pmaxMipmapLevelClamp, + const textureReference* texRef); +/** + * @brief Gets the mipmapped array bound to a texture reference. + * + * @param [out] pArray Pointer of the mipmapped array. + * @param [in] texRef Pointer of texture reference. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefGetMipMappedArray( + hipMipmappedArray_t* pArray, + const textureReference* texRef); +/** + * @brief Sets an bound address for a texture reference. + * + * @param [out] ByteOffset Pointer of the offset in bytes. + * @param [in] texRef Pointer of texture reference. + * @param [in] dptr Pointer of device address to bind. + * @param [in] bytes Size in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddress( + size_t* ByteOffset, + textureReference* texRef, + hipDeviceptr_t dptr, + size_t bytes); +/** + * @brief Set a bind an address as a 2D texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] desc Pointer of array descriptor. + * @param [in] dptr Pointer of device address to bind. + * @param [in] Pitch Pitch in bytes. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetAddress2D( + textureReference* texRef, + const HIP_ARRAY_DESCRIPTOR* desc, + hipDeviceptr_t dptr, + size_t Pitch); +/** + * @brief Sets the maximum anisotropy for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [out] maxAniso Value of the maximum anisotropy. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMaxAnisotropy( + textureReference* texRef, + unsigned int maxAniso); +/** + * @brief Sets border color for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] pBorderColor Pointer of border color. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetBorderColor( + textureReference* texRef, + float* pBorderColor); +/** + * @brief Sets mipmap filter mode for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] fm Value of filter mode. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapFilterMode( + textureReference* texRef, + enum hipTextureFilterMode fm); +/** + * @brief Sets mipmap level bias for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] bias Value of mipmap bias. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapLevelBias( + textureReference* texRef, + float bias); +/** + * @brief Sets mipmap level clamp for a texture reference. + * + * @param [in] texRef Pointer of texture reference. + * @param [in] minMipMapLevelClamp Value of minimum mipmap level clamp. + * @param [in] maxMipMapLevelClamp Value of maximum mipmap level clamp. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmapLevelClamp( + textureReference* texRef, + float minMipMapLevelClamp, + float maxMipMapLevelClamp); +/** + * @brief Binds mipmapped array to a texture reference. + * + * @param [in] texRef Pointer of texture reference to bind. + * @param [in] mipmappedArray Pointer of mipmapped array to bind. + * @param [in] Flags Flags should be set as HIP_TRSA_OVERRIDE_FORMAT, as a valid value. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning This API is deprecated. + * + */ +DEPRECATED(DEPRECATED_MSG) +hipError_t hipTexRefSetMipmappedArray( + textureReference* texRef, + struct hipMipmappedArray* mipmappedArray, + unsigned int Flags); + +// doxygen end deprecated texture management +/** + * @} + */ + +// doxygen end Texture management +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Runtime Runtime Compilation + * @{ + * This section describes the runtime compilation functions of HIP runtime API. + * + */ +// This group is for HIPrtc + +// doxygen end Runtime +/** + * @} + */ + +/** + * + * @defgroup Callback Callback Activity APIs + * @{ + * This section describes the callback/Activity of HIP runtime API. + */ +/** + * @brief Returns HIP API name by ID. + * + * @param [in] id ID of HIP API + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipApiName(uint32_t id); +/** + * @brief Returns kernel name reference by function name. + * + * @param [in] f Name of function + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipKernelNameRef(const hipFunction_t f); +/** + * @brief Retrives kernel for a given host pointer, unless stated otherwise. + * + * @param [in] hostFunction Pointer of host function. + * @param [in] stream Stream the kernel is executed on. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +const char* hipKernelNameRefByPtr(const void* hostFunction, hipStream_t stream); +/** + * @brief Returns device ID on the stream. + * + * @param [in] stream Stream of device executed on. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +int hipGetStreamDeviceId(hipStream_t stream); + +// doxygen end Callback +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Graph Graph Management + * @{ + * This section describes the graph management types & functions of HIP runtime API. + */ + +/** + * @brief Begins graph capture on a stream. + * + * @param [in] stream - Stream to initiate capture. + * @param [in] mode - Controls the interaction of this capture sequence with other API calls that + * are not safe. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamBeginCapture(hipStream_t stream, hipStreamCaptureMode mode); + +/** +* @brief Begins graph capture on a stream to an existing graph. +* +* @param [in] stream - Stream to initiate capture. +* @param [in] graph - Graph to capture into. +* @param [in] dependencies - Dependencies of the first node captured in the stream. Can be NULL if +* numDependencies is 0. +* @param [in] dependencyData - Optional array of data associated with each dependency. +* @param [in] numDependencies - Number of dependencies. +* @param [in] mode - Controls the interaction of this capture sequence with other API calls that +are not safe. +* +* @returns #hipSuccess, #hipErrorInvalidValue +* +* @warning : param "const hipGraphEdgeData* dependencyData" is currently not supported and has to +passed as nullptr. This API is marked as beta, meaning, while this is feature complete, it is still +open to changes and may have outstanding issues. +* +*/ +hipError_t hipStreamBeginCaptureToGraph(hipStream_t stream, hipGraph_t graph, + const hipGraphNode_t* dependencies, + const hipGraphEdgeData* dependencyData, + size_t numDependencies, hipStreamCaptureMode mode); + +/** + * @brief Ends capture on a stream, returning the captured graph. + * + * @param [in] stream - Stream to end capture. + * @param [out] pGraph - returns the graph captured. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamEndCapture(hipStream_t stream, hipGraph_t* pGraph); + +/** + * @brief Get capture status of a stream. + * + * @param [in] stream - Stream under capture. + * @param [out] pCaptureStatus - returns current status of the capture. + * @param [out] pId - unique ID of the capture. + * + * @returns #hipSuccess, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamGetCaptureInfo(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus, + unsigned long long* pId); + +/** + * @brief Get stream's capture state + * + * @param [in] stream - Stream under capture. + * @param [out] captureStatus_out - returns current status of the capture. + * @param [out] id_out - unique ID of the capture. + * @param [in] graph_out - returns the graph being captured into. + * @param [out] dependencies_out - returns pointer to an array of nodes. + * @param [out] numDependencies_out - returns size of the array returned in dependencies_out. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamGetCaptureInfo_v2(hipStream_t stream, hipStreamCaptureStatus* captureStatus_out, + unsigned long long* id_out __dparm(0), + hipGraph_t* graph_out __dparm(0), + const hipGraphNode_t** dependencies_out __dparm(0), + size_t* numDependencies_out __dparm(0)); + +/** + * @brief Get stream's capture state + * + * @param [in] stream - Stream under capture. + * @param [out] pCaptureStatus - returns current status of the capture. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorStreamCaptureImplicit + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamIsCapturing(hipStream_t stream, hipStreamCaptureStatus* pCaptureStatus); + +/** + * @brief Update the set of dependencies in a capturing stream + * + * @param [in] stream Stream under capture. + * @param [in] dependencies pointer to an array of nodes to Add/Replace. + * @param [in] numDependencies size of the array in dependencies. + * @param [in] flags Flag how to update dependency set. Should be one of value in enum + * #hipStreamUpdateCaptureDependenciesFlags + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorIllegalState + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipStreamUpdateCaptureDependencies(hipStream_t stream, hipGraphNode_t* dependencies, + size_t numDependencies, + unsigned int flags __dparm(0)); + +/** + * @brief Swaps the stream capture mode of a thread. + * + * @param [in] mode - Pointer to mode value to swap with the current mode + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipThreadExchangeStreamCaptureMode(hipStreamCaptureMode* mode); + +/** + * @brief Creates a graph + * + * @param [out] pGraph - pointer to graph to create. + * @param [in] flags - flags for graph creation, must be 0. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphCreate(hipGraph_t* pGraph, unsigned int flags); + +/** + * @brief Destroys a graph + * + * @param [in] graph - instance of graph to destroy. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphDestroy(hipGraph_t graph); + +/** + * @brief Adds dependency edges to a graph. + * + * @param [in] graph - instance of the graph to add dependencies. + * @param [in] from - pointer to the graph nodes with dependenties to add from. + * @param [in] to - pointer to the graph nodes to add dependenties to. + * @param [in] numDependencies - the number of dependencies to add. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphAddDependencies(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, size_t numDependencies); + +/** + * @brief Removes dependency edges from a graph. + * + * @param [in] graph - instance of the graph to remove dependencies. + * @param [in] from - Array of nodes that provide the dependencies. + * @param [in] to - Array of dependent nodes. + * @param [in] numDependencies - the number of dependencies to remove. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphRemoveDependencies(hipGraph_t graph, const hipGraphNode_t* from, + const hipGraphNode_t* to, size_t numDependencies); + +/** + * @brief Returns a graph's dependency edges. + * + * @param [in] graph - instance of the graph to get the edges from. + * @param [out] from - pointer to the graph nodes to return edge endpoints. + * @param [out] to - pointer to the graph nodes to return edge endpoints. + * @param [out] numEdges - returns number of edges. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * from and to may both be NULL, in which case this function only returns the number of edges in + * numEdges. Otherwise, numEdges entries will be filled in. If numEdges is higher than the actual + * number of edges, the remaining entries in from and to will be set to NULL, and the number of + * edges actually returned will be written to numEdges + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetEdges(hipGraph_t graph, hipGraphNode_t* from, hipGraphNode_t* to, + size_t* numEdges); + +/** + * @brief Returns graph nodes. + * + * @param [in] graph - instance of graph to get the nodes. + * @param [out] nodes - pointer to return the graph nodes. + * @param [out] numNodes - returns number of graph nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * nodes may be NULL, in which case this function will return the number of nodes in numNodes. + * Otherwise, numNodes entries will be filled in. If numNodes is higher than the actual number of + * nodes, the remaining entries in nodes will be set to NULL, and the number of nodes actually + * obtained will be returned in numNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetNodes(hipGraph_t graph, hipGraphNode_t* nodes, size_t* numNodes); + +/** + * @brief Returns graph's root nodes. + * + * @param [in] graph - instance of the graph to get the nodes. + * @param [out] pRootNodes - pointer to return the graph's root nodes. + * @param [out] pNumRootNodes - returns the number of graph's root nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * pRootNodes may be NULL, in which case this function will return the number of root nodes in + * pNumRootNodes. Otherwise, pNumRootNodes entries will be filled in. If pNumRootNodes is higher + * than the actual number of root nodes, the remaining entries in pRootNodes will be set to NULL, + * and the number of nodes actually obtained will be returned in pNumRootNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphGetRootNodes(hipGraph_t graph, hipGraphNode_t* pRootNodes, + size_t* pNumRootNodes); + +/** + * @brief Returns a node's dependencies. + * + * @param [in] node - graph node to get the dependencies from. + * @param [out] pDependencies - pointer to to return the dependencies. + * @param [out] pNumDependencies - returns the number of graph node dependencies. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * pDependencies may be NULL, in which case this function will return the number of dependencies in + * pNumDependencies. Otherwise, pNumDependencies entries will be filled in. If pNumDependencies is + * higher than the actual number of dependencies, the remaining entries in pDependencies will be set + * to NULL, and the number of nodes actually obtained will be returned in pNumDependencies. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetDependencies(hipGraphNode_t node, hipGraphNode_t* pDependencies, + size_t* pNumDependencies); + +/** + * @brief Returns a node's dependent nodes. + * + * @param [in] node - graph node to get the Dependent nodes from. + * @param [out] pDependentNodes - pointer to return the graph dependent nodes. + * @param [out] pNumDependentNodes - returns the number of graph node dependent nodes. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * DependentNodes may be NULL, in which case this function will return the number of dependent nodes + * in pNumDependentNodes. Otherwise, pNumDependentNodes entries will be filled in. If + * pNumDependentNodes is higher than the actual number of dependent nodes, the remaining entries in + * pDependentNodes will be set to NULL, and the number of nodes actually obtained will be returned + * in pNumDependentNodes. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetDependentNodes(hipGraphNode_t node, hipGraphNode_t* pDependentNodes, + size_t* pNumDependentNodes); + +/** + * @brief Returns a node's type. + * + * @param [in] node - instance of the graph to add dependencies. + * @param [out] pType - pointer to the return the type + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeGetType(hipGraphNode_t node, hipGraphNodeType* pType); + +/** + * @brief Remove a node from the graph. + * + * @param [in] node - graph node to remove + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphDestroyNode(hipGraphNode_t node); + +/** + * @brief Clones a graph. + * + * @param [out] pGraphClone - Returns newly created cloned graph. + * @param [in] originalGraph - original graph to clone from. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryAllocation + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphClone(hipGraph_t* pGraphClone, hipGraph_t originalGraph); + +/** + * @brief Finds a cloned version of a node. + * + * @param [out] pNode - Returns the cloned node. + * @param [in] originalNode - original node handle. + * @param [in] clonedGraph - Cloned graph to query. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphNodeFindInClone(hipGraphNode_t* pNode, hipGraphNode_t originalNode, + hipGraph_t clonedGraph); + +/** + * @brief Creates an executable graph from a graph + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [out] pErrorNode - pointer to error node in case error occured in graph instantiation, + * it could modify the correponding node. + * @param [out] pLogBuffer - pointer to log buffer. + * @param [out] bufferSize - the size of log buffer. + * + * @returns #hipSuccess, #hipErrorOutOfMemory + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + */ +hipError_t hipGraphInstantiate(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphNode_t* pErrorNode, char* pLogBuffer, size_t bufferSize); + +/** + * @brief Creates an executable graph from a graph. + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [in] flags - Flags to control instantiation. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues.It does not support + * any of flag and is behaving as hipGraphInstantiate. + */ +hipError_t hipGraphInstantiateWithFlags(hipGraphExec_t* pGraphExec, hipGraph_t graph, + unsigned long long flags); + +/** + * @brief Creates an executable graph from a graph. + * + * @param [out] pGraphExec - pointer to instantiated executable graph that is created. + * @param [in] graph - instance of graph to instantiate. + * @param [in] instantiateParams - Graph Instantiate Params + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphInstantiateWithParams(hipGraphExec_t* pGraphExec, hipGraph_t graph, + hipGraphInstantiateParams *instantiateParams); +/** + * @brief launches an executable graph in a stream + * + * @param [in] graphExec - instance of executable graph to launch. + * @param [in] stream - instance of stream in which to launch executable graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphLaunch(hipGraphExec_t graphExec, hipStream_t stream); + +/** + * @brief uploads an executable graph in a stream + * + * @param [in] graphExec - instance of executable graph to launch. + * @param [in] stream - instance of stream in which to launch executable graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphUpload(hipGraphExec_t graphExec, hipStream_t stream); + +/** + * @brief Creates a kernel execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - pointer to the dependencies on the kernel execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams - pointer to the parameters for the node. + * @returns #hipSuccess, #hipErrorInvalidValue. + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddNode(hipGraphNode_t *pGraphNode, hipGraph_t graph, + const hipGraphNode_t *pDependencies, size_t numDependencies, + hipGraphNodeParams *nodeParams); + +/** + * @brief Destroys an executable graph + * + * @param [in] graphExec - instance of executable graph to destry. + * + * @returns #hipSuccess. + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecDestroy(hipGraphExec_t graphExec); + +// Check whether an executable graph can be updated with a graph and perform the update if possible. +/** + * @brief Check whether an executable graph can be updated with a graph and perform the update if * + * possible. + * + * @param [in] hGraphExec - instance of executable graph to update. + * @param [in] hGraph - graph that contains the updated parameters. + * @param [in] hErrorNode_out - node which caused the permissibility check to forbid the update. + * @param [in] updateResult_out - Whether the graph update was permitted. + * @returns #hipSuccess, #hipErrorGraphExecUpdateFailure + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecUpdate(hipGraphExec_t hGraphExec, hipGraph_t hGraph, + hipGraphNode_t* hErrorNode_out, + hipGraphExecUpdateResult* updateResult_out); + +/** + * @brief Creates a kernel execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - pointer to the dependencies on the kernel execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pNodeParams - pointer to the parameters to the kernel execution node on the GPU. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorInvalidDeviceFunction + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddKernelNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipKernelNodeParams* pNodeParams); + +/** + * @brief Gets kernel node's parameters. + * + * @param [in] node - instance of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeGetParams(hipGraphNode_t node, hipKernelNodeParams* pNodeParams); + +/** + * @brief Sets a kernel node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeSetParams(hipGraphNode_t node, const hipKernelNodeParams* pNodeParams); + +/** + * @brief Sets the parameters for a kernel node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the kernel node parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecKernelNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipKernelNodeParams* pNodeParams); + +/** + * @brief Creates a memcpy node and adds it to a graph. + * + * @param [out] phGraphNode - pointer to graph node to create. + * @param [in] hGraph - instance of graph to add the created node. + * @param [in] dependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] copyParams - const pointer to the parameters for the memory copy. + * @param [in] ctx - cotext related to current device. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDrvGraphAddMemcpyNode(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, + size_t numDependencies, + const HIP_MEMCPY3D* copyParams, hipCtx_t ctx); +/** + * @brief Creates a memcpy node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pCopyParams - const pointer to the parameters for the memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipMemcpy3DParms* pCopyParams); +/** + * @brief Gets a memcpy node's parameters. + * + * @param [in] node - instance of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeGetParams(hipGraphNode_t node, hipMemcpy3DParms* pNodeParams); + +/** + * @brief Sets a memcpy node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParams(hipGraphNode_t node, const hipMemcpy3DParms* pNodeParams); + +/** + * @brief Sets a node attribute. + * + * @param [in] hNode - instance of the node to set parameters to. + * @param [in] attr - the attribute node is set to. + * @param [in] value - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeSetAttribute(hipGraphNode_t hNode, hipKernelNodeAttrID attr, + const hipKernelNodeAttrValue* value); +/** + * @brief Gets a node attribute. + * + * @param [in] hNode - instance of the node to set parameters to. + * @param [in] attr - the attribute node is set to. + * @param [in] value - const pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeGetAttribute(hipGraphNode_t hNode, hipKernelNodeAttrID attr, + hipKernelNodeAttrValue* value); +/** + * @brief Sets the parameters for a memcpy node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - const pointer to the kernel node parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + hipMemcpy3DParms* pNodeParams); + +/** + * @brief Creates a 1D memcpy node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNode1D(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + void* dst, const void* src, size_t count, hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to perform a 1-dimensional copy. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParams1D(hipGraphNode_t node, void* dst, const void* src, + size_t count, hipMemcpyKind kind); + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to perform a 1-dimensional + * copy. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] src - pointer to memory address to the source. + * @param [in] count - the size of the memory to copy. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParams1D(hipGraphExec_t hGraphExec, hipGraphNode_t node, + void* dst, const void* src, size_t count, + hipMemcpyKind kind); + +/** + * @brief Creates a memcpy node to copy from a symbol on the device and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNodeFromSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, void* dst, const void* symbol, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to copy from a symbol on the device. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParamsFromSymbol(hipGraphNode_t node, void* dst, const void* symbol, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to copy from a symbol on the + * * device. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] dst - pointer to memory address to the destination. + * @param [in] symbol - Device symbol address. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParamsFromSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, + void* dst, const void* symbol, size_t count, + size_t offset, hipMemcpyKind kind); + +/** + * @brief Creates a memcpy node to copy to a symbol on the device and adds it to a graph. + * + * @param [out] pGraphNode - pointer to graph node to create. + * @param [in] graph - instance of graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memcpy execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemcpyNodeToSymbol(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, + size_t numDependencies, const void* symbol, + const void* src, size_t count, size_t offset, + hipMemcpyKind kind); + +/** + * @brief Sets a memcpy node's parameters to copy to a symbol on the device. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemcpyNodeSetParamsToSymbol(hipGraphNode_t node, const void* symbol, + const void* src, size_t count, size_t offset, + hipMemcpyKind kind); + + +/** + * @brief Sets the parameters for a memcpy node in the given graphExec to copy to a symbol on the + * device. + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] symbol - Device symbol address. + * @param [in] src - pointer to memory address of the src. + * @param [in] count - the size of the memory to copy. + * @param [in] offset - Offset from start of symbol in bytes. + * @param [in] kind - the type of memory copy. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemcpyNodeSetParamsToSymbol(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const void* symbol, const void* src, + size_t count, size_t offset, hipMemcpyKind kind); + +/** + * @brief Creates a memset node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pMemsetParams - const pointer to the parameters for the memory set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemsetNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipMemsetParams* pMemsetParams); + +/** + * @brief Gets a memset node's parameters. + * + * @param [in] node - instane of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemsetNodeGetParams(hipGraphNode_t node, hipMemsetParams* pNodeParams); + +/** + * @brief Sets a memset node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemsetNodeSetParams(hipGraphNode_t node, const hipMemsetParams* pNodeParams); + +/** + * @brief Sets the parameters for a memset node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecMemsetNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipMemsetParams* pNodeParams); + +/** + * @brief Creates a host execution node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] pNodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddHostNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipHostNodeParams* pNodeParams); + +/** + * @brief Returns a host node's parameters. + * + * @param [in] node - instane of the node to get parameters from. + * @param [out] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphHostNodeGetParams(hipGraphNode_t node, hipHostNodeParams* pNodeParams); + +/** + * @brief Sets a host node's parameters. + * + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphHostNodeSetParams(hipGraphNode_t node, const hipHostNodeParams* pNodeParams); + +/** + * @brief Sets the parameters for a host node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - instance of the node to set parameters to. + * @param [in] pNodeParams - pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecHostNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + const hipHostNodeParams* pNodeParams); + +/** + * @brief Creates a child graph node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] childGraph - the graph to clone into this node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddChildGraphNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipGraph_t childGraph); + +/** + * @brief Gets a handle to the embedded graph of a child graph node. + * + * @param [in] node - instane of the node to get child graph. + * @param [out] pGraph - pointer to get the graph. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphChildGraphNodeGetGraph(hipGraphNode_t node, hipGraph_t* pGraph); + +/** + * @brief Updates node parameters in the child graph node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] node - node from the graph which was used to instantiate graphExec. + * @param [in] childGraph - child graph with updated parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecChildGraphNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t node, + hipGraph_t childGraph); + +/** + * @brief Creates an empty node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node is add to. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEmptyNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies); + + +/** + * @brief Creates an event record node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node to be added. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @param [in] event - Event for the node. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEventRecordNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipEvent_t event); + +/** + * @brief Returns the event associated with an event record node. + * + * @param [in] node - instane of the node to get event from. + * @param [out] event_out - Pointer to return the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventRecordNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out); + +/** + * @brief Sets an event record node's event. + * + * @param [in] node - instane of the node to set event to. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventRecordNodeSetEvent(hipGraphNode_t node, hipEvent_t event); + +/** + * @brief Sets the event for an event record node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] hNode - node from the graph which was used to instantiate graphExec. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecEventRecordNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + hipEvent_t event); + +/** + * @brief Creates an event wait node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create and add to the graph. + * @param [in] graph - instane of the graph the node to be added. + * @param [in] pDependencies - const pointer to the node dependenties. + * @param [in] numDependencies - the number of dependencies. + * @param [in] event - Event for the node. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddEventWaitNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + hipEvent_t event); + + +/** + * @brief Returns the event associated with an event wait node. + * + * @param [in] node - instane of the node to get event from. + * @param [out] event_out - Pointer to return the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventWaitNodeGetEvent(hipGraphNode_t node, hipEvent_t* event_out); + +/** + * @brief Sets an event wait node's event. + * + * @param [in] node - instane of the node to set event to. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphEventWaitNodeSetEvent(hipGraphNode_t node, hipEvent_t event); + +/** + * @brief Sets the event for an event record node in the given graphExec. + * + * @param [in] hGraphExec - instance of the executable graph with the node. + * @param [in] hNode - node from the graph which was used to instantiate graphExec. + * @param [in] event - pointer to the event. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecEventWaitNodeSetEvent(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + hipEvent_t event); + +/** + * @brief Creates a memory allocation node and adds it to a graph + * + * @param [out] pGraphNode - Pointer to the graph node to create and add to the graph + * @param [in] graph - Instane of the graph the node to be added + * @param [in] pDependencies - Const pointer to the node dependenties + * @param [in] numDependencies - The number of dependencies + * @param [in] pNodeParams - Node parameters for memory allocation + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemAllocNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, hipMemAllocNodeParams* pNodeParams); + +/** + * @brief Returns parameters for memory allocation node + * + * @param [in] node - Memory allocation node for a query + * @param [out] pNodeParams - Parameters for the specified memory allocation node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemAllocNodeGetParams(hipGraphNode_t node, hipMemAllocNodeParams* pNodeParams); + +/** + * @brief Creates a memory free node and adds it to a graph + * + * @param [out] pGraphNode - Pointer to the graph node to create and add to the graph + * @param [in] graph - Instane of the graph the node to be added + * @param [in] pDependencies - Const pointer to the node dependenties + * @param [in] numDependencies - The number of dependencies + * @param [in] dev_ptr - Pointer to the memory to be freed + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddMemFreeNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, void* dev_ptr); + +/** + * @brief Returns parameters for memory free node + * + * @param [in] node - Memory free node for a query + * @param [out] dev_ptr - Device pointer for the specified memory free node + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphMemFreeNodeGetParams(hipGraphNode_t node, void* dev_ptr); + +/** + * @brief Get the mem attribute for graphs. + * + * @param [in] device - device the attr is get for. + * @param [in] attr - attr to get. + * @param [out] value - value for specific attr. + * @returns #hipSuccess, #hipErrorInvalidDevice + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGetGraphMemAttribute(int device, hipGraphMemAttributeType attr, void* value); + +/** + * @brief Set the mem attribute for graphs. + * + * @param [in] device - device the attr is set for. + * @param [in] attr - attr to set. + * @param [in] value - value for specific attr. + * @returns #hipSuccess, #hipErrorInvalidDevice + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceSetGraphMemAttribute(int device, hipGraphMemAttributeType attr, void* value); + +/** + * @brief Free unused memory on specific device used for graph back to OS. + * + * @param [in] device - device the memory is used for graphs + * @returns #hipSuccess, #hipErrorInvalidDevice + * + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDeviceGraphMemTrim(int device); + +/** + * @brief Create an instance of userObject to manage lifetime of a resource. + * + * @param [out] object_out - pointer to instace of userobj. + * @param [in] ptr - pointer to pass to destroy function. + * @param [in] destroy - destroy callback to remove resource. + * @param [in] initialRefcount - reference to resource. + * @param [in] flags - flags passed to API. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectCreate(hipUserObject_t* object_out, void* ptr, hipHostFn_t destroy, + unsigned int initialRefcount, unsigned int flags); + +/** + * @brief Release number of references to resource. + * + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectRelease(hipUserObject_t object, unsigned int count __dparm(1)); + +/** + * @brief Retain number of references to resource. + * + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipUserObjectRetain(hipUserObject_t object, unsigned int count __dparm(1)); + +/** + * @brief Retain user object for graphs. + * + * @param [in] graph - pointer to graph to retain the user object for. + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @param [in] flags - flags passed to API. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphRetainUserObject(hipGraph_t graph, hipUserObject_t object, + unsigned int count __dparm(1), unsigned int flags __dparm(0)); + +/** + * @brief Release user object from graphs. + * + * @param [in] graph - pointer to graph to retain the user object for. + * @param [in] object - pointer to instace of userobj. + * @param [in] count - reference to resource to be retained. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphReleaseUserObject(hipGraph_t graph, hipUserObject_t object, + unsigned int count __dparm(1)); + +/** + * @brief Write a DOT file describing graph structure. + * + * @param [in] graph - graph object for which DOT file has to be generated. + * @param [in] path - path to write the DOT file. + * @param [in] flags - Flags from hipGraphDebugDotFlags to get additional node information. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorOperatingSystem + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphDebugDotPrint(hipGraph_t graph, const char* path, unsigned int flags); + +/** + * @brief Copies attributes from source node to destination node. + * + * Copies attributes from source node to destination node. + * Both node must have the same context. + * + * @param [out] hDst - Destination node. + * @param [in] hSrc - Source node. + * For list of attributes see ::hipKernelNodeAttrID. + * + * @returns #hipSuccess, #hipErrorInvalidContext + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphKernelNodeCopyAttributes(hipGraphNode_t hSrc, hipGraphNode_t hDst); + +/** + * @brief Enables or disables the specified node in the given graphExec + * + * Sets hNode to be either enabled or disabled. Disabled nodes are functionally equivalent + * to empty nodes until they are reenabled. Existing node parameters are not affected by + * disabling/enabling the node. + * + * The node is identified by the corresponding hNode in the non-executable graph, from which the + * executable graph was instantiated. + * + * hNode must not have been removed from the original graph. + * + * @note Currently only kernel, memset and memcpy nodes are supported. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] isEnabled - Node is enabled if != 0, otherwise the node is disabled. + * + * @returns #hipSuccess, #hipErrorInvalidValue, + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphNodeSetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int isEnabled); +/** + * @brief Query whether a node in the given graphExec is enabled + * + * Sets isEnabled to 1 if hNode is enabled, or 0 if it is disabled. + * + * The node is identified by the corresponding node in the non-executable graph, from which the + * executable graph was instantiated. + * + * hNode must not have been removed from the original graph. + * + * @note Currently only kernel, memset and memcpy nodes are supported. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] isEnabled - Location to return the enabled status of the node. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphNodeGetEnabled(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + unsigned int* isEnabled); + +/** + * @brief Creates a external semaphor wait node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddExternalSemaphoresWaitNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipExternalSemaphoreWaitNodeParams* nodeParams); + +/** + * @brief Creates a external semaphor signal node and adds it to a graph. + * + * @param [out] pGraphNode - pointer to the graph node to create. + * @param [in] graph - instance of the graph to add the created node. + * @param [in] pDependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - the number of the dependencies. + * @param [in] nodeParams -pointer to the parameters. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphAddExternalSemaphoresSignalNode(hipGraphNode_t* pGraphNode, hipGraph_t graph, + const hipGraphNode_t* pDependencies, size_t numDependencies, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore signal node. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresSignalNodeSetParams(hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore wait node. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresWaitNodeSetParams(hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); +/** + * @brief Returns external semaphore signal node params. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] params_out - Pointer to params. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresSignalNodeGetParams(hipGraphNode_t hNode, + hipExternalSemaphoreSignalNodeParams* params_out); +/** + * @brief Returns external semaphore wait node params. + * + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [out] params_out - Pointer to params. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExternalSemaphoresWaitNodeGetParams(hipGraphNode_t hNode, + hipExternalSemaphoreWaitNodeParams* params_out); +/** + * @brief Updates node parameters in the external semaphore signal node in the given graphExec. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecExternalSemaphoresSignalNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + const hipExternalSemaphoreSignalNodeParams* nodeParams); +/** + * @brief Updates node parameters in the external semaphore wait node in the given graphExec. + * + * @param [in] hGraphExec - The executable graph in which to set the specified node. + * @param [in] hNode - Node from the graph from which graphExec was instantiated. + * @param [in] nodeParams - Pointer to the params to be set. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipGraphExecExternalSemaphoresWaitNodeSetParams(hipGraphExec_t hGraphExec, hipGraphNode_t hNode, + const hipExternalSemaphoreWaitNodeParams* nodeParams); + +/** + * @brief Creates a memset node and adds it to a graph. + * + * @param [out] phGraphNode - pointer to graph node to create. + * @param [in] hGraph - instance of graph to add the created node to. + * @param [in] dependencies - const pointer to the dependencies on the memset execution node. + * @param [in] numDependencies - number of the dependencies. + * @param [in] memsetParams - const pointer to the parameters for the memory set. + * @param [in] ctx - cotext related to current device. + * @returns #hipSuccess, #hipErrorInvalidValue + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + */ +hipError_t hipDrvGraphAddMemsetNode(hipGraphNode_t* phGraphNode, hipGraph_t hGraph, + const hipGraphNode_t* dependencies, size_t numDependencies, + const HIP_MEMSET_NODE_PARAMS* memsetParams, hipCtx_t ctx); + +// doxygen end graph API +/** + * @} + */ + + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Virtual Virtual Memory Management + * @{ + * This section describes the virtual memory management functions of HIP runtime API. + * + * @note Please note, the virtual memory management functions of HIP runtime API are implemented + * on Linux, under development on Windows. + */ + +/** + * @brief Frees an address range reservation made via hipMemAddressReserve + * + * @param [in] devPtr - starting address of the range. + * @param [in] size - size of the range. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemAddressFree(void* devPtr, size_t size); + +/** + * @brief Reserves an address range + * + * @param [out] ptr - starting address of the reserved range. + * @param [in] size - size of the reservation. + * @param [in] alignment - alignment of the address. + * @param [in] addr - requested starting address of the range. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemAddressReserve(void** ptr, size_t size, size_t alignment, void* addr, unsigned long long flags); + +/** + * @brief Creates a memory allocation described by the properties and size + * + * @param [out] handle - value of the returned handle. + * @param [in] size - size of the allocation. + * @param [in] prop - properties of the allocation. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemCreate(hipMemGenericAllocationHandle_t* handle, size_t size, const hipMemAllocationProp* prop, unsigned long long flags); + +/** + * @brief Exports an allocation to a requested shareable handle type. + * + * @param [out] shareableHandle - value of the returned handle. + * @param [in] handle - handle to share. + * @param [in] handleType - type of the shareable handle. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemExportToShareableHandle(void* shareableHandle, hipMemGenericAllocationHandle_t handle, hipMemAllocationHandleType handleType, unsigned long long flags); + +/** + * @brief Get the access flags set for the given location and ptr. + * + * @param [out] flags - flags for this location. + * @param [in] location - target location. + * @param [in] ptr - address to check the access flags. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemGetAccess(unsigned long long* flags, const hipMemLocation* location, void* ptr); + +/** + * @brief Calculates either the minimal or recommended granularity. + * + * @param [out] granularity - returned granularity. + * @param [in] prop - location properties. + * @param [in] option - determines which granularity to return. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + * + */ +hipError_t hipMemGetAllocationGranularity(size_t* granularity, const hipMemAllocationProp* prop, hipMemAllocationGranularity_flags option); + +/** + * @brief Retrieve the property structure of the given handle. + * + * @param [out] prop - properties of the given handle. + * @param [in] handle - handle to perform the query on. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux under development on Windows. + */ +hipError_t hipMemGetAllocationPropertiesFromHandle(hipMemAllocationProp* prop, hipMemGenericAllocationHandle_t handle); + +/** + * @brief Imports an allocation from a requested shareable handle type. + * + * @param [out] handle - returned value. + * @param [in] osHandle - shareable handle representing the memory allocation. + * @param [in] shHandleType - handle type. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemImportFromShareableHandle(hipMemGenericAllocationHandle_t* handle, void* osHandle, hipMemAllocationHandleType shHandleType); + +/** + * @brief Maps an allocation handle to a reserved virtual address range. + * + * @param [in] ptr - address where the memory will be mapped. + * @param [in] size - size of the mapping. + * @param [in] offset - offset into the memory, currently must be zero. + * @param [in] handle - memory allocation to be mapped. + * @param [in] flags - currently unused, must be zero. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemMap(void* ptr, size_t size, size_t offset, hipMemGenericAllocationHandle_t handle, unsigned long long flags); + +/** + * @brief Maps or unmaps subregions of sparse HIP arrays and sparse HIP mipmapped arrays. + * + * @param [in] mapInfoList - list of hipArrayMapInfo. + * @param [in] count - number of hipArrayMapInfo in mapInfoList. + * @param [in] stream - stream identifier for the stream to use for map or unmap operations. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemMapArrayAsync(hipArrayMapInfo* mapInfoList, unsigned int count, hipStream_t stream); + +/** + * @brief Release a memory handle representing a memory allocation which was previously allocated through hipMemCreate. + * + * @param [in] handle - handle of the memory allocation. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRelease(hipMemGenericAllocationHandle_t handle); + +/** + * @brief Returns the allocation handle of the backing memory allocation given the address. + * + * @param [out] handle - handle representing addr. + * @param [in] addr - address to look up. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemRetainAllocationHandle(hipMemGenericAllocationHandle_t* handle, void* addr); + +/** + * @brief Set the access flags for each location specified in desc for the given virtual address range. + * + * @param [in] ptr - starting address of the virtual address range. + * @param [in] size - size of the range. + * @param [in] desc - array of hipMemAccessDesc. + * @param [in] count - number of hipMemAccessDesc in desc. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemSetAccess(void* ptr, size_t size, const hipMemAccessDesc* desc, size_t count); + +/** + * @brief Unmap memory allocation of a given address range. + * + * @param [in] ptr - starting address of the range to unmap. + * @param [in] size - size of the virtual address range. + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorNotSupported + * @warning : This API is marked as beta, meaning, while this is feature complete, + * it is still open to changes and may have outstanding issues. + * + * @note This API is implemented on Linux, under development on Windows. + */ +hipError_t hipMemUnmap(void* ptr, size_t size); + +// doxygen end virtual memory management API +/** + * @} + */ +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup GL OpenGL Interop + * @{ + * This section describes the OpenGL and graphics interoperability functions of HIP runtime API. + */ + +/** + * @brief Maps a graphics resource for access. + * + * @param [in] count - Number of resources to map. + * @param [in] resources - Pointer of resources to map. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorInvalidResourceHandle + * + */ +hipError_t hipGraphicsMapResources(int count, hipGraphicsResource_t* resources, + hipStream_t stream __dparm(0) ); +/** + * @brief Get an array through which to access a subresource of a mapped graphics resource. + * + * @param [out] array - Pointer of array through which a subresource of resource may be accessed. + * @param [in] resource - Mapped resource to access. + * @param [in] arrayIndex - Array index for the subresource to access. + * @param [in] mipLevel - Mipmap level for the subresource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + * @note In this API, the value of arrayIndex higher than zero is currently not supported. + * + */ +hipError_t hipGraphicsSubResourceGetMappedArray(hipArray_t* array, hipGraphicsResource_t resource, + unsigned int arrayIndex, unsigned int mipLevel); +/** + * @brief Gets device accessible address of a graphics resource. + * + * @param [out] devPtr - Pointer of device through which graphic resource may be accessed. + * @param [out] size - Size of the buffer accessible from devPtr. + * @param [in] resource - Mapped resource to access. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipGraphicsResourceGetMappedPointer(void** devPtr, size_t* size, + hipGraphicsResource_t resource); +/** + * @brief Unmaps graphics resources. + * + * @param [in] count - Number of resources to unmap. + * @param [in] resources - Pointer of resources to unmap. + * @param [in] stream - Stream for synchronization. + * + * @returns #hipSuccess, #hipErrorInvalidValue, #hipErrorUnknown, #hipErrorContextIsDestroyed + * + */ +hipError_t hipGraphicsUnmapResources(int count, hipGraphicsResource_t* resources, + hipStream_t stream __dparm(0)); +/** + * @brief Unregisters a graphics resource. + * + * @param [in] resource - Graphics resources to unregister. + * + * @returns #hipSuccess + * + */ +hipError_t hipGraphicsUnregisterResource(hipGraphicsResource_t resource); +// doxygen end GL Interop +/** + * @} + */ + +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @defgroup Surface Surface Object + * @{ + * + * This section describes surface object functions of HIP runtime API. + * + * @note APIs in this section are under development. + * + */ + +/** + * @brief Create a surface object. + * + * @param [out] pSurfObject Pointer of surface object to be created. + * @param [in] pResDesc Pointer of suface object descriptor. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +hipError_t hipCreateSurfaceObject(hipSurfaceObject_t* pSurfObject, const hipResourceDesc* pResDesc); +/** + * @brief Destroy a surface object. + * + * @param [in] surfaceObject Surface object to be destroyed. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +hipError_t hipDestroySurfaceObject(hipSurfaceObject_t surfaceObject); +// end of surface +/** +* @} +*/ +#ifdef __cplusplus +} /* extern "c" */ +#endif +#ifdef __cplusplus +#if defined(__clang__) && defined(__HIP__) +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + T f, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0) { + return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize, reinterpret_cast(f),dynSharedMemPerBlk,blockSizeLimit); +} +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeWithFlags(int* gridSize, int* blockSize, + T f, size_t dynSharedMemPerBlk = 0, int blockSizeLimit = 0, unsigned int flags = 0 ) { + return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize, reinterpret_cast(f),dynSharedMemPerBlk,blockSizeLimit); +} +#endif // defined(__clang__) && defined(__HIP__) + +/** + * @brief Gets the address of a symbol. + * @ingroup Memory + * @param [out] devPtr - Returns device pointer associated with symbol. + * @param [in] symbol - Device symbol. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +hipError_t hipGetSymbolAddress(void** devPtr, const T &symbol) { + return ::hipGetSymbolAddress(devPtr, (const void *)&symbol); +} +/** + * @ingroup Memory + * @brief Gets the size of a symbol. + * + * @param [out] size - Returns the size of a symbol. + * @param [in] symbol - Device symbol address. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +hipError_t hipGetSymbolSize(size_t* size, const T &symbol) { + return ::hipGetSymbolSize(size, (const void *)&symbol); +} + +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbol + */ +template +hipError_t hipMemcpyToSymbol(const T& symbol, const void* src, size_t sizeBytes, + size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyHostToDevice)) { + return ::hipMemcpyToSymbol((const void*)&symbol, src, sizeBytes, offset, kind); +} +/** + * @ingroup Memory + * @brief Copies data to the given symbol on the device asynchronously on the stream. + * + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyToSymbolAsync + */ +template +hipError_t hipMemcpyToSymbolAsync(const T& symbol, const void* src, size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)) { + return ::hipMemcpyToSymbolAsync((const void*)&symbol, src, sizeBytes, offset, kind, stream); +} +/** + * @brief Copies data from the given symbol on the device. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbol + */ +template +hipError_t hipMemcpyFromSymbol(void* dst, const T &symbol, + size_t sizeBytes, size_t offset __dparm(0), + hipMemcpyKind kind __dparm(hipMemcpyDeviceToHost)) { + return ::hipMemcpyFromSymbol(dst, (const void*)&symbol, sizeBytes, offset, kind); +} +/** + * @brief Copies data from the given symbol on the device asynchronously on the stream. + * @ingroup Memory + * @returns #hipSuccess, #hipErrorInvalidMemcpyDirection, #hipErrorInvalidValue + * + * @see hipMemcpyFromSymbolAsync + */ +template +hipError_t hipMemcpyFromSymbolAsync(void* dst, const T& symbol, size_t sizeBytes, size_t offset, + hipMemcpyKind kind, hipStream_t stream __dparm(0)) { + return ::hipMemcpyFromSymbolAsync(dst, (const void*)&symbol, sizeBytes, offset, kind, stream); +} + +/** + * @brief Returns occupancy for a kernel function. + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessor( + int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk) { + return hipOccupancyMaxActiveBlocksPerMultiprocessor( + numBlocks, reinterpret_cast(f), blockSize, dynSharedMemPerBlk); +} +/** + * @brief Returns occupancy for a device function with the specified flags. + * + * @ingroup Occupancy + * @param [out] numBlocks - Pointer of occupancy in number of blocks. + * @param [in] f - The kernel function to launch on the device. + * @param [in] blockSize - The block size as kernel launched. + * @param [in] dynSharedMemPerBlk - Dynamic shared memory in bytes per block. + * @param [in] flags - Flag to handle the behavior for the occupancy calculator. + * + * @returns #hipSuccess, #hipErrorInvalidValue + * + */ +template +inline hipError_t hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int* numBlocks, T f, int blockSize, size_t dynSharedMemPerBlk, unsigned int flags) { + return hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + numBlocks, reinterpret_cast(f), blockSize, dynSharedMemPerBlk, flags); +} +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @param [out] min_grid_size minimum grid size needed to achieve the best potential occupancy + * @param [out] block_size block size required for the best potential occupancy + * @param [in] func device function symbol + * @param [in] block_size_to_dynamic_smem_size - a unary function/functor that takes block size, + * and returns the size, in bytes, of dynamic shared memory needed for a block + * @param [in] block_size_limit the maximum block size \p func is designed to work with. 0 means no limit. + * @param [in] flags reserved + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue, + * #hipErrorUnknown + */ +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags( + int* min_grid_size, + int* block_size, + T func, + UnaryFunction block_size_to_dynamic_smem_size, + int block_size_limit = 0, + unsigned int flags = 0) { + if (min_grid_size == nullptr || block_size == nullptr || + reinterpret_cast(func) == nullptr) { + return hipErrorInvalidValue; + } + + int dev; + hipError_t status; + if ((status = hipGetDevice(&dev)) != hipSuccess) { + return status; + } + + int max_threads_per_cu; + if ((status = hipDeviceGetAttribute(&max_threads_per_cu, + hipDeviceAttributeMaxThreadsPerMultiProcessor, dev)) != hipSuccess) { + return status; + } + + int warp_size; + if ((status = hipDeviceGetAttribute(&warp_size, + hipDeviceAttributeWarpSize, dev)) != hipSuccess) { + return status; + } + + int max_cu_count; + if ((status = hipDeviceGetAttribute(&max_cu_count, + hipDeviceAttributeMultiprocessorCount, dev)) != hipSuccess) { + return status; + } + + struct hipFuncAttributes attr; + if ((status = hipFuncGetAttributes(&attr, reinterpret_cast(func))) != hipSuccess) { + return status; + } + + // Initial limits for the execution + const int func_max_threads_per_block = attr.maxThreadsPerBlock; + if (block_size_limit == 0) { + block_size_limit = func_max_threads_per_block; + } + + if (func_max_threads_per_block < block_size_limit) { + block_size_limit = func_max_threads_per_block; + } + + const int block_size_limit_aligned = + ((block_size_limit + (warp_size - 1)) / warp_size) * warp_size; + + // For maximum search + int max_threads = 0; + int max_block_size{}; + int max_num_blocks{}; + for (int block_size_check_aligned = block_size_limit_aligned; + block_size_check_aligned > 0; + block_size_check_aligned -= warp_size) { + // Make sure the logic uses the requested limit and not aligned + int block_size_check = (block_size_limit < block_size_check_aligned) ? + block_size_limit : block_size_check_aligned; + + size_t dyn_smem_size = block_size_to_dynamic_smem_size(block_size_check); + int optimal_blocks; + if ((status = hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + &optimal_blocks, func, block_size_check, dyn_smem_size, flags)) != hipSuccess) { + return status; + } + + int total_threads = block_size_check * optimal_blocks; + if (total_threads > max_threads) { + max_block_size = block_size_check; + max_num_blocks = optimal_blocks; + max_threads = total_threads; + } + + // Break if the logic reached possible maximum + if (max_threads_per_cu == max_threads) { + break; + } + } + + // Grid size is the number of blocks per CU * CU count + *min_grid_size = max_num_blocks * max_cu_count; + *block_size = max_block_size; + + return status; +} + +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @param [out] min_grid_size minimum grid size needed to achieve the best potential occupancy + * @param [out] block_size block size required for the best potential occupancy + * @param [in] func device function symbol + * @param [in] block_size_to_dynamic_smem_size - a unary function/functor that takes block size, + * and returns the size, in bytes, of dynamic shared memory needed for a block + * @param [in] block_size_limit the maximum block size \p func is designed to work with. 0 means no limit. + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidDeviceFunction, #hipErrorInvalidValue, + * #hipErrorUnknown + */ +template +static hipError_t __host__ inline hipOccupancyMaxPotentialBlockSizeVariableSMem( + int* min_grid_size, + int* block_size, + T func, + UnaryFunction block_size_to_dynamic_smem_size, + int block_size_limit = 0) +{ + return hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags(min_grid_size, block_size, func, + block_size_to_dynamic_smem_size, block_size_limit); +} +/** + * @brief Returns grid and block size that achieves maximum potential occupancy for a device function + * + * @ingroup Occupancy + * + * Returns in \p *min_grid_size and \p *block_size a suggested grid / + * block size pair that achieves the best potential occupancy + * (i.e. the maximum number of active warps on the current device with the smallest number + * of blocks for a particular function). + * + * @return #hipSuccess, #hipErrorInvalidDevice, #hipErrorInvalidValue + * + * @see hipOccupancyMaxPotentialBlockSize + */ +template +inline hipError_t hipOccupancyMaxPotentialBlockSize(int* gridSize, int* blockSize, + F kernel, size_t dynSharedMemPerBlk, uint32_t blockSizeLimit) { +return hipOccupancyMaxPotentialBlockSize(gridSize, blockSize,(hipFunction_t)kernel, dynSharedMemPerBlk, blockSizeLimit); +} +/** + * @brief Launches a device function + * + * @ingroup Execution + * + * @param [in] f device function symbol + * @param [in] gridDim grid dimentions + * @param [in] blockDim block dimentions + * @param [in] kernelParams kernel parameters + * @param [in] sharedMemBytes shared memory in bytes + * @param [in] stream stream on which kernel launched + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ +template +inline hipError_t hipLaunchCooperativeKernel(T f, dim3 gridDim, dim3 blockDim, + void** kernelParams, unsigned int sharedMemBytes, hipStream_t stream) { + return hipLaunchCooperativeKernel(reinterpret_cast(f), gridDim, + blockDim, kernelParams, sharedMemBytes, stream); +} +/** + * @brief Launches device function on multiple devices where thread blocks can cooperate and + * synchronize on execution. + * + * @ingroup Execution + * + * @param [in] launchParamsList list of kernel launch parameters, one per device + * @param [in] numDevices size of launchParamsList array + * @param [in] flags flag to handle launch behavior + * + * @return #hipSuccess, #hipErrorLaunchFailure, #hipErrorInvalidValue, + * #hipErrorInvalidResourceHandle + * + */ +template +inline hipError_t hipLaunchCooperativeKernelMultiDevice(hipLaunchParams* launchParamsList, + unsigned int numDevices, unsigned int flags = 0) { + return hipLaunchCooperativeKernelMultiDevice(launchParamsList, numDevices, flags); +} +/** + * + * @ingroup Module + * + * @brief Launches kernels on multiple devices and guarantees all specified kernels are dispatched + * on respective streams before enqueuing any other work on the specified streams from any other threads + * + * + * @param [in] launchParamsList List of launch parameters, one per device. + * @param [in] numDevices Size of the launchParamsList array. + * @param [in] flags Flags to control launch behavior. + * + * @returns #hipSuccess, #hipErrorInvalidValue + */ +template +inline hipError_t hipExtLaunchMultiKernelMultiDevice(hipLaunchParams* launchParamsList, + unsigned int numDevices, unsigned int flags = 0) { + return hipExtLaunchMultiKernelMultiDevice(launchParamsList, numDevices, flags); +} +/** + * @brief Binds a memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture(size_t* offset, const struct texture& tex, + const void* devPtr, size_t size = UINT_MAX) { + return hipBindTexture(offset, &tex, devPtr, &tex.channelDesc, size); +} +/** + * @brief Binds a memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of memory on the device. + * @param [in] desc Texture channel format. + * @param [in] size Size of memory in bites. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t + hipBindTexture(size_t* offset, const struct texture& tex, const void* devPtr, + const struct hipChannelFormatDesc& desc, size_t size = UINT_MAX) { + return hipBindTexture(offset, &tex, devPtr, &desc, size); +} +/** + * @brief Binds a 2D memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture2D( + size_t *offset, + const struct texture &tex, + const void *devPtr, + size_t width, + size_t height, + size_t pitch) +{ + return hipBindTexture2D(offset, &tex, devPtr, &tex.channelDesc, width, height, pitch); +} +/** + * @brief Binds a 2D memory area to a texture. + * + * @ingroup TextureD + * + * @param [in] offset Offset in bytes. + * @param [in] tex Texture to bind. + * @param [in] devPtr Pointer of 2D memory area on the device. + * @param [in] desc Texture channel format. + * @param [in] width Width in texel units. + * @param [in] height Height in texel units. + * @param [in] pitch Pitch in bytes. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTexture2D( + size_t *offset, + const struct texture &tex, + const void *devPtr, + const struct hipChannelFormatDesc &desc, + size_t width, + size_t height, + size_t pitch) +{ + return hipBindTexture2D(offset, &tex, devPtr, &desc, width, height, pitch); +} +/** + * @brief Binds an array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToArray( + const struct texture &tex, + hipArray_const_t array) +{ + struct hipChannelFormatDesc desc; + hipError_t err = hipGetChannelDesc(&desc, array); + return (err == hipSuccess) ? hipBindTextureToArray(&tex, array, &desc) : err; +} +/** + * @brief Binds an array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] array Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToArray( + const struct texture &tex, + hipArray_const_t array, + const struct hipChannelFormatDesc &desc) +{ + return hipBindTextureToArray(&tex, array, &desc); +} +/** + * @brief Binds a mipmapped array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToMipmappedArray( + const struct texture &tex, + hipMipmappedArray_const_t mipmappedArray) +{ + struct hipChannelFormatDesc desc; + hipArray_t levelArray; + hipError_t err = hipGetMipmappedArrayLevel(&levelArray, mipmappedArray, 0); + if (err != hipSuccess) { + return err; + } + err = hipGetChannelDesc(&desc, levelArray); + return (err == hipSuccess) ? hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc) : err; +} +/** + * @brief Binds a mipmapped array to a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to bind. + * @param [in] mipmappedArray Mipmapped Array of memory on the device. + * @param [in] desc Texture channel format. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipBindTextureToMipmappedArray( + const struct texture &tex, + hipMipmappedArray_const_t mipmappedArray, + const struct hipChannelFormatDesc &desc) +{ + return hipBindTextureToMipmappedArray(&tex, mipmappedArray, &desc); +} +/** + * @brief Unbinds a texture. + * + * @ingroup TextureD + * + * @param [in] tex Texture to unbind. + * + * @warning This API is deprecated. + * + */ +template +DEPRECATED(DEPRECATED_MSG) +static inline hipError_t hipUnbindTexture( + const struct texture &tex) +{ + return hipUnbindTexture(&tex); +} +/** + *------------------------------------------------------------------------------------------------- + *------------------------------------------------------------------------------------------------- + * @ingroup StreamO + * @{ + * + * This section describes wrappers for stream Ordered allocation from memory pool functions of + * HIP runtime API. + * + * @note APIs in this section are implemented on Linux, under development on Windows. + * + */ + +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +static inline hipError_t hipMallocAsync( + void** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(dev_ptr, size, mem_pool, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool on the stream + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocAsync( + T** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocAsync( + T** dev_ptr, + size_t size, + hipStream_t stream) { + return hipMallocAsync(reinterpret_cast(dev_ptr), size, stream); +} +/** + * @brief C++ wrappers for allocations from a memory pool + * + * This is an alternate C++ calls for @p hipMallocFromPoolAsync made available through + * function overloading. + * + * @see hipMallocFromPoolAsync + * + * @note This API is implemented on Linux, under development on Windows. + */ +template +static inline hipError_t hipMallocFromPoolAsync( + T** dev_ptr, + size_t size, + hipMemPool_t mem_pool, + hipStream_t stream) { + return hipMallocFromPoolAsync(reinterpret_cast(dev_ptr), size, mem_pool, stream); +} +/** +* @} +*/ + + +#endif // __cplusplus + +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + + +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "hip/nvidia_detail/nvidia_hip_runtime_api.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + + +/** + * @brief: C++ wrapper for hipMalloc + * @ingroup Memory + * Perform automatic type conversion to eliminate need for excessive typecasting (ie void**) + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipMalloc + */ +#if defined(__cplusplus) && !defined(__HIP_DISABLE_CPP_FUNCTIONS__) +template +static inline hipError_t hipMalloc(T** devPtr, size_t size) { + return hipMalloc((void**)devPtr, size); +} +/** + * @brief: C++ wrapper for hipHostMalloc + * @ingroup Memory + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipHostMalloc + */ +template +static inline hipError_t hipHostMalloc(T** ptr, size_t size, + unsigned int flags = hipHostMallocDefault) { + return hipHostMalloc((void**)ptr, size, flags); +} +/** + * @brief: C++ wrapper for hipMallocManaged + * + * @ingroup MemoryM + * Provide an override to automatically typecast the pointer type from void**, and also provide a + * default for the flags. + * + * __HIP_DISABLE_CPP_FUNCTIONS__ macro can be defined to suppress these + * wrappers. It is useful for applications which need to obtain decltypes of + * HIP runtime APIs. + * + * @see hipMallocManaged + * + */ +template +static inline hipError_t hipMallocManaged(T** devPtr, size_t size, + unsigned int flags = hipMemAttachGlobal) { + return hipMallocManaged((void**)devPtr, size, flags); +} + + +#endif +#endif +// doxygen end HIP API +/** + * @} + */ +#include + +#if USE_PROF_API +#include +#endif diff --git a/shared/package-files/1f/1fdce5678cf8561e137e33580c1b313fbc20b902e9c427c963239c9b5c995377/test_util.py b/shared/package-files/1f/1fdce5678cf8561e137e33580c1b313fbc20b902e9c427c963239c9b5c995377/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..00c9743ed0a2664039060ef149d30f165bf2f465 --- /dev/null +++ b/shared/package-files/1f/1fdce5678cf8561e137e33580c1b313fbc20b902e9c427c963239c9b5c995377/test_util.py @@ -0,0 +1,243 @@ +"""Tests for distutils.util.""" + +import email +import email.generator +import email.policy +import io +import os +import pathlib +import sys +import sysconfig as stdlib_sysconfig +import unittest.mock as mock +from copy import copy +from distutils import sysconfig, util +from distutils.errors import DistutilsByteCompileError, DistutilsPlatformError +from distutils.util import ( + byte_compile, + change_root, + check_environ, + convert_path, + get_host_platform, + get_platform, + grok_environment_error, + rfc822_escape, + split_quoted, + strtobool, +) + +import pytest + + +@pytest.fixture(autouse=True) +def environment(monkeypatch): + monkeypatch.setattr(os, 'name', os.name) + monkeypatch.setattr(sys, 'platform', sys.platform) + monkeypatch.setattr(sys, 'version', sys.version) + monkeypatch.setattr(os, 'sep', os.sep) + monkeypatch.setattr(os.path, 'join', os.path.join) + monkeypatch.setattr(os.path, 'isabs', os.path.isabs) + monkeypatch.setattr(os.path, 'splitdrive', os.path.splitdrive) + monkeypatch.setattr(sysconfig, '_config_vars', copy(sysconfig._config_vars)) + + +@pytest.mark.usefixtures('save_env') +class TestUtil: + def test_get_host_platform(self): + with mock.patch('os.name', 'nt'): + with mock.patch('sys.version', '... [... (ARM64)]'): + assert get_host_platform() == 'win-arm64' + with mock.patch('sys.version', '... [... (ARM)]'): + assert get_host_platform() == 'win-arm32' + + with mock.patch('sys.version_info', (3, 9, 0, 'final', 0)): + assert get_host_platform() == stdlib_sysconfig.get_platform() + + def test_get_platform(self): + with mock.patch('os.name', 'nt'): + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x86'}): + assert get_platform() == 'win32' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'x64'}): + assert get_platform() == 'win-amd64' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm'}): + assert get_platform() == 'win-arm32' + with mock.patch.dict('os.environ', {'VSCMD_ARG_TGT_ARCH': 'arm64'}): + assert get_platform() == 'win-arm64' + + def test_convert_path(self): + expected = os.sep.join(('', 'home', 'to', 'my', 'stuff')) + assert convert_path('/home/to/my/stuff') == expected + assert convert_path(pathlib.Path('/home/to/my/stuff')) == expected + assert convert_path('.') == os.curdir + + def test_change_root(self): + # linux/mac + os.name = 'posix' + + def _isabs(path): + return path[0] == '/' + + os.path.isabs = _isabs + + def _join(*path): + return '/'.join(path) + + os.path.join = _join + + assert change_root('/root', '/old/its/here') == '/root/old/its/here' + assert change_root('/root', 'its/here') == '/root/its/here' + + # windows + os.name = 'nt' + os.sep = '\\' + + def _isabs(path): + return path.startswith('c:\\') + + os.path.isabs = _isabs + + def _splitdrive(path): + if path.startswith('c:'): + return ('', path.replace('c:', '')) + return ('', path) + + os.path.splitdrive = _splitdrive + + def _join(*path): + return '\\'.join(path) + + os.path.join = _join + + assert ( + change_root('c:\\root', 'c:\\old\\its\\here') == 'c:\\root\\old\\its\\here' + ) + assert change_root('c:\\root', 'its\\here') == 'c:\\root\\its\\here' + + # BugsBunny os (it's a great os) + os.name = 'BugsBunny' + with pytest.raises(DistutilsPlatformError): + change_root('c:\\root', 'its\\here') + + # XXX platforms to be covered: mac + + def test_check_environ(self): + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + check_environ() + + assert os.environ['PLAT'] == get_platform() + + @pytest.mark.skipif("os.name != 'posix'") + def test_check_environ_getpwuid(self): + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + import pwd + + # only set pw_dir field, other fields are not used + result = pwd.struct_passwd(( + None, + None, + None, + None, + None, + '/home/distutils', + None, + )) + with mock.patch.object(pwd, 'getpwuid', return_value=result): + check_environ() + assert os.environ['HOME'] == '/home/distutils' + + util.check_environ.cache_clear() + os.environ.pop('HOME', None) + + # bpo-10496: Catch pwd.getpwuid() error + with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError): + check_environ() + assert 'HOME' not in os.environ + + def test_split_quoted(self): + assert split_quoted('""one"" "two" \'three\' \\four') == [ + 'one', + 'two', + 'three', + 'four', + ] + + def test_strtobool(self): + yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') + no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') + + for y in yes: + assert strtobool(y) + + for n in no: + assert not strtobool(n) + + indent = 8 * ' ' + + @pytest.mark.parametrize( + "given,wanted", + [ + # 0x0b, 0x0c, ..., etc are also considered a line break by Python + ("hello\x0b\nworld\n", f"hello\x0b{indent}\n{indent}world\n{indent}"), + ("hello\x1eworld", f"hello\x1e{indent}world"), + ("", ""), + ( + "I am a\npoor\nlonesome\nheader\n", + f"I am a\n{indent}poor\n{indent}lonesome\n{indent}header\n{indent}", + ), + ], + ) + def test_rfc822_escape(self, given, wanted): + """ + We want to ensure a multi-line header parses correctly. + + For interoperability, the escaped value should also "round-trip" over + `email.generator.Generator.flatten` and `email.message_from_*` + (see pypa/setuptools#4033). + + The main issue is that internally `email.policy.EmailPolicy` uses + `splitlines` which will split on some control chars. If all the new lines + are not prefixed with spaces, the parser will interrupt reading + the current header and produce an incomplete value, while + incorrectly interpreting the rest of the headers as part of the payload. + """ + res = rfc822_escape(given) + + policy = email.policy.EmailPolicy( + utf8=True, + mangle_from_=False, + max_line_length=0, + ) + with io.StringIO() as buffer: + raw = f"header: {res}\nother-header: 42\n\npayload\n" + orig = email.message_from_string(raw) + email.generator.Generator(buffer, policy=policy).flatten(orig) + buffer.seek(0) + regen = email.message_from_file(buffer) + + for msg in (orig, regen): + assert msg.get_payload() == "payload\n" + assert msg["other-header"] == "42" + # Generator may replace control chars with `\n` + assert set(msg["header"].splitlines()) == set(res.splitlines()) + + assert res == wanted + + def test_dont_write_bytecode(self): + # makes sure byte_compile raise a DistutilsError + # if sys.dont_write_bytecode is True + old_dont_write_bytecode = sys.dont_write_bytecode + sys.dont_write_bytecode = True + try: + with pytest.raises(DistutilsByteCompileError): + byte_compile([]) + finally: + sys.dont_write_bytecode = old_dont_write_bytecode + + def test_grok_environment_error(self): + # test obsolete function to ensure backward compat (#4931) + exc = OSError("Unable to find batch file") + msg = grok_environment_error(exc) + assert msg == "error: Unable to find batch file" diff --git a/shared/package-files/1f/1fdd98b6a358d24a4ed8872ed44cb6888b4adfc66128c9c98bfd8507070a4af5/test_vlen_utf8.py b/shared/package-files/1f/1fdd98b6a358d24a4ed8872ed44cb6888b4adfc66128c9c98bfd8507070a4af5/test_vlen_utf8.py new file mode 100644 index 0000000000000000000000000000000000000000..514c7dc1629a51b018dd77fdf760d7cb82a6dd1c --- /dev/null +++ b/shared/package-files/1f/1fdd98b6a358d24a4ed8872ed44cb6888b4adfc66128c9c98bfd8507070a4af5/test_vlen_utf8.py @@ -0,0 +1,91 @@ +import unittest + +import numpy as np +import pytest + +try: + from numcodecs.vlen import VLenUTF8 +except ImportError as e: # pragma: no cover + raise unittest.SkipTest("vlen-utf8 not available") from e +from numcodecs.tests.common import ( + assert_array_items_equal, + check_backwards_compatibility, + check_config, + check_encode_decode_array, + check_repr, + greetings, +) + +arrays = [ + np.array(['foo', 'bar', 'baz'] * 300, dtype=object), + np.array(greetings * 100, dtype=object), + np.array(['foo', 'bar', 'baz'] * 300, dtype=object).reshape(90, 10), + np.array(greetings * 1000, dtype=object).reshape(len(greetings), 100, 10, order='F'), +] + + +def test_encode_decode(): + for arr in arrays: + codec = VLenUTF8() + check_encode_decode_array(arr, codec) + + +def test_config(): + codec = VLenUTF8() + check_config(codec) + + +def test_repr(): + check_repr("VLenUTF8()") + + +def test_backwards_compatibility(): + check_backwards_compatibility(VLenUTF8.codec_id, arrays, [VLenUTF8()]) + + +def test_encode_errors(): + codec = VLenUTF8() + with pytest.raises(TypeError): + codec.encode(1234) + with pytest.raises(TypeError): + codec.encode([1234, 5678]) + with pytest.raises(TypeError): + codec.encode(np.ones(10, dtype='i4')) + + +def test_decode_errors(): + codec = VLenUTF8() + with pytest.raises(TypeError): + codec.decode(1234) + # these should look like corrupt data + with pytest.raises(ValueError): + codec.decode(b'foo') + with pytest.raises(ValueError): + codec.decode(np.arange(2, 3, dtype='i4')) + with pytest.raises(ValueError): + codec.decode(np.arange(10, 20, dtype='i4')) + with pytest.raises(TypeError): + codec.decode('foo') + + # test out parameter + enc = codec.encode(arrays[0]) + with pytest.raises(TypeError): + codec.decode(enc, out=b'foo') + with pytest.raises(TypeError): + codec.decode(enc, out='foo') + with pytest.raises(TypeError): + codec.decode(enc, out=123) + with pytest.raises(ValueError): + codec.decode(enc, out=np.zeros(10, dtype='i4')) + + +@pytest.mark.parametrize("writable", [True, False]) +def test_encode_utf8(writable): + a = np.array(['foo', None, 'bar'], dtype=object) + if not writable: + a.setflags(write=False) + codec = VLenUTF8() + enc = codec.encode(a) + dec = codec.decode(enc) + expect = np.array(['foo', '', 'bar'], dtype=object) + assert_array_items_equal(expect, dec) diff --git a/shared/package-files/1f/1fe81718dcf25c917a7e05ca4635a6e4be20c29df5d66970e30b96d0cd5acad2/ReduceUtils.h b/shared/package-files/1f/1fe81718dcf25c917a7e05ca4635a6e4be20c29df5d66970e30b96d0cd5acad2/ReduceUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..fd7c4a2750a6c953fb30d29cd13c6924c99bec39 --- /dev/null +++ b/shared/package-files/1f/1fe81718dcf25c917a7e05ca4635a6e4be20c29df5d66970e30b96d0cd5acad2/ReduceUtils.h @@ -0,0 +1,238 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +using namespace vec; + +#define AT_DISPATCH_REDUCTION_TYPES(op, ...) \ + [&] { \ + switch (op) { \ + case ReductionType::SUM: { \ + static constexpr auto reduce = ReductionType::SUM; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MEAN: { \ + static constexpr auto reduce = ReductionType::MEAN; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MIN: { \ + static constexpr auto reduce = ReductionType::MIN; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MAX: { \ + static constexpr auto reduce = ReductionType::MAX; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::PROD: { \ + static constexpr auto reduce = ReductionType::PROD; \ + return __VA_ARGS__(); \ + } \ + } \ + }() + +template +inline vec_scalar_t init_value() { + using acc_t = vec_scalar_t; + acc_t val; + if (reduce == ReductionType::SUM || + reduce == ReductionType::MEAN) { + val = static_cast(0); + } else if (reduce == ReductionType::PROD) { + val = static_cast(1); + } else if (reduce == ReductionType::MAX) { + val = -std::numeric_limits::infinity(); + } else { + TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN); + val = std::numeric_limits::infinity(); + } + return val; +} + +template +inline vec_scalar_t init_value(const std::optional& initial) { + using acc_t = vec_scalar_t; + if (initial.has_value()) { + return initial.value().to(); + } else { + return init_value(); + } +} + +template +inline void init(scalar_t* out, int64_t size, const vec_scalar_t& val) { + using Vec = Vectorized>; + map( + [val](Vec x) { return Vec(val); }, + out, + out, + size); +} + +template +inline void init(scalar_t* out, int64_t size, const std::optional& initial) { + using acc_t = vec_scalar_t; + acc_t val = init_value(initial); + init(out, size, val); +} + +// overload with `include_self`, used by scatter_reduce +template +inline void init(scalar_t* out, int64_t size, bool include_self = false) { + using acc_t = vec_scalar_t; + if (!include_self) { + acc_t val = init_value(); + init(out, size, val); + } +} + +template +inline void _init(scalar_t* self_ptr, at::opmath_type* buffer_ptr, int64_t size, bool include_self) { + if (!include_self) { + init, reduce>(buffer_ptr, size, include_self); + } else { + vec::convert(self_ptr, buffer_ptr, size); + } +} + +template +inline std::enable_if_t, scalar_t> +_max(const scalar_t& x, const scalar_t& y) { + return at::_isnan(y) ? y : std::max(x, y); +} + +template +inline Vectorized _max(const Vectorized& x, const Vectorized& y) { + // vec::maximum propagates NaN + return vec::maximum(x, y); +} + +template +inline std::enable_if_t, Vec2> +_max(const vec_t& x, const vec_t& y) { + // vec::maximum propagates NaN + return maximum(x, y); +} + +template +inline std::enable_if_t, scalar_t> +_min(const scalar_t& x, const scalar_t& y) { + return at::_isnan(y) ? y : std::min(x, y); +} + +template +inline Vectorized _min(const Vectorized& x, const Vectorized& y) { + // vec::minimum propagates NaN + return vec::minimum(x, y); +} + +template +inline std::enable_if_t, Vec2> +_min(const vec_t& x, const vec_t& y) { + // vec::minimum propagates NaN + return minimum(x, y); +} + +template , int> = 0> +inline void map_acc( + const Op& vec_fun, + accumut* output_data, + const accumut* input_data, + const scalar_t* input_data2, + int64_t size) { + using Vec = vec::Vectorized; + using aVec = vec::Vectorized; + int64_t d = 0; + constexpr int64_t kVecSize = Vec::size(); + constexpr int64_t kaVecSize = aVec::size(); + for (d = 0; d < size - (size % kVecSize); d += kVecSize) { + Vec data2_vec = Vec::loadu(input_data2 + d); + auto [data2_avec0, data2_avec1] = convert_to_float(data2_vec); + aVec input_vec0 = aVec::loadu(input_data + d); + aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize); + vec_fun(input_vec0, data2_avec0).store(output_data + d); + vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize); + } + if (size - d > 0) { + int64_t tail_size = size - d; + Vec data2_vec = Vec::loadu(input_data2 + d, tail_size); + auto [data2_avec0, data2_avec1] = convert_to_float(data2_vec); + if (tail_size > kaVecSize) { + aVec input_vec0 = aVec::loadu(input_data + d); + aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize, tail_size - kaVecSize); + vec_fun(input_vec0, data2_avec0).store(output_data + d); + vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize, tail_size - kaVecSize); + } else { + aVec input_vec0 = aVec::loadu(input_data + d, tail_size); + vec_fun(input_vec0, data2_avec0).store(output_data + d, tail_size); + } + } +} + +// for Max and Min, propagate NaN: +template +inline T update(const T& x, const T& y) { + if (reduce == ReductionType::SUM || + reduce == ReductionType::MEAN) { + return x + y; + } else if (reduce == ReductionType::PROD) { + return x * y; + } else if (reduce == ReductionType::MAX) { + return _max(x, y); + } else { + TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN); + return _min(x, y); + } +} + +template +inline void update(scalar_t* out, const scalar_t* data, int64_t K) { + using Vec = vec::Vectorized>; + map2( + [](Vec x, Vec y) { return update(x, y); }, + out, + out, + data, + K); +} + +template , int> = 0> +inline void update(at::opmath_type* out, const scalar_t* data, int64_t K) { + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + map_acc( + [](Vec x, Vec y) { return update(x, y); }, + out, + out, + data, + K); +} + +template +inline void write(scalar_t* out, int64_t count, int64_t K) { + using Vec = vec::Vectorized>; + if (reduce == ReductionType::MEAN) { + if (count > 0) { + vec::map( + [count](Vec x) { return x / Vec(count); }, + out, + out, + K); + } + } +} + +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/shared/package-files/1f/1feaff10aa699c62dc9988caf0b48fad9128ee0e038f229b5aa45e581f19f914/_dedup_tensors.cpython-311.pyc b/shared/package-files/1f/1feaff10aa699c62dc9988caf0b48fad9128ee0e038f229b5aa45e581f19f914/_dedup_tensors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6034c88cd28043ae84b394643b8491a7d73bc0f0 Binary files /dev/null and b/shared/package-files/1f/1feaff10aa699c62dc9988caf0b48fad9128ee0e038f229b5aa45e581f19f914/_dedup_tensors.cpython-311.pyc differ diff --git a/shared/package-files/1f/1feb49115c495be8b3c453d6642d6a581583ad355f7b68ae6c3530618b6eb3cb/test_duplicates.cpython-311.pyc b/shared/package-files/1f/1feb49115c495be8b3c453d6642d6a581583ad355f7b68ae6c3530618b6eb3cb/test_duplicates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c042de4472c22e4deb57e9e1bc5aaf56e6dbc62 Binary files /dev/null and b/shared/package-files/1f/1feb49115c495be8b3c453d6642d6a581583ad355f7b68ae6c3530618b6eb3cb/test_duplicates.cpython-311.pyc differ diff --git a/shared/package-files/1f/1fed3b5a757802f8e1b06509d5e760d921fe615191e1ae16981286c3c2a27866/_fsdp_init.cpython-311.pyc b/shared/package-files/1f/1fed3b5a757802f8e1b06509d5e760d921fe615191e1ae16981286c3c2a27866/_fsdp_init.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e952fa93d9adfa6219e28eba39d2ecc8dbbd09b Binary files /dev/null and b/shared/package-files/1f/1fed3b5a757802f8e1b06509d5e760d921fe615191e1ae16981286c3c2a27866/_fsdp_init.cpython-311.pyc differ diff --git a/shared/package-files/1f/1ff17aa5880f52a5fd646f19d5a4c4847028f29068eaea3711cefa04385e6ebc/test_domains.cpython-311.pyc b/shared/package-files/1f/1ff17aa5880f52a5fd646f19d5a4c4847028f29068eaea3711cefa04385e6ebc/test_domains.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70233aade122b6aecbd5fc6926b7f3f8565f6f94 Binary files /dev/null and b/shared/package-files/1f/1ff17aa5880f52a5fd646f19d5a4c4847028f29068eaea3711cefa04385e6ebc/test_domains.cpython-311.pyc differ diff --git a/shared/package-files/1f/1ff6e6a14a1571ae4e35cfaf53c99e5f0c3e4018c28f5774eff29dc5af228394/test_hist_method.cpython-311.pyc b/shared/package-files/1f/1ff6e6a14a1571ae4e35cfaf53c99e5f0c3e4018c28f5774eff29dc5af228394/test_hist_method.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4d7951d4f77c18c3cb51d498b588b21e3626cbf Binary files /dev/null and b/shared/package-files/1f/1ff6e6a14a1571ae4e35cfaf53c99e5f0c3e4018c28f5774eff29dc5af228394/test_hist_method.cpython-311.pyc differ diff --git a/shared/package-files/1f/1ff7432fcf4049ec77b08f05f7671e5c8272e50775dfbaf14dadb4463fbd9760/test_sympy_parser.py b/shared/package-files/1f/1ff7432fcf4049ec77b08f05f7671e5c8272e50775dfbaf14dadb4463fbd9760/test_sympy_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..43ecccbe262ffb4093248d891aa7423c8f62c628 --- /dev/null +++ b/shared/package-files/1f/1ff7432fcf4049ec77b08f05f7671e5c8272e50775dfbaf14dadb4463fbd9760/test_sympy_parser.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- + + +import builtins +import types + +from sympy.assumptions import Q +from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq, Lt, Le, Gt, Ge, Ne +from sympy.functions import exp, factorial, factorial2, sin, Min, Max +from sympy.logic import And +from sympy.series import Limit +from sympy.testing.pytest import raises + +from sympy.parsing.sympy_parser import ( + parse_expr, standard_transformations, rationalize, TokenError, + split_symbols, implicit_multiplication, convert_equals_signs, + convert_xor, function_exponentiation, lambda_notation, auto_symbol, + repeated_decimals, implicit_multiplication_application, + auto_number, factorial_notation, implicit_application, + _transformation, T + ) + + +def test_sympy_parser(): + x = Symbol('x') + inputs = { + '2*x': 2 * x, + '3.00': Float(3), + '22/7': Rational(22, 7), + '2+3j': 2 + 3*I, + 'exp(x)': exp(x), + 'x!': factorial(x), + 'x!!': factorial2(x), + '(x + 1)! - 1': factorial(x + 1) - 1, + '3.[3]': Rational(10, 3), + '.0[3]': Rational(1, 30), + '3.2[3]': Rational(97, 30), + '1.3[12]': Rational(433, 330), + '1 + 3.[3]': Rational(13, 3), + '1 + .0[3]': Rational(31, 30), + '1 + 3.2[3]': Rational(127, 30), + '.[0011]': Rational(1, 909), + '0.1[00102] + 1': Rational(366697, 333330), + '1.[0191]': Rational(10190, 9999), + '10!': 3628800, + '-(2)': -Integer(2), + '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], + 'Symbol("x").free_symbols': x.free_symbols, + "S('S(3).n(n=3)')": Float(3, 3), + 'factorint(12, visual=True)': Mul( + Pow(2, 2, evaluate=False), + Pow(3, 1, evaluate=False), + evaluate=False), + 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), + 'Q.even(x)': Q.even(x), + + + } + for text, result in inputs.items(): + assert parse_expr(text) == result + + raises(TypeError, lambda: + parse_expr('x', standard_transformations)) + raises(TypeError, lambda: + parse_expr('x', transformations=lambda x,y: 1)) + raises(TypeError, lambda: + parse_expr('x', transformations=(lambda x,y: 1,))) + raises(TypeError, lambda: parse_expr('x', transformations=((),))) + raises(TypeError, lambda: parse_expr('x', {}, [], [])) + raises(TypeError, lambda: parse_expr('x', [], [], {})) + raises(TypeError, lambda: parse_expr('x', [], [], {})) + + +def test_rationalize(): + inputs = { + '0.123': Rational(123, 1000) + } + transformations = standard_transformations + (rationalize,) + for text, result in inputs.items(): + assert parse_expr(text, transformations=transformations) == result + + +def test_factorial_fail(): + inputs = ['x!!!', 'x!!!!', '(!)'] + + + for text in inputs: + try: + parse_expr(text) + assert False + except TokenError: + assert True + + +def test_repeated_fail(): + inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]', + '0.1[[1]]', '0x1.1[1]'] + + + # All are valid Python, so only raise TypeError for invalid indexing + for text in inputs: + raises(TypeError, lambda: parse_expr(text)) + + + inputs = ['0.1[', '0.1[1', '0.1[]'] + for text in inputs: + raises((TokenError, SyntaxError), lambda: parse_expr(text)) + + +def test_repeated_dot_only(): + assert parse_expr('.[1]') == Rational(1, 9) + assert parse_expr('1 + .[1]') == Rational(10, 9) + + +def test_local_dict(): + local_dict = { + 'my_function': lambda x: x + 2 + } + inputs = { + 'my_function(2)': Integer(4) + } + for text, result in inputs.items(): + assert parse_expr(text, local_dict=local_dict) == result + + +def test_local_dict_split_implmult(): + t = standard_transformations + (split_symbols, implicit_multiplication,) + w = Symbol('w', real=True) + y = Symbol('y') + assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w + + +def test_local_dict_symbol_to_fcn(): + x = Symbol('x') + d = {'foo': Function('bar')} + assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) + d = {'foo': Symbol('baz')} + raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d)) + + +def test_global_dict(): + global_dict = { + 'Symbol': Symbol + } + inputs = { + 'Q & S': And(Symbol('Q'), Symbol('S')) + } + for text, result in inputs.items(): + assert parse_expr(text, global_dict=global_dict) == result + + +def test_no_globals(): + + # Replicate creating the default global_dict: + default_globals = {} + exec('from sympy import *', default_globals) + builtins_dict = vars(builtins) + for name, obj in builtins_dict.items(): + if isinstance(obj, types.BuiltinFunctionType): + default_globals[name] = obj + default_globals['max'] = Max + default_globals['min'] = Min + + # Need to include Symbol or parse_expr will not work: + default_globals.pop('Symbol') + global_dict = {'Symbol':Symbol} + + for name in default_globals: + obj = parse_expr(name, global_dict=global_dict) + assert obj == Symbol(name) + + +def test_issue_2515(): + raises(TokenError, lambda: parse_expr('(()')) + raises(TokenError, lambda: parse_expr('"""')) + + +def test_issue_7663(): + x = Symbol('x') + e = '2*(x+1)' + assert parse_expr(e, evaluate=False) == parse_expr(e, evaluate=False) + assert parse_expr(e, evaluate=False).equals(2*(x+1)) + +def test_recursive_evaluate_false_10560(): + inputs = { + '4*-3' : '4*-3', + '-4*3' : '(-4)*3', + "-2*x*y": '(-2)*x*y', + "x*-4*x": "x*(-4)*x" + } + for text, result in inputs.items(): + assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) + + +def test_function_evaluate_false(): + inputs = [ + 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)', + 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)', + 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)', + 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)', + 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)', + 'exp(0)', 'log(0)', 'sqrt(0)', + ] + for case in inputs: + expr = parse_expr(case, evaluate=False) + assert case == str(expr) != str(expr.doit()) + assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)' + assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)' + + +def test_issue_10773(): + inputs = { + '-10/5': '(-10)/5', + '-10/-5' : '(-10)/(-5)', + } + for text, result in inputs.items(): + assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) + + +def test_split_symbols(): + transformations = standard_transformations + \ + (split_symbols, implicit_multiplication,) + x = Symbol('x') + y = Symbol('y') + xy = Symbol('xy') + + + assert parse_expr("xy") == xy + assert parse_expr("xy", transformations=transformations) == x*y + + +def test_split_symbols_function(): + transformations = standard_transformations + \ + (split_symbols, implicit_multiplication,) + x = Symbol('x') + y = Symbol('y') + a = Symbol('a') + f = Function('f') + + + assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) + assert parse_expr("af(x+1)", transformations=transformations, + local_dict={'f':f}) == a*f(x+1) + + +def test_functional_exponent(): + t = standard_transformations + (convert_xor, function_exponentiation) + x = Symbol('x') + y = Symbol('y') + a = Symbol('a') + yfcn = Function('y') + assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2 + assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y + assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y + assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x)) + assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x)) + + +def test_match_parentheses_implicit_multiplication(): + transformations = standard_transformations + \ + (implicit_multiplication,) + raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations)) + + +def test_convert_equals_signs(): + transformations = standard_transformations + \ + (convert_equals_signs, ) + x = Symbol('x') + y = Symbol('y') + assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x) + assert parse_expr("y = x", transformations=transformations) == Eq(y, x) + assert parse_expr("(2*y = x) = False", + transformations=transformations) == Eq(Eq(2*y, x), False) + + +def test_parse_function_issue_3539(): + x = Symbol('x') + f = Function('f') + assert parse_expr('f(x)') == f(x) + +def test_issue_24288(): + assert parse_expr("1 < 2", evaluate=False) == Lt(1, 2, evaluate=False) + assert parse_expr("1 <= 2", evaluate=False) == Le(1, 2, evaluate=False) + assert parse_expr("1 > 2", evaluate=False) == Gt(1, 2, evaluate=False) + assert parse_expr("1 >= 2", evaluate=False) == Ge(1, 2, evaluate=False) + assert parse_expr("1 != 2", evaluate=False) == Ne(1, 2, evaluate=False) + assert parse_expr("1 == 2", evaluate=False) == Eq(1, 2, evaluate=False) + assert parse_expr("1 < 2 < 3", evaluate=False) == And(Lt(1, 2, evaluate=False), Lt(2, 3, evaluate=False), evaluate=False) + assert parse_expr("1 <= 2 <= 3", evaluate=False) == And(Le(1, 2, evaluate=False), Le(2, 3, evaluate=False), evaluate=False) + assert parse_expr("1 < 2 <= 3 < 4", evaluate=False) == \ + And(Lt(1, 2, evaluate=False), Le(2, 3, evaluate=False), Lt(3, 4, evaluate=False), evaluate=False) + # Valid Python relational operators that SymPy does not decide how to handle them yet + raises(ValueError, lambda: parse_expr("1 in 2", evaluate=False)) + raises(ValueError, lambda: parse_expr("1 is 2", evaluate=False)) + raises(ValueError, lambda: parse_expr("1 not in 2", evaluate=False)) + raises(ValueError, lambda: parse_expr("1 is not 2", evaluate=False)) + +def test_split_symbols_numeric(): + transformations = ( + standard_transformations + + (implicit_multiplication_application,)) + + n = Symbol('n') + expr1 = parse_expr('2**n * 3**n') + expr2 = parse_expr('2**n3**n', transformations=transformations) + assert expr1 == expr2 == 2**n*3**n + + expr1 = parse_expr('n12n34', transformations=transformations) + assert expr1 == n*12*n*34 + + +def test_unicode_names(): + assert parse_expr('α') == Symbol('α') + + +def test_python3_features(): + assert parse_expr("123_456") == 123456 + assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495) + assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333) + assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99) + assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990) + assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000) + + +def test_issue_19501(): + x = Symbol('x') + eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=( + standard_transformations + + (implicit_multiplication_application,))) + assert eq.free_symbols == {x} + + +def test_parsing_definitions(): + from sympy.abc import x + assert len(_transformation) == 12 # if this changes, extend below + assert _transformation[0] == lambda_notation + assert _transformation[1] == auto_symbol + assert _transformation[2] == repeated_decimals + assert _transformation[3] == auto_number + assert _transformation[4] == factorial_notation + assert _transformation[5] == implicit_multiplication_application + assert _transformation[6] == convert_xor + assert _transformation[7] == implicit_application + assert _transformation[8] == implicit_multiplication + assert _transformation[9] == convert_equals_signs + assert _transformation[10] == function_exponentiation + assert _transformation[11] == rationalize + assert T[:5] == T[0,1,2,3,4] == standard_transformations + t = _transformation + assert T[-1, 0] == (t[len(t) - 1], t[0]) + assert T[:5, 8] == standard_transformations + (t[8],) + assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10 + assert parse_expr('sin 3x', transformations='implicit') == sin(3*x) + + +def test_builtins(): + cases = [ + ('abs(x)', 'Abs(x)'), + ('max(x, y)', 'Max(x, y)'), + ('min(x, y)', 'Min(x, y)'), + ('pow(x, y)', 'Pow(x, y)'), + ] + for built_in_func_call, sympy_func_call in cases: + assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call) + assert str(parse_expr('pow(38, -1, 97)')) == '23' + + +def test_issue_22822(): + raises(ValueError, lambda: parse_expr('x', {'': 1})) + data = {'some_parameter': None} + assert parse_expr('some_parameter is None', data) is True diff --git a/shared/package-files/1f/1ff79f959ef15aa9434201118a49f9fe6f7ceacdc389ba3225f3be0c3eaa781a/_pack_padded_sequence_ops.h b/shared/package-files/1f/1ff79f959ef15aa9434201118a49f9fe6f7ceacdc389ba3225f3be0c3eaa781a/_pack_padded_sequence_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cd7ab1a718363ec419f23e449e8e26d9e0174734 --- /dev/null +++ b/shared/package-files/1f/1ff79f959ef15aa9434201118a49f9fe6f7ceacdc389ba3225f3be0c3eaa781a/_pack_padded_sequence_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _pack_padded_sequence { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_pack_padded_sequence"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & input, const at::Tensor & lengths, bool batch_first); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & lengths, bool batch_first); +}; + +struct TORCH_API _pack_padded_sequence_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_pack_padded_sequence"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_pack_padded_sequence.out(Tensor input, Tensor lengths, bool batch_first, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))"; + static ::std::tuple call(const at::Tensor & input, const at::Tensor & lengths, bool batch_first, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & lengths, bool batch_first, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/1f/1fffb88b0db56b649a6bc1da32cb25386f43bbf4cde3dd9c3861ddfc1caebd70/_unsafe_index_put_compositeexplicitautograd_dispatch.h b/shared/package-files/1f/1fffb88b0db56b649a6bc1da32cb25386f43bbf4cde3dd9c3861ddfc1caebd70/_unsafe_index_put_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..05b1d3e81464e4b31846e5694dcd1fee210069ee --- /dev/null +++ b/shared/package-files/1f/1fffb88b0db56b649a6bc1da32cb25386f43bbf4cde3dd9c3861ddfc1caebd70/_unsafe_index_put_compositeexplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor _unsafe_index_put(const at::Tensor & self, const c10::List<::std::optional> & indices, const at::Tensor & values, bool accumulate=false); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/2c/2c0e7e7714c8768ebc4d552af882029b2e61b2e595b84d8a3e2e81574d5a345b/__init__.cpython-311.pyc b/shared/package-files/2c/2c0e7e7714c8768ebc4d552af882029b2e61b2e595b84d8a3e2e81574d5a345b/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc385d9ca85b071f3031bfe4595989c556297d13 Binary files /dev/null and b/shared/package-files/2c/2c0e7e7714c8768ebc4d552af882029b2e61b2e595b84d8a3e2e81574d5a345b/__init__.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c3b5360e6a7e71191d816c84782e2cbd327056a0328084f7c53dc818c734a45/__init__.cpython-311.pyc b/shared/package-files/2c/2c3b5360e6a7e71191d816c84782e2cbd327056a0328084f7c53dc818c734a45/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d62d0ba68f082d40c1e263229181a201b99aac7 Binary files /dev/null and b/shared/package-files/2c/2c3b5360e6a7e71191d816c84782e2cbd327056a0328084f7c53dc818c734a45/__init__.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c4129a5cfdfc2990796a790c4057cc81154ec6d9012b54c8517a60c2d9ec027/uniform_cpu_dispatch.h b/shared/package-files/2c/2c4129a5cfdfc2990796a790c4057cc81154ec6d9012b54c8517a60c2d9ec027/uniform_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e17a1e82433565be67befe802a9d2b24d073a821 --- /dev/null +++ b/shared/package-files/2c/2c4129a5cfdfc2990796a790c4057cc81154ec6d9012b54c8517a60c2d9ec027/uniform_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor & uniform_(at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/2c/2c452d744d1a5e40dc61737223fd7d19c96878505c7b50636fa988addc354afa/handlers.py b/shared/package-files/2c/2c452d744d1a5e40dc61737223fd7d19c96878505c7b50636fa988addc354afa/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..8c40fa04a4968e591448922ede7d61c88cd3e488 --- /dev/null +++ b/shared/package-files/2c/2c452d744d1a5e40dc61737223fd7d19c96878505c7b50636fa988addc354afa/handlers.py @@ -0,0 +1,1604 @@ +# Copyright 2001-2021 by Vinay Sajip. All Rights Reserved. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee is hereby granted, +# provided that the above copyright notice appear in all copies and that +# both that copyright notice and this permission notice appear in +# supporting documentation, and that the name of Vinay Sajip +# not be used in advertising or publicity pertaining to distribution +# of the software without specific, written prior permission. +# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +""" +Additional handlers for the logging package for Python. The core package is +based on PEP 282 and comments thereto in comp.lang.python. + +Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved. + +To use, simply 'import logging.handlers' and log away! +""" + +import io, logging, socket, os, pickle, struct, time, re +from stat import ST_DEV, ST_INO, ST_MTIME +import queue +import threading +import copy + +# +# Some constants... +# + +DEFAULT_TCP_LOGGING_PORT = 9020 +DEFAULT_UDP_LOGGING_PORT = 9021 +DEFAULT_HTTP_LOGGING_PORT = 9022 +DEFAULT_SOAP_LOGGING_PORT = 9023 +SYSLOG_UDP_PORT = 514 +SYSLOG_TCP_PORT = 514 + +_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day + +class BaseRotatingHandler(logging.FileHandler): + """ + Base class for handlers that rotate log files at a certain point. + Not meant to be instantiated directly. Instead, use RotatingFileHandler + or TimedRotatingFileHandler. + """ + namer = None + rotator = None + + def __init__(self, filename, mode, encoding=None, delay=False, errors=None): + """ + Use the specified filename for streamed logging + """ + logging.FileHandler.__init__(self, filename, mode=mode, + encoding=encoding, delay=delay, + errors=errors) + self.mode = mode + self.encoding = encoding + self.errors = errors + + def emit(self, record): + """ + Emit a record. + + Output the record to the file, catering for rollover as described + in doRollover(). + """ + try: + if self.shouldRollover(record): + self.doRollover() + logging.FileHandler.emit(self, record) + except Exception: + self.handleError(record) + + def rotation_filename(self, default_name): + """ + Modify the filename of a log file when rotating. + + This is provided so that a custom filename can be provided. + + The default implementation calls the 'namer' attribute of the + handler, if it's callable, passing the default name to + it. If the attribute isn't callable (the default is None), the name + is returned unchanged. + + :param default_name: The default name for the log file. + """ + if not callable(self.namer): + result = default_name + else: + result = self.namer(default_name) + return result + + def rotate(self, source, dest): + """ + When rotating, rotate the current log. + + The default implementation calls the 'rotator' attribute of the + handler, if it's callable, passing the source and dest arguments to + it. If the attribute isn't callable (the default is None), the source + is simply renamed to the destination. + + :param source: The source filename. This is normally the base + filename, e.g. 'test.log' + :param dest: The destination filename. This is normally + what the source is rotated to, e.g. 'test.log.1'. + """ + if not callable(self.rotator): + # Issue 18940: A file may not have been created if delay is True. + if os.path.exists(source): + os.rename(source, dest) + else: + self.rotator(source, dest) + +class RotatingFileHandler(BaseRotatingHandler): + """ + Handler for logging to a set of files, which switches from one file + to the next when the current file reaches a certain size. + """ + def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, + encoding=None, delay=False, errors=None): + """ + Open the specified file and use it as the stream for logging. + + By default, the file grows indefinitely. You can specify particular + values of maxBytes and backupCount to allow the file to rollover at + a predetermined size. + + Rollover occurs whenever the current log file is nearly maxBytes in + length. If backupCount is >= 1, the system will successively create + new files with the same pathname as the base file, but with extensions + ".1", ".2" etc. appended to it. For example, with a backupCount of 5 + and a base file name of "app.log", you would get "app.log", + "app.log.1", "app.log.2", ... through to "app.log.5". The file being + written to is always "app.log" - when it gets filled up, it is closed + and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. + exist, then they are renamed to "app.log.2", "app.log.3" etc. + respectively. + + If maxBytes is zero, rollover never occurs. + """ + # If rotation/rollover is wanted, it doesn't make sense to use another + # mode. If for example 'w' were specified, then if there were multiple + # runs of the calling application, the logs from previous runs would be + # lost if the 'w' is respected, because the log file would be truncated + # on each run. + if maxBytes > 0: + mode = 'a' + if "b" not in mode: + encoding = io.text_encoding(encoding) + BaseRotatingHandler.__init__(self, filename, mode, encoding=encoding, + delay=delay, errors=errors) + self.maxBytes = maxBytes + self.backupCount = backupCount + + def doRollover(self): + """ + Do a rollover, as described in __init__(). + """ + if self.stream: + self.stream.close() + self.stream = None + if self.backupCount > 0: + for i in range(self.backupCount - 1, 0, -1): + sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i)) + dfn = self.rotation_filename("%s.%d" % (self.baseFilename, + i + 1)) + if os.path.exists(sfn): + if os.path.exists(dfn): + os.remove(dfn) + os.rename(sfn, dfn) + dfn = self.rotation_filename(self.baseFilename + ".1") + if os.path.exists(dfn): + os.remove(dfn) + self.rotate(self.baseFilename, dfn) + if not self.delay: + self.stream = self._open() + + def shouldRollover(self, record): + """ + Determine if rollover should occur. + + Basically, see if the supplied record would cause the file to exceed + the size limit we have. + """ + # See bpo-45401: Never rollover anything other than regular files + if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename): + return False + if self.stream is None: # delay was set... + self.stream = self._open() + if self.maxBytes > 0: # are we rolling over? + msg = "%s\n" % self.format(record) + self.stream.seek(0, 2) #due to non-posix-compliant Windows feature + if self.stream.tell() + len(msg) >= self.maxBytes: + return True + return False + +class TimedRotatingFileHandler(BaseRotatingHandler): + """ + Handler for logging to a file, rotating the log file at certain timed + intervals. + + If backupCount is > 0, when rollover is done, no more than backupCount + files are kept - the oldest ones are deleted. + """ + def __init__(self, filename, when='h', interval=1, backupCount=0, + encoding=None, delay=False, utc=False, atTime=None, + errors=None): + encoding = io.text_encoding(encoding) + BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding, + delay=delay, errors=errors) + self.when = when.upper() + self.backupCount = backupCount + self.utc = utc + self.atTime = atTime + # Calculate the real rollover interval, which is just the number of + # seconds between rollovers. Also set the filename suffix used when + # a rollover occurs. Current 'when' events supported: + # S - Seconds + # M - Minutes + # H - Hours + # D - Days + # midnight - roll over at midnight + # W{0-6} - roll over on a certain day; 0 - Monday + # + # Case of the 'when' specifier is not important; lower or upper case + # will work. + if self.when == 'S': + self.interval = 1 # one second + self.suffix = "%Y-%m-%d_%H-%M-%S" + extMatch = r"(? '6': + raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) + self.dayOfWeek = int(self.when[1]) + self.suffix = "%Y-%m-%d" + extMatch = r"(?= self.rolloverAt: + # See #89564: Never rollover anything other than regular files + if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename): + # The file is not a regular file, so do not rollover, but do + # set the next rollover time to avoid repeated checks. + self.rolloverAt = self.computeRollover(t) + return False + + return True + return False + + def getFilesToDelete(self): + """ + Determine the files to delete when rolling over. + + More specific than the earlier method, which just used glob.glob(). + """ + dirName, baseName = os.path.split(self.baseFilename) + fileNames = os.listdir(dirName) + result = [] + if self.namer is None: + prefix = baseName + '.' + plen = len(prefix) + for fileName in fileNames: + if fileName[:plen] == prefix: + suffix = fileName[plen:] + if self.extMatch.fullmatch(suffix): + result.append(os.path.join(dirName, fileName)) + else: + for fileName in fileNames: + # Our files could be just about anything after custom naming, + # but they should contain the datetime suffix. + # Try to find the datetime suffix in the file name and verify + # that the file name can be generated by this handler. + m = self.extMatch.search(fileName) + while m: + dfn = self.namer(self.baseFilename + "." + m[0]) + if os.path.basename(dfn) == fileName: + result.append(os.path.join(dirName, fileName)) + break + m = self.extMatch.search(fileName, m.start() + 1) + + if len(result) < self.backupCount: + result = [] + else: + result.sort() + result = result[:len(result) - self.backupCount] + return result + + def doRollover(self): + """ + do a rollover; in this case, a date/time stamp is appended to the filename + when the rollover happens. However, you want the file to be named for the + start of the interval, not the current time. If there is a backup count, + then we have to get a list of matching filenames, sort them and remove + the one with the oldest suffix. + """ + # get the time that this sequence started at and make it a TimeTuple + currentTime = int(time.time()) + t = self.rolloverAt - self.interval + if self.utc: + timeTuple = time.gmtime(t) + else: + timeTuple = time.localtime(t) + dstNow = time.localtime(currentTime)[-1] + dstThen = timeTuple[-1] + if dstNow != dstThen: + if dstNow: + addend = 3600 + else: + addend = -3600 + timeTuple = time.localtime(t + addend) + dfn = self.rotation_filename(self.baseFilename + "." + + time.strftime(self.suffix, timeTuple)) + if os.path.exists(dfn): + # Already rolled over. + return + + if self.stream: + self.stream.close() + self.stream = None + self.rotate(self.baseFilename, dfn) + if self.backupCount > 0: + for s in self.getFilesToDelete(): + os.remove(s) + if not self.delay: + self.stream = self._open() + self.rolloverAt = self.computeRollover(currentTime) + +class WatchedFileHandler(logging.FileHandler): + """ + A handler for logging to a file, which watches the file + to see if it has changed while in use. This can happen because of + usage of programs such as newsyslog and logrotate which perform + log file rotation. This handler, intended for use under Unix, + watches the file to see if it has changed since the last emit. + (A file has changed if its device or inode have changed.) + If it has changed, the old file stream is closed, and the file + opened to get a new stream. + + This handler is not appropriate for use under Windows, because + under Windows open files cannot be moved or renamed - logging + opens the files with exclusive locks - and so there is no need + for such a handler. Furthermore, ST_INO is not supported under + Windows; stat always returns zero for this value. + + This handler is based on a suggestion and patch by Chad J. + Schroeder. + """ + def __init__(self, filename, mode='a', encoding=None, delay=False, + errors=None): + if "b" not in mode: + encoding = io.text_encoding(encoding) + logging.FileHandler.__init__(self, filename, mode=mode, + encoding=encoding, delay=delay, + errors=errors) + self.dev, self.ino = -1, -1 + self._statstream() + + def _statstream(self): + if self.stream: + sres = os.fstat(self.stream.fileno()) + self.dev, self.ino = sres[ST_DEV], sres[ST_INO] + + def reopenIfNeeded(self): + """ + Reopen log file if needed. + + Checks if the underlying file has changed, and if it + has, close the old stream and reopen the file to get the + current stream. + """ + # Reduce the chance of race conditions by stat'ing by path only + # once and then fstat'ing our new fd if we opened a new log stream. + # See issue #14632: Thanks to John Mulligan for the problem report + # and patch. + try: + # stat the file by path, checking for existence + sres = os.stat(self.baseFilename) + except FileNotFoundError: + sres = None + # compare file system stat with that of our stream file handle + if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: + if self.stream is not None: + # we have an open file handle, clean it up + self.stream.flush() + self.stream.close() + self.stream = None # See Issue #21742: _open () might fail. + # open a new file handle and get new stat info from that fd + self.stream = self._open() + self._statstream() + + def emit(self, record): + """ + Emit a record. + + If underlying file has changed, reopen the file before emitting the + record to it. + """ + self.reopenIfNeeded() + logging.FileHandler.emit(self, record) + + +class SocketHandler(logging.Handler): + """ + A handler class which writes logging records, in pickle format, to + a streaming socket. The socket is kept open across logging calls. + If the peer resets it, an attempt is made to reconnect on the next call. + The pickle which is sent is that of the LogRecord's attribute dictionary + (__dict__), so that the receiver does not need to have the logging module + installed in order to process the logging event. + + To unpickle the record at the receiving end into a LogRecord, use the + makeLogRecord function. + """ + + def __init__(self, host, port): + """ + Initializes the handler with a specific host address and port. + + When the attribute *closeOnError* is set to True - if a socket error + occurs, the socket is silently closed and then reopened on the next + logging call. + """ + logging.Handler.__init__(self) + self.host = host + self.port = port + if port is None: + self.address = host + else: + self.address = (host, port) + self.sock = None + self.closeOnError = False + self.retryTime = None + # + # Exponential backoff parameters. + # + self.retryStart = 1.0 + self.retryMax = 30.0 + self.retryFactor = 2.0 + + def makeSocket(self, timeout=1): + """ + A factory method which allows subclasses to define the precise + type of socket they want. + """ + if self.port is not None: + result = socket.create_connection(self.address, timeout=timeout) + else: + result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + result.settimeout(timeout) + try: + result.connect(self.address) + except OSError: + result.close() # Issue 19182 + raise + return result + + def createSocket(self): + """ + Try to create a socket, using an exponential backoff with + a max retry time. Thanks to Robert Olson for the original patch + (SF #815911) which has been slightly refactored. + """ + now = time.time() + # Either retryTime is None, in which case this + # is the first time back after a disconnect, or + # we've waited long enough. + if self.retryTime is None: + attempt = True + else: + attempt = (now >= self.retryTime) + if attempt: + try: + self.sock = self.makeSocket() + self.retryTime = None # next time, no delay before trying + except OSError: + #Creation failed, so set the retry time and return. + if self.retryTime is None: + self.retryPeriod = self.retryStart + else: + self.retryPeriod = self.retryPeriod * self.retryFactor + if self.retryPeriod > self.retryMax: + self.retryPeriod = self.retryMax + self.retryTime = now + self.retryPeriod + + def send(self, s): + """ + Send a pickled string to the socket. + + This function allows for partial sends which can happen when the + network is busy. + """ + if self.sock is None: + self.createSocket() + #self.sock can be None either because we haven't reached the retry + #time yet, or because we have reached the retry time and retried, + #but are still unable to connect. + if self.sock: + try: + self.sock.sendall(s) + except OSError: #pragma: no cover + self.sock.close() + self.sock = None # so we can call createSocket next time + + def makePickle(self, record): + """ + Pickles the record in binary format with a length prefix, and + returns it ready for transmission across the socket. + """ + ei = record.exc_info + if ei: + # just to get traceback text into record.exc_text ... + dummy = self.format(record) + # See issue #14436: If msg or args are objects, they may not be + # available on the receiving end. So we convert the msg % args + # to a string, save it as msg and zap the args. + d = dict(record.__dict__) + d['msg'] = record.getMessage() + d['args'] = None + d['exc_info'] = None + # Issue #25685: delete 'message' if present: redundant with 'msg' + d.pop('message', None) + s = pickle.dumps(d, 1) + slen = struct.pack(">L", len(s)) + return slen + s + + def handleError(self, record): + """ + Handle an error during logging. + + An error has occurred during logging. Most likely cause - + connection lost. Close the socket so that we can retry on the + next event. + """ + if self.closeOnError and self.sock: + self.sock.close() + self.sock = None #try to reconnect next time + else: + logging.Handler.handleError(self, record) + + def emit(self, record): + """ + Emit a record. + + Pickles the record and writes it to the socket in binary format. + If there is an error with the socket, silently drop the packet. + If there was a problem with the socket, re-establishes the + socket. + """ + try: + s = self.makePickle(record) + self.send(s) + except Exception: + self.handleError(record) + + def close(self): + """ + Closes the socket. + """ + self.acquire() + try: + sock = self.sock + if sock: + self.sock = None + sock.close() + logging.Handler.close(self) + finally: + self.release() + +class DatagramHandler(SocketHandler): + """ + A handler class which writes logging records, in pickle format, to + a datagram socket. The pickle which is sent is that of the LogRecord's + attribute dictionary (__dict__), so that the receiver does not need to + have the logging module installed in order to process the logging event. + + To unpickle the record at the receiving end into a LogRecord, use the + makeLogRecord function. + + """ + def __init__(self, host, port): + """ + Initializes the handler with a specific host address and port. + """ + SocketHandler.__init__(self, host, port) + self.closeOnError = False + + def makeSocket(self): + """ + The factory method of SocketHandler is here overridden to create + a UDP socket (SOCK_DGRAM). + """ + if self.port is None: + family = socket.AF_UNIX + else: + family = socket.AF_INET + s = socket.socket(family, socket.SOCK_DGRAM) + return s + + def send(self, s): + """ + Send a pickled string to a socket. + + This function no longer allows for partial sends which can happen + when the network is busy - UDP does not guarantee delivery and + can deliver packets out of sequence. + """ + if self.sock is None: + self.createSocket() + self.sock.sendto(s, self.address) + +class SysLogHandler(logging.Handler): + """ + A handler class which sends formatted logging records to a syslog + server. Based on Sam Rushing's syslog module: + http://www.nightmare.com/squirl/python-ext/misc/syslog.py + Contributed by Nicolas Untz (after which minor refactoring changes + have been made). + """ + + # from : + # ====================================================================== + # priorities/facilities are encoded into a single 32-bit quantity, where + # the bottom 3 bits are the priority (0-7) and the top 28 bits are the + # facility (0-big number). Both the priorities and the facilities map + # roughly one-to-one to strings in the syslogd(8) source code. This + # mapping is included in this file. + # + # priorities (these are ordered) + + LOG_EMERG = 0 # system is unusable + LOG_ALERT = 1 # action must be taken immediately + LOG_CRIT = 2 # critical conditions + LOG_ERR = 3 # error conditions + LOG_WARNING = 4 # warning conditions + LOG_NOTICE = 5 # normal but significant condition + LOG_INFO = 6 # informational + LOG_DEBUG = 7 # debug-level messages + + # facility codes + LOG_KERN = 0 # kernel messages + LOG_USER = 1 # random user-level messages + LOG_MAIL = 2 # mail system + LOG_DAEMON = 3 # system daemons + LOG_AUTH = 4 # security/authorization messages + LOG_SYSLOG = 5 # messages generated internally by syslogd + LOG_LPR = 6 # line printer subsystem + LOG_NEWS = 7 # network news subsystem + LOG_UUCP = 8 # UUCP subsystem + LOG_CRON = 9 # clock daemon + LOG_AUTHPRIV = 10 # security/authorization messages (private) + LOG_FTP = 11 # FTP daemon + LOG_NTP = 12 # NTP subsystem + LOG_SECURITY = 13 # Log audit + LOG_CONSOLE = 14 # Log alert + LOG_SOLCRON = 15 # Scheduling daemon (Solaris) + + # other codes through 15 reserved for system use + LOG_LOCAL0 = 16 # reserved for local use + LOG_LOCAL1 = 17 # reserved for local use + LOG_LOCAL2 = 18 # reserved for local use + LOG_LOCAL3 = 19 # reserved for local use + LOG_LOCAL4 = 20 # reserved for local use + LOG_LOCAL5 = 21 # reserved for local use + LOG_LOCAL6 = 22 # reserved for local use + LOG_LOCAL7 = 23 # reserved for local use + + priority_names = { + "alert": LOG_ALERT, + "crit": LOG_CRIT, + "critical": LOG_CRIT, + "debug": LOG_DEBUG, + "emerg": LOG_EMERG, + "err": LOG_ERR, + "error": LOG_ERR, # DEPRECATED + "info": LOG_INFO, + "notice": LOG_NOTICE, + "panic": LOG_EMERG, # DEPRECATED + "warn": LOG_WARNING, # DEPRECATED + "warning": LOG_WARNING, + } + + facility_names = { + "auth": LOG_AUTH, + "authpriv": LOG_AUTHPRIV, + "console": LOG_CONSOLE, + "cron": LOG_CRON, + "daemon": LOG_DAEMON, + "ftp": LOG_FTP, + "kern": LOG_KERN, + "lpr": LOG_LPR, + "mail": LOG_MAIL, + "news": LOG_NEWS, + "ntp": LOG_NTP, + "security": LOG_SECURITY, + "solaris-cron": LOG_SOLCRON, + "syslog": LOG_SYSLOG, + "user": LOG_USER, + "uucp": LOG_UUCP, + "local0": LOG_LOCAL0, + "local1": LOG_LOCAL1, + "local2": LOG_LOCAL2, + "local3": LOG_LOCAL3, + "local4": LOG_LOCAL4, + "local5": LOG_LOCAL5, + "local6": LOG_LOCAL6, + "local7": LOG_LOCAL7, + } + + # Originally added to work around GH-43683. Unnecessary since GH-50043 but kept + # for backwards compatibility. + priority_map = { + "DEBUG" : "debug", + "INFO" : "info", + "WARNING" : "warning", + "ERROR" : "error", + "CRITICAL" : "critical" + } + + def __init__(self, address=('localhost', SYSLOG_UDP_PORT), + facility=LOG_USER, socktype=None): + """ + Initialize a handler. + + If address is specified as a string, a UNIX socket is used. To log to a + local syslogd, "SysLogHandler(address="/dev/log")" can be used. + If facility is not specified, LOG_USER is used. If socktype is + specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific + socket type will be used. For Unix sockets, you can also specify a + socktype of None, in which case socket.SOCK_DGRAM will be used, falling + back to socket.SOCK_STREAM. + """ + logging.Handler.__init__(self) + + self.address = address + self.facility = facility + self.socktype = socktype + self.socket = None + self.createSocket() + + def _connect_unixsocket(self, address): + use_socktype = self.socktype + if use_socktype is None: + use_socktype = socket.SOCK_DGRAM + self.socket = socket.socket(socket.AF_UNIX, use_socktype) + try: + self.socket.connect(address) + # it worked, so set self.socktype to the used type + self.socktype = use_socktype + except OSError: + self.socket.close() + if self.socktype is not None: + # user didn't specify falling back, so fail + raise + use_socktype = socket.SOCK_STREAM + self.socket = socket.socket(socket.AF_UNIX, use_socktype) + try: + self.socket.connect(address) + # it worked, so set self.socktype to the used type + self.socktype = use_socktype + except OSError: + self.socket.close() + raise + + def createSocket(self): + """ + Try to create a socket and, if it's not a datagram socket, connect it + to the other end. This method is called during handler initialization, + but it's not regarded as an error if the other end isn't listening yet + --- the method will be called again when emitting an event, + if there is no socket at that point. + """ + address = self.address + socktype = self.socktype + + if isinstance(address, str): + self.unixsocket = True + # Syslog server may be unavailable during handler initialisation. + # C's openlog() function also ignores connection errors. + # Moreover, we ignore these errors while logging, so it's not worse + # to ignore it also here. + try: + self._connect_unixsocket(address) + except OSError: + pass + else: + self.unixsocket = False + if socktype is None: + socktype = socket.SOCK_DGRAM + host, port = address + ress = socket.getaddrinfo(host, port, 0, socktype) + if not ress: + raise OSError("getaddrinfo returns an empty list") + for res in ress: + af, socktype, proto, _, sa = res + err = sock = None + try: + sock = socket.socket(af, socktype, proto) + if socktype == socket.SOCK_STREAM: + sock.connect(sa) + break + except OSError as exc: + err = exc + if sock is not None: + sock.close() + if err is not None: + raise err + self.socket = sock + self.socktype = socktype + + def encodePriority(self, facility, priority): + """ + Encode the facility and priority. You can pass in strings or + integers - if strings are passed, the facility_names and + priority_names mapping dictionaries are used to convert them to + integers. + """ + if isinstance(facility, str): + facility = self.facility_names[facility] + if isinstance(priority, str): + priority = self.priority_names[priority] + return (facility << 3) | priority + + def close(self): + """ + Closes the socket. + """ + self.acquire() + try: + sock = self.socket + if sock: + self.socket = None + sock.close() + logging.Handler.close(self) + finally: + self.release() + + def mapPriority(self, levelName): + """ + Map a logging level name to a key in the priority_names map. + This is useful in two scenarios: when custom levels are being + used, and in the case where you can't do a straightforward + mapping by lowercasing the logging level name because of locale- + specific issues (see SF #1524081). + """ + return self.priority_map.get(levelName, "warning") + + ident = '' # prepended to all messages + append_nul = True # some old syslog daemons expect a NUL terminator + + def emit(self, record): + """ + Emit a record. + + The record is formatted, and then sent to the syslog server. If + exception information is present, it is NOT sent to the server. + """ + try: + msg = self.format(record) + if self.ident: + msg = self.ident + msg + if self.append_nul: + msg += '\000' + + # We need to convert record level to lowercase, maybe this will + # change in the future. + prio = '<%d>' % self.encodePriority(self.facility, + self.mapPriority(record.levelname)) + prio = prio.encode('utf-8') + # Message is a string. Convert to bytes as required by RFC 5424 + msg = msg.encode('utf-8') + msg = prio + msg + + if not self.socket: + self.createSocket() + + if self.unixsocket: + try: + self.socket.send(msg) + except OSError: + self.socket.close() + self._connect_unixsocket(self.address) + self.socket.send(msg) + elif self.socktype == socket.SOCK_DGRAM: + self.socket.sendto(msg, self.address) + else: + self.socket.sendall(msg) + except Exception: + self.handleError(record) + +class SMTPHandler(logging.Handler): + """ + A handler class which sends an SMTP email for each logging event. + """ + def __init__(self, mailhost, fromaddr, toaddrs, subject, + credentials=None, secure=None, timeout=5.0): + """ + Initialize the handler. + + Initialize the instance with the from and to addresses and subject + line of the email. To specify a non-standard SMTP port, use the + (host, port) tuple format for the mailhost argument. To specify + authentication credentials, supply a (username, password) tuple + for the credentials argument. To specify the use of a secure + protocol (TLS), pass in a tuple for the secure argument. This will + only be used when authentication credentials are supplied. The tuple + will be either an empty tuple, or a single-value tuple with the name + of a keyfile, or a 2-value tuple with the names of the keyfile and + certificate file. (This tuple is passed to the `starttls` method). + A timeout in seconds can be specified for the SMTP connection (the + default is one second). + """ + logging.Handler.__init__(self) + if isinstance(mailhost, (list, tuple)): + self.mailhost, self.mailport = mailhost + else: + self.mailhost, self.mailport = mailhost, None + if isinstance(credentials, (list, tuple)): + self.username, self.password = credentials + else: + self.username = None + self.fromaddr = fromaddr + if isinstance(toaddrs, str): + toaddrs = [toaddrs] + self.toaddrs = toaddrs + self.subject = subject + self.secure = secure + self.timeout = timeout + + def getSubject(self, record): + """ + Determine the subject for the email. + + If you want to specify a subject line which is record-dependent, + override this method. + """ + return self.subject + + def emit(self, record): + """ + Emit a record. + + Format the record and send it to the specified addressees. + """ + try: + import smtplib + from email.message import EmailMessage + import email.utils + + port = self.mailport + if not port: + port = smtplib.SMTP_PORT + smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) + msg = EmailMessage() + msg['From'] = self.fromaddr + msg['To'] = ','.join(self.toaddrs) + msg['Subject'] = self.getSubject(record) + msg['Date'] = email.utils.localtime() + msg.set_content(self.format(record)) + if self.username: + if self.secure is not None: + smtp.ehlo() + smtp.starttls(*self.secure) + smtp.ehlo() + smtp.login(self.username, self.password) + smtp.send_message(msg) + smtp.quit() + except Exception: + self.handleError(record) + +class NTEventLogHandler(logging.Handler): + """ + A handler class which sends events to the NT Event Log. Adds a + registry entry for the specified application name. If no dllname is + provided, win32service.pyd (which contains some basic message + placeholders) is used. Note that use of these placeholders will make + your event logs big, as the entire message source is held in the log. + If you want slimmer logs, you have to pass in the name of your own DLL + which contains the message definitions you want to use in the event log. + """ + def __init__(self, appname, dllname=None, logtype="Application"): + logging.Handler.__init__(self) + try: + import win32evtlogutil, win32evtlog + self.appname = appname + self._welu = win32evtlogutil + if not dllname: + dllname = os.path.split(self._welu.__file__) + dllname = os.path.split(dllname[0]) + dllname = os.path.join(dllname[0], r'win32service.pyd') + self.dllname = dllname + self.logtype = logtype + # Administrative privileges are required to add a source to the registry. + # This may not be available for a user that just wants to add to an + # existing source - handle this specific case. + try: + self._welu.AddSourceToRegistry(appname, dllname, logtype) + except Exception as e: + # This will probably be a pywintypes.error. Only raise if it's not + # an "access denied" error, else let it pass + if getattr(e, 'winerror', None) != 5: # not access denied + raise + self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE + self.typemap = { + logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, + logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, + logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, + logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, + logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, + } + except ImportError: + print("The Python Win32 extensions for NT (service, event "\ + "logging) appear not to be available.") + self._welu = None + + def getMessageID(self, record): + """ + Return the message ID for the event record. If you are using your + own messages, you could do this by having the msg passed to the + logger being an ID rather than a formatting string. Then, in here, + you could use a dictionary lookup to get the message ID. This + version returns 1, which is the base message ID in win32service.pyd. + """ + return 1 + + def getEventCategory(self, record): + """ + Return the event category for the record. + + Override this if you want to specify your own categories. This version + returns 0. + """ + return 0 + + def getEventType(self, record): + """ + Return the event type for the record. + + Override this if you want to specify your own types. This version does + a mapping using the handler's typemap attribute, which is set up in + __init__() to a dictionary which contains mappings for DEBUG, INFO, + WARNING, ERROR and CRITICAL. If you are using your own levels you will + either need to override this method or place a suitable dictionary in + the handler's typemap attribute. + """ + return self.typemap.get(record.levelno, self.deftype) + + def emit(self, record): + """ + Emit a record. + + Determine the message ID, event category and event type. Then + log the message in the NT event log. + """ + if self._welu: + try: + id = self.getMessageID(record) + cat = self.getEventCategory(record) + type = self.getEventType(record) + msg = self.format(record) + self._welu.ReportEvent(self.appname, id, cat, type, [msg]) + except Exception: + self.handleError(record) + + def close(self): + """ + Clean up this handler. + + You can remove the application name from the registry as a + source of event log entries. However, if you do this, you will + not be able to see the events as you intended in the Event Log + Viewer - it needs to be able to access the registry to get the + DLL name. + """ + #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) + logging.Handler.close(self) + +class HTTPHandler(logging.Handler): + """ + A class which sends records to a web server, using either GET or + POST semantics. + """ + def __init__(self, host, url, method="GET", secure=False, credentials=None, + context=None): + """ + Initialize the instance with the host, the request URL, and the method + ("GET" or "POST") + """ + logging.Handler.__init__(self) + method = method.upper() + if method not in ["GET", "POST"]: + raise ValueError("method must be GET or POST") + if not secure and context is not None: + raise ValueError("context parameter only makes sense " + "with secure=True") + self.host = host + self.url = url + self.method = method + self.secure = secure + self.credentials = credentials + self.context = context + + def mapLogRecord(self, record): + """ + Default implementation of mapping the log record into a dict + that is sent as the CGI data. Overwrite in your class. + Contributed by Franz Glasner. + """ + return record.__dict__ + + def getConnection(self, host, secure): + """ + get a HTTP[S]Connection. + + Override when a custom connection is required, for example if + there is a proxy. + """ + import http.client + if secure: + connection = http.client.HTTPSConnection(host, context=self.context) + else: + connection = http.client.HTTPConnection(host) + return connection + + def emit(self, record): + """ + Emit a record. + + Send the record to the web server as a percent-encoded dictionary + """ + try: + import urllib.parse + host = self.host + h = self.getConnection(host, self.secure) + url = self.url + data = urllib.parse.urlencode(self.mapLogRecord(record)) + if self.method == "GET": + if (url.find('?') >= 0): + sep = '&' + else: + sep = '?' + url = url + "%c%s" % (sep, data) + h.putrequest(self.method, url) + # support multiple hosts on one IP address... + # need to strip optional :port from host, if present + i = host.find(":") + if i >= 0: + host = host[:i] + # See issue #30904: putrequest call above already adds this header + # on Python 3.x. + # h.putheader("Host", host) + if self.method == "POST": + h.putheader("Content-type", + "application/x-www-form-urlencoded") + h.putheader("Content-length", str(len(data))) + if self.credentials: + import base64 + s = ('%s:%s' % self.credentials).encode('utf-8') + s = 'Basic ' + base64.b64encode(s).strip().decode('ascii') + h.putheader('Authorization', s) + h.endheaders() + if self.method == "POST": + h.send(data.encode('utf-8')) + h.getresponse() #can't do anything with the result + except Exception: + self.handleError(record) + +class BufferingHandler(logging.Handler): + """ + A handler class which buffers logging records in memory. Whenever each + record is added to the buffer, a check is made to see if the buffer should + be flushed. If it should, then flush() is expected to do what's needed. + """ + def __init__(self, capacity): + """ + Initialize the handler with the buffer size. + """ + logging.Handler.__init__(self) + self.capacity = capacity + self.buffer = [] + + def shouldFlush(self, record): + """ + Should the handler flush its buffer? + + Returns true if the buffer is up to capacity. This method can be + overridden to implement custom flushing strategies. + """ + return (len(self.buffer) >= self.capacity) + + def emit(self, record): + """ + Emit a record. + + Append the record. If shouldFlush() tells us to, call flush() to process + the buffer. + """ + self.buffer.append(record) + if self.shouldFlush(record): + self.flush() + + def flush(self): + """ + Override to implement custom flushing behaviour. + + This version just zaps the buffer to empty. + """ + self.acquire() + try: + self.buffer.clear() + finally: + self.release() + + def close(self): + """ + Close the handler. + + This version just flushes and chains to the parent class' close(). + """ + try: + self.flush() + finally: + logging.Handler.close(self) + +class MemoryHandler(BufferingHandler): + """ + A handler class which buffers logging records in memory, periodically + flushing them to a target handler. Flushing occurs whenever the buffer + is full, or when an event of a certain severity or greater is seen. + """ + def __init__(self, capacity, flushLevel=logging.ERROR, target=None, + flushOnClose=True): + """ + Initialize the handler with the buffer size, the level at which + flushing should occur and an optional target. + + Note that without a target being set either here or via setTarget(), + a MemoryHandler is no use to anyone! + + The ``flushOnClose`` argument is ``True`` for backward compatibility + reasons - the old behaviour is that when the handler is closed, the + buffer is flushed, even if the flush level hasn't been exceeded nor the + capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. + """ + BufferingHandler.__init__(self, capacity) + self.flushLevel = flushLevel + self.target = target + # See Issue #26559 for why this has been added + self.flushOnClose = flushOnClose + + def shouldFlush(self, record): + """ + Check for buffer full or a record at the flushLevel or higher. + """ + return (len(self.buffer) >= self.capacity) or \ + (record.levelno >= self.flushLevel) + + def setTarget(self, target): + """ + Set the target handler for this handler. + """ + self.acquire() + try: + self.target = target + finally: + self.release() + + def flush(self): + """ + For a MemoryHandler, flushing means just sending the buffered + records to the target, if there is one. Override if you want + different behaviour. + + The record buffer is only cleared if a target has been set. + """ + self.acquire() + try: + if self.target: + for record in self.buffer: + self.target.handle(record) + self.buffer.clear() + finally: + self.release() + + def close(self): + """ + Flush, if appropriately configured, set the target to None and lose the + buffer. + """ + try: + if self.flushOnClose: + self.flush() + finally: + self.acquire() + try: + self.target = None + BufferingHandler.close(self) + finally: + self.release() + + +class QueueHandler(logging.Handler): + """ + This handler sends events to a queue. Typically, it would be used together + with a multiprocessing Queue to centralise logging to file in one process + (in a multi-process application), so as to avoid file write contention + between processes. + + This code is new in Python 3.2, but this class can be copy pasted into + user code for use with earlier Python versions. + """ + + def __init__(self, queue): + """ + Initialise an instance, using the passed queue. + """ + logging.Handler.__init__(self) + self.queue = queue + + def enqueue(self, record): + """ + Enqueue a record. + + The base implementation uses put_nowait. You may want to override + this method if you want to use blocking, timeouts or custom queue + implementations. + """ + self.queue.put_nowait(record) + + def prepare(self, record): + """ + Prepare a record for queuing. The object returned by this method is + enqueued. + + The base implementation formats the record to merge the message and + arguments, and removes unpickleable items from the record in-place. + Specifically, it overwrites the record's `msg` and + `message` attributes with the merged message (obtained by + calling the handler's `format` method), and sets the `args`, + `exc_info` and `exc_text` attributes to None. + + You might want to override this method if you want to convert + the record to a dict or JSON string, or send a modified copy + of the record while leaving the original intact. + """ + # The format operation gets traceback text into record.exc_text + # (if there's exception data), and also returns the formatted + # message. We can then use this to replace the original + # msg + args, as these might be unpickleable. We also zap the + # exc_info, exc_text and stack_info attributes, as they are no longer + # needed and, if not None, will typically not be pickleable. + msg = self.format(record) + # bpo-35726: make copy of record to avoid affecting other handlers in the chain. + record = copy.copy(record) + record.message = msg + record.msg = msg + record.args = None + record.exc_info = None + record.exc_text = None + record.stack_info = None + return record + + def emit(self, record): + """ + Emit a record. + + Writes the LogRecord to the queue, preparing it for pickling first. + """ + try: + self.enqueue(self.prepare(record)) + except Exception: + self.handleError(record) + + +class QueueListener(object): + """ + This class implements an internal threaded listener which watches for + LogRecords being added to a queue, removes them and passes them to a + list of handlers for processing. + """ + _sentinel = None + + def __init__(self, queue, *handlers, respect_handler_level=False): + """ + Initialise an instance with the specified queue and + handlers. + """ + self.queue = queue + self.handlers = handlers + self._thread = None + self.respect_handler_level = respect_handler_level + + def dequeue(self, block): + """ + Dequeue a record and return it, optionally blocking. + + The base implementation uses get. You may want to override this method + if you want to use timeouts or work with custom queue implementations. + """ + return self.queue.get(block) + + def start(self): + """ + Start the listener. + + This starts up a background thread to monitor the queue for + LogRecords to process. + """ + self._thread = t = threading.Thread(target=self._monitor) + t.daemon = True + t.start() + + def prepare(self, record): + """ + Prepare a record for handling. + + This method just returns the passed-in record. You may want to + override this method if you need to do any custom marshalling or + manipulation of the record before passing it to the handlers. + """ + return record + + def handle(self, record): + """ + Handle a record. + + This just loops through the handlers offering them the record + to handle. + """ + record = self.prepare(record) + for handler in self.handlers: + if not self.respect_handler_level: + process = True + else: + process = record.levelno >= handler.level + if process: + handler.handle(record) + + def _monitor(self): + """ + Monitor the queue for records, and ask the handler + to deal with them. + + This method runs on a separate, internal thread. + The thread will terminate if it sees a sentinel object in the queue. + """ + q = self.queue + has_task_done = hasattr(q, 'task_done') + while True: + try: + record = self.dequeue(True) + if record is self._sentinel: + if has_task_done: + q.task_done() + break + self.handle(record) + if has_task_done: + q.task_done() + except queue.Empty: + break + + def enqueue_sentinel(self): + """ + This is used to enqueue the sentinel record. + + The base implementation uses put_nowait. You may want to override this + method if you want to use timeouts or work with custom queue + implementations. + """ + self.queue.put_nowait(self._sentinel) + + def stop(self): + """ + Stop the listener. + + This asks the thread to terminate, and then waits for it to do so. + Note that if you don't call this before your application exits, there + may be some records still left on the queue, which won't be processed. + """ + self.enqueue_sentinel() + self._thread.join() + self._thread = None diff --git a/shared/package-files/2c/2c4666ac0f3e77f494291b9a68ee0c80ff6a8b55aa382fdd874897df106481f8/textutils.c b/shared/package-files/2c/2c4666ac0f3e77f494291b9a68ee0c80ff6a8b55aa382fdd874897df106481f8/textutils.c new file mode 100644 index 0000000000000000000000000000000000000000..b2c29a89379d6f5db42928e72759c5e31a2ea1a5 --- /dev/null +++ b/shared/package-files/2c/2c4666ac0f3e77f494291b9a68ee0c80ff6a8b55aa382fdd874897df106481f8/textutils.c @@ -0,0 +1,497 @@ +/* textutils.c -- non-bioinformatics utility routines for text etc. + + Copyright (C) 2016, 2018-2020 Genome Research Ltd. + + Author: John Marshall + +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. */ + +#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h +#include + +#include +#include + +#include "htslib/hfile.h" +#include "htslib/kstring.h" +#include "htslib/sam.h" // For stringify_argv() declaration + +#include "hts_internal.h" + +static int dehex(char c) +{ + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + else if (c >= 'A' && c <= 'F') return c - 'A' + 10; + else if (c >= '0' && c <= '9') return c - '0'; + else return -1; // Hence dehex('\0') = -1 +} + +int hts_decode_percent(char *dest, size_t *destlen, const char *s) +{ + char *d = dest; + int hi, lo; + + while (*s) { + if (*s == '%' && (hi = dehex(s[1])) >= 0 && (lo = dehex(s[2])) >= 0) { + *d++ = (hi << 4) | lo; + s += 3; + } + else *d++ = *s++; + } + + *d = '\0'; + *destlen = d - dest; + return 0; +} + +static int debase64(char c) +{ + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + else if (c >= 'A' && c <= 'Z') return c - 'A'; + else if (c >= '0' && c <= '9') return c - '0' + 52; + else if (c == '/') return 63; + else if (c == '+') return 62; + else return -1; // Hence debase64('\0') = -1 +} + +size_t hts_base64_decoded_length(size_t len) +{ + size_t nquartets = (len + 2) / 4; + return 3 * nquartets; +} + +int hts_decode_base64(char *dest, size_t *destlen, const char *s) +{ + char *d = dest; + int x0, x1, x2, x3; + + while (1) { + x0 = debase64(*s++); + x1 = (x0 >= 0)? debase64(*s++) : -1; + x2 = (x1 >= 0)? debase64(*s++) : -1; + x3 = (x2 >= 0)? debase64(*s++) : -1; + if (x3 < 0) break; + + *d++ = (x0 << 2) | (x1 >> 4); + *d++ = (x1 << 4) | (x2 >> 2); + *d++ = (x2 << 6) | x3; + } + + if (x1 >= 0) *d++ = (x0 << 2) | (x1 >> 4); + if (x2 >= 0) *d++ = (x1 << 4) | (x2 >> 2); + + *destlen = d - dest; + return 0; +} + +static char *encode_utf8(char *s, unsigned x) +{ + if (x >= 0x10000) { + *s++ = 0xF0 | (x >> 18); + *s++ = 0x80 | ((x >> 12) & 0x3F); + *s++ = 0x80 | ((x >> 6) & 0x3F); + *s++ = 0x80 | (x & 0x3F); + } + else if (x >= 0x800) { + *s++ = 0xE0 | (x >> 12); + *s++ = 0x80 | ((x >> 6) & 0x3F); + *s++ = 0x80 | (x & 0x3F); + } + else if (x >= 0x80) { + *s++ = 0xC0 | (x >> 6); + *s++ = 0x80 | (x & 0x3F); + } + else *s++ = x; + + return s; +} + +static char *sscan_string(char *s) +{ + char *d = s; + int d1, d2, d3, d4; + + for (;;) switch (*s) { + case '\\': + switch (s[1]) { + case '\0': *d = '\0'; return s+1; + case 'b': *d++ = '\b'; s += 2; break; + case 'f': *d++ = '\f'; s += 2; break; + case 'n': *d++ = '\n'; s += 2; break; + case 'r': *d++ = '\r'; s += 2; break; + case 't': *d++ = '\t'; s += 2; break; + default: *d++ = s[1]; s += 2; break; + case 'u': + if ((d1 = dehex(s[2])) >= 0 && (d2 = dehex(s[3])) >= 0 && + (d3 = dehex(s[4])) >= 0 && (d4 = dehex(s[5])) >= 0) { + d = encode_utf8(d, d1 << 12 | d2 << 8 | d3 << 4 | d4); + s += 6; + } + break; + } + break; + + case '"': + *d = '\0'; + return s+1; + + case '\0': + *d = '\0'; + return s; + + default: + *d++ = *s++; + break; + } +} + +static int fscan_string(hFILE *fp, kstring_t *d) +{ + int c, d1, d2, d3, d4; + uint32_t e = 0; + + while ((c = hgetc(fp)) != EOF) switch (c) { + case '\\': + if ((c = hgetc(fp)) == EOF) return e == 0 ? 0 : -1; + switch (c) { + case 'b': e |= kputc('\b', d) < 0; break; + case 'f': e |= kputc('\f', d) < 0; break; + case 'n': e |= kputc('\n', d) < 0; break; + case 'r': e |= kputc('\r', d) < 0; break; + case 't': e |= kputc('\t', d) < 0; break; + default: e |= kputc(c, d) < 0; break; + case 'u': + if ((c = hgetc(fp)) != EOF && (d1 = dehex(c)) >= 0 && + (c = hgetc(fp)) != EOF && (d2 = dehex(c)) >= 0 && + (c = hgetc(fp)) != EOF && (d3 = dehex(c)) >= 0 && + (c = hgetc(fp)) != EOF && (d4 = dehex(c)) >= 0) { + char buf[8]; + char *lim = encode_utf8(buf, d1 << 12 | d2 << 8 | d3 << 4 | d4); + e |= kputsn(buf, lim - buf, d) < 0; + } + break; + } + break; + + case '"': + return e == 0 ? 0 : -1; + + default: + e |= kputc(c, d) < 0; + break; + } + return e == 0 ? 0 : -1; +} + +static char token_type(hts_json_token *token) +{ + const char *s = token->str; + + switch (*s) { + case 'f': + return (strcmp(s, "false") == 0)? 'b' : '?'; + case 'n': + return (strcmp(s, "null") == 0)? '.' : '?'; + case 't': + return (strcmp(s, "true") == 0)? 'b' : '?'; + case '-': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + return 'n'; + default: + return '?'; + } +} + +HTSLIB_EXPORT +hts_json_token * hts_json_alloc_token(void) { + return calloc(1, sizeof(hts_json_token)); +} + +HTSLIB_EXPORT +char hts_json_token_type(hts_json_token *token) { + return token->type; +} + +HTSLIB_EXPORT +void hts_json_free_token(hts_json_token *token) { + free(token); +} + +HTSLIB_EXPORT +char *hts_json_token_str(hts_json_token *token) { + return token->str; +} + +HTSLIB_EXPORT +char hts_json_snext(char *str, size_t *state, hts_json_token *token) +{ + char *s = &str[*state >> 2]; + int hidden = *state & 3; + + if (hidden) { + *state &= ~3; + return token->type = "?}]?"[hidden]; + } + +#define STATE(s,h) (((s) - str) << 2 | (h)) + + for (;;) switch (*s) { + case ' ': + case '\t': + case '\r': + case '\n': + case ',': + case ':': + s++; + continue; + + case '\0': + return token->type = '\0'; + + case '{': + case '[': + case '}': + case ']': + *state = STATE(s+1, 0); + return token->type = *s; + + case '"': + token->str = s+1; + *state = STATE(sscan_string(s+1), 0); + return token->type = 's'; + + default: + token->str = s; + s += strcspn(s, " \t\r\n,]}"); + hidden = (*s == '}')? 1 : (*s == ']')? 2 : 0; + if (*s != '\0') *s++ = '\0'; + *state = STATE(s, hidden); + return token->type = token_type(token); + } + +#undef STATE +} + +HTSLIB_EXPORT +char hts_json_fnext(struct hFILE *fp, hts_json_token *token, kstring_t *kstr) +{ + char peek; + int c; + + for (;;) switch (c = hgetc(fp)) { + case ' ': + case '\t': + case '\r': + case '\n': + case ',': + case ':': + continue; + + case EOF: + return token->type = '\0'; + + case '{': + case '[': + case '}': + case ']': + return token->type = c; + + case '"': + kstr->l = 0; + fscan_string(fp, kstr); + if (kstr->l == 0) kputsn("", 0, kstr); + token->str = kstr->s; + return token->type = 's'; + + default: + kstr->l = 0; + kputc(c, kstr); + while (hpeek(fp, &peek, 1) == 1 && !strchr(" \t\r\n,]}", peek)) { + if ((c = hgetc(fp)) == EOF) break; + kputc(c, kstr); + } + token->str = kstr->s; + return token->type = token_type(token); + } +} + + +typedef char hts_json_nextfn(void *arg1, void *arg2, hts_json_token *token); + +static char skip_value(char type, hts_json_nextfn *next, void *arg1, void *arg2) +{ + hts_json_token token; + int level; + + switch (type? type : next(arg1, arg2, &token)) { + case '\0': + return '\0'; + + case '?': + case '}': + case ']': + return '?'; + + case '{': + case '[': + level = 1; + break; + + default: + return 'v'; + } + + while (level > 0) + switch (next(arg1, arg2, &token)) { + case '\0': + return '\0'; + + case '?': + return '?'; + + case '{': + case '[': + level++; + break; + + case '}': + case ']': + --level; + break; + + default: + break; + } + + return 'v'; +} + +static char snext(void *arg1, void *arg2, hts_json_token *token) +{ + return hts_json_snext(arg1, arg2, token); +} + +HTSLIB_EXPORT +char hts_json_sskip_value(char *str, size_t *state, char type) +{ + return skip_value(type, snext, str, state); +} + +static char fnext(void *arg1, void *arg2, hts_json_token *token) +{ + return hts_json_fnext(arg1, token, arg2); +} + +HTSLIB_EXPORT +char hts_json_fskip_value(struct hFILE *fp, char type) +{ + kstring_t str = { 0, 0, NULL }; + char ret = skip_value(type, fnext, fp, &str); + free(str.s); + return ret; +} + +/* + * A function to help with construction of CL tags in @PG records. + * Takes an argc, argv pair and returns a single space-separated string. + * This string should be deallocated by the calling function. + * + * Returns malloced char * on success + * NULL on failure + */ +char *stringify_argv(int argc, char *argv[]) { + char *str, *cp; + size_t nbytes = 1; + int i, j; + + /* Allocate */ + for (i = 0; i < argc; i++) { + if (i > 0) nbytes += 1; + nbytes += strlen(argv[i]); + } + if (!(str = malloc(nbytes))) + return NULL; + + /* Copy */ + cp = str; + for (i = 0; i < argc; i++) { + if (i > 0) *cp++ = ' '; + j = 0; + while (argv[i][j]) { + if (argv[i][j] == '\t') + *cp++ = ' '; + else + *cp++ = argv[i][j]; + j++; + } + } + *cp++ = 0; + + return str; +} + +/* Utility function for printing possibly malicious text data + */ +const char * +hts_strprint(char *buf, size_t buflen, char quote, const char *s, size_t len) +{ + const char *slim = (len < SIZE_MAX)? &s[len] : NULL; + char *t = buf, *bufend = buf + buflen; + + size_t qlen = quote? 1 : 0; + if (quote) *t++ = quote; + + for (; slim? (s < slim) : (*s); s++) { + char c; + size_t clen; + switch (*s) { + case '\n': c = 'n'; clen = 2; break; + case '\r': c = 'r'; clen = 2; break; + case '\t': c = 't'; clen = 2; break; + case '\0': c = '0'; clen = 2; break; + case '\\': c = '\\'; clen = 2; break; + default: + c = *s; + if (c == quote) clen = 2; + else clen = isprint_c(c)? 1 : 4; + break; + } + + if (t-buf + clen + qlen >= buflen) { + while (t-buf + 3 + qlen >= buflen) t--; + if (quote) *t++ = quote; + strcpy(t, "..."); + return buf; + } + + if (clen == 4) { + snprintf(t, bufend - t, "\\x%02X", (unsigned char) c); + t += clen; + } + else { + if (clen == 2) *t++ = '\\'; + *t++ = c; + } + } + + if (quote) *t++ = quote; + *t = '\0'; + return buf; +} diff --git a/shared/package-files/2c/2c597682a80a7f1287860340dd16683c79bca0c72047e9bc2d27d62487888ba3/list_contains.cpython-311.pyc b/shared/package-files/2c/2c597682a80a7f1287860340dd16683c79bca0c72047e9bc2d27d62487888ba3/list_contains.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..699b7e1873c6549f3a17bd482243e7c1aa580a70 Binary files /dev/null and b/shared/package-files/2c/2c597682a80a7f1287860340dd16683c79bca0c72047e9bc2d27d62487888ba3/list_contains.cpython-311.pyc differ diff --git a/shared/package-files/2c/2c78f9c0b54614a7b76a5c2ab83b20e271cef5365148aaacb32d98f44602452f/addmv_native.h b/shared/package-files/2c/2c78f9c0b54614a7b76a5c2ab83b20e271cef5365148aaacb32d98f44602452f/addmv_native.h new file mode 100644 index 0000000000000000000000000000000000000000..8ec7efba2bd16475220288b2bcfe079348cf02cb --- /dev/null +++ b/shared/package-files/2c/2c78f9c0b54614a7b76a5c2ab83b20e271cef5365148aaacb32d98f44602452f/addmv_native.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_addmv_out_cpu : public at::meta::structured_addmv { +void impl(const at::Tensor & self, const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha, const at::Tensor & out); +}; +struct TORCH_API structured_addmv_out_cuda : public at::meta::structured_addmv { +void impl(const at::Tensor & self, const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha, const at::Tensor & out); +}; +TORCH_API at::Tensor & addmv_out_sparse_compressed(const at::Tensor & self, const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +TORCH_API at::Tensor & addmv_out_sparse_compressed_cuda(const at::Tensor & self, const at::Tensor & mat, const at::Tensor & vec, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/2c/2c9da730c0d00c232687b2f800b84b4fb8c5eb146e4ee78ca8662ceb34d36963/test_construction.cpython-311.pyc b/shared/package-files/2c/2c9da730c0d00c232687b2f800b84b4fb8c5eb146e4ee78ca8662ceb34d36963/test_construction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70e57150e0f4e5962a5d4cb0d9e2afaa1911026f Binary files /dev/null and b/shared/package-files/2c/2c9da730c0d00c232687b2f800b84b4fb8c5eb146e4ee78ca8662ceb34d36963/test_construction.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cb24b14b78d0558dde88271adf7dea2daf2f17e2e27ecedd4cf882104aa967b/caching.cpython-311.pyc b/shared/package-files/2c/2cb24b14b78d0558dde88271adf7dea2daf2f17e2e27ecedd4cf882104aa967b/caching.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a02938d959f1eaad90e3abe6efd7b70c84d616d4 Binary files /dev/null and b/shared/package-files/2c/2cb24b14b78d0558dde88271adf7dea2daf2f17e2e27ecedd4cf882104aa967b/caching.cpython-311.pyc differ diff --git a/shared/package-files/2c/2cdec74ac03f3ddfd638a5dd46db9c87bba636dfb5c39d768ebcd4411907e0da/gather.h b/shared/package-files/2c/2cdec74ac03f3ddfd638a5dd46db9c87bba636dfb5c39d768ebcd4411907e0da/gather.h new file mode 100644 index 0000000000000000000000000000000000000000..554c3601b9e3cbecf3f7bd1e5a131bd20b882c63 --- /dev/null +++ b/shared/package-files/2c/2cdec74ac03f3ddfd638a5dd46db9c87bba636dfb5c39d768ebcd4411907e0da/gather.h @@ -0,0 +1,54 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & gather_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, bool sparse_grad=false) { + return at::_ops::gather_out::call(self, dim, index, sparse_grad, out); +} +// aten::gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & gather_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, bool sparse_grad, at::Tensor & out) { + return at::_ops::gather_out::call(self, dim, index, sparse_grad, out); +} + +// aten::gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor +inline at::Tensor gather(const at::Tensor & self, int64_t dim, const at::Tensor & index, bool sparse_grad=false) { + return at::_ops::gather::call(self, dim, index, sparse_grad); +} + +// aten::gather.dimname_out(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & gather_out(at::Tensor & out, const at::Tensor & self, at::Dimname dim, const at::Tensor & index, bool sparse_grad=false) { + return at::_ops::gather_dimname_out::call(self, dim, index, sparse_grad, out); +} +// aten::gather.dimname_out(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & gather_outf(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, bool sparse_grad, at::Tensor & out) { + return at::_ops::gather_dimname_out::call(self, dim, index, sparse_grad, out); +} + +// aten::gather.dimname(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False) -> Tensor +inline at::Tensor gather(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, bool sparse_grad=false) { + return at::_ops::gather_dimname::call(self, dim, index, sparse_grad); +} + +} diff --git a/shared/package-files/4a/4a05504de59d53611285e1772abbfddf02df3a44f4ad0e74131532ab6ce74222/depth_first_search.cpython-311.pyc b/shared/package-files/4a/4a05504de59d53611285e1772abbfddf02df3a44f4ad0e74131532ab6ce74222/depth_first_search.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a977c48f77831d147a5c5ea15764bffc4ce90c5 Binary files /dev/null and b/shared/package-files/4a/4a05504de59d53611285e1772abbfddf02df3a44f4ad0e74131532ab6ce74222/depth_first_search.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a072161f75bfe2b2f4dcefc925c189fffeb127e3d5435972899a4f9cf50038e/_convolution_double_backward_ops.h b/shared/package-files/4a/4a072161f75bfe2b2f4dcefc925c189fffeb127e3d5435972899a4f9cf50038e/_convolution_double_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..22d5f91290d9ccb702c033cdb6de713731fdd368 --- /dev/null +++ b/shared/package-files/4a/4a072161f75bfe2b2f4dcefc925c189fffeb127e3d5435972899a4f9cf50038e/_convolution_double_backward_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _convolution_double_backward { + using schema = ::std::tuple (const ::std::optional &, const ::std::optional &, const ::std::optional &, const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, bool, c10::SymIntArrayRef, c10::SymInt, ::std::array); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_convolution_double_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)"; + static ::std::tuple call(const ::std::optional & ggI, const ::std::optional & ggW, const ::std::optional & ggb, const at::Tensor & gO, const at::Tensor & weight, const at::Tensor & self, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const ::std::optional & ggI, const ::std::optional & ggW, const ::std::optional & ggb, const at::Tensor & gO, const at::Tensor & weight, const at::Tensor & self, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, ::std::array output_mask); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4a/4a076d56e5525848f3dcb0df8177033fd8f85178ff285ebdf846ade0acf02064/_nested_tensor_strides_native.h b/shared/package-files/4a/4a076d56e5525848f3dcb0df8177033fd8f85178ff285ebdf846ade0acf02064/_nested_tensor_strides_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2f71cbe1d17eb5aa399854d7045899c419ed0d8d --- /dev/null +++ b/shared/package-files/4a/4a076d56e5525848f3dcb0df8177033fd8f85178ff285ebdf846ade0acf02064/_nested_tensor_strides_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _nested_tensor_strides_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor _nested_tensor_strides(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/4a/4a0956e8dc55946a6c00a9970da0a66c9012ba886103bba6f906d734e02e9293/test_assert_interval_array_equal.cpython-311.pyc b/shared/package-files/4a/4a0956e8dc55946a6c00a9970da0a66c9012ba886103bba6f906d734e02e9293/test_assert_interval_array_equal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a42f493c278589efa8f68c5b9c0017e7a91bc952 Binary files /dev/null and b/shared/package-files/4a/4a0956e8dc55946a6c00a9970da0a66c9012ba886103bba6f906d734e02e9293/test_assert_interval_array_equal.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a10c0c477d9e5d5ce51bfec8573a93723b5e041b4e2e727b2db7c766858cdc7/libcalignmentfile.c b/shared/package-files/4a/4a10c0c477d9e5d5ce51bfec8573a93723b5e041b4e2e727b2db7c766858cdc7/libcalignmentfile.c new file mode 100644 index 0000000000000000000000000000000000000000..fcd3d5e69f20493a1f6d53d84293b52b20c068fe --- /dev/null +++ b/shared/package-files/4a/4a10c0c477d9e5d5ce51bfec8573a93723b5e041b4e2e727b2db7c766858cdc7/libcalignmentfile.c @@ -0,0 +1,61070 @@ +/* Generated by Cython 3.1.2 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "define_macros": [ + [ + "BUILDING_WHEEL", + null + ] + ], + "depends": [ + "/project/htslib/htslib/bgzf.h", + "/project/htslib/htslib/cram.h", + "/project/htslib/htslib/faidx.h", + "/project/htslib/htslib/hfile.h", + "/project/htslib/htslib/hts.h", + "/project/htslib/htslib/kstring.h", + "/project/htslib/htslib/sam.h", + "/project/htslib/htslib/tbx.h", + "/project/htslib/htslib/vcf.h", + "/project/htslib/htslib/vcfutils.h", + "/project/pysam/htslib_util.h", + "/project/pysam/pysam_stream.h" + ], + "extra_compile_args": [ + "-Wno-unused", + "-Wno-strict-prototypes", + "-Wno-sign-compare", + "-Wno-error=declaration-after-statement" + ], + "extra_link_args": [ + "-Wl,-rpath,$ORIGIN" + ], + "include_dirs": [ + "pysam", + "/project/pysam", + "/project/htslib", + "/project/samtools", + "/project/samtools/lz4", + "/project/bcftools", + "/project" + ], + "language": "c", + "libraries": [ + "z", + "lzma", + "bz2", + "z", + "m", + "curl", + "crypto", + "chtslib.cpython-310-x86_64-linux-gnu", + "cutils.cpython-310-x86_64-linux-gnu" + ], + "library_dirs": [ + "/project/pysam", + "/project", + "build/lib.linux-x86_64-cpython-310/pysam", + "build/lib.linux-x86_64-cpython-310/pysam", + "build/lib.linux-x86_64-cpython-310/pysam", + "build/lib.linux-x86_64-cpython-310/pysam", + "build/lib.linux-x86_64-cpython-310/pysam" + ], + "name": "pysam.libcalignmentfile", + "sources": [ + "pysam/libcalignmentfile.pyx" + ] + }, + "module_name": "pysam.libcalignmentfile" +} +END: Cython Metadata */ + +#ifndef PY_SSIZE_T_CLEAN +#define PY_SSIZE_T_CLEAN +#endif /* PY_SSIZE_T_CLEAN */ +/* InitLimitedAPI */ +#if defined(Py_LIMITED_API) && !defined(CYTHON_LIMITED_API) + #define CYTHON_LIMITED_API 1 +#endif + +#include "Python.h" +#ifndef Py_PYTHON_H + #error Python headers needed to compile C extensions, please install development version of Python. +#elif PY_VERSION_HEX < 0x03080000 + #error Cython requires Python 3.8+. +#else +#define __PYX_ABI_VERSION "3_1_2" +#define CYTHON_HEX_VERSION 0x030102F0 +#define CYTHON_FUTURE_DIVISION 1 +/* CModulePreamble */ +#include +#ifndef offsetof + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) +#endif +#if !defined(_WIN32) && !defined(WIN32) && !defined(MS_WINDOWS) + #ifndef __stdcall + #define __stdcall + #endif + #ifndef __cdecl + #define __cdecl + #endif + #ifndef __fastcall + #define __fastcall + #endif +#endif +#ifndef DL_IMPORT + #define DL_IMPORT(t) t +#endif +#ifndef DL_EXPORT + #define DL_EXPORT(t) t +#endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #define HAVE_LONG_LONG +#endif +#ifndef PY_LONG_LONG + #define PY_LONG_LONG LONG_LONG +#endif +#ifndef Py_HUGE_VAL + #define Py_HUGE_VAL HUGE_VAL +#endif +#define __PYX_LIMITED_VERSION_HEX PY_VERSION_HEX +#if defined(GRAALVM_PYTHON) + /* For very preliminary testing purposes. Most variables are set the same as PyPy. + The existence of this section does not imply that anything works or is even tested */ + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 1 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 +#elif defined(PYPY_VERSION) + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #if PY_VERSION_HEX < 0x03090000 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #elif !defined(CYTHON_PEP489_MULTI_PHASE_INIT) + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #undef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PYPY_VERSION_NUM >= 0x07030C00) + #endif + #undef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 0 + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07031100) + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 +#elif defined(CYTHON_LIMITED_API) + #ifdef Py_LIMITED_API + #undef __PYX_LIMITED_VERSION_HEX + #define __PYX_LIMITED_VERSION_HEX Py_LIMITED_API + #endif + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_LIMITED_API 1 + #define CYTHON_COMPILING_IN_GRAAL 0 + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #undef CYTHON_CLINE_IN_TRACEBACK + #define CYTHON_CLINE_IN_TRACEBACK 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 1 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #endif + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #undef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #undef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING 0 + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND (__PYX_LIMITED_VERSION_HEX >= 0x030A0000) + #endif + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #undef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 0 + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 0 + #endif + #undef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS 0 +#else + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_LIMITED_API 0 + #define CYTHON_COMPILING_IN_GRAAL 0 + #ifdef Py_GIL_DISABLED + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 1 + #else + #define CYTHON_COMPILING_IN_CPYTHON_FREETHREADING 0 + #endif + #if PY_VERSION_HEX < 0x030A0000 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #elif !defined(CYTHON_USE_TYPE_SLOTS) + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #ifndef CYTHON_USE_TYPE_SPECS + #define CYTHON_USE_TYPE_SPECS 0 + #endif + #ifndef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #ifndef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLIST_INTERNALS) + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING || PY_VERSION_HEX >= 0x030B00A2 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 1 + #elif !defined(CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS) + #define CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_ASSUME_SAFE_SIZE + #define CYTHON_ASSUME_SAFE_SIZE 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_FAST_GIL + #define CYTHON_FAST_GIL 0 + #elif !defined(CYTHON_FAST_GIL) + #define CYTHON_FAST_GIL (PY_VERSION_HEX < 0x030C00A6) + #endif + #ifndef CYTHON_METH_FASTCALL + #define CYTHON_METH_FASTCALL 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP487_INIT_SUBCLASS + #define CYTHON_PEP487_INIT_SUBCLASS 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 1 + #endif + #ifndef CYTHON_USE_MODULE_STATE + #define CYTHON_USE_MODULE_STATE 0 + #endif + #ifndef CYTHON_USE_SYS_MONITORING + #define CYTHON_USE_SYS_MONITORING (PY_VERSION_HEX >= 0x030d00B1) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 1 + #endif + #ifndef CYTHON_USE_AM_SEND + #define CYTHON_USE_AM_SEND 1 + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + #undef CYTHON_USE_DICT_VERSIONS + #define CYTHON_USE_DICT_VERSIONS 0 + #elif !defined(CYTHON_USE_DICT_VERSIONS) + #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX < 0x030C00A5 && !CYTHON_USE_MODULE_STATE) + #endif + #ifndef CYTHON_USE_EXC_INFO_STACK + #define CYTHON_USE_EXC_INFO_STACK 1 + #endif + #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC 1 + #endif + #ifndef CYTHON_USE_FREELISTS + #define CYTHON_USE_FREELISTS (!CYTHON_COMPILING_IN_CPYTHON_FREETHREADING) + #endif +#endif +#ifndef CYTHON_FAST_PYCCALL +#define CYTHON_FAST_PYCCALL CYTHON_FAST_PYCALL +#endif +#ifndef CYTHON_VECTORCALL +#if CYTHON_COMPILING_IN_LIMITED_API +#define CYTHON_VECTORCALL (__PYX_LIMITED_VERSION_HEX >= 0x030C0000) +#else +#define CYTHON_VECTORCALL (CYTHON_FAST_PYCCALL && PY_VERSION_HEX >= 0x030800B1) +#endif +#endif +#define CYTHON_BACKPORT_VECTORCALL (CYTHON_METH_FASTCALL && PY_VERSION_HEX < 0x030800B1) +#if CYTHON_USE_PYLONG_INTERNALS + #undef SHIFT + #undef BASE + #undef MASK + #ifdef SIZEOF_VOID_P + enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; + #endif +#endif +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#ifndef CYTHON_RESTRICT + #if defined(__GNUC__) + #define CYTHON_RESTRICT __restrict__ + #elif defined(_MSC_VER) && _MSC_VER >= 1400 + #define CYTHON_RESTRICT __restrict + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_RESTRICT restrict + #else + #define CYTHON_RESTRICT + #endif +#endif +#ifndef CYTHON_UNUSED + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(maybe_unused) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(maybe_unused) + #define CYTHON_UNUSED [[maybe_unused]] + #endif + #endif + #endif +#endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR + #define CYTHON_MAYBE_UNUSED_VAR(x) CYTHON_UNUSED_VAR(x) +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON && !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_USE_CPP_STD_MOVE + #if defined(__cplusplus) && (\ + __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1600)) + #define CYTHON_USE_CPP_STD_MOVE 1 + #else + #define CYTHON_USE_CPP_STD_MOVE 0 + #endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + #endif + #endif + #if _MSC_VER < 1300 + #ifdef _WIN64 + typedef unsigned long long __pyx_uintptr_t; + #else + typedef unsigned int __pyx_uintptr_t; + #endif + #else + #ifdef _WIN64 + typedef unsigned __int64 __pyx_uintptr_t; + #else + typedef unsigned __int32 __pyx_uintptr_t; + #endif + #endif +#else + #include + typedef uintptr_t __pyx_uintptr_t; +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) + /* for clang __has_cpp_attribute(fallthrough) is true even before C++17 + * but leads to warnings with -pedantic, since it is a C++17 feature */ + #if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L) + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif +#ifndef Py_UNREACHABLE + #define Py_UNREACHABLE() assert(0); abort() +#endif +#ifdef __cplusplus + template + struct __PYX_IS_UNSIGNED_IMPL {static const bool value = T(0) < T(-1);}; + #define __PYX_IS_UNSIGNED(type) (__PYX_IS_UNSIGNED_IMPL::value) +#else + #define __PYX_IS_UNSIGNED(type) (((type)-1) > 0) +#endif +#if CYTHON_COMPILING_IN_PYPY == 1 + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x030A0000) +#else + #define __PYX_NEED_TP_PRINT_SLOT (PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000) +#endif +#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) + +/* CInitCode */ +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +/* PythonCompatibility */ +#define __PYX_BUILD_PY_SSIZE_T "n" +#define CYTHON_FORMAT_SSIZE_T "z" +#define __Pyx_BUILTIN_MODULE_NAME "builtins" +#define __Pyx_DefaultClassType PyType_Type +#if CYTHON_COMPILING_IN_LIMITED_API + #ifndef CO_OPTIMIZED + static int CO_OPTIMIZED; + #endif + #ifndef CO_NEWLOCALS + static int CO_NEWLOCALS; + #endif + #ifndef CO_VARARGS + static int CO_VARARGS; + #endif + #ifndef CO_VARKEYWORDS + static int CO_VARKEYWORDS; + #endif + #ifndef CO_ASYNC_GENERATOR + static int CO_ASYNC_GENERATOR; + #endif + #ifndef CO_GENERATOR + static int CO_GENERATOR; + #endif + #ifndef CO_COROUTINE + static int CO_COROUTINE; + #endif +#else + #ifndef CO_COROUTINE + #define CO_COROUTINE 0x80 + #endif + #ifndef CO_ASYNC_GENERATOR + #define CO_ASYNC_GENERATOR 0x200 + #endif +#endif +static int __Pyx_init_co_variables(void); +#if PY_VERSION_HEX >= 0x030900A4 || defined(Py_IS_TYPE) + #define __Pyx_IS_TYPE(ob, type) Py_IS_TYPE(ob, type) +#else + #define __Pyx_IS_TYPE(ob, type) (((const PyObject*)ob)->ob_type == (type)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_Is) + #define __Pyx_Py_Is(x, y) Py_Is(x, y) +#else + #define __Pyx_Py_Is(x, y) ((x) == (y)) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsNone) + #define __Pyx_Py_IsNone(ob) Py_IsNone(ob) +#else + #define __Pyx_Py_IsNone(ob) __Pyx_Py_Is((ob), Py_None) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsTrue) + #define __Pyx_Py_IsTrue(ob) Py_IsTrue(ob) +#else + #define __Pyx_Py_IsTrue(ob) __Pyx_Py_Is((ob), Py_True) +#endif +#if PY_VERSION_HEX >= 0x030A00B1 || defined(Py_IsFalse) + #define __Pyx_Py_IsFalse(ob) Py_IsFalse(ob) +#else + #define __Pyx_Py_IsFalse(ob) __Pyx_Py_Is((ob), Py_False) +#endif +#define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) +#if PY_VERSION_HEX >= 0x030900F0 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyObject_GC_IsFinalized(o) PyObject_GC_IsFinalized(o) +#else + #define __Pyx_PyObject_GC_IsFinalized(o) _PyGC_FINALIZED(o) +#endif +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif +#ifndef Py_TPFLAGS_HAVE_FINALIZE + #define Py_TPFLAGS_HAVE_FINALIZE 0 +#endif +#ifndef Py_TPFLAGS_SEQUENCE + #define Py_TPFLAGS_SEQUENCE 0 +#endif +#ifndef Py_TPFLAGS_MAPPING + #define Py_TPFLAGS_MAPPING 0 +#endif +#ifndef METH_STACKLESS + #define METH_STACKLESS 0 +#endif +#ifndef METH_FASTCALL + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #if PY_VERSION_HEX >= 0x030d00A4 + # define __Pyx_PyCFunctionFast PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords PyCFunctionFastWithKeywords + #else + # define __Pyx_PyCFunctionFast _PyCFunctionFast + # define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords + #endif +#endif +#if CYTHON_METH_FASTCALL + #define __Pyx_METH_FASTCALL METH_FASTCALL + #define __Pyx_PyCFunction_FastCall __Pyx_PyCFunctionFast + #define __Pyx_PyCFunction_FastCallWithKeywords __Pyx_PyCFunctionFastWithKeywords +#else + #define __Pyx_METH_FASTCALL METH_VARARGS + #define __Pyx_PyCFunction_FastCall PyCFunction + #define __Pyx_PyCFunction_FastCallWithKeywords PyCFunctionWithKeywords +#endif +#if CYTHON_VECTORCALL + #define __pyx_vectorcallfunc vectorcallfunc + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET PY_VECTORCALL_ARGUMENTS_OFFSET + #define __Pyx_PyVectorcall_NARGS(n) PyVectorcall_NARGS((size_t)(n)) +#elif CYTHON_BACKPORT_VECTORCALL + typedef PyObject *(*__pyx_vectorcallfunc)(PyObject *callable, PyObject *const *args, + size_t nargsf, PyObject *kwnames); + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(((size_t)(n)) & ~__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)) +#else + #define __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET 0 + #define __Pyx_PyVectorcall_NARGS(n) ((Py_ssize_t)(n)) +#endif +#if PY_VERSION_HEX >= 0x030900B1 +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_CheckExact(func) +#else +#define __Pyx_PyCFunction_CheckExact(func) PyCFunction_Check(func) +#endif +#define __Pyx_CyOrPyCFunction_Check(func) PyCFunction_Check(func) +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) (((PyCFunctionObject*)(func))->m_ml->ml_meth) +#elif !CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyOrPyCFunction_GET_FUNCTION(func) PyCFunction_GET_FUNCTION(func) +#endif +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_CyOrPyCFunction_GET_FLAGS(func) (((PyCFunctionObject*)(func))->m_ml->ml_flags) +static CYTHON_INLINE PyObject* __Pyx_CyOrPyCFunction_GET_SELF(PyObject *func) { + return (__Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_STATIC) ? NULL : ((PyCFunctionObject*)func)->m_self; +} +#endif +static CYTHON_INLINE int __Pyx__IsSameCFunction(PyObject *func, void (*cfunc)(void)) { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyCFunction_Check(func) && PyCFunction_GetFunction(func) == (PyCFunction) cfunc; +#else + return PyCFunction_Check(func) && PyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +#endif +} +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCFunction(func, cfunc) +#if __PYX_LIMITED_VERSION_HEX < 0x03090000 + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) ((void)m, PyType_FromSpecWithBases(s, b)) + typedef PyObject *(*__Pyx_PyCMethod)(PyObject *, PyTypeObject *, PyObject *const *, size_t, PyObject *); +#else + #define __Pyx_PyType_FromModuleAndSpec(m, s, b) PyType_FromModuleAndSpec(m, s, b) + #define __Pyx_PyCMethod PyCMethod +#endif +#ifndef METH_METHOD + #define METH_METHOD 0x200 +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) +#elif CYTHON_COMPILING_IN_GRAAL + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) _PyFrame_SetLineNumber((frame), (lineno)) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyThreadState_Current PyThreadState_Get() +#elif !CYTHON_FAST_THREAD_STATE + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x030d00A1 + #define __Pyx_PyThreadState_Current PyThreadState_GetUnchecked() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#endif +#if CYTHON_USE_MODULE_STATE +static CYTHON_INLINE void *__Pyx__PyModule_GetState(PyObject *op) +{ + void *result; + result = PyModule_GetState(op); + if (!result) + Py_FatalError("Couldn't find the module state"); + return result; +} +#define __Pyx_PyModule_GetState(o) (__pyx_mstatetype *)__Pyx__PyModule_GetState(o) +#else +#define __Pyx_PyModule_GetState(op) ((void)op,__pyx_mstate_global) +#endif +#define __Pyx_PyObject_GetSlot(obj, name, func_ctype) __Pyx_PyType_GetSlot(Py_TYPE((PyObject *) obj), name, func_ctype) +#define __Pyx_PyObject_TryGetSlot(obj, name, func_ctype) __Pyx_PyType_TryGetSlot(Py_TYPE(obj), name, func_ctype) +#define __Pyx_PyObject_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#define __Pyx_PyObject_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSubSlot(Py_TYPE(obj), sub, name, func_ctype) +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((type)->name) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype) __Pyx_PyType_GetSlot(type, name, func_ctype) + #define __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) (((type)->sub) ? ((type)->sub->name) : NULL) + #define __Pyx_PyType_TryGetSubSlot(type, sub, name, func_ctype) __Pyx_PyType_GetSubSlot(type, sub, name, func_ctype) +#else + #define __Pyx_PyType_GetSlot(type, name, func_ctype) ((func_ctype) PyType_GetSlot((type), Py_##name)) + #define __Pyx_PyType_TryGetSlot(type, name, func_ctype)\ + ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000 ||\ + (PyType_GetFlags(type) & Py_TPFLAGS_HEAPTYPE) || __Pyx_get_runtime_version() >= 0x030A0000) ?\ + __Pyx_PyType_GetSlot(type, name, func_ctype) : NULL) + #define __Pyx_PyType_GetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_GetSlot(obj, name, func_ctype) + #define __Pyx_PyType_TryGetSubSlot(obj, sub, name, func_ctype) __Pyx_PyType_TryGetSlot(obj, name, func_ctype) +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) +#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_UNICODE_INTERNALS +#define __Pyx_PyDict_GetItemStrWithError(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStr(PyObject *dict, PyObject *name) { + PyObject *res = __Pyx_PyDict_GetItemStrWithError(dict, name); + if (res == NULL) PyErr_Clear(); + return res; +} +#elif !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 +#define __Pyx_PyDict_GetItemStrWithError PyDict_GetItemWithError +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#else +static CYTHON_INLINE PyObject * __Pyx_PyDict_GetItemStrWithError(PyObject *dict, PyObject *name) { +#if CYTHON_COMPILING_IN_PYPY + return PyDict_GetItem(dict, name); +#else + PyDictEntry *ep; + PyDictObject *mp = (PyDictObject*) dict; + long hash = ((PyStringObject *) name)->ob_shash; + assert(hash != -1); + ep = (mp->ma_lookup)(mp, name, hash); + if (ep == NULL) { + return NULL; + } + return ep->me_value; +#endif +} +#define __Pyx_PyDict_GetItemStr PyDict_GetItem +#endif +#if CYTHON_USE_TYPE_SLOTS + #define __Pyx_PyType_GetFlags(tp) (((PyTypeObject *)tp)->tp_flags) + #define __Pyx_PyType_HasFeature(type, feature) ((__Pyx_PyType_GetFlags(type) & (feature)) != 0) +#else + #define __Pyx_PyType_GetFlags(tp) (PyType_GetFlags((PyTypeObject *)tp)) + #define __Pyx_PyType_HasFeature(type, feature) PyType_HasFeature(type, feature) +#endif +#define __Pyx_PyObject_GetIterNextFunc(iterator) __Pyx_PyObject_GetSlot(iterator, tp_iternext, iternextfunc) +#if CYTHON_USE_TYPE_SPECS && PY_VERSION_HEX >= 0x03080000 +#define __Pyx_PyHeapTypeObject_GC_Del(obj) {\ + PyTypeObject *type = Py_TYPE((PyObject*)obj);\ + assert(__Pyx_PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE));\ + PyObject_GC_Del(obj);\ + Py_DECREF(type);\ +} +#else +#define __Pyx_PyHeapTypeObject_GC_Del(obj) PyObject_GC_Del(obj) +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_PyUnicode_READY(op) (0) + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_ReadChar(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((void)u, 1114111U) + #define __Pyx_PyUnicode_KIND(u) ((void)u, (0)) + #define __Pyx_PyUnicode_DATA(u) ((void*)u) + #define __Pyx_PyUnicode_READ(k, d, i) ((void)k, PyUnicode_ReadChar((PyObject*)(d), i)) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GetLength(u)) +#else + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_READY(op) (0) + #else + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #endif + #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) + #define __Pyx_PyUnicode_KIND(u) ((int)PyUnicode_KIND(u)) + #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) + #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, (Py_UCS4) ch) + #if PY_VERSION_HEX >= 0x030C0000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) + #else + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) + #else + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) + #endif + #endif +#endif +#if CYTHON_COMPILING_IN_PYPY + #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) +#else + #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ + PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) +#endif +#if CYTHON_COMPILING_IN_PYPY + #if !defined(PyUnicode_DecodeUnicodeEscape) + #define PyUnicode_DecodeUnicodeEscape(s, size, errors) PyUnicode_Decode(s, size, "unicode_escape", errors) + #endif + #if !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) + #endif + #if !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) + #endif + #if !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) + #endif +#endif +#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#if CYTHON_COMPILING_IN_CPYTHON + #define __Pyx_PySequence_ListKeepNew(obj)\ + (likely(PyList_CheckExact(obj) && Py_REFCNT(obj) == 1) ? __Pyx_NewRef(obj) : PySequence_List(obj)) +#else + #define __Pyx_PySequence_ListKeepNew(obj) PySequence_List(obj) +#endif +#ifndef PySet_CheckExact + #define PySet_CheckExact(obj) __Pyx_IS_TYPE(obj, &PySet_Type) +#endif +#if PY_VERSION_HEX >= 0x030900A4 + #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) +#else + #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) + #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) +#endif +#if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyList_GetItemRef(o, i) (likely((i) >= 0) ? PySequence_GetItem(o, i) : (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) + #else + #define __Pyx_PyList_GetItemRef(o, i) PySequence_ITEM(o, i) + #endif +#elif CYTHON_COMPILING_IN_LIMITED_API || !CYTHON_ASSUME_SAFE_MACROS + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyList_GetItemRef(o, i) PyList_GetItemRef(o, i) + #else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_XNewRef(PyList_GetItem(o, i)) + #endif +#else + #define __Pyx_PyList_GetItemRef(o, i) __Pyx_NewRef(PyList_GET_ITEM(o, i)) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyDict_GetItemRef(dict, key, result) PyDict_GetItemRef(dict, key, result) +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyObject_GetItem(dict, key); + if (*result == NULL) { + if (PyErr_ExceptionMatches(PyExc_KeyError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + return 1; +} +#else +static CYTHON_INLINE int __Pyx_PyDict_GetItemRef(PyObject *dict, PyObject *key, PyObject **result) { + *result = PyDict_GetItemWithError(dict, key); + if (*result == NULL) { + return PyErr_Occurred() ? -1 : 0; + } + Py_INCREF(*result); + return 1; +} +#endif +#if defined(CYTHON_DEBUG_VISIT_CONST) && CYTHON_DEBUG_VISIT_CONST + #define __Pyx_VISIT_CONST(obj) Py_VISIT(obj) +#else + #define __Pyx_VISIT_CONST(obj) +#endif +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PySequence_ITEM(o, i) PySequence_ITEM(o, i) + #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) (PyTuple_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GET_ITEM(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) (PyList_SET_ITEM(o, i, v), (0)) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GET_ITEM(o, i) +#else + #define __Pyx_PySequence_ITEM(o, i) PySequence_GetItem(o, i) + #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) + #define __Pyx_PyTuple_SET_ITEM(o, i, v) PyTuple_SetItem(o, i, v) + #define __Pyx_PyTuple_GET_ITEM(o, i) PyTuple_GetItem(o, i) + #define __Pyx_PyList_SET_ITEM(o, i, v) PyList_SetItem(o, i, v) + #define __Pyx_PyList_GET_ITEM(o, i) PyList_GetItem(o, i) +#endif +#if CYTHON_ASSUME_SAFE_SIZE + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_GET_SIZE(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_GET_SIZE(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_GET_SIZE(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_GET_SIZE(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_GET_SIZE(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GET_LENGTH(o) +#else + #define __Pyx_PyTuple_GET_SIZE(o) PyTuple_Size(o) + #define __Pyx_PyList_GET_SIZE(o) PyList_Size(o) + #define __Pyx_PySet_GET_SIZE(o) PySet_Size(o) + #define __Pyx_PyBytes_GET_SIZE(o) PyBytes_Size(o) + #define __Pyx_PyByteArray_GET_SIZE(o) PyByteArray_Size(o) + #define __Pyx_PyUnicode_GET_LENGTH(o) PyUnicode_GetLength(o) +#endif +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + #define __Pyx_PyImport_AddModuleRef(name) PyImport_AddModuleRef(name) +#else + static CYTHON_INLINE PyObject *__Pyx_PyImport_AddModuleRef(const char *name) { + PyObject *module = PyImport_AddModule(name); + Py_XINCREF(module); + return module; + } +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_InternFromString) + #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) +#endif +#define __Pyx_PyLong_FromHash_t PyLong_FromSsize_t +#define __Pyx_PyLong_AsHash_t __Pyx_PyIndex_AsSsize_t +#if __PYX_LIMITED_VERSION_HEX >= 0x030A0000 + #define __Pyx_PySendResult PySendResult +#else + typedef enum { + PYGEN_RETURN = 0, + PYGEN_ERROR = -1, + PYGEN_NEXT = 1, + } __Pyx_PySendResult; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX < 0x030A00A3 + typedef __Pyx_PySendResult (*__Pyx_pyiter_sendfunc)(PyObject *iter, PyObject *value, PyObject **result); +#else + #define __Pyx_pyiter_sendfunc sendfunc +#endif +#if !CYTHON_USE_AM_SEND +#define __PYX_HAS_PY_AM_SEND 0 +#elif __PYX_LIMITED_VERSION_HEX >= 0x030A0000 +#define __PYX_HAS_PY_AM_SEND 1 +#else +#define __PYX_HAS_PY_AM_SEND 2 // our own backported implementation +#endif +#if __PYX_HAS_PY_AM_SEND < 2 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods +#else + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + __Pyx_pyiter_sendfunc am_send; + } __Pyx_PyAsyncMethodsStruct; + #define __Pyx_SlotTpAsAsync(s) ((PyAsyncMethods*)(s)) +#endif +#if CYTHON_USE_AM_SEND && PY_VERSION_HEX < 0x030A00F0 + #define __Pyx_TPFLAGS_HAVE_AM_SEND (1UL << 21) +#else + #define __Pyx_TPFLAGS_HAVE_AM_SEND (0) +#endif +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyInterpreterState_Get() PyInterpreterState_Get() +#else +#define __Pyx_PyInterpreterState_Get() PyThreadState_Get()->interp +#endif +#if CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030A0000 +#ifdef __cplusplus +extern "C" +#endif +PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static int __Pyx_init_co_variable(PyObject *inspect, const char* name, int *write_to) { + int value; + PyObject *py_value = PyObject_GetAttrString(inspect, name); + if (!py_value) return 0; + value = (int) PyLong_AsLong(py_value); + Py_DECREF(py_value); + *write_to = value; + return value != -1 || !PyErr_Occurred(); +} +static int __Pyx_init_co_variables(void) { + PyObject *inspect; + int result; + inspect = PyImport_ImportModule("inspect"); + result = +#if !defined(CO_OPTIMIZED) + __Pyx_init_co_variable(inspect, "CO_OPTIMIZED", &CO_OPTIMIZED) && +#endif +#if !defined(CO_NEWLOCALS) + __Pyx_init_co_variable(inspect, "CO_NEWLOCALS", &CO_NEWLOCALS) && +#endif +#if !defined(CO_VARARGS) + __Pyx_init_co_variable(inspect, "CO_VARARGS", &CO_VARARGS) && +#endif +#if !defined(CO_VARKEYWORDS) + __Pyx_init_co_variable(inspect, "CO_VARKEYWORDS", &CO_VARKEYWORDS) && +#endif +#if !defined(CO_ASYNC_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_ASYNC_GENERATOR", &CO_ASYNC_GENERATOR) && +#endif +#if !defined(CO_GENERATOR) + __Pyx_init_co_variable(inspect, "CO_GENERATOR", &CO_GENERATOR) && +#endif +#if !defined(CO_COROUTINE) + __Pyx_init_co_variable(inspect, "CO_COROUTINE", &CO_COROUTINE) && +#endif + 1; + Py_DECREF(inspect); + return result ? 0 : -1; +} +#else +static int __Pyx_init_co_variables(void) { + return 0; // It's a limited API-only feature +} +#endif + +/* MathInitCode */ +#if defined(_WIN32) || defined(WIN32) || defined(MS_WINDOWS) + #ifndef _USE_MATH_DEFINES + #define _USE_MATH_DEFINES + #endif +#endif +#include +#ifdef NAN +#define __PYX_NAN() ((float) NAN) +#else +static CYTHON_INLINE float __PYX_NAN() { + float value; + memset(&value, 0xFF, sizeof(value)); + return value; +} +#endif +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl +#endif + +#ifndef CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#define CYTHON_CLINE_IN_TRACEBACK_RUNTIME 0 +#endif +#ifndef CYTHON_CLINE_IN_TRACEBACK +#define CYTHON_CLINE_IN_TRACEBACK CYTHON_CLINE_IN_TRACEBACK_RUNTIME +#endif +#if CYTHON_CLINE_IN_TRACEBACK +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; __pyx_clineno = __LINE__; (void) __pyx_clineno; } +#else +#define __PYX_MARK_ERR_POS(f_index, lineno) { __pyx_filename = __pyx_f[f_index]; (void) __pyx_filename; __pyx_lineno = lineno; (void) __pyx_lineno; (void) __pyx_clineno; } +#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ + { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } + +#ifdef CYTHON_EXTERN_C + #undef __PYX_EXTERN_C + #define __PYX_EXTERN_C CYTHON_EXTERN_C +#elif defined(__PYX_EXTERN_C) + #ifdef _MSC_VER + #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.") + #else + #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead. + #endif +#else + #ifdef __cplusplus + #define __PYX_EXTERN_C extern "C" + #else + #define __PYX_EXTERN_C extern + #endif +#endif + +#define __PYX_HAVE__pysam__libcalignmentfile +#define __PYX_HAVE_API__pysam__libcalignmentfile +/* Early includes */ +#include +#include +#include +#include + + #if PY_MAJOR_VERSION >= 3 + #define __Pyx_PyFloat_FromString(obj) PyFloat_FromString(obj) + #else + #define __Pyx_PyFloat_FromString(obj) PyFloat_FromString(obj, NULL) + #endif + +#include + + #if PY_MAJOR_VERSION <= 2 + #define PyDict_GetItemWithError _PyDict_GetItemWithError + #endif + + + #if PY_VERSION_HEX < 0x030d0000 + static CYTHON_INLINE int __Pyx_PyWeakref_GetRef(PyObject *ref, PyObject **pobj) + { + PyObject *obj = PyWeakref_GetObject(ref); + if (obj == NULL) { + // SystemError if ref is NULL + *pobj = NULL; + return -1; + } + if (obj == Py_None) { + *pobj = NULL; + return 0; + } + Py_INCREF(obj); + *pobj = obj; + return 1; + } + #else + #define __Pyx_PyWeakref_GetRef PyWeakref_GetRef + #endif + +#include "pythread.h" + + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030600) && !defined(PyContextVar_Get) + #define PyContextVar_Get(var, d, v) ((d) ? ((void)(var), Py_INCREF(d), (v)[0] = (d), 0) : ((v)[0] = NULL, 0) ) + #endif + + + #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API + #ifdef _MSC_VER + #pragma message ("This module uses CPython specific internals of 'array.array', which are not available in PyPy or the limited API.") + #else + #warning This module uses CPython specific internals of 'array.array', which are not available in PyPy or the limited API. + #endif + #endif + +#include +#include "stdarg.h" +#include "htslib/kstring.h" +#include "htslib_util.h" +#include "htslib/hfile.h" +#include "htslib/bgzf.h" +#include "htslib/hts.h" +#include "htslib/sam.h" +#include "htslib/faidx.h" +#include "htslib/tbx.h" +#include "htslib/vcf.h" +#include "htslib/vcfutils.h" +#include "htslib/cram.h" +#include "pysam_stream.h" +#include +#ifdef _OPENMP +#include +#endif /* _OPENMP */ + +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) +#define CYTHON_WITHOUT_ASSERTIONS +#endif + +#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 +#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 +#define __PYX_DEFAULT_STRING_ENCODING "" +#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString +#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX))) ) +static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { + return (size_t) i < (size_t) limit; +} +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s); +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char*); +#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) +#define __Pyx_PyBytes_FromString PyBytes_FromString +#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); +#if CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AS_STRING(s) +#else + #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AsString(s)) + #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AsString(s)) + #define __Pyx_PyByteArray_AsString(s) PyByteArray_AsString(s) +#endif +#define __Pyx_PyObject_AsWritableString(s) ((char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*)(__pyx_uintptr_t) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +#define __Pyx_PyUnicode_FromOrdinal(o) PyUnicode_FromOrdinal((int)o) +#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode +static CYTHON_INLINE PyObject *__Pyx_NewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_NewRef) + return Py_NewRef(obj); +#else + Py_INCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_XNewRef(PyObject *obj) { +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030a0000 || defined(Py_XNewRef) + return Py_XNewRef(obj); +#else + Py_XINCREF(obj); + return obj; +#endif +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b); +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t); +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject*); +#if CYTHON_ASSUME_SAFE_MACROS +#define __Pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AS_DOUBLE(x) +#else +#define __Pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) +#define __Pyx_PyFloat_AS_DOUBLE(x) PyFloat_AsDouble(x) +#endif +#define __Pyx_PyFloat_AsFloat(x) ((float) __Pyx_PyFloat_AsDouble(x)) +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#if CYTHON_USE_PYLONG_INTERNALS + #if PY_VERSION_HEX >= 0x030C00A7 + #ifndef _PyLong_SIGN_MASK + #define _PyLong_SIGN_MASK 3 + #endif + #ifndef _PyLong_NON_SIZE_BITS + #define _PyLong_NON_SIZE_BITS 3 + #endif + #define __Pyx_PyLong_Sign(x) (((PyLongObject*)x)->long_value.lv_tag & _PyLong_SIGN_MASK) + #define __Pyx_PyLong_IsNeg(x) ((__Pyx_PyLong_Sign(x) & 2) != 0) + #define __Pyx_PyLong_IsNonNeg(x) (!__Pyx_PyLong_IsNeg(x)) + #define __Pyx_PyLong_IsZero(x) (__Pyx_PyLong_Sign(x) & 1) + #define __Pyx_PyLong_IsPos(x) (__Pyx_PyLong_Sign(x) == 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) (__Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) ((Py_ssize_t) (((PyLongObject*)x)->long_value.lv_tag >> _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_SignedDigitCount(x)\ + ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * __Pyx_PyLong_DigitCount(x)) + #if defined(PyUnstable_Long_IsCompact) && defined(PyUnstable_Long_CompactValue) + #define __Pyx_PyLong_IsCompact(x) PyUnstable_Long_IsCompact((PyLongObject*) x) + #define __Pyx_PyLong_CompactValue(x) PyUnstable_Long_CompactValue((PyLongObject*) x) + #else + #define __Pyx_PyLong_IsCompact(x) (((PyLongObject*)x)->long_value.lv_tag < (2 << _PyLong_NON_SIZE_BITS)) + #define __Pyx_PyLong_CompactValue(x) ((1 - (Py_ssize_t) __Pyx_PyLong_Sign(x)) * (Py_ssize_t) __Pyx_PyLong_Digits(x)[0]) + #endif + typedef Py_ssize_t __Pyx_compact_pylong; + typedef size_t __Pyx_compact_upylong; + #else + #define __Pyx_PyLong_IsNeg(x) (Py_SIZE(x) < 0) + #define __Pyx_PyLong_IsNonNeg(x) (Py_SIZE(x) >= 0) + #define __Pyx_PyLong_IsZero(x) (Py_SIZE(x) == 0) + #define __Pyx_PyLong_IsPos(x) (Py_SIZE(x) > 0) + #define __Pyx_PyLong_CompactValueUnsigned(x) ((Py_SIZE(x) == 0) ? 0 : __Pyx_PyLong_Digits(x)[0]) + #define __Pyx_PyLong_DigitCount(x) __Pyx_sst_abs(Py_SIZE(x)) + #define __Pyx_PyLong_SignedDigitCount(x) Py_SIZE(x) + #define __Pyx_PyLong_IsCompact(x) (Py_SIZE(x) == 0 || Py_SIZE(x) == 1 || Py_SIZE(x) == -1) + #define __Pyx_PyLong_CompactValue(x)\ + ((Py_SIZE(x) == 0) ? (sdigit) 0 : ((Py_SIZE(x) < 0) ? -(sdigit)__Pyx_PyLong_Digits(x)[0] : (sdigit)__Pyx_PyLong_Digits(x)[0])) + typedef sdigit __Pyx_compact_pylong; + typedef digit __Pyx_compact_upylong; + #endif + #if PY_VERSION_HEX >= 0x030C00A5 + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->long_value.ob_digit) + #else + #define __Pyx_PyLong_Digits(x) (((PyLongObject*)x)->ob_digit) + #endif +#endif +#if __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) +#elif __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeASCII(c_str, size, NULL) +#else + #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) +#endif + + +/* Test for GCC > 2.95 */ +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) + #define likely(x) __builtin_expect(!!(x), 1) + #define unlikely(x) __builtin_expect(!!(x), 0) +#else /* !__GNUC__ or GCC < 2.95 */ + #define likely(x) (x) + #define unlikely(x) (x) +#endif /* __GNUC__ */ +/* PretendToInitialize */ +#ifdef __cplusplus +#if __cplusplus > 201103L +#include +#endif +template +static void __Pyx_pretend_to_initialize(T* ptr) { +#if __cplusplus > 201103L + if ((std::is_trivially_default_constructible::value)) +#endif + *ptr = T(); + (void)ptr; +} +#else +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } +#endif + + +#if !CYTHON_USE_MODULE_STATE +static PyObject *__pyx_m = NULL; +#endif +static int __pyx_lineno; +static int __pyx_clineno = 0; +static const char * const __pyx_cfilenm = __FILE__; +static const char *__pyx_filename; + +/* #### Code section: filename_table ### */ + +static const char* const __pyx_f[] = { + "pysam/libcalignmentfile.pyx", + "cpython/contextvars.pxd", + "array.pxd", + "", + "pysam/libcalignmentfile.pxd", + "cpython/type.pxd", + "cpython/bool.pxd", + "cpython/complex.pxd", + "pysam/libcfaidx.pxd", + "pysam/libcalignedsegment.pxd", +}; +/* #### Code section: utility_code_proto_before_types ### */ +/* Atomics.proto */ +#include +#ifndef CYTHON_ATOMICS + #define CYTHON_ATOMICS 1 +#endif +#define __PYX_CYTHON_ATOMICS_ENABLED() CYTHON_ATOMICS +#define __PYX_GET_CYTHON_COMPILING_IN_CPYTHON_FREETHREADING() CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __pyx_atomic_int_type int +#define __pyx_nonatomic_int_type int +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__)) + #include +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ + (defined(_MSC_VER) && _MSC_VER >= 1700))) + #include +#endif +#if CYTHON_ATOMICS && (defined(__STDC_VERSION__) &&\ + (__STDC_VERSION__ >= 201112L) &&\ + !defined(__STDC_NO_ATOMICS__) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type atomic_int + #define __pyx_atomic_ptr_type atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) atomic_fetch_add_explicit(value, 1, memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) atomic_fetch_add_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) atomic_fetch_sub_explicit(value, 1, memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) atomic_load(value) + #define __pyx_atomic_store(value, new_value) atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) atomic_load_explicit(value, memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) atomic_load_explicit(value, memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C atomics" + #endif +#elif CYTHON_ATOMICS && (defined(__cplusplus) && (\ + (__cplusplus >= 201103L) ||\ +\ + (defined(_MSC_VER) && _MSC_VER >= 1700)) &&\ + ATOMIC_INT_LOCK_FREE == 2) + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type std::atomic_int + #define __pyx_atomic_ptr_type std::atomic_uintptr_t + #define __pyx_nonatomic_ptr_type uintptr_t + #define __pyx_atomic_incr_relaxed(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_relaxed) + #define __pyx_atomic_incr_acq_rel(value) std::atomic_fetch_add_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_decr_acq_rel(value) std::atomic_fetch_sub_explicit(value, 1, std::memory_order_acq_rel) + #define __pyx_atomic_sub(value, arg) std::atomic_fetch_sub(value, arg) + #define __pyx_atomic_int_cmp_exchange(value, expected, desired) std::atomic_compare_exchange_strong(value, expected, desired) + #define __pyx_atomic_load(value) std::atomic_load(value) + #define __pyx_atomic_store(value, new_value) std::atomic_store(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) std::atomic_load_explicit(value, std::memory_order_relaxed) + #define __pyx_atomic_pointer_load_acquire(value) std::atomic_load_explicit(value, std::memory_order_acquire) + #define __pyx_atomic_pointer_exchange(value, new_value) std::atomic_exchange(value, (__pyx_nonatomic_ptr_type)new_value) + #if defined(__PYX_DEBUG_ATOMICS) && defined(_MSC_VER) + #pragma message ("Using standard C++ atomics") + #elif defined(__PYX_DEBUG_ATOMICS) + #warning "Using standard C++ atomics" + #endif +#elif CYTHON_ATOMICS && (__GNUC__ >= 5 || (__GNUC__ == 4 &&\ + (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL__ >= 2)))) + #define __pyx_atomic_ptr_type void* + #define __pyx_atomic_incr_relaxed(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_incr_acq_rel(value) __sync_fetch_and_add(value, 1) + #define __pyx_atomic_decr_acq_rel(value) __sync_fetch_and_sub(value, 1) + #define __pyx_atomic_sub(value, arg) __sync_fetch_and_sub(value, arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = __sync_val_compare_and_swap(value, *expected, desired); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_store(value, new_value) __sync_lock_test_and_set(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_load_acquire(value) __sync_fetch_and_add(value, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) __sync_lock_test_and_set(value, (__pyx_atomic_ptr_type)new_value) + #ifdef __PYX_DEBUG_ATOMICS + #warning "Using GNU atomics" + #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) + #include + #undef __pyx_atomic_int_type + #define __pyx_atomic_int_type long + #define __pyx_atomic_ptr_type void* + #undef __pyx_nonatomic_int_type + #define __pyx_nonatomic_int_type long + #pragma intrinsic (_InterlockedExchangeAdd, _InterlockedExchange, _InterlockedCompareExchange, _InterlockedCompareExchangePointer, _InterlockedExchangePointer) + #define __pyx_atomic_incr_relaxed(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_incr_acq_rel(value) _InterlockedExchangeAdd(value, 1) + #define __pyx_atomic_decr_acq_rel(value) _InterlockedExchangeAdd(value, -1) + #define __pyx_atomic_sub(value, arg) _InterlockedExchangeAdd(value, -arg) + static CYTHON_INLINE int __pyx_atomic_int_cmp_exchange(__pyx_atomic_int_type* value, __pyx_nonatomic_int_type* expected, __pyx_nonatomic_int_type desired) { + __pyx_nonatomic_int_type old = _InterlockedCompareExchange(value, desired, *expected); + int result = old == *expected; + *expected = old; + return result; + } + #define __pyx_atomic_load(value) _InterlockedExchangeAdd(value, 0) + #define __pyx_atomic_store(value, new_value) _InterlockedExchange(value, new_value) + #define __pyx_atomic_pointer_load_relaxed(value) *(void * volatile *)value + #define __pyx_atomic_pointer_load_acquire(value) _InterlockedCompareExchangePointer(value, 0, 0) + #define __pyx_atomic_pointer_exchange(value, new_value) _InterlockedExchangePointer(value, (__pyx_atomic_ptr_type)new_value) + #ifdef __PYX_DEBUG_ATOMICS + #pragma message ("Using MSVC atomics") + #endif +#else + #undef CYTHON_ATOMICS + #define CYTHON_ATOMICS 0 + #ifdef __PYX_DEBUG_ATOMICS + #warning "Not using atomics" + #endif +#endif +#if CYTHON_ATOMICS + #define __pyx_add_acquisition_count(memview)\ + __pyx_atomic_incr_relaxed(__pyx_get_slice_count_pointer(memview)) + #define __pyx_sub_acquisition_count(memview)\ + __pyx_atomic_decr_acq_rel(__pyx_get_slice_count_pointer(memview)) +#else + #define __pyx_add_acquisition_count(memview)\ + __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) + #define __pyx_sub_acquisition_count(memview)\ + __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) +#endif + +/* Profile_config.proto */ +#ifndef CYTHON_PROFILE +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + #define CYTHON_PROFILE 0 +#else + #define CYTHON_PROFILE 1 +#endif +#endif +#ifndef CYTHON_TRACE_NOGIL + #define CYTHON_TRACE_NOGIL 0 +#else + #if CYTHON_TRACE_NOGIL && !defined(CYTHON_TRACE) + #define CYTHON_TRACE 1 + #endif +#endif +#ifndef CYTHON_TRACE + #define CYTHON_TRACE 0 +#endif +#if CYTHON_PROFILE || CYTHON_TRACE +#if CYTHON_USE_SYS_MONITORING + typedef enum { + __Pyx_Monitoring_PY_START = 0, + __Pyx_Monitoring_PY_RETURN, + __Pyx_Monitoring_PY_UNWIND, + __Pyx_Monitoring_LINE, + __Pyx_Monitoring_RAISE, + __Pyx_Monitoring_RERAISE, + __Pyx_Monitoring_EXCEPTION_HANDLED, + __Pyx_Monitoring_PY_RESUME, + __Pyx_Monitoring_PY_YIELD, + __Pyx_Monitoring_STOP_ITERATION, + } __Pyx_Monitoring_Event_Index; + static const unsigned char __Pyx_MonitoringEventTypes[] = { + PY_MONITORING_EVENT_PY_START, + PY_MONITORING_EVENT_PY_RETURN, + PY_MONITORING_EVENT_PY_UNWIND, + PY_MONITORING_EVENT_LINE, + PY_MONITORING_EVENT_RAISE, + PY_MONITORING_EVENT_RERAISE, + PY_MONITORING_EVENT_EXCEPTION_HANDLED, + PY_MONITORING_EVENT_PY_RESUME, + PY_MONITORING_EVENT_PY_YIELD, + PY_MONITORING_EVENT_STOP_ITERATION, + }; + #define __Pyx_MonitoringEventTypes_CyFunc_count (sizeof(__Pyx_MonitoringEventTypes) - 3) + #define __Pyx_MonitoringEventTypes_CyGen_count (sizeof(__Pyx_MonitoringEventTypes)) +#endif +#endif + +/* NoFastGil.proto */ +#define __Pyx_PyGILState_Ensure PyGILState_Ensure +#define __Pyx_PyGILState_Release PyGILState_Release +#define __Pyx_FastGIL_Remember() +#define __Pyx_FastGIL_Forget() +#define __Pyx_FastGilFuncInit() + +/* IncludeStructmemberH.proto */ +#include + +/* CriticalSections.proto */ +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +#define __Pyx_PyCriticalSection void* +#define __Pyx_PyCriticalSection2 void* +#define __Pyx_PyCriticalSection_Begin1(cs, arg) (void)cs +#define __Pyx_PyCriticalSection_Begin2(cs, arg1, arg2) (void)cs +#define __Pyx_PyCriticalSection_End1(cs) +#define __Pyx_PyCriticalSection_End2(cs) +#else +#define __Pyx_PyCriticalSection PyCriticalSection +#define __Pyx_PyCriticalSection2 PyCriticalSection2 +#define __Pyx_PyCriticalSection_Begin1 PyCriticalSection_Begin +#define __Pyx_PyCriticalSection_Begin2 PyCriticalSection2_Begin +#define __Pyx_PyCriticalSection_End1 PyCriticalSection_End +#define __Pyx_PyCriticalSection_End2 PyCriticalSection2_End +#endif +#if PY_VERSION_HEX < 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_BEGIN_CRITICAL_SECTION(o) { +#define __Pyx_END_CRITICAL_SECTION() } +#else +#define __Pyx_BEGIN_CRITICAL_SECTION Py_BEGIN_CRITICAL_SECTION +#define __Pyx_END_CRITICAL_SECTION Py_END_CRITICAL_SECTION +#endif + +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* #### Code section: numeric_typedefs ### */ +/* #### Code section: complex_type_declarations ### */ +/* #### Code section: type_declarations ### */ + +/*--- Type declarations ---*/ +#ifndef _ARRAYARRAY_H +struct arrayobject; +typedef struct arrayobject arrayobject; +#endif +struct __pyx_obj_5pysam_10libchtslib_HTSFile; +struct __pyx_obj_5pysam_9libcfaidx_FastaFile; +struct __pyx_obj_5pysam_9libcfaidx_FastqProxy; +struct __pyx_obj_5pysam_9libcfaidx_FastxRecord; +struct __pyx_obj_5pysam_9libcfaidx_FastxFile; +struct __pyx_obj_5pysam_9libcfaidx_FastqFile; +struct __pyx_obj_5pysam_9libcfaidx_Fastafile; +struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache; +struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment; +struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn; +struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead; +struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader; +struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs; +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll; +struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads; +struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall; +struct __pyx_opt_args_7cpython_11contextvars_get_value; +struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default; + +/* "cpython/contextvars.pxd":116 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the default value of the context variable, +*/ +struct __pyx_opt_args_7cpython_11contextvars_get_value { + int __pyx_n; + PyObject *default_value; +}; + +/* "cpython/contextvars.pxd":134 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value_no_default(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the provided default value if no such value was found. +*/ +struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default { + int __pyx_n; + PyObject *default_value; +}; +struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array; +struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array; + +/* "pysam/libcfaidx.pxd":50 + * cdef cython.str to_string(self) + * cdef cython.str tostring(self) + * cpdef array.array get_quality_array(self, int offset=*) # <<<<<<<<<<<<<< + * + * +*/ +struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array { + int __pyx_n; + int offset; +}; + +/* "pysam/libcfaidx.pxd":60 + * cdef cython.str to_string(self) + * cdef cython.str tostring(self) + * cpdef array.array get_quality_array(self, int offset=*) # <<<<<<<<<<<<<< + * + * cdef class FastxFile: +*/ +struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array { + int __pyx_n; + int offset; +}; +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag; +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag; +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring; + +/* "pysam/libcalignedsegment.pxd":31 + * + * from pysam.libcalignmentfile cimport AlignmentFile, AlignmentHeader + * ctypedef AlignmentFile AlignmentFile_t # <<<<<<<<<<<<<< + * + * +*/ +typedef struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_t_5pysam_18libcalignedsegment_AlignmentFile_t; + +/* "pysam/libcalignedsegment.pxd":64 + * # add an alignment tag with value to the AlignedSegment + * # an existing tag of the same name will be replaced. + * cpdef set_tag(self, tag, value, value_type=?, replace=?) # <<<<<<<<<<<<<< + * + * # get an alignment tag from the AlignedSegment +*/ +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag { + int __pyx_n; + PyObject *value_type; + PyObject *replace; +}; + +/* "pysam/libcalignedsegment.pxd":67 + * + * # get an alignment tag from the AlignedSegment + * cpdef get_tag(self, tag, with_value_type=?) # <<<<<<<<<<<<<< + * + * # return true if tag exists +*/ +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag { + int __pyx_n; + PyObject *with_value_type; +}; + +/* "pysam/libcalignedsegment.pxd":76 + * + * # returns a valid sam alignment string (deprecated) + * cpdef tostring(self, htsfile=*) # <<<<<<<<<<<<<< + * + * +*/ +struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring { + int __pyx_n; + PyObject *htsfile; +}; +struct __pyx_opt_args_5pysam_9libcutils_parse_region; +struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno; +struct __pyx_opt_args_5pysam_9libcutils_qualitystring_to_array; +struct __pyx_opt_args_5pysam_9libcutils_array_to_qualitystring; +struct __pyx_opt_args_5pysam_9libcutils_qualities_to_qualitystring; +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str; +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_bytes; +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str_w_len; +struct __pyx_opt_args_5pysam_9libcutils_force_str; +struct __pyx_opt_args_5pysam_9libcutils_force_bytes; +struct __pyx_opt_args_5pysam_9libcutils_decode_bytes; + +/* "pysam/libcutils.pxd":8 + * from cpython cimport array as c_array + * + * cpdef parse_region(contig=*, start=*, stop=*, region=*, reference=*, end=*) # <<<<<<<<<<<<<< + * + * cdef int libc_whence_from_io(int whence) +*/ +struct __pyx_opt_args_5pysam_9libcutils_parse_region { + int __pyx_n; + PyObject *contig; + PyObject *start; + PyObject *stop; + PyObject *region; + PyObject *reference; + PyObject *end; +}; + +/* "pysam/libcutils.pxd":12 + * cdef int libc_whence_from_io(int whence) + * + * cdef OSError_from_errno(message, filename=*) # <<<<<<<<<<<<<< + * + * ######################################################################### +*/ +struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno { + int __pyx_n; + PyObject *filename; +}; + +/* "pysam/libcutils.pxd":17 + * # Utility functions for quality string conversions + * + * cpdef c_array.array qualitystring_to_array(input_str, int offset=*) # <<<<<<<<<<<<<< + * cpdef array_to_qualitystring(c_array.array arr, int offset=*) + * cpdef qualities_to_qualitystring(qualities, int offset=*) +*/ +struct __pyx_opt_args_5pysam_9libcutils_qualitystring_to_array { + int __pyx_n; + int offset; +}; + +/* "pysam/libcutils.pxd":18 + * + * cpdef c_array.array qualitystring_to_array(input_str, int offset=*) + * cpdef array_to_qualitystring(c_array.array arr, int offset=*) # <<<<<<<<<<<<<< + * cpdef qualities_to_qualitystring(qualities, int offset=*) + * +*/ +struct __pyx_opt_args_5pysam_9libcutils_array_to_qualitystring { + int __pyx_n; + int offset; +}; + +/* "pysam/libcutils.pxd":19 + * cpdef c_array.array qualitystring_to_array(input_str, int offset=*) + * cpdef array_to_qualitystring(c_array.array arr, int offset=*) + * cpdef qualities_to_qualitystring(qualities, int offset=*) # <<<<<<<<<<<<<< + * + * ######################################################################## +*/ +struct __pyx_opt_args_5pysam_9libcutils_qualities_to_qualitystring { + int __pyx_n; + int offset; +}; + +/* "pysam/libcutils.pxd":31 + * ## Python 3 compatibility functions + * ######################################################################## + * cdef charptr_to_str(const char *s, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef bytes charptr_to_bytes(const char *s, encoding=*, errors=*) + * cdef charptr_to_str_w_len(const char* s, size_t n, encoding=*, errors=*) +*/ +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; + +/* "pysam/libcutils.pxd":32 + * ######################################################################## + * cdef charptr_to_str(const char *s, encoding=*, errors=*) + * cdef bytes charptr_to_bytes(const char *s, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef charptr_to_str_w_len(const char* s, size_t n, encoding=*, errors=*) + * cdef force_str(object s, encoding=*, errors=*) +*/ +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_bytes { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; + +/* "pysam/libcutils.pxd":33 + * cdef charptr_to_str(const char *s, encoding=*, errors=*) + * cdef bytes charptr_to_bytes(const char *s, encoding=*, errors=*) + * cdef charptr_to_str_w_len(const char* s, size_t n, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef force_str(object s, encoding=*, errors=*) + * cdef bytes force_bytes(object s, encoding=*, errors=*) +*/ +struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str_w_len { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; + +/* "pysam/libcutils.pxd":34 + * cdef bytes charptr_to_bytes(const char *s, encoding=*, errors=*) + * cdef charptr_to_str_w_len(const char* s, size_t n, encoding=*, errors=*) + * cdef force_str(object s, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef bytes force_bytes(object s, encoding=*, errors=*) + * cdef decode_bytes(bytes s, encoding=*, errors=*) +*/ +struct __pyx_opt_args_5pysam_9libcutils_force_str { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; + +/* "pysam/libcutils.pxd":35 + * cdef charptr_to_str_w_len(const char* s, size_t n, encoding=*, errors=*) + * cdef force_str(object s, encoding=*, errors=*) + * cdef bytes force_bytes(object s, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef decode_bytes(bytes s, encoding=*, errors=*) + * cdef bytes encode_filename(object filename) +*/ +struct __pyx_opt_args_5pysam_9libcutils_force_bytes { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; + +/* "pysam/libcutils.pxd":36 + * cdef force_str(object s, encoding=*, errors=*) + * cdef bytes force_bytes(object s, encoding=*, errors=*) + * cdef decode_bytes(bytes s, encoding=*, errors=*) # <<<<<<<<<<<<<< + * cdef bytes encode_filename(object filename) + * cdef from_string_and_size(const char *s, size_t length) +*/ +struct __pyx_opt_args_5pysam_9libcutils_decode_bytes { + int __pyx_n; + PyObject *encoding; + PyObject *errors; +}; +struct __pyx_t_5pysam_17libcalignmentfile___iterdata; +typedef struct __pyx_t_5pysam_17libcalignmentfile___iterdata __pyx_t_5pysam_17libcalignmentfile___iterdata; +struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator; +struct __pyx_opt_args_5pysam_17libcalignmentfile_fill_AlignmentHeader_from_list; + +/* "pysam/libcalignmentfile.pxd":25 + * # Utility types + * + * ctypedef struct __iterdata: # <<<<<<<<<<<<<< + * htsFile * htsfile + * bam_hdr_t * header +*/ +struct __pyx_t_5pysam_17libcalignmentfile___iterdata { + htsFile *htsfile; + bam_hdr_t *header; + hts_itr_t *iter; + faidx_t *fastafile; + int tid; + char *seq; + int seq_len; + int min_mapping_quality; + int flag_require; + int flag_filter; + int compute_baq; + int redo_baq; + int ignore_orphans; + int adjust_capq_threshold; +}; + +/* "pysam/libcalignmentfile.pxd":121 + * cdef int cnext(self) + * cdef char * get_sequence(self) + * cdef _setup_iterator(self, # <<<<<<<<<<<<<< + * int tid, + * int start, +*/ +struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator { + int __pyx_n; + int multiple_iterators; +}; + +/* "pysam/libcalignmentfile.pyx":187 + * # the following should be class-method for VariantHeader, but cdef @classmethods + * # are not implemented in cython. + * cdef int fill_AlignmentHeader_from_list(bam_hdr_t *dest, # <<<<<<<<<<<<<< + * reference_names, + * reference_lengths, +*/ +struct __pyx_opt_args_5pysam_17libcalignmentfile_fill_AlignmentHeader_from_list { + int __pyx_n; + PyObject *add_sq_text; + PyObject *text; +}; + +/* "pysam/libchtslib.pxd":2706 + * + * + * cdef class HTSFile(object): # <<<<<<<<<<<<<< + * cdef htsFile *htsfile # pointer to htsFile structure + * cdef int64_t start_offset # BGZF offset of first record +*/ +struct __pyx_obj_5pysam_10libchtslib_HTSFile { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile *__pyx_vtab; + htsFile *htsfile; + int64_t start_offset; + PyObject *filename; + PyObject *mode; + PyObject *threads; + PyObject *index_filename; + int is_stream; + int is_remote; + int duplicate_filehandle; +}; + + +/* "pysam/libcfaidx.pxd":38 + * int * dret) + * + * cdef class FastaFile: # <<<<<<<<<<<<<< + * cdef bint is_remote + * cdef object _filename, _references, _lengths, reference2length +*/ +struct __pyx_obj_5pysam_9libcfaidx_FastaFile { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile *__pyx_vtab; + int is_remote; + PyObject *_filename; + PyObject *_references; + PyObject *_lengths; + PyObject *reference2length; + faidx_t *fastafile; +}; + + +/* "pysam/libcfaidx.pxd":46 + * + * + * cdef class FastqProxy: # <<<<<<<<<<<<<< + * cdef kseq_t * _delegate + * cdef cython.str to_string(self) +*/ +struct __pyx_obj_5pysam_9libcfaidx_FastqProxy { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy *__pyx_vtab; + kseq_t *_delegate; +}; + + +/* "pysam/libcfaidx.pxd":53 + * + * + * cdef class FastxRecord: # <<<<<<<<<<<<<< + * """ + * Python container for pysam.libcfaidx.FastqProxy with persistence. +*/ +struct __pyx_obj_5pysam_9libcfaidx_FastxRecord { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord *__pyx_vtab; + PyObject *comment; + PyObject *quality; + PyObject *sequence; + PyObject *name; +}; + + +/* "pysam/libcfaidx.pxd":62 + * cpdef array.array get_quality_array(self, int offset=*) + * + * cdef class FastxFile: # <<<<<<<<<<<<<< + * cdef object _filename + * cdef BGZF * fastqfile +*/ +struct __pyx_obj_5pysam_9libcfaidx_FastxFile { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile *__pyx_vtab; + PyObject *_filename; + BGZF *fastqfile; + kseq_t *entry; + int persist; + int is_remote; +}; + + +/* "pysam/libcfaidx.pxd":74 + * + * # Compatibility Layer for pysam 0.8.1 + * cdef class FastqFile(FastxFile): # <<<<<<<<<<<<<< + * pass + * +*/ +struct __pyx_obj_5pysam_9libcfaidx_FastqFile { + struct __pyx_obj_5pysam_9libcfaidx_FastxFile __pyx_base; +}; + + +/* "pysam/libcfaidx.pxd":79 + * + * # Compatibility Layer for pysam < 0.8 + * cdef class Fastafile(FastaFile): # <<<<<<<<<<<<<< + * pass + * +*/ +struct __pyx_obj_5pysam_9libcfaidx_Fastafile { + struct __pyx_obj_5pysam_9libcfaidx_FastaFile __pyx_base; +}; + + +/* "pysam/libcalignedsegment.pxd":34 + * + * + * cdef class _AlignedSegment_Cache: # For internal use only # <<<<<<<<<<<<<< + * cdef clear_query_sequences(self) + * cdef clear_query_qualities(self) +*/ +struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_18libcalignedsegment__AlignedSegment_Cache *__pyx_vtab; + PyObject *query_sequence; + PyObject *query_alignment_sequence; + PyObject *query_qualities; + PyObject *query_qualities_str; + PyObject *query_alignment_qualities; + PyObject *query_alignment_qualities_str; +}; + + +/* "pysam/libcalignedsegment.pxd":47 + * + * # Note: need to declare all C fields and methods here + * cdef class AlignedSegment: # <<<<<<<<<<<<<< + * + * # object that this AlignedSegment represents +*/ +struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment *__pyx_vtab; + bam1_t *_delegate; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; + struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache *cache; + PyObject *unused1; + PyObject *unused2; + PyObject *unused3; +}; + + +/* "pysam/libcalignedsegment.pxd":79 + * + * + * cdef class PileupColumn: # <<<<<<<<<<<<<< + * cdef const bam_pileup1_t ** plp + * cdef int tid +*/ +struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn { + PyObject_HEAD + bam_pileup1_t const **plp; + int tid; + int pos; + int n_pu; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; + uint32_t min_base_quality; + kstring_t buf; + char *reference_sequence; +}; + + +/* "pysam/libcalignedsegment.pxd":89 + * cdef char * reference_sequence + * + * cdef class PileupRead: # <<<<<<<<<<<<<< + * cdef int32_t _qpos + * cdef AlignedSegment _alignment +*/ +struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead { + PyObject_HEAD + int32_t _qpos; + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *_alignment; + int _indel; + int _level; + uint32_t _is_del; + uint32_t _is_head; + uint32_t _is_tail; + uint32_t _is_refskip; +}; + + +/* "pysam/libcalignmentfile.pxd":42 + * + * + * cdef class AlignmentHeader(object): # <<<<<<<<<<<<<< + * cdef bam_hdr_t *ptr + * +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader { + PyObject_HEAD + bam_hdr_t *ptr; +}; + + +/* "pysam/libcalignmentfile.pxd":45 + * cdef bam_hdr_t *ptr + * + * cdef class AlignmentFile(HTSFile): # <<<<<<<<<<<<<< + * cdef readonly object reference_filename + * cdef readonly AlignmentHeader header +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile { + struct __pyx_obj_5pysam_10libchtslib_HTSFile __pyx_base; + PyObject *reference_filename; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; + hts_idx_t *index; + bam1_t *b; +}; + + +/* "pysam/libcalignmentfile.pxd":62 + * + * + * cdef class IteratorRow: # <<<<<<<<<<<<<< + * cdef int retval + * cdef bam1_t * b +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow { + PyObject_HEAD + int retval; + bam1_t *b; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; + htsFile *htsfile; + hts_idx_t *index; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; + int owns_samfile; +}; + + +/* "pysam/libcalignmentfile.pxd":72 + * + * + * cdef class IteratorRowRegion(IteratorRow): # <<<<<<<<<<<<<< + * cdef hts_itr_t * iter + * cdef bam1_t * getCurrent(self) +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_vtab; + hts_itr_t *iter; +}; + + +/* "pysam/libcalignmentfile.pxd":78 + * + * + * cdef class IteratorRowHead(IteratorRow): # <<<<<<<<<<<<<< + * cdef int max_rows + * cdef int current_row +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_vtab; + int max_rows; + int current_row; +}; + + +/* "pysam/libcalignmentfile.pxd":85 + * + * + * cdef class IteratorRowAll(IteratorRow): # <<<<<<<<<<<<<< + * cdef bam1_t * getCurrent(self) + * cdef int cnext(self) +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_vtab; +}; + + +/* "pysam/libcalignmentfile.pxd":90 + * + * + * cdef class IteratorRowAllRefs(IteratorRow): # <<<<<<<<<<<<<< + * cdef int tid + * cdef IteratorRowRegion rowiter +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; + int tid; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *rowiter; +}; + + +/* "pysam/libcalignmentfile.pxd":95 + * + * + * cdef class IteratorRowSelection(IteratorRow): # <<<<<<<<<<<<<< + * cdef int current_pos + * cdef positions +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow __pyx_base; + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_vtab; + int current_pos; + PyObject *positions; +}; + + +/* "pysam/libcalignmentfile.pxd":102 + * + * + * cdef class IteratorColumn: # <<<<<<<<<<<<<< + * + * # result of the last plbuf_push +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn { + PyObject_HEAD + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *__pyx_vtab; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *iter; + int tid; + int pos; + int n_plp; + uint32_t min_base_quality; + bam_pileup1_t const *plp; + bam_mplp_t pileup_iter; + __pyx_t_5pysam_17libcalignmentfile___iterdata iterdata; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; + struct __pyx_obj_5pysam_9libcfaidx_FastaFile *fastafile; + PyObject *stepper; + int max_depth; + int ignore_overlaps; +}; + + +/* "pysam/libcalignmentfile.pxd":134 + * + * + * cdef class IteratorColumnRegion(IteratorColumn): # <<<<<<<<<<<<<< + * cdef int start + * cdef int stop +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; + int start; + int stop; + int truncate; +}; + + +/* "pysam/libcalignmentfile.pxd":140 + * + * + * cdef class IteratorColumnAllRefs(IteratorColumn): # <<<<<<<<<<<<<< + * pass + * +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; +}; + + +/* "pysam/libcalignmentfile.pxd":144 + * + * + * cdef class IteratorColumnAll(IteratorColumn): # <<<<<<<<<<<<<< + * pass + * +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; +}; + + +/* "pysam/libcalignmentfile.pxd":148 + * + * + * cdef class IndexedReads: # <<<<<<<<<<<<<< + * cdef AlignmentFile samfile + * cdef htsFile * htsfile +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads { + PyObject_HEAD + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *samfile; + htsFile *htsfile; + PyObject *index; + int owns_samfile; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *header; +}; + + +/* "pysam/libcalignmentfile.pyx":2814 + * + * + * cdef class SNPCall: # <<<<<<<<<<<<<< + * '''the results of a SNP call.''' + * cdef int _tid +*/ +struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall { + PyObject_HEAD + int _tid; + int _pos; + char _reference_base; + char _genotype; + int _consensus_quality; + int _snp_quality; + int _rms_mapping_quality; + int _coverage; +}; + + + +/* "pysam/libchtslib.pxd":2706 + * + * + * cdef class HTSFile(object): # <<<<<<<<<<<<<< + * cdef htsFile *htsfile # pointer to htsFile structure + * cdef int64_t start_offset # BGZF offset of first record +*/ + +struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile { + htsFile *(*_open_htsfile)(struct __pyx_obj_5pysam_10libchtslib_HTSFile *); +}; +static struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile *__pyx_vtabptr_5pysam_10libchtslib_HTSFile; + + +/* "pysam/libcfaidx.pxd":38 + * int * dret) + * + * cdef class FastaFile: # <<<<<<<<<<<<<< + * cdef bint is_remote + * cdef object _filename, _references, _lengths, reference2length +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile { + char *(*_fetch)(struct __pyx_obj_5pysam_9libcfaidx_FastaFile *, char *, int, int, int *); +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile *__pyx_vtabptr_5pysam_9libcfaidx_FastaFile; + + +/* "pysam/libcfaidx.pxd":46 + * + * + * cdef class FastqProxy: # <<<<<<<<<<<<<< + * cdef kseq_t * _delegate + * cdef cython.str to_string(self) +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy { + PyObject *(*to_string)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *); + PyObject *(*tostring)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *); + arrayobject *(*get_quality_array)(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_9libcfaidx_10FastqProxy_get_quality_array *__pyx_optional_args); +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy *__pyx_vtabptr_5pysam_9libcfaidx_FastqProxy; + + +/* "pysam/libcfaidx.pxd":53 + * + * + * cdef class FastxRecord: # <<<<<<<<<<<<<< + * """ + * Python container for pysam.libcfaidx.FastqProxy with persistence. +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord { + PyObject *(*to_string)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *); + PyObject *(*tostring)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *); + arrayobject *(*get_quality_array)(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_9libcfaidx_11FastxRecord_get_quality_array *__pyx_optional_args); +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord *__pyx_vtabptr_5pysam_9libcfaidx_FastxRecord; + + +/* "pysam/libcfaidx.pxd":62 + * cpdef array.array get_quality_array(self, int offset=*) + * + * cdef class FastxFile: # <<<<<<<<<<<<<< + * cdef object _filename + * cdef BGZF * fastqfile +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile { + kseq_t *(*getCurrent)(struct __pyx_obj_5pysam_9libcfaidx_FastxFile *); + int (*cnext)(struct __pyx_obj_5pysam_9libcfaidx_FastxFile *); +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile *__pyx_vtabptr_5pysam_9libcfaidx_FastxFile; + + +/* "pysam/libcfaidx.pxd":74 + * + * # Compatibility Layer for pysam 0.8.1 + * cdef class FastqFile(FastxFile): # <<<<<<<<<<<<<< + * pass + * +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile { + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile __pyx_base; +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile *__pyx_vtabptr_5pysam_9libcfaidx_FastqFile; + + +/* "pysam/libcfaidx.pxd":79 + * + * # Compatibility Layer for pysam < 0.8 + * cdef class Fastafile(FastaFile): # <<<<<<<<<<<<<< + * pass + * +*/ + +struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile { + struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile __pyx_base; +}; +static struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile *__pyx_vtabptr_5pysam_9libcfaidx_Fastafile; + + +/* "pysam/libcalignedsegment.pxd":34 + * + * + * cdef class _AlignedSegment_Cache: # For internal use only # <<<<<<<<<<<<<< + * cdef clear_query_sequences(self) + * cdef clear_query_qualities(self) +*/ + +struct __pyx_vtabstruct_5pysam_18libcalignedsegment__AlignedSegment_Cache { + PyObject *(*clear_query_sequences)(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache *); + PyObject *(*clear_query_qualities)(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache *); +}; +static struct __pyx_vtabstruct_5pysam_18libcalignedsegment__AlignedSegment_Cache *__pyx_vtabptr_5pysam_18libcalignedsegment__AlignedSegment_Cache; + + +/* "pysam/libcalignedsegment.pxd":47 + * + * # Note: need to declare all C fields and methods here + * cdef class AlignedSegment: # <<<<<<<<<<<<<< + * + * # object that this AlignedSegment represents +*/ + +struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment { + PyObject *(*set_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_set_tag *__pyx_optional_args); + PyObject *(*get_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_get_tag *__pyx_optional_args); + PyObject *(*has_tag)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, PyObject *, int __pyx_skip_dispatch); + PyObject *(*to_string)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch); + PyObject *(*tostring)(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch, struct __pyx_opt_args_5pysam_18libcalignedsegment_14AlignedSegment_tostring *__pyx_optional_args); +}; +static struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment *__pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment; + + +/* "pysam/libcalignmentfile.pyx":582 + * + * + * cdef class AlignmentFile(HTSFile): # <<<<<<<<<<<<<< + * """AlignmentFile(filepath_or_object, mode=None, template=None, + * reference_names=None, reference_lengths=None, text=NULL, +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile { + struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile __pyx_base; + bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *); + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *); + int (*write)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile *__pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile; + + +/* "pysam/libcalignmentfile.pyx":2055 + * + * + * cdef class IteratorRowRegion(IteratorRow): # <<<<<<<<<<<<<< + * """*(AlignmentFile samfile, int tid, int beg, int stop, + * int multiple_iterators=False)* +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion { + bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *); + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion; + + +/* "pysam/libcalignmentfile.pyx":2116 + * + * + * cdef class IteratorRowHead(IteratorRow): # <<<<<<<<<<<<<< + * """*(AlignmentFile samfile, n, int multiple_iterators=False)* + * +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead { + bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *); + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead; + + +/* "pysam/libcalignmentfile.pyx":2167 + * + * + * cdef class IteratorRowAll(IteratorRow): # <<<<<<<<<<<<<< + * """*(AlignmentFile samfile, int multiple_iterators=False)* + * +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll { + bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *); + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll; + + +/* "pysam/libcalignmentfile.pyx":2271 + * + * + * cdef class IteratorRowSelection(IteratorRow): # <<<<<<<<<<<<<< + * """*(AlignmentFile samfile)* + * +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection { + bam1_t *(*getCurrent)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *); + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection; + + +/* "pysam/libcalignmentfile.pyx":2443 + * + * + * cdef class IteratorColumn: # <<<<<<<<<<<<<< + * '''abstract base class for iterators over columns. + * +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn { + int (*cnext)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); + char *(*get_sequence)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); + PyObject *(*_setup_iterator)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, int, int, int, struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator *__pyx_optional_args); + PyObject *(*_setup_raw_rest_iterator)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); + PyObject *(*reset)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, PyObject *, PyObject *, PyObject *); + PyObject *(*_free_pileup_iter)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); + char *(*getSequence)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *); +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; + + +/* "pysam/libcalignmentfile.pyx":2693 + * + * + * cdef class IteratorColumnRegion(IteratorColumn): # <<<<<<<<<<<<<< + * '''iterates over a region only. + * ''' +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion { + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion; + + +/* "pysam/libcalignmentfile.pyx":2743 + * + * + * cdef class IteratorColumnAllRefs(IteratorColumn): # <<<<<<<<<<<<<< + * """iterates over all columns by chaining iterators over each reference + * """ +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs { + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + + +/* "pysam/libcalignmentfile.pyx":2785 + * + * + * cdef class IteratorColumnAll(IteratorColumn): # <<<<<<<<<<<<<< + * """iterates over all columns, without using an index + * """ +*/ + +struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAll { + struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_base; +}; +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAll; +/* #### Code section: utility_code_proto ### */ + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ +#ifndef CYTHON_REFNANNY + #define CYTHON_REFNANNY 0 +#endif +#if CYTHON_REFNANNY + typedef struct { + void (*INCREF)(void*, PyObject*, Py_ssize_t); + void (*DECREF)(void*, PyObject*, Py_ssize_t); + void (*GOTREF)(void*, PyObject*, Py_ssize_t); + void (*GIVEREF)(void*, PyObject*, Py_ssize_t); + void* (*SetupContext)(const char*, Py_ssize_t, const char*); + void (*FinishContext)(void**); + } __Pyx_RefNannyAPIStruct; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; + static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); + #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), (__LINE__), (__FILE__));\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContextNogil() {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __Pyx_RefNannyFinishContext();\ + PyGILState_Release(__pyx_gilstate_save);\ + } + #define __Pyx_RefNannyFinishContext()\ + __Pyx_RefNanny->FinishContext(&__pyx_refnanny) + #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), (__LINE__)) + #define __Pyx_XINCREF(r) do { if((r) == NULL); else {__Pyx_INCREF(r); }} while(0) + #define __Pyx_XDECREF(r) do { if((r) == NULL); else {__Pyx_DECREF(r); }} while(0) + #define __Pyx_XGOTREF(r) do { if((r) == NULL); else {__Pyx_GOTREF(r); }} while(0) + #define __Pyx_XGIVEREF(r) do { if((r) == NULL); else {__Pyx_GIVEREF(r);}} while(0) +#else + #define __Pyx_RefNannyDeclarations + #define __Pyx_RefNannySetupContext(name, acquire_gil) + #define __Pyx_RefNannyFinishContextNogil() + #define __Pyx_RefNannyFinishContext() + #define __Pyx_INCREF(r) Py_INCREF(r) + #define __Pyx_DECREF(r) Py_DECREF(r) + #define __Pyx_GOTREF(r) + #define __Pyx_GIVEREF(r) + #define __Pyx_XINCREF(r) Py_XINCREF(r) + #define __Pyx_XDECREF(r) Py_XDECREF(r) + #define __Pyx_XGOTREF(r) + #define __Pyx_XGIVEREF(r) +#endif +#define __Pyx_Py_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; Py_XDECREF(tmp);\ + } while (0) +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ + } while (0) +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ + } while (0) +#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) +#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) + +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#if PY_VERSION_HEX >= 0x030C00A6 +#define __Pyx_PyErr_Occurred() (__pyx_tstate->current_exception != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->current_exception ? (PyObject*) Py_TYPE(__pyx_tstate->current_exception) : (PyObject*) NULL) +#else +#define __Pyx_PyErr_Occurred() (__pyx_tstate->curexc_type != NULL) +#define __Pyx_PyErr_CurrentExceptionType() (__pyx_tstate->curexc_type) +#endif +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() (PyErr_Occurred() != NULL) +#define __Pyx_PyErr_CurrentExceptionType() PyErr_Occurred() +#endif + +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A6 +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) +#else +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) +#endif + +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); +#else +#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) +#endif + +/* PyObjectGetAttrStrNoError.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); + +/* GetBuiltinName.proto */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name); + +/* TupleAndListFromArray.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n); +#endif +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject* __Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n); +#endif + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); + +/* fastcall.proto */ +#if CYTHON_AVOID_BORROWED_REFS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_PySequence_ITEM(args, i) +#elif CYTHON_ASSUME_SAFE_MACROS + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_NewRef(__Pyx_PyTuple_GET_ITEM(args, i)) +#else + #define __Pyx_ArgRef_VARARGS(args, i) __Pyx_XNewRef(PyTuple_GetItem(args, i)) +#endif +#define __Pyx_NumKwargs_VARARGS(kwds) PyDict_Size(kwds) +#define __Pyx_KwValues_VARARGS(args, nargs) NULL +#define __Pyx_GetKwValue_VARARGS(kw, kwvalues, s) __Pyx_PyDict_GetItemStrWithError(kw, s) +#define __Pyx_KwargsAsDict_VARARGS(kw, kwvalues) PyDict_Copy(kw) +#if CYTHON_METH_FASTCALL + #define __Pyx_ArgRef_FASTCALL(args, i) __Pyx_NewRef(args[i]) + #define __Pyx_NumKwargs_FASTCALL(kwds) __Pyx_PyTuple_GET_SIZE(kwds) + #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs)) + static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API + CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues); + #else + #define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw) + #endif +#else + #define __Pyx_ArgRef_FASTCALL __Pyx_ArgRef_VARARGS + #define __Pyx_NumKwargs_FASTCALL __Pyx_NumKwargs_VARARGS + #define __Pyx_KwValues_FASTCALL __Pyx_KwValues_VARARGS + #define __Pyx_GetKwValue_FASTCALL __Pyx_GetKwValue_VARARGS + #define __Pyx_KwargsAsDict_FASTCALL __Pyx_KwargsAsDict_VARARGS +#endif +#define __Pyx_ArgsSlice_VARARGS(args, start, stop) PyTuple_GetSlice(args, start, stop) +#if CYTHON_METH_FASTCALL || (CYTHON_COMPILING_IN_CPYTHON && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) __Pyx_PyTuple_FromArray(args + start, stop - start) +#else +#define __Pyx_ArgsSlice_FASTCALL(args, start, stop) PyTuple_GetSlice(args, start, stop) +#endif + +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); + +/* ParseKeywords.proto */ +static CYTHON_INLINE int __Pyx_ParseKeywords( + PyObject *kwds, PyObject *const *kwvalues, PyObject ** const argnames[], + PyObject *kwds2, PyObject *values[], + Py_ssize_t num_pos_args, Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs +); + +/* CallCFunction.proto */ +#define __Pyx_CallCFunction(cfunc, self, args)\ + ((PyCFunction)(void(*)(void))(cfunc)->func)(self, args) +#define __Pyx_CallCFunctionWithKeywords(cfunc, self, args, kwargs)\ + ((PyCFunctionWithKeywords)(void(*)(void))(cfunc)->func)(self, args, kwargs) +#define __Pyx_CallCFunctionFast(cfunc, self, args, nargs)\ + ((__Pyx_PyCFunctionFast)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs) +#define __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, nargs, kwnames)\ + ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))(PyCFunction)(cfunc)->func)(self, args, nargs, kwnames) + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#if !CYTHON_VECTORCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); +#endif +#define __Pyx_BUILD_ASSERT_EXPR(cond)\ + (sizeof(char [1 - 2*!(cond)]) - 1) +#ifndef Py_MEMBER_SIZE +#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) +#endif +#if !CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03080000 + #include "frameobject.h" + #define __Pxy_PyFrame_Initialize_Offsets() + #define __Pyx_PyFrame_GetLocalsplus(frame) ((frame)->f_localsplus) +#else + static size_t __pyx_pyframe_localsplus_offset = 0; + #include "frameobject.h" + #define __Pxy_PyFrame_Initialize_Offsets()\ + ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ + (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) + #define __Pyx_PyFrame_GetLocalsplus(frame)\ + (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) +#endif +#endif +#endif + +/* PyObjectCall.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); +#else +#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) +#endif + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectFastCall.proto */ +#define __Pyx_PyObject_FastCall(func, args, nargs) __Pyx_PyObject_FastCallDict(func, args, (size_t)(nargs), NULL) +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs); + +/* UnpackUnboundCMethod.proto */ +typedef struct { + PyObject *type; + PyObject **method_name; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && CYTHON_ATOMICS + __pyx_atomic_int_type initialized; +#endif + PyCFunction func; + PyObject *method; + int flag; +} __Pyx_CachedCFunction; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING +static CYTHON_INLINE int __Pyx_CachedCFunction_GetAndSetInitializing(__Pyx_CachedCFunction *cfunc) { +#if !CYTHON_ATOMICS + return 1; +#else + __pyx_nonatomic_int_type expected = 0; + if (__pyx_atomic_int_cmp_exchange(&cfunc->initialized, &expected, 1)) { + return 0; + } + return expected; +#endif +} +static CYTHON_INLINE void __Pyx_CachedCFunction_SetFinishedInitializing(__Pyx_CachedCFunction *cfunc) { +#if CYTHON_ATOMICS + __pyx_atomic_store(&cfunc->initialized, 2); +#endif +} +#else +#define __Pyx_CachedCFunction_GetAndSetInitializing(cfunc) 2 +#define __Pyx_CachedCFunction_SetFinishedInitializing(cfunc) +#endif + +/* CallUnboundCMethod2.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2); +#else +#define __Pyx_CallUnboundCMethod2(cfunc, self, arg1, arg2) __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2) +#endif + +/* RaiseArgTupleInvalid.proto */ +static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, + Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); + +/* Profile.proto */ +#if CYTHON_TRACE + #undef CYTHON_PROFILE_REUSE_FRAME +#endif +#if CYTHON_USE_MODULE_STATE + #undef CYTHON_PROFILE_REUSE_CODEOBJ + #define CYTHON_PROFILE_REUSE_CODEOBJ 0 + #undef CYTHON_PROFILE_REUSE_FRAME +#endif +#ifndef CYTHON_PROFILE_REUSE_CODEOBJ + #define CYTHON_PROFILE_REUSE_CODEOBJ 1 +#endif +#ifndef CYTHON_PROFILE_REUSE_FRAME + #define CYTHON_PROFILE_REUSE_FRAME 0 +#endif +#if CYTHON_USE_SYS_MONITORING && (CYTHON_PROFILE || CYTHON_TRACE) + #define __PYX_MONITORING_ABI_SUFFIX "_mon" +#else + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_PROFILE || CYTHON_TRACE +#if CYTHON_USE_SYS_MONITORING + typedef uint64_t __pyx_monitoring_version_type; + #define __Pyx_TraceDeclarationsFunc\ + PyObject *__pyx_frame_code = NULL;\ + PyMonitoringState __pyx_pymonitoring_state[__Pyx_MonitoringEventTypes_CyFunc_count];\ + int __pyx_exception_already_reported = 0;\ + const int __pyx_sys_monitoring_disabled_in_parallel = 0; CYTHON_UNUSED_VAR(__pyx_sys_monitoring_disabled_in_parallel); + #define __Pyx_TraceDeclarationsGen\ + PyObject *__pyx_frame_code = Py_NewRef(__pyx_generator->gi_code);\ + PyMonitoringState* __pyx_pymonitoring_state = __pyx_generator->__pyx_pymonitoring_state;\ + __pyx_monitoring_version_type __pyx_pymonitoring_version = __pyx_generator->__pyx_pymonitoring_version;\ + int __pyx_exception_already_reported = 0;\ + const int __pyx_sys_monitoring_disabled_in_parallel = 0; CYTHON_UNUSED_VAR(__pyx_sys_monitoring_disabled_in_parallel); + #define __Pyx_IsTracing(event_id) ((!__pyx_sys_monitoring_disabled_in_parallel) && (__pyx_pymonitoring_state[event_id]).active) + #define __Pyx_TraceFrameInit(codeobj)\ + if (codeobj) __pyx_frame_code = codeobj; + #define __Pyx_TurnOffSysMonitoringInParallel\ + const int __pyx_sys_monitoring_disabled_in_parallel = 1;\ + CYTHON_UNUSED_VAR(__pyx_sys_monitoring_disabled_in_parallel); + CYTHON_UNUSED static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); + CYTHON_UNUSED static int __Pyx__TraceStartFunc(PyMonitoringState *state_array, PyObject *code_obj, int offset, int skip_event); + CYTHON_UNUSED static int __Pyx__TraceStartGen(PyMonitoringState *state_array, __pyx_monitoring_version_type *version, PyObject *code_obj, int offset); + CYTHON_UNUSED static int __Pyx__TraceResumeGen(PyMonitoringState *state_array, __pyx_monitoring_version_type *version, PyObject *code_obj, int offset); + CYTHON_UNUSED static void __Pyx__TraceException(PyMonitoringState *monitoring_state, PyObject *code_obj, int offset, int reraised); + #define __Pyx_PyMonitoring_ExitScope(nogil)\ + if (nogil) {\ + (void) __pyx_exception_already_reported;\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + PyMonitoring_ExitScope();\ + Py_XDECREF(__pyx_frame_code);\ + PyGILState_Release(state);\ + }\ + } else {\ + PyMonitoring_ExitScope();\ + Py_XDECREF(__pyx_frame_code);\ + } + #define __Pyx_TraceStartFunc(funcname, srcfile, firstlineno, offset, nogil, skip_event, goto_error)\ + if ((0) ); else {\ + int ret = 0;\ + memset(__pyx_pymonitoring_state, 0, sizeof(__pyx_pymonitoring_state));\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + if (!__Pyx_PyThreadState_Current->tracing) {\ + if (likely(__pyx_frame_code)) Py_INCREF(__pyx_frame_code);\ + else __pyx_frame_code = (PyObject*) __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno);\ + if (unlikely(!__pyx_frame_code)) goto_error;\ + ret = __Pyx__TraceStartFunc(__pyx_pymonitoring_state, __pyx_frame_code, offset, skip_event);\ + }\ + PyGILState_Release(state);\ + }\ + } else {\ + if (!__Pyx_PyThreadState_Current->tracing) {\ + if (likely(__pyx_frame_code)) Py_INCREF(__pyx_frame_code);\ + else __pyx_frame_code = (PyObject*) __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno);\ + if (unlikely(!__pyx_frame_code)) goto_error;\ + ret = __Pyx__TraceStartFunc(__pyx_pymonitoring_state, __pyx_frame_code, offset, skip_event);\ + }\ + }\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceStartGen(funcname, srcfile, firstlineno, offset, nogil, skip_event, goto_error)\ + if ((0) ); else {\ + int ret = __Pyx__TraceStartGen(__pyx_pymonitoring_state, &__pyx_pymonitoring_version, __pyx_frame_code, offset);\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceResumeGen(funcname, srcfile, firstlineno, offset, goto_error)\ + if ((0) ); else {\ + int ret = __Pyx__TraceResumeGen(__pyx_pymonitoring_state, &__pyx_pymonitoring_version, __pyx_frame_code, offset);\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceYield(result, offset, goto_error)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_PY_YIELD)); else {\ + int ret = PyMonitoring_FirePyYieldEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_RETURN], __pyx_frame_code, offset, result);\ + PyMonitoring_ExitScope();\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceException(offset, reraised, fresh)\ + if (!__Pyx_IsTracing((reraised) ? __Pyx_Monitoring_RERAISE : __Pyx_Monitoring_RAISE)); else {\ + if (fresh || reraised || !__pyx_exception_already_reported) {\ + __Pyx__TraceException(&__pyx_pymonitoring_state[(reraised) ? __Pyx_Monitoring_RERAISE : __Pyx_Monitoring_RAISE], __pyx_frame_code, offset, reraised);\ + }\ + __pyx_exception_already_reported = 1;\ + } + #define __Pyx_TraceExceptionDone() __pyx_exception_already_reported = 0 + #define __Pyx_TraceExceptionHandled(offset)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_EXCEPTION_HANDLED)); else {\ + (void) PyMonitoring_FireExceptionHandledEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_EXCEPTION_HANDLED], __pyx_frame_code, offset);\ + __pyx_exception_already_reported = 0;\ + } + #define __Pyx_TraceReturnValue(result, offset, nogil, goto_error)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_PY_RETURN)); else {\ + int ret = 0;\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + ret = PyMonitoring_FirePyReturnEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_RETURN], __pyx_frame_code, offset, result);\ + PyGILState_Release(state);\ + }\ + } else {\ + ret = PyMonitoring_FirePyReturnEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_RETURN], __pyx_frame_code, offset, result);\ + }\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceReturnCValue(cresult, convert_function, offset, nogil, goto_error)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_PY_RETURN)); else {\ + int ret = 0;\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + PyObject *pyvalue = convert_function(cresult);\ + if (unlikely(!pyvalue)) {\ + PyErr_Clear();\ + pyvalue = Py_None; Py_INCREF(Py_None);\ + }\ + ret = PyMonitoring_FirePyReturnEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_RETURN], __pyx_frame_code, offset, pyvalue);\ + Py_DECREF(pyvalue);\ + PyGILState_Release(state);\ + }\ + } else {\ + PyObject *pyvalue = convert_function(cresult);\ + if (unlikely(!pyvalue)) {\ + PyErr_Clear();\ + pyvalue = Py_None; Py_INCREF(Py_None);\ + }\ + ret = PyMonitoring_FirePyReturnEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_RETURN], __pyx_frame_code, offset, pyvalue);\ + Py_DECREF(pyvalue);\ + }\ + if (unlikely(ret == -1)) goto_error;\ + } + #define __Pyx_TraceExceptionUnwind(offset, nogil)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_PY_UNWIND)); else {\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + (void) PyMonitoring_FirePyUnwindEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_UNWIND], __pyx_frame_code, offset);\ + PyGILState_Release(state);\ + }\ + } else {\ + (void) PyMonitoring_FirePyUnwindEvent(&__pyx_pymonitoring_state[__Pyx_Monitoring_PY_UNWIND], __pyx_frame_code, offset);\ + }\ + } + #if CYTHON_TRACE + CYTHON_UNUSED static int __Pyx__TraceLine(PyMonitoringState *monitoring_state, PyObject *code_obj, int line, int offset); + #define __Pyx_TraceLine(line, offset, nogil, goto_error)\ + if (!__Pyx_IsTracing(__Pyx_Monitoring_LINE)); else {\ + int ret = 0;\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyGILState_STATE state = PyGILState_Ensure();\ + ret = __Pyx__TraceLine(&__pyx_pymonitoring_state[__Pyx_Monitoring_LINE], __pyx_frame_code, line, offset);\ + PyGILState_Release(state);\ + }\ + } else {\ + ret = __Pyx__TraceLine(&__pyx_pymonitoring_state[__Pyx_Monitoring_LINE], __pyx_frame_code, line, offset);\ + }\ + if (unlikely(ret == -1)) goto_error;\ + } + #endif +#else + #include "compile.h" + #include "frameobject.h" + #include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif + #if CYTHON_PROFILE_REUSE_FRAME + #define CYTHON_FRAME_MODIFIER static + #define CYTHON_FRAME_DEL(frame) + #else + #define CYTHON_FRAME_MODIFIER + #define CYTHON_FRAME_DEL(frame) Py_CLEAR(frame) + #endif + #if CYTHON_PROFILE_REUSE_CODEOBJ + #define CYTHON_CODEOBJ_MODIFIER static + #else + #define CYTHON_CODEOBJ_MODIFIER + #endif + #define __Pyx_TraceDeclarationsFunc\ + CYTHON_CODEOBJ_MODIFIER PyCodeObject *__pyx_frame_code = NULL;\ + CYTHON_FRAME_MODIFIER PyFrameObject *__pyx_frame = NULL;\ + int __Pyx_use_tracing = 0; + #define __Pyx_TraceDeclarationsGen\ + PyObject *__pyx_frame_code = __pyx_generator->gi_code;\ + CYTHON_FRAME_MODIFIER PyFrameObject *__pyx_frame = NULL;\ + int __Pyx_use_tracing = 0; + #define __Pyx_TraceFrameInit(codeobj)\ + if (codeobj) __pyx_frame_code = (PyCodeObject*) codeobj; + #define __Pyx_PyMonitoring_ExitScope(nogil) {} + #define __Pyx_TraceException(offset, reraised, fresh) {} + #define __Pyx_TraceExceptionHandled(offset) {} + #define __Pyx_TraceExceptionDone() {} + #define __Pyx_TurnOffSysMonitoringInParallel {} // Only needed for freethreading +#if PY_VERSION_HEX >= 0x030b00a2 + #if PY_VERSION_HEX >= 0x030C00b1 + #define __Pyx_IsTracing(tstate, check_tracing, check_funcs)\ + ((!(check_tracing) || !(tstate)->tracing) &&\ + (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc))) + #else + #define __Pyx_IsTracing(tstate, check_tracing, check_funcs)\ + (unlikely((tstate)->cframe->use_tracing) &&\ + (!(check_tracing) || !(tstate)->tracing) &&\ + (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc))) + #endif + #define __Pyx_EnterTracing(tstate) PyThreadState_EnterTracing(tstate) + #define __Pyx_LeaveTracing(tstate) PyThreadState_LeaveTracing(tstate) +#elif PY_VERSION_HEX >= 0x030a00b1 + #define __Pyx_IsTracing(tstate, check_tracing, check_funcs)\ + (unlikely((tstate)->cframe->use_tracing) &&\ + (!(check_tracing) || !(tstate)->tracing) &&\ + (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc))) + #define __Pyx_EnterTracing(tstate)\ + do { tstate->tracing++; tstate->cframe->use_tracing = 0; } while (0) + #define __Pyx_LeaveTracing(tstate)\ + do {\ + tstate->tracing--;\ + tstate->cframe->use_tracing = ((CYTHON_TRACE && tstate->c_tracefunc != NULL)\ + || tstate->c_profilefunc != NULL);\ + } while (0) +#else + #define __Pyx_IsTracing(tstate, check_tracing, check_funcs)\ + (unlikely((tstate)->use_tracing) &&\ + (!(check_tracing) || !(tstate)->tracing) &&\ + (!(check_funcs) || (tstate)->c_profilefunc || (CYTHON_TRACE && (tstate)->c_tracefunc))) + #define __Pyx_EnterTracing(tstate)\ + do { tstate->tracing++; tstate->use_tracing = 0; } while (0) + #define __Pyx_LeaveTracing(tstate)\ + do {\ + tstate->tracing--;\ + tstate->use_tracing = ((CYTHON_TRACE && tstate->c_tracefunc != NULL)\ + || tstate->c_profilefunc != NULL);\ + } while (0) +#endif + #define __Pyx_TraceStartFunc(funcname, srcfile, firstlineno, offset, nogil, skip_event, goto_error)\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyThreadState *tstate;\ + PyGILState_STATE state = PyGILState_Ensure();\ + tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 1, 1)) {\ + __Pyx_use_tracing = __Pyx_TraceSetupAndCall((PyCodeObject**)&__pyx_frame_code, &__pyx_frame, tstate, funcname, srcfile, firstlineno, skip_event);\ + }\ + PyGILState_Release(state);\ + if (unlikely(__Pyx_use_tracing < 0)) goto_error;\ + }\ + } else {\ + PyThreadState* tstate = PyThreadState_GET();\ + if (__Pyx_IsTracing(tstate, 1, 1)) {\ + __Pyx_use_tracing = __Pyx_TraceSetupAndCall((PyCodeObject**)&__pyx_frame_code, &__pyx_frame, tstate, funcname, srcfile, firstlineno, skip_event);\ + if (unlikely(__Pyx_use_tracing < 0)) goto_error;\ + }\ + } + #define __Pyx_TraceStartGen __Pyx_TraceStartFunc + #define __Pyx_TraceYield(result, offset, goto_error)\ + if (likely(!__Pyx_use_tracing)); else {\ + PyThreadState* tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, (PyObject*)result, 0);\ + }\ + if ((1)); else goto_error;\ + } + #define __Pyx_TraceResumeGen(funcname, srcfile, firstlineno, offset, goto_error)\ + __Pyx_TraceStartFunc(funcname, srcfile, firstlineno, offset, 0, 0, goto_error) + CYTHON_UNUSED static void __Pyx_call_return_trace_func(PyThreadState *tstate, PyFrameObject *frame, PyObject *result, int delete_frame) { + PyObject *type, *value, *traceback; + __Pyx_ErrFetchInState(tstate, &type, &value, &traceback); + __Pyx_EnterTracing(tstate); + if (CYTHON_TRACE && tstate->c_tracefunc) + tstate->c_tracefunc(tstate->c_traceobj, frame, PyTrace_RETURN, result); + if (tstate->c_profilefunc) + tstate->c_profilefunc(tstate->c_profileobj, frame, PyTrace_RETURN, result); + if (delete_frame) { + CYTHON_FRAME_DEL(frame); + } + __Pyx_LeaveTracing(tstate); + __Pyx_ErrRestoreInState(tstate, type, value, traceback); + } + #define __Pyx_TraceReturnValue(result, offset, nogil, goto_error)\ + if (likely(!__Pyx_use_tracing)); else {\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyThreadState *tstate;\ + PyGILState_STATE state = PyGILState_Ensure();\ + tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, (PyObject*)result, 1);\ + }\ + PyGILState_Release(state);\ + }\ + } else {\ + PyThreadState* tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, (PyObject*)result, 1);\ + }\ + }\ + if ((1)); else goto_error;\ + } + #define __Pyx_TraceReturnCValue(cresult, convert_function, offset, nogil, goto_error)\ + if (likely(!__Pyx_use_tracing)); else {\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyThreadState *tstate;\ + PyGILState_STATE state = PyGILState_Ensure();\ + tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + PyObject *pyvalue = convert_function(cresult);\ + if (unlikely(!pyvalue)) goto_error;\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, pyvalue, 1);\ + Py_DECREF(pyvalue);\ + }\ + PyGILState_Release(state);\ + }\ + } else {\ + PyThreadState* tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + PyObject *pyvalue = convert_function(cresult);\ + if (unlikely(!pyvalue)) goto_error;\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, pyvalue, 1);\ + Py_DECREF(pyvalue);\ + }\ + }\ + } + #define __Pyx_TraceExceptionUnwind(offset, nogil)\ + if (likely(!__Pyx_use_tracing)); else {\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyThreadState *tstate;\ + PyGILState_STATE state = PyGILState_Ensure();\ + tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, Py_None, 1);\ + }\ + PyGILState_Release(state);\ + }\ + } else {\ + PyThreadState* tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0)) {\ + __Pyx_call_return_trace_func(tstate, __pyx_frame, Py_None, 1);\ + }\ + }\ + } + static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, PyThreadState* tstate, const char *funcname, const char *srcfile, int firstlineno, int skip_event); +#if CYTHON_TRACE + CYTHON_UNUSED static int __Pyx_call_line_trace_func(PyThreadState *tstate, PyFrameObject *frame, int line); + #define __Pyx_TraceLine(line, offset, nogil, goto_error)\ + if (likely(!__Pyx_use_tracing)); else {\ + int ret = 0;\ + if (nogil) {\ + if (CYTHON_TRACE_NOGIL) {\ + PyThreadState *tstate;\ + PyGILState_STATE state = __Pyx_PyGILState_Ensure();\ + tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0) && tstate->c_tracefunc && __pyx_frame->f_trace) {\ + ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, line);\ + }\ + __Pyx_PyGILState_Release(state);\ + }\ + } else {\ + PyThreadState* tstate = __Pyx_PyThreadState_Current;\ + if (__Pyx_IsTracing(tstate, 0, 0) && tstate->c_tracefunc && __pyx_frame->f_trace) {\ + ret = __Pyx_call_line_trace_func(tstate, __pyx_frame, line);\ + }\ + }\ + if (unlikely(ret)) goto_error;\ + } +#endif +#endif +#else + #define __Pyx_TraceDeclarationsFunc + #define __Pyx_TraceDeclarationsGen + #define __Pyx_TraceExceptionDone() {} + #define __Pyx_TraceFrameInit(codeobj) {} + #define __Pyx_TurnOffSysMonitoringInParallel {} + #define __Pyx_PyMonitoring_ExitScope(nogil) {} + #define __Pyx_TraceException(offset, reraised, fresh) {} + #define __Pyx_TraceExceptionUnwind(offset, nogil) {} + #define __Pyx_TraceExceptionHandled(offset) {} + #define __Pyx_TraceStartFunc(funcname, srcfile, firstlineno, offset, nogil, skip_event, goto_error) if ((1)); else goto_error; + #define __Pyx_TraceStartGen __Pyx_TraceStartFunc + #define __Pyx_TraceResumeGen(funcname, srcfile, firstlineno, offset, goto_error) if ((1)); else goto_error; + #define __Pyx_TraceYield(result, offset, goto_error) if ((1)); else goto_error; + #define __Pyx_TraceReturnValue(result, offset, nogil, goto_error)\ + if ((1)); else goto_error; + #define __Pyx_TraceReturnCValue(cresult, convert_function, offset, nogil, goto_error)\ + if ((1)); else { (void) convert_function; goto_error } +#endif +#if !CYTHON_TRACE + #define __Pyx_TraceLine(line, offset, nogil, goto_error) if ((1)); else goto_error; +#endif + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) +#endif + +/* PyObjectFastCallMethod.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_PyObject_FastCallMethod(name, args, nargsf) PyObject_VectorcallMethod(name, args, nargsf, NULL) +#else +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf); +#endif + +/* PyObjectFormatAndDecref.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f); +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f); + +/* PyObject_Unicode.proto */ +#define __Pyx_PyObject_Unicode(obj)\ + (likely(PyUnicode_CheckExact(obj)) ? __Pyx_NewRef(obj) : PyObject_Str(obj)) + +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* ObjectGetItem.proto */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key); +#else +#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) +#endif + +/* JoinPyUnicode.proto */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char); + +/* PyDictVersioning.proto */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) +#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ + (version_var) = __PYX_GET_DICT_VERSION(dict);\ + (cache_var) = (value); +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ + (VAR) = __pyx_dict_cached_value;\ + } else {\ + (VAR) = __pyx_dict_cached_value = (LOOKUP);\ + __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ + }\ +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); +#else +#define __PYX_GET_DICT_VERSION(dict) (0) +#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) +#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); +#endif + +/* GetModuleGlobalName.proto */ +#if CYTHON_USE_DICT_VERSIONS +#define __Pyx_GetModuleGlobalName(var, name) do {\ + static PY_UINT64_T __pyx_dict_version = 0;\ + static PyObject *__pyx_dict_cached_value = NULL;\ + (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_mstate_global->__pyx_d))) ?\ + (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ + __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +#define __Pyx_GetModuleGlobalNameUncached(var, name) do {\ + PY_UINT64_T __pyx_dict_version;\ + PyObject *__pyx_dict_cached_value;\ + (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ +} while(0) +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); +#else +#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) +#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); +#endif + +/* PySequenceContains.proto */ +static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { + int result = PySequence_Contains(seq, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* RaiseException.proto */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); + +/* PyLongCompare.proto */ +static CYTHON_INLINE int __Pyx_PyLong_BoolEqObjC(PyObject *op1, PyObject *op2, long intval, long inplace); + +/* RejectKeywords.proto */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds); + +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS +static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { + PyListObject* L = (PyListObject*) list; + Py_ssize_t len = Py_SIZE(list); + if (likely(L->allocated > len)) { + Py_INCREF(x); + #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 + L->ob_item[len] = x; + #else + PyList_SET_ITEM(list, len, x); + #endif + __Pyx_SET_SIZE(list, len + 1); + return 0; + } + return PyList_Append(list, x); +} +#else +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) +#endif + +/* SliceObject.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( + PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** py_start, PyObject** py_stop, PyObject** py_slice, + int has_cstart, int has_cstop, int wraparound); + +/* DictGetItem.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); +#define __Pyx_PyObject_Dict_GetItem(obj, name)\ + (likely(PyDict_CheckExact(obj)) ?\ + __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) +#else +#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) +#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) +#endif + +/* GetTopmostException.proto */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); +#endif + +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); + +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); + +/* UnicodeConcatInPlace.proto */ +# if CYTHON_COMPILING_IN_CPYTHON + #if CYTHON_REFNANNY + #define __Pyx_PyUnicode_ConcatInPlace(left, right) __Pyx_PyUnicode_ConcatInPlaceImpl(&left, right, __pyx_refnanny) + #else + #define __Pyx_PyUnicode_ConcatInPlace(left, right) __Pyx_PyUnicode_ConcatInPlaceImpl(&left, right) + #endif + static CYTHON_INLINE PyObject *__Pyx_PyUnicode_ConcatInPlaceImpl(PyObject **p_left, PyObject *right + #if CYTHON_REFNANNY + , void* __pyx_refnanny + #endif + ); +#else +#define __Pyx_PyUnicode_ConcatInPlace __Pyx_PyUnicode_Concat +#endif +#define __Pyx_PyUnicode_ConcatInPlaceSafe(left, right) ((unlikely((left) == Py_None) || unlikely((right) == Py_None)) ?\ + PyNumber_InPlaceAdd(left, right) : __Pyx_PyUnicode_ConcatInPlace(left, right)) + +/* WriteUnraisableException.proto */ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback, int nogil); + +/* AssertionsEnabled.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API || (CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030C0000) + static int __pyx_assertions_enabled_flag; + #define __pyx_assertions_enabled() (__pyx_assertions_enabled_flag) + static int __Pyx_init_assertions_enabled(void) { + PyObject *builtins, *debug, *debug_str; + int flag; + builtins = PyEval_GetBuiltins(); + if (!builtins) goto bad; + debug_str = PyUnicode_FromStringAndSize("__debug__", 9); + if (!debug_str) goto bad; + debug = PyObject_GetItem(builtins, debug_str); + Py_DECREF(debug_str); + if (!debug) goto bad; + flag = PyObject_IsTrue(debug); + Py_DECREF(debug); + if (flag == -1) goto bad; + __pyx_assertions_enabled_flag = flag; + return 0; + bad: + __pyx_assertions_enabled_flag = 1; + return -1; + } +#else + #define __Pyx_init_assertions_enabled() (0) + #define __pyx_assertions_enabled() (!Py_OptimizeFlag) +#endif + +/* PyObjectCall2Args.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* PyObjectGetMethod.proto */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); + +/* PyObjectCallMethod1.proto */ +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); + +/* append.proto */ +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x); + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* KeywordStringCheck.proto */ +static CYTHON_INLINE int __Pyx_CheckKeywordStrings(const char* function_name, PyObject *kw); + +/* PyDictContains.proto */ +static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { + int result = PyDict_Contains(dict, item); + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely(__Pyx_IS_TYPE(obj, type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); + +/* HasAttr.proto */ +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_HasAttr(o, n) PyObject_HasAttrWithError(o, n) +#else +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); +#endif + +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); + +/* PyObjectVectorCallKwBuilder.proto */ +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#if CYTHON_VECTORCALL +#if PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_Vectorcall_CallFromBuilder PyObject_Vectorcall +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder _PyObject_Vectorcall +#endif +#define __Pyx_MakeVectorcallBuilderKwds(n) PyTuple_New(n) +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n); +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n); +#else +#define __Pyx_Object_Vectorcall_CallFromBuilder __Pyx_PyObject_FastCallDict +#define __Pyx_MakeVectorcallBuilderKwds(n) __Pyx_PyDict_NewPresized(n) +#define __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n) PyDict_SetItem(builder, key, value) +#define __Pyx_VectorcallBuilder_AddArgStr(key, value, builder, args, n) PyDict_SetItemString(builder, key, value) +#endif + +/* PyObjectVectorCallMethodKwBuilder.proto */ +#if CYTHON_VECTORCALL && PY_VERSION_HEX >= 0x03090000 +#define __Pyx_Object_VectorcallMethod_CallFromBuilder PyObject_VectorcallMethod +#else +static PyObject *__Pyx_Object_VectorcallMethod_CallFromBuilder(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#endif + +/* PyLongCompare.proto */ +static CYTHON_INLINE int __Pyx_PyLong_BoolNeObjC(PyObject *op1, PyObject *op2, long intval, long inplace); + +/* PyObjectCallNoArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); + +/* PyObjectCallMethod0.proto */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* RaiseNoneIterError.proto */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); + +/* UnpackTupleError.proto */ +static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); + +/* UnpackTuple2.proto */ +static CYTHON_INLINE int __Pyx_unpack_tuple2( + PyObject* tuple, PyObject** value1, PyObject** value2, int is_tuple, int has_known_size, int decref_tuple); +static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** value1, PyObject** value2, int decref_tuple); +static int __Pyx_unpack_tuple2_generic( + PyObject* tuple, PyObject** value1, PyObject** value2, int has_known_size, int decref_tuple); + +/* dict_iter.proto */ +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_is_dict); +static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); + +/* MergeKeywords.proto */ +static int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping); + +/* PyLongBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE PyObject* __Pyx_PyLong_AndObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); +#else +#define __Pyx_PyLong_AndObjC(op1, op2, intval, inplace, zerodivision_check)\ + (inplace ? PyNumber_InPlaceAnd(op1, op2) : PyNumber_And(op1, op2)) +#endif + +/* RaiseUnexpectedTypeError.proto */ +static int __Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj); + +/* SetStringIndexingError.proto */ +static void __Pyx_SetStringIndexingError(const char* message, int has_gil); + +/* GetItemIntUnicode.proto */ +#define __Pyx_GetItemInt_Unicode(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck, has_gil)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Unicode_Fast(o, (Py_ssize_t)i, wraparound, boundscheck, has_gil) :\ + (__Pyx_SetStringIndexingError("string index out of range", has_gil), (Py_UCS4)-1)) +static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, + int wraparound, int boundscheck, int has_gil); + +/* RaiseUnboundLocalError.proto */ +static void __Pyx_RaiseUnboundLocalError(const char *varname); + +/* pyfrozenset_new.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it); + +/* PySetContains.proto */ +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq); + +/* dict_getitem_default.proto */ +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value); + +/* CallUnboundCMethod1.proto */ +CYTHON_UNUSED +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg); +#else +#define __Pyx_CallUnboundCMethod1(cfunc, self, arg) __Pyx__CallUnboundCMethod1(cfunc, self, arg) +#endif + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); + +/* CallNextTpDealloc.proto */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc); + +/* CallNextTpTraverse.proto */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse); + +/* CallTypeTraverse.proto */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#define __Pyx_call_type_traverse(o, always_call, visit, arg) 0 +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg); +#endif + +/* CallNextTpClear.proto */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear); + +/* LimitedApiGetTypeDict.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp); +#endif + +/* SetItemOnTypeDict.proto */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v); +#define __Pyx_SetItemOnTypeDict(tp, k, v) __Pyx__SetItemOnTypeDict((PyTypeObject*)tp, k, v) + +/* FixUpExtensionType.proto */ +static CYTHON_INLINE int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type); + +/* ValidateBasesTuple.proto */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases); +#endif + +/* PyType_Ready.proto */ +CYTHON_UNUSED static int __Pyx_PyType_Ready(PyTypeObject *t); + +/* DelItemOnTypeDict.proto */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k); +#define __Pyx_DelItemOnTypeDict(tp, k) __Pyx__DelItemOnTypeDict((PyTypeObject*)tp, k) + +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* TypeImport.proto */ +#ifndef __PYX_HAVE_RT_ImportType_proto_3_1_2 +#define __PYX_HAVE_RT_ImportType_proto_3_1_2 +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#include +#endif +#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || __cplusplus >= 201103L +#define __PYX_GET_STRUCT_ALIGNMENT_3_1_2(s) alignof(s) +#else +#define __PYX_GET_STRUCT_ALIGNMENT_3_1_2(s) sizeof(void*) +#endif +enum __Pyx_ImportType_CheckSize_3_1_2 { + __Pyx_ImportType_CheckSize_Error_3_1_2 = 0, + __Pyx_ImportType_CheckSize_Warn_3_1_2 = 1, + __Pyx_ImportType_CheckSize_Ignore_3_1_2 = 2 +}; +static PyTypeObject *__Pyx_ImportType_3_1_2(PyObject* module, const char *module_name, const char *class_name, size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_1_2 check_size); +#endif + +/* GetVTable.proto */ +static void* __Pyx_GetVtable(PyTypeObject *type); + +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyTypeObject* typeptr , void* vtable); + +/* MergeVTables.proto */ +static int __Pyx_MergeVtables(PyTypeObject *type); + +/* ImportDottedModule.proto */ +static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple); +static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple); + +/* ListPack.proto */ +static PyObject *__Pyx_PyList_Pack(Py_ssize_t n, ...); + +/* FetchSharedCythonModule.proto */ +static PyObject *__Pyx_FetchSharedCythonABIModule(void); + +/* dict_setdefault.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *default_value, int is_safe_type); + +/* FetchCommonType.proto */ +static PyTypeObject* __Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases); + +/* CommonTypesMetaclass.proto */ +static int __pyx_CommonTypesMetaclass_init(PyObject *module); +#define __Pyx_CommonTypesMetaclass_USED + +/* PyMethodNew.proto */ +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ); + +/* PyVectorcallFastCallDict.proto */ +#if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw); +#endif + +/* CythonFunctionShared.proto */ +#define __Pyx_CyFunction_USED +#define __Pyx_CYFUNCTION_STATICMETHOD 0x01 +#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 +#define __Pyx_CYFUNCTION_CCLASS 0x04 +#define __Pyx_CYFUNCTION_COROUTINE 0x08 +#define __Pyx_CyFunction_GetClosure(f)\ + (((__pyx_CyFunctionObject *) (f))->func_closure) +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + #define __Pyx_CyFunction_GetClassObj(f)\ + (((__pyx_CyFunctionObject *) (f))->func_classobj) +#else + #define __Pyx_CyFunction_GetClassObj(f)\ + ((PyObject*) ((PyCMethodObject *) (f))->mm_class) +#endif +#define __Pyx_CyFunction_SetClassObj(f, classobj)\ + __Pyx__CyFunction_SetClassObj((__pyx_CyFunctionObject *) (f), (classobj)) +#define __Pyx_CyFunction_Defaults(type, f)\ + ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ + ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) +typedef struct { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject_HEAD + PyObject *func; +#elif PY_VERSION_HEX < 0x030900B1 + PyCFunctionObject func; +#else + PyCMethodObject func; +#endif +#if CYTHON_BACKPORT_VECTORCALL ||\ + (CYTHON_COMPILING_IN_LIMITED_API && CYTHON_METH_FASTCALL) + __pyx_vectorcallfunc func_vectorcall; +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_weakreflist; +#endif + PyObject *func_dict; + PyObject *func_name; + PyObject *func_qualname; + PyObject *func_doc; + PyObject *func_globals; + PyObject *func_code; + PyObject *func_closure; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + PyObject *func_classobj; +#endif + PyObject *defaults; + int flags; + PyObject *defaults_tuple; + PyObject *defaults_kwdict; + PyObject *(*defaults_getter)(PyObject *); + PyObject *func_annotations; + PyObject *func_is_coroutine; +} __pyx_CyFunctionObject; +#undef __Pyx_CyOrPyCFunction_Check +#define __Pyx_CyFunction_Check(obj) __Pyx_TypeCheck(obj, __pyx_mstate_global->__pyx_CyFunctionType) +#define __Pyx_CyOrPyCFunction_Check(obj) __Pyx_TypeCheck2(obj, __pyx_mstate_global->__pyx_CyFunctionType, &PyCFunction_Type) +#define __Pyx_CyFunction_CheckExact(obj) __Pyx_IS_TYPE(obj, __pyx_mstate_global->__pyx_CyFunctionType) +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)); +#undef __Pyx_IsSameCFunction +#define __Pyx_IsSameCFunction(func, cfunc) __Pyx__IsSameCyOrCFunction(func, cfunc) +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject* op, PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj); +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, + PyTypeObject *defaults_type); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, + PyObject *tuple); +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, + PyObject *dict); +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, + PyObject *dict); +static int __pyx_CyFunction_init(PyObject *module); +#if CYTHON_METH_FASTCALL +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames); +#if CYTHON_BACKPORT_VECTORCALL || CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_func_vectorcall(f) (((__pyx_CyFunctionObject*)f)->func_vectorcall) +#else +#define __Pyx_CyFunction_func_vectorcall(f) (((PyCFunctionObject*)f)->vectorcall) +#endif +#endif + +/* CythonFunction.proto */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, + int flags, PyObject* qualname, + PyObject *closure, + PyObject *module, PyObject *globals, + PyObject* code); + +/* ClassMethod.proto */ +#if !CYTHON_COMPILING_IN_LIMITED_API +#include "descrobject.h" +#endif +CYTHON_UNUSED static PyObject* __Pyx_Method_ClassMethod(PyObject *method); + +/* GetNameInClass.proto */ +#define __Pyx_GetNameInClass(var, nmspace, name) (var) = __Pyx__GetNameInClass(nmspace, name) +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name); + +/* CLineInTraceback.proto */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#else +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#endif + +/* CodeObjectCache.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject __Pyx_CachedCodeObjectType; +#else +typedef PyCodeObject __Pyx_CachedCodeObjectType; +#endif +typedef struct { + __Pyx_CachedCodeObjectType* code_object; + int code_line; +} __Pyx_CodeObjectCacheEntry; +struct __Pyx_CodeObjectCache { + int count; + int max_count; + __Pyx_CodeObjectCacheEntry* entries; + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_int_type accessor_count; + #endif +}; +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line); +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object); + +/* AddTraceback.proto */ +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename); + +/* ArrayAPI.proto */ +#ifndef _ARRAYARRAY_H +#define _ARRAYARRAY_H +typedef struct arraydescr { + int typecode; + int itemsize; + PyObject * (*getitem)(struct arrayobject *, Py_ssize_t); + int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *); + char *formats; +} arraydescr; +struct arrayobject { + PyObject_HEAD + Py_ssize_t ob_size; + union { + char *ob_item; + float *as_floats; + double *as_doubles; + int *as_ints; + unsigned int *as_uints; + unsigned char *as_uchars; + signed char *as_schars; + char *as_chars; + unsigned long *as_ulongs; + long *as_longs; + unsigned long long *as_ulonglongs; + long long *as_longlongs; + short *as_shorts; + unsigned short *as_ushorts; + #if PY_VERSION_HEX >= 0x030d0000 + Py_DEPRECATED(3.13) + #endif + wchar_t *as_pyunicodes; + void *as_voidptr; + } data; + Py_ssize_t allocated; + struct arraydescr *ob_descr; + PyObject *weakreflist; + int ob_exports; +}; +#ifndef NO_NEWARRAY_INLINE +static CYTHON_INLINE PyObject * newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr) { + arrayobject *op; + size_t nbytes; + if (size < 0) { + PyErr_BadInternalCall(); + return NULL; + } + nbytes = size * descr->itemsize; + if (nbytes / descr->itemsize != (size_t)size) { + return PyErr_NoMemory(); + } + op = (arrayobject *) type->tp_alloc(type, 0); + if (op == NULL) { + return NULL; + } + op->ob_descr = descr; + op->allocated = size; + op->weakreflist = NULL; + __Pyx_SET_SIZE(op, size); + if (size <= 0) { + op->data.ob_item = NULL; + } + else { + op->data.ob_item = PyMem_NEW(char, nbytes); + if (op->data.ob_item == NULL) { + Py_DECREF(op); + return PyErr_NoMemory(); + } + } + return (PyObject *) op; +} +#else +PyObject* newarrayobject(PyTypeObject *type, Py_ssize_t size, + struct arraydescr *descr); +#endif +static CYTHON_INLINE int resize(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + PyMem_Resize(items, char, (size_t)(n * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + __Pyx_SET_SIZE(self, n); + self->allocated = n; + return 0; +} +static CYTHON_INLINE int resize_smart(arrayobject *self, Py_ssize_t n) { + void *items = (void*) self->data.ob_item; + Py_ssize_t newsize; + if (n < self->allocated && n*4 > self->allocated) { + __Pyx_SET_SIZE(self, n); + return 0; + } + newsize = n + (n / 2) + 1; + if (newsize <= n) { + PyErr_NoMemory(); + return -1; + } + PyMem_Resize(items, char, (size_t)(newsize * self->ob_descr->itemsize)); + if (items == NULL) { + PyErr_NoMemory(); + return -1; + } + self->data.ob_item = (char*) items; + __Pyx_SET_SIZE(self, n); + self->allocated = newsize; + return 0; +} +#endif + +/* GCCDiagnostics.proto */ +#if !defined(__INTEL_COMPILER) && defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) +#define __Pyx_HAS_GCC_DIAGNOSTIC +#endif + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_char(char value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE char __Pyx_PyLong_As_char(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE uint32_t __Pyx_PyLong_As_uint32_t(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int32_t(int32_t value); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_uint32_t(uint32_t value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int64_t __Pyx_PyLong_As_int64_t(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE int32_t __Pyx_PyLong_As_int32_t(PyObject *); + +/* CIntToPy.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_uint64_t(uint64_t value); + +/* CIntFromPy.proto */ +static CYTHON_INLINE uint64_t __Pyx_PyLong_As_uint64_t(PyObject *); + +/* FormatTypeName.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API +typedef PyObject *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%U" +#define __Pyx_DECREF_TypeName(obj) Py_XDECREF(obj) +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 +#define __Pyx_PyType_GetFullyQualifiedName PyType_GetFullyQualifiedName +#else +static __Pyx_TypeName __Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp); +#endif +#else // !LIMITED_API +typedef const char *__Pyx_TypeName; +#define __Pyx_FMT_TYPENAME "%.200s" +#define __Pyx_PyType_GetFullyQualifiedName(tp) ((tp)->tp_name) +#define __Pyx_DECREF_TypeName(obj) +#endif + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) __Pyx_IsAnySubtype2(Py_TYPE(obj), (PyTypeObject *)type1, (PyTypeObject *)type2) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_TypeCheck2(obj, type1, type2) (PyObject_TypeCheck(obj, (PyTypeObject *)type1) || PyObject_TypeCheck(obj, (PyTypeObject *)type2)) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2) { + return PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2); +} +#endif +#define __Pyx_PyErr_ExceptionMatches2(err1, err2) __Pyx_PyErr_GivenExceptionMatches2(__Pyx_PyErr_CurrentExceptionType(), err1, err2) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) +#ifdef PyExceptionInstance_Check + #define __Pyx_PyBaseException_Check(obj) PyExceptionInstance_Check(obj) +#else + #define __Pyx_PyBaseException_Check(obj) __Pyx_TypeCheck(obj, PyExc_BaseException) +#endif + +/* GetRuntimeVersion.proto */ +static unsigned long __Pyx_get_runtime_version(void); + +/* CheckBinaryVersion.proto */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer); + +/* FunctionImport.proto */ +static int __Pyx_ImportFunction_3_1_2(PyObject *module, const char *funcname, void (**f)(void), const char *sig); + +/* MultiPhaseInitModuleState.proto */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +static PyObject *__Pyx_State_FindModule(void*); +static int __Pyx_State_AddModule(PyObject* module, void*); +static int __Pyx_State_RemoveModule(void*); +#elif CYTHON_USE_MODULE_STATE +#define __Pyx_State_FindModule PyState_FindModule +#define __Pyx_State_AddModule PyState_AddModule +#define __Pyx_State_RemoveModule PyState_RemoveModule +#endif + +/* #### Code section: module_declarations ### */ +/* CythonABIVersion.proto */ +#if CYTHON_COMPILING_IN_LIMITED_API + #if CYTHON_METH_FASTCALL + #define __PYX_FASTCALL_ABI_SUFFIX "_fastcall" + #else + #define __PYX_FASTCALL_ABI_SUFFIX + #endif + #define __PYX_LIMITED_ABI_SUFFIX "limited" __PYX_FASTCALL_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#else + #define __PYX_LIMITED_ABI_SUFFIX +#endif +#if __PYX_HAS_PY_AM_SEND == 1 + #define __PYX_AM_SEND_ABI_SUFFIX +#elif __PYX_HAS_PY_AM_SEND == 2 + #define __PYX_AM_SEND_ABI_SUFFIX "amsendbackport" +#else + #define __PYX_AM_SEND_ABI_SUFFIX "noamsend" +#endif +#ifndef __PYX_MONITORING_ABI_SUFFIX + #define __PYX_MONITORING_ABI_SUFFIX +#endif +#if CYTHON_USE_TP_FINALIZE + #define __PYX_TP_FINALIZE_ABI_SUFFIX +#else + #define __PYX_TP_FINALIZE_ABI_SUFFIX "nofinalize" +#endif +#if CYTHON_USE_FREELISTS || !defined(__Pyx_AsyncGen_USED) + #define __PYX_FREELISTS_ABI_SUFFIX +#else + #define __PYX_FREELISTS_ABI_SUFFIX "nofreelists" +#endif +#define CYTHON_ABI __PYX_ABI_VERSION __PYX_LIMITED_ABI_SUFFIX __PYX_MONITORING_ABI_SUFFIX __PYX_TP_FINALIZE_ABI_SUFFIX __PYX_FREELISTS_ABI_SUFFIX __PYX_AM_SEND_ABI_SUFFIX +#define __PYX_ABI_MODULE_NAME "_cython_" CYTHON_ABI +#define __PYX_TYPE_MODULE_PREFIX __PYX_ABI_MODULE_NAME "." + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4real_real(PyComplexObject *__pyx_v_self); /* proto*/ +#endif +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4imag_imag(PyComplexObject *__pyx_v_self); /* proto*/ +#endif +static int __pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_write(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read, int __pyx_skip_dispatch); /* proto*/ +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto*/ +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto*/ +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self); /* proto*/ +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self); /* proto*/ +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self); /* proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto*/ +static char *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_get_sequence(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, int __pyx_v_tid, int __pyx_v_start, int __pyx_v_stop, struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator *__pyx_optional_args); /* proto*/ +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_raw_rest_iterator(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto*/ +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_reset(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, PyObject *__pyx_v_tid, PyObject *__pyx_v_start, PyObject *__pyx_v_stop); /* proto*/ +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__free_pileup_iter(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto*/ +static char *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_getSequence(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto*/ + +/* Module declarations from "libc.stdint" */ + +/* Module declarations from "libc.string" */ + +/* Module declarations from "libc.stdlib" */ + +/* Module declarations from "libc.stdio" */ + +/* Module declarations from "cython" */ + +/* Module declarations from "cpython.version" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.type" */ + +/* Module declarations from "cpython.object" */ + +/* Module declarations from "cpython.ref" */ + +/* Module declarations from "cpython.exc" */ + +/* Module declarations from "cpython.module" */ + +/* Module declarations from "cpython.mem" */ + +/* Module declarations from "cpython.tuple" */ + +/* Module declarations from "cpython.list" */ + +/* Module declarations from "cpython.sequence" */ + +/* Module declarations from "cpython.mapping" */ + +/* Module declarations from "cpython.iterator" */ + +/* Module declarations from "cpython.number" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.bool" */ + +/* Module declarations from "cpython.long" */ + +/* Module declarations from "cpython.float" */ + +/* Module declarations from "__builtin__" */ + +/* Module declarations from "cpython.complex" */ + +/* Module declarations from "libc.stddef" */ + +/* Module declarations from "cpython.unicode" */ + +/* Module declarations from "cpython.pyport" */ + +/* Module declarations from "cpython.dict" */ + +/* Module declarations from "cpython.instance" */ + +/* Module declarations from "cpython.function" */ + +/* Module declarations from "cpython.method" */ + +/* Module declarations from "cpython.weakref" */ + +/* Module declarations from "cpython.getargs" */ + +/* Module declarations from "cpython.pythread" */ + +/* Module declarations from "cpython.pystate" */ + +/* Module declarations from "cpython.set" */ + +/* Module declarations from "cpython.buffer" */ + +/* Module declarations from "cpython.bytes" */ + +/* Module declarations from "cpython.pycapsule" */ + +/* Module declarations from "cpython.contextvars" */ + +/* Module declarations from "cpython" */ + +/* Module declarations from "array" */ + +/* Module declarations from "cpython.array" */ +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *, Py_ssize_t, int); /*proto*/ +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *, char *, Py_ssize_t); /*proto*/ + +/* Module declarations from "posix.types" */ + +/* Module declarations from "pysam.libchtslib" */ + +/* Module declarations from "pysam.libcfaidx" */ + +/* Module declarations from "pysam.libcalignedsegment" */ +static struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *(*__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment)(bam1_t *, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *); /*proto*/ +static struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn *(*__pyx_f_5pysam_18libcalignedsegment_makePileupColumn)(bam_pileup1_t const **, int, int, int, uint32_t, char *, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *); /*proto*/ + +/* Module declarations from "libc.errno" */ + +/* Module declarations from "pysam.libcutils" */ +static PyObject *(*__pyx_f_5pysam_9libcutils_OSError_from_errno)(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno *__pyx_optional_args); /*proto*/ +static PyObject *(*__pyx_f_5pysam_9libcutils_charptr_to_str)(char const *, struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str *__pyx_optional_args); /*proto*/ +static PyObject *(*__pyx_f_5pysam_9libcutils_force_str)(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_force_str *__pyx_optional_args); /*proto*/ +static PyObject *(*__pyx_f_5pysam_9libcutils_force_bytes)(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_force_bytes *__pyx_optional_args); /*proto*/ +static PyObject *(*__pyx_f_5pysam_9libcutils_encode_filename)(PyObject *); /*proto*/ +static PyObject *(*__pyx_f_5pysam_9libcutils_from_string_and_size)(char const *, size_t); /*proto*/ + +/* Module declarations from "pysam.libcalignmentfile" */ +static int __pyx_v_5pysam_17libcalignmentfile_MAX_POS; +static struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(bam_hdr_t *); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile___advance_nofilter(void *, bam1_t *); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile___advance_raw_nofilter(void *, bam1_t *); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile___advance_all(void *, bam1_t *); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile___advance_raw_all(void *, bam1_t *); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile___advance_samtools(void *, bam1_t *); /*proto*/ +static PyObject *__pyx_f_5pysam_17libcalignmentfile___pyx_unpickle_SNPCall__set_state(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *, PyObject *); /*proto*/ +/* #### Code section: typeinfo ### */ +/* #### Code section: before_global_var ### */ +#define __Pyx_MODULE_NAME "pysam.libcalignmentfile" +extern int __pyx_module_is_main_pysam__libcalignmentfile; +int __pyx_module_is_main_pysam__libcalignmentfile = 0; + +/* Implementation of "pysam.libcalignmentfile" */ +/* #### Code section: global_var ### */ +static PyObject *__pyx_builtin_ImportError; +static PyObject *__pyx_builtin_ValueError; +static PyObject *__pyx_builtin_MemoryError; +static PyObject *__pyx_builtin_sum; +static PyObject *__pyx_builtin_KeyError; +static PyObject *__pyx_builtin_zip; +static PyObject *__pyx_builtin_range; +static PyObject *__pyx_builtin_AssertionError; +static PyObject *__pyx_builtin_enumerate; +static PyObject *__pyx_builtin_TypeError; +static PyObject *__pyx_builtin_AttributeError; +static PyObject *__pyx_builtin_NotImplementedError; +static PyObject *__pyx_builtin_IOError; +static PyObject *__pyx_builtin_StopIteration; +static PyObject *__pyx_builtin_super; +static PyObject *__pyx_builtin_map; +static PyObject *__pyx_builtin_OSError; +/* #### Code section: string_decls ### */ +static const char __pyx_k_[] = ":"; +static const char __pyx_k_L[] = "L"; +static const char __pyx_k_N[] = "N"; +static const char __pyx_k_Q[] = "\200\001\330\004\n\210+\220Q"; +static const char __pyx_k_b[] = "b"; +static const char __pyx_k_c[] = "c"; +static const char __pyx_k_h[] = "h"; +static const char __pyx_k_n[] = "n"; +static const char __pyx_k_r[] = "r"; +static const char __pyx_k_s[] = "@%s"; +static const char __pyx_k_t[] = "t"; +static const char __pyx_k_w[] = "w"; +static const char __pyx_k_x[] = "x"; +static const char __pyx_k_y[] = "y"; +static const char __pyx_k_4q[] = "\210\001\330\014\023\2204\220q"; +static const char __pyx_k_4y[] = "\210\001\330\014\023\2204\220y\240\001"; +static const char __pyx_k_AH[] = "AH"; +static const char __pyx_k_AN[] = "AN"; +static const char __pyx_k_AS[] = "AS"; +static const char __pyx_k_BC[] = "BC"; +static const char __pyx_k_CL[] = "CL"; +static const char __pyx_k_CN[] = "CN"; +static const char __pyx_k_CO[] = "CO"; +static const char __pyx_k_DS[] = "DS"; +static const char __pyx_k_DT[] = "DT"; +static const char __pyx_k_FO[] = "FO"; +static const char __pyx_k_GO[] = "GO"; +static const char __pyx_k_HD[] = "HD"; +static const char __pyx_k_ID[] = "ID"; +static const char __pyx_k_KS[] = "KS"; +static const char __pyx_k_LB[] = "LB"; +static const char __pyx_k_LN[] = "LN"; +static const char __pyx_k_M5[] = "M5"; +static const char __pyx_k_PG[] = "PG"; +static const char __pyx_k_PI[] = "PI"; +static const char __pyx_k_PL[] = "PL"; +static const char __pyx_k_PM[] = "PM"; +static const char __pyx_k_PN[] = "PN"; +static const char __pyx_k_PP[] = "PP"; +static const char __pyx_k_PU[] = "PU"; +static const char __pyx_k_RG[] = "RG"; +static const char __pyx_k_SM[] = "SM"; +static const char __pyx_k_SN[] = "SN"; +static const char __pyx_k_SO[] = "SO"; +static const char __pyx_k_SP[] = "SP"; +static const char __pyx_k_SQ[] = "@SQ"; +static const char __pyx_k_SS[] = "SS"; +static const char __pyx_k_TP[] = "TP"; +static const char __pyx_k_UR[] = "UR"; +static const char __pyx_k_VN[] = "VN"; +static const char __pyx_k__2[] = "\t"; +static const char __pyx_k__3[] = "\n"; +static const char __pyx_k__4[] = ""; +static const char __pyx_k__5[] = " \000"; +static const char __pyx_k__6[] = "@"; +static const char __pyx_k__7[] = "': '"; +static const char __pyx_k__8[] = "'"; +static const char __pyx_k__9[] = "-"; +static const char __pyx_k_gc[] = "gc"; +static const char __pyx_k_io[] = "io"; +static const char __pyx_k_nt[] = "nt"; +static const char __pyx_k_op[] = "op"; +static const char __pyx_k_os[] = "os"; +static const char __pyx_k_rU[] = "rU"; +static const char __pyx_k_rb[] = "rb"; +static const char __pyx_k_rc[] = "rc"; +static const char __pyx_k_re[] = "re"; +static const char __pyx_k_sq[] = "sq"; +static const char __pyx_k_wb[] = "wb"; +static const char __pyx_k_wc[] = "wc"; +static const char __pyx_k_wh[] = "wh"; +static const char __pyx_k_4t1[] = "\210\001\330\014\023\2204\220t\2301"; +static const char __pyx_k_A_Q[] = "\200A\360\010\000\t\r\320\014%\240Q"; +static const char __pyx_k_A_q[] = "\200A\330\010\017\210q"; +static const char __pyx_k_A_t[] = "\200A\330\010\017\210t\220>\240\021"; +static const char __pyx_k_Q_2[] = "\320\007\032\230'\240\024\240Q"; +static const char __pyx_k_QfA[] = "\200\001\330\004%\240Q\240f\250A"; +static const char __pyx_k__11[] = "."; +static const char __pyx_k__12[] = "?"; +static const char __pyx_k__13[] = "\230\021"; +static const char __pyx_k__14[] = "\240!"; +static const char __pyx_k_all[] = "all"; +static const char __pyx_k_beg[] = "beg"; +static const char __pyx_k_cls[] = "cls"; +static const char __pyx_k_end[] = "end"; +static const char __pyx_k_get[] = "get"; +static const char __pyx_k_hdr[] = "hdr"; +static const char __pyx_k_idx[] = "idx"; +static const char __pyx_k_key[] = "key"; +static const char __pyx_k_len[] = "__len__"; +static const char __pyx_k_map[] = "map"; +static const char __pyx_k_new[] = "__new__"; +static const char __pyx_k_plp[] = "plp"; +static const char __pyx_k_pop[] = "pop"; +static const char __pyx_k_pos[] = "pos"; +static const char __pyx_k_ref[] = "ref"; +static const char __pyx_k_res[] = "res"; +static const char __pyx_k_ret[] = "ret"; +static const char __pyx_k_seq[] = "seq"; +static const char __pyx_k_str[] = "__str__"; +static const char __pyx_k_sum[] = "sum"; +static const char __pyx_k_tid[] = "tid"; +static const char __pyx_k_wb0[] = "wb0"; +static const char __pyx_k_wbu[] = "wbu"; +static const char __pyx_k_zip[] = "zip"; +static const char __pyx_k_56_1[] = "\200\001\360\006\00056\330-;\2701"; +static const char __pyx_k_A_G1[] = "\200A\330\010\014\210G\2201"; +static const char __pyx_k_A_iq[] = "\200A\330\010\016\210i\220q\230\001"; +static const char __pyx_k_A_t1[] = "\200A\330\010\017\210t\2201"; +static const char __pyx_k_SQ_2[] = "SQ"; +static const char __pyx_k_args[] = "args"; +static const char __pyx_k_bool[] = "__bool__"; +static const char __pyx_k_code[] = "code"; +static const char __pyx_k_copy[] = "copy"; +static const char __pyx_k_data[] = "data"; +static const char __pyx_k_dest[] = "dest"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_exit[] = "__exit__"; +static const char __pyx_k_find[] = "find"; +static const char __pyx_k_flag[] = "flag"; +static const char __pyx_k_func[] = "__func__"; +static const char __pyx_k_head[] = "head"; +static const char __pyx_k_init[] = "__init__"; +static const char __pyx_k_iter[] = "__iter__"; +static const char __pyx_k_keys[] = "keys"; +static const char __pyx_k_line[] = "line"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_make[] = "_make"; +static const char __pyx_k_mate[] = "mate"; +static const char __pyx_k_mode[] = "mode"; +static const char __pyx_k_name[] = "name"; +static const char __pyx_k_next[] = "__next__"; +static const char __pyx_k_open[] = "_open"; +static const char __pyx_k_port[] = "port"; +static const char __pyx_k_qpos[] = "qpos"; +static const char __pyx_k_read[] = "read"; +static const char __pyx_k_rtid[] = "rtid"; +static const char __pyx_k_self[] = "self"; +static const char __pyx_k_spec[] = "__spec__"; +static const char __pyx_k_stop[] = "stop"; +static const char __pyx_k_tell[] = "tell"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_text[] = "text"; +static const char __pyx_k_warn[] = "warn"; +static const char __pyx_k_5Rq_L[] = "\320\007\032\230'\320!5\260R\260q\270\004\270L\310\001"; +static const char __pyx_k_A_F_q[] = "\200A\330\010\014\210F\220!\330\010\017\210q"; +static const char __pyx_k_A_a_1[] = "\210\001\330\014\020\220\014\230A\340\021\022\330\020\024\320\024)\250\021\250$\250a\330\014\023\2201"; +static const char __pyx_k_A_at1[] = "\200A\330\010\017\320\017\"\240!\240;\250a\250t\2601"; +static const char __pyx_k_A_q_A[] = "\200A\330\010\027\220q\230\004\230A"; +static const char __pyx_k_A_t81[] = "\200A\340\010\017\210t\2208\2301"; +static const char __pyx_k_A_t82[] = "\200A\330\010\017\210t\2208\2302\230\\\250\021\250!"; +static const char __pyx_k_A_t9A[] = "\200A\360\006\000\t\020\210t\2209\230A"; +static const char __pyx_k_A_t_2[] = "\200A\330\010\017\210t\220=\240\001"; +static const char __pyx_k_A_t_3[] = "\200A\330\010\017\210t\220>\240\021\240!"; +static const char __pyx_k_all_2[] = "__all__"; +static const char __pyx_k_array[] = "array"; +static const char __pyx_k_avQ_2[] = "\320\004)\250\021\360&\000\t\020\210\230a\230v\240Q\330\0372\260!"; +static const char __pyx_k_btext[] = "btext"; +static const char __pyx_k_build[] = "build"; +static const char __pyx_k_cigar[] = "cigar"; +static const char __pyx_k_cinit[] = "__cinit__"; +static const char __pyx_k_close[] = "close"; +static const char __pyx_k_cmode[] = "cmode"; +static const char __pyx_k_cnext[] = "cnext"; +static const char __pyx_k_count[] = "count"; +static const char __pyx_k_ctext[] = "ctext"; +static const char __pyx_k_enter[] = "__enter__"; +static const char __pyx_k_fetch[] = "fetch"; +static const char __pyx_k_field[] = "field"; +static const char __pyx_k_get_2[] = "__get__"; +static const char __pyx_k_index[] = "index"; +static const char __pyx_k_items[] = "items"; +static const char __pyx_k_lines[] = "lines"; +static const char __pyx_k_n_plp[] = "n_plp"; +static const char __pyx_k_qname[] = "qname"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_reset[] = "reset"; +static const char __pyx_k_rstop[] = "rstop"; +static const char __pyx_k_split[] = "split"; +static const char __pyx_k_start[] = "start"; +static const char __pyx_k_state[] = "state"; +static const char __pyx_k_strip[] = "strip"; +static const char __pyx_k_super[] = "super"; +static const char __pyx_k_total[] = "total"; +static const char __pyx_k_value[] = "value"; +static const char __pyx_k_write[] = "write"; +static const char __pyx_k_5Rq_Na[] = "\320\007\032\230'\320!5\260R\260q\270\004\320\250\021\330\030\031\330\030+\2501\360\010\000\025\034\320\033-\250Q\330\030\031\330\030+\2501\340\014\017\210q\330\020\026\220j\240\001\330\024\025\340\014\017\320\017\"\240#\240Q\330\020\026\220j\240\001\330\024\025\340\014\023\220>\240\021\240!\330\"5\260Q"; +static const char __pyx_k_A_q_1_q_82Rt1_1A_Kq_a_G1_4q_a_5[] = "\200A\340\023\024\330%&\330\036\037\330 !\330!\"\330\023\024\330\025\026\330\023\024\330\032\033\330\035\036\330\033\034\330\027\030\330\035\036\330\035\036\330\034\035\330\035\036\330\037 \330#$\330 !\330\035\036\330\026\027\360\016\000\t \230q\330\010)\250\021\330\010 \240\001\330\010\033\2301\330\010\037\230q\360\006\000\t\014\2108\2202\220R\220t\2301\360\014\000\014\022\220\032\2301\230A\330\010\014\210K\220q\360\006\000\t\014\210?\230'\240\021\330\014\036\230a\330\010\013\320\013\034\230G\2401\330\014 \240\001\360\006\000\t\014\2104\210q\330\014\020\220\006\220a\360\006\000\t\014\2105\220\003\2201\330\014\023\2201\340\010\013\210?\230$\230e\2403\240a\330\014\023\2201\340\010\017\210u\220D\230\005\230U\240&\250\006\250a\330\030\037\230v\240Q\330\030\036\230a\330\014-\250R\250q\340\010\014\320\014$\240A\360\006\000\t\014\210:\220Q\320\026*\250!\330\014\022\320\022%\240Q\330\020\021\340\r\027\220q\320\030,\250A\330\014\020\220\014\230A\330\014\027\220q\330\014\020\220\r\230Q\330\014\020\220\r\230Q\340\r\024\220A\320\025)\250\021\330\014\017\320\017!\240\021\330\020\026\220j\240\001\240\021\330\014\020\220\014\230A\340\014\r\330\020\033\230?\250!\2503\250a\320/A\300\021\330\020\034\230A\330\023\024\330\020\033\2301\330\014\020\220\r\230Q\330\014\020\220\r\230Q\360\006\000\r\021\220\014\230K\240\260a\260q\330\014\030\230\001\330\014\020\220\r\230Y\240a\240q\330\014\020\220\r\230T\240\032\2503\250a\360\006\000\t\014\2105\220\003\2201\330\014\023\2201\340\010\014\210H\220K\230q\240\001\330\010\014\320\014\"\320\"7\260\300a\330\014\r\340\010\013\2104\210q\220\003\2203\220a\360\006\000\r\020\210u\220I\230S\240\007\240s\250%\250t\3203C\3004\300q\330\020\026\220j\240\001\330\024\025\360\006\000\r\020\210q\360\006\000\021\025\220J\230h\240g\250U\260!\330\021\033\2301\230H\240A\330\020\024\220J\230f\240E\250\021\330\021\033\2301\230H\240A\330\020\024\220J\230o\250Z\260q\270\001\330\021!\240\024\240Q\330\020\024\220J\230o\320-=\270Q\330\024\025\330\024\025\330\024 \240""\001\330\024\031\230\021\330\021\022\330\020\024\220J\230o\250Z\260q\270\001\340\020\026\220j\240\001\240\021\340\014\020\220\013\2304\230~\250Q\340\014\017\210t\2209\230C\230q\330\020\023\2201\330\024\032\320\032,\250A\320-N\310a\340\024\032\230*\240A\320%I\310\027\320PQ\320QZ\320Z[\320[\\\330\014\017\210\230d\240#\240Q\240a\330\020\024\320\024$\240A\240Q\360\010\000\r\020\210t\2203\220e\2304\230q\330\020\024\320\024(\250\001\250\024\250Z\260t\320;P\320PS\320ST\330\024\032\230*\240A\240Q\360\006\000\r\020\210t\2203\220e\2303\230d\240#\240U\250#\250T\260\023\260A\330\020\026\220d\230'\240\021\330\025\026\330\024\032\230-\240q\250\004\250J\260a\330\020\023\2204\220r\230\021\330\024\032\320\032,\250A\320-H\310\001\340\r\021\220\021\220#\220S\230\001\340\014\020\220\013\2304\230~\250Q\340\014\017\210t\2209\230C\230q\330\020\023\2201\330\024\032\320\032,\250A\320-N\310a\340\024\032\230*\240A\320%I\310\027\320PQ\320QZ\320Z[\320[\\\340\014\017\210t\2208\2307\240*\250C\250q\330\020\026\220j\240\001\240\021\340\014\017\210\230d\240#\240Q\240a\330\020\024\320\024$\240A\240Q\340\014\020\320\020!\240\021\240!\360\006\000\r\020\210t\2208\2303\230d\240!\330\025\026\330\024\032\230,\240a\240t\2501\330\020\023\2204\220s\230!\330\024\032\230*\240A\330\030\031\33035\260Q\330\020\024\220J\320\0361\260\021\260!\360\n\000\021\024\320\023#\2404\240q\340\024\030\230\n\240/\3201A\300\021\330\030(\250\001\330\030*\250!\330\030$\240A\330\030\035\230Q\340\031\032\330\030\036\230l\250!\2504\250q\330\024\027\220t\2303\230a\330\030\036\230j\250\001\330\034\035\340\024\030\230\n\320\"5\260Q\260a\360\006\000\r\020\210t\2209\230D\240\001\330\020&\240d\250!\330\020\033\2301\230D\240\001\330\034\035\330\034\035\340\014\017\210y\230\004\230D\240\007\240}\260C\260q\330\020\026\220j\240\001\330\025\026\340')\250\021\340\014\017\210t\2208\2303\230d\240!\330\020\024\320\024&\240o\260S\270\001\330\020\023\2204\220q\330\024!\240\035\250o\270Q\270d\300!\340\020\023\220:\230S\240\001\330\031\032\330\030""\034\230I\240_\260A\260T\270\032\300;\310a\3305H\310\001\310\021\340\024\027\220t\2304\230w\240e\250;\260c\270\021\330\030\033\2301\330\034\"\320\"4\260A\3205R\320RV\320VW\340\034\"\240'\250\021\320*K\3102\310T\320QR\340\025\026\330\024\032\230'\240\021\240!\360\006\000\021\024\2204\220t\2301\330\024\030\320\030(\250\004\250E\260\021"; +static const char __pyx_k_AlignmentFile___setstate_cython[] = "AlignmentFile.__setstate_cython__"; +static const char __pyx_k_AlignmentFile_find_introns_slow[] = "AlignmentFile.find_introns_slow"; +static const char __pyx_k_AlignmentHeader___reduce_cython[] = "AlignmentHeader.__reduce_cython__"; +static const char __pyx_k_AlignmentHeader__build_sequence[] = "AlignmentHeader._build_sequence_section"; +static const char __pyx_k_AlignmentHeader_from_references[] = "AlignmentHeader.from_references"; +static const char __pyx_k_IteratorColumnRegion___setstate[] = "IteratorColumnRegion.__setstate_cython__"; +static const char __pyx_k_IteratorRowHead___reduce_cython[] = "IteratorRowHead.__reduce_cython__"; +static const char __pyx_k_IteratorRowSelection___setstate[] = "IteratorRowSelection.__setstate_cython__"; +static const char __pyx_k_fetch_called_on_bamfile_without[] = "fetch called on bamfile without index"; +static const char __pyx_k_file_does_not_contain_alignment[] = "file does not contain alignment data"; +static const char __pyx_k_incomplete_sequence_information[] = "incomplete sequence information in '%s'"; +static const char __pyx_k_k_l_Z___kkx_y_D_D_E_E_I_I_U_U_h[] = "\200\001\330\004\020\320\020&\240k\260\021\260$\260l\300-\310{\320Z[\320[_\320_k\320kx\360\000\000y\001D\002\360\000\000D\002E\002\360\000\000E\002I\002\360\000\000I\002U\002\360\000\000U\002]\002\360\000\000]\002h\002\360\000\000h\002i\002\360\000\000i\002m\002\360\000\000m\002y\002\360\000\000y\002L\003\360\000\000L\003W\003\360\000\000W\003X\003\360\000\000X\003\\\003\360\000\000\\\003h\003\360\000\000h\003@\004\360\000\000@\004K\004\360\000\000K\004L\004\360\000\000L\004P\004\360\000\000P\004\\\004\360\000\000\\\004l\004\360\000\000l\004w\004\360\000\000w\004x\004\360\000\000x\004|\004\360\000\000|\004H\005\360\000\000H\005P\005\360\000\000P\005[\005\360\000\000[\005\\\005\360\000\000\\\005]\005\330\004\007\200s\210!\210=\230\002\230\"\230D\240\007\240q\250\016\260a\330\010\024\220I\230W\240A\240[\260\001\260\021"; +static const char __pyx_k_malformatted_header_no_in_field[] = "malformatted header: no ':' in field"; +static const char __pyx_k_wrong_sequence_information_in_s[] = "wrong sequence information in '%s'"; +static const char __pyx_k_A6_T_5_5_c_A_4A_5_c_A_4A_Rs_A_HD[] = "\200A\3606\000\t\036\230T\240\032\2505\260\001\340\010\013\2105\220\002\220,\230c\240\021\330\014\022\220*\230A\320\0354\260A\330\036\"\240!\330\010\013\2105\220\002\220,\230c\240\021\330\014\022\220*\230A\320\0354\260A\330\036\"\240!\360\006\000\t\026\220[\240\002\240!\330\010\020\220\005\220R\220s\230\"\230A\360\020\000\t\r\210H\220D\230\006\230a\330\020\024\220J\230e\2401\330\020\024\220J\230e\2406\250\022\2501\330\020\024\220D\230\n\240%\240q\330\020#\2401\330\014\017\210t\2206\230\022\2305\240\003\2402\240Q\330\017\023\220<\230s\240$\240a\330\020\021\340\014\022\220*\230A\230Q\340\010\017\210q"; +static const char __pyx_k_AFXXY_3a_3aq_AQ_5_5_A_2U_1_1_Ct3[] = "\200A\330FX\320XY\340\010\013\2103\210a\320\017 \240\003\2403\240a\240q\330\014\022\220*\230A\230Q\360\006\000\t\014\2105\220\003\2205\230\004\230A\330\014\023\2202\220U\230!\2301\320\0341\260\027\270\001\270\023\270C\270t\3003\300e\3103\310a\330\020!\240\021\340\010\017\210s\320\022)\250\021\250&\3200A\300\021"; +static const char __pyx_k_A_12_H_Qd_E_a_I_HA_IXT_a_IWA_IXQ[] = "\200A\360\010\00012\360\006\000\t\r\210H\320\024%\240Q\240d\250*\260E\270\027\300\006\300a\330\010\014\210I\220[\240\004\240H\250A\330\010\014\210I\220X\230T\240\025\240a\330\010\014\210I\220W\230A\330\010\014\210I\220X\230Q\330\010\014\210I\220Z\230t\2408\2507\260!\340\010\013\2104\210{\230'\240\021\330\014\020\220\t\230\035\240d\250*\260A\340\014\020\220\t\230\035\240a\360\010\000\t\r\320\014\036\230a\360\006\000\t\r\210A\210U\220'\230\021\230$\230a\340\010\013\2104\210y\230\003\2305\240\003\2404\240y\260\003\2601\330\021\022\330\020\024\220O\240=\260\001\260\021\3301A\300\021\300!\33012\330\r\021\220\031\230#\230Q\330\021\022\330\020\024\220O\240=\260\001\260\021\3301A\300\021\300!\33012\330\r\021\220\031\230#\230Q\330\021\022\330\020\024\220O\240=\260\001\260\021\3301A\300\021\300!\33012\340\014\022\220*\230A\330\020@\300\002\300$\300a\340\010\013\2104\210q\330\021\022\330\020#\2401\240D\250\016\260d\270!\340\010\013\2104\210q\330\021\022\330\020&\240a\240t\2501"; +static const char __pyx_k_A_4_Cs_4_HA_D_4q_1M_k_a_4r_A_4xq[] = "\200A\360\006\000\t\014\2104\210}\230C\230s\240!\2404\240}\260H\270A\360\006\000\t\035\230D\240\n\250!\2504\250q\330\r\016\330\014\022\220)\2301\230M\250\021\250$\250k\270\025\270a\330\010\013\2104\210r\220\021\330\014\022\320\022$\240A\240^\2604\260x\270q\330\010\014\320\014\034\230A\340\010\037\230t\2407\250!\330\r\016\330\014\022\220)\2301\230D\240\001\330\034\035\330\034 \240\001\330\010\017\210q"; +static const char __pyx_k_A_4y_1_4wc_1D_y_Q_Kq_Ja_4r_4vS_z[] = "\200A\360\006\000\t\014\2104\210y\230\003\2301\330\014\r\340\010\013\2104\210w\220c\230\021\330\014\033\2301\230D\240\001\330\014\020\220\t\230\021\340\010\027\220y\240\001\240\024\240Q\330\010\014\210K\220q\340\010\014\210J\220a\340\010\013\2104\210r\220\022\2204\220v\230S\240\001\330\014\017\210z\230\021\230$\230l\250%\250q\330\020\026\320\026(\250\001\320);\2704\270q\340\020\026\320\026(\250\001\250\021"; +static const char __pyx_k_A_A_4t1_AQ_A_A_3a_A_HD_awa_Q_A_1[] = "\200A\330\025\026\330\024\025\330\023\024\330\025\026\330\030\031\330\034\035\330\030\031\330\022\023\360|\001\000\t\035\230A\340\010\013\2104\210t\2201\330\014\022\220*\230A\230Q\340\010!\240\021\330\010\013\210>\230\023\230A\330\014\034\230A\330\r\033\2303\230a\330\014\034\230A\340\010\014\210H\220D\230\006\230a\230w\240a\330\037%\240Q\330\037$\240A\330\037)\250\021\330\037#\2401\330\037&\240a\330\037)\250\021\340\014\017\210~\230S\240\001\340\020\024\220D\230\006\320\0365\260Q\330\024\025\330\021\037\230s\240!\360\010\000\021\024\2204\220}\240A\240Q\330\024\025\330\014\027\220q\340\010\017\210q"; +static const char __pyx_k_A_D_a_2Rq_AQ_2S_q_Q_A_A_A_A_IQ_H[] = "\200A\360\006\000\t\r\210D\220\006\220a\330\010\013\2102\210R\210q\330\014\022\220*\230A\230Q\340\010\013\2102\210S\220\001\330\014\r\340\010\017\320\017\037\230q\240\001\240\024\240Q\330 $\240A\330 $\240A\330 $\240A\330 $\240A\330 $\240I\250Q\330 $\240H\250A"; +static const char __pyx_k_A_D_d_q_6_gZq_r_4A_6_A_AQ_6_1_AQ[] = "\200A\360\006\000\036\037\330\034\035\330\036\037\330)*\330%&\330!\"\330\033\034\360D\002\000\t'\240d\320*?\270q\300\001\330\010\032\230)\2406\250\027\260\n\270!\330\010\031\230\030\240\025\240g\250Z\260q\330\010\020\220\t\230\026\230r\320!4\260A\340\010\013\2106\220\023\220A\330\014\022\220*\230A\230Q\330\010\013\2106\220\022\2201\330\014\022\220*\230A\230Q\340\010\032\230&\240\002\240!\330\0105\260V\2701\270E\300\021\360\n\000\t\032\230\026\230q\320 4\260M\300\021\330\010\031\230\026\230q\320 4\260M\300\021\330\010\031\230\026\230q\320 4\260M\300\021\330\010\031\230\026\230q\320 4\260M\300\021\360\016\000\t\026\220Q\330\010!\240\021\360\006\000\t\014\210>\230\023\230A\330\014\034\230A\330\r\033\2303\230a\330\014\034\230A\340\010\036\320\0360\260\003\2601\330\010\014\210H\220D\230\006\230a\230w\240a\330\037)\250\021\330\037%\240Q\330\037$\240A\330\037#\2401\330\037&\240a\340\014\017\210~\230S\240\001\340\020\024\220D\230\006\320\0365\260Q\330\024\025\330\021\037\230s\240!\360\010\000\021\024\2204\220}\240A\240Q\330\024\025\360\006\000\r\023\220$\220a\330\014\017\210t\2203\220a\330\020\021\330\014\026\220d\230!\340\014\020\220\006\220j\240\004\320$6\260a\260q\330\020\023\2205\230\007\230u\240D\250\007\250w\260e\2701\330\023\032\230#\230Y\240a\360\006\000\025\031\230\013\2404\240x\250t\2607\270!\2706\300\023\300L\320PS\320SW\320WX\330\030\033\2303\230a\230v\240S\250\001\330\034#\2405\250\n\260!\2607\270\"\270K\300q\330\030\033\2303\230a\230v\240S\250\001\330\034#\2405\250\n\260!\2607\270\"\270K\300q\330\030\033\2303\230a\230v\240S\250\001\330\034#\2405\250\n\260!\2607\270\"\270K\300q\330\030\033\2303\230a\230v\240S\250\001\330\034#\2405\250\n\260!\2607\270\"\270K\300q\340\010\017\210y\230\t\240\031\250!"; +static const char __pyx_k_A_F_r_1_j_r_A_t1_4wb_A_4uCt1_1AT[] = "\200A\360\010\000\t\n\330\014\020\220\004\220F\230!\330\014\017\210r\220\022\2201\330\020\026\220j\240\001\240\021\340\014\017\210r\220\023\220A\330\020\021\340\014\017\210t\2201\330\020\023\2204\220w\230b\240\004\240A\330\024\025\330\020\023\2204\220u\230C\230t\2401\330\024\025\340\014\023\320\023#\2401\240A\240T\250\021\330$(\250\001\330$(\250\001\330$(\250\001\330$(\250\001\330$(\250\t\260\021\330$(\250\010\260\001"; +static const char __pyx_k_A_O1_5_q_Kq_A_S_HG6_3a_t4vS_k_wa[] = "\200A\360\006\000\t%\240O\2601\360\010\000\t\014\2105\220\007\220q\330\014\024\220K\230q\240\001\330\014\024\220A\330\014\025\220S\230\001\230\021\330\014\020\220\004\220H\230G\2406\250\021\250'\260\022\2603\260a\330\014\017\210t\2204\220v\230S\240\001\330\020\026\220k\240\021\320\"?\270w\300a\300w\310b\320PT\320TU\330\014\020\220\004\220J\230a\330\014\022\220!\2204\220t\2307\240'\250\027\260\002\260!\340\010\013\320\013\033\2304\230q\330\014\036\230a\230{\250!\2505\260\004\260G\2701\340\014\020\220\004\220M\240\023\240A\240Q\340\014\020\220\003\2201\220A\220S\230\001\320\031*\250\"\250A\330\014\020\220\004\220O\2408\2506\260\021\260#\260Q\330\014\017\210t\2204\220}\240C\240q\330\020\026\220k\240\021\320\"?\270w\300a\300s\310!\340\014\020\220\004\220N\240+\250V\2601\260C\260q\330\014\017\210t\2204\220|\2403\240a\330\020\026\220k\240\021\320\"?\270w\300a\300s\310!\340\014\020\220\007\220y\240\004\240D\250\001\330\020\024\220D\230\013\2401\240E\320):\270!\2701\330\020\027\220\240a\240q\330\020\024\220D\230\014\240A\240U\250'\260\026\260q\270\003\2701\270F\300\"\300C\300q\330\020\023\2204\220t\230<\240q\250\003\2503\250a\330\024\032\230+\240Q\320&C\3007\310!\3103\310a\310v\320UW\320WZ\320Z[\330\020\027\220q\230\004\230D\240\014\250A\250T\260\026\260s\270!\2701\340\010\017\210q"; +static const char __pyx_k_A_k_E_t3aq_JnA_q_y_5_A_nCq_q_2WJ[] = "\200A\360\022\000\t\017\210k\230\030\240\021\330\010\014\210E\220\021\330\014\017\210t\2203\220a\220q\330\020 \240\001\330\020\024\220J\230n\250A\320-?\270q\330\024\027\220y\240\003\2405\250\004\250A\330\030 \240\001\330\031\"\240$\240n\260C\260q\330\030\037\230q\330\030\033\2302\230W\240J\250a\330\030\034\230A\330\030\034\230A\330\024$\240A\330\010\017\210q"; +static const char __pyx_k_A_k_S_3a_E_AQ_AQ_vS_F_3c_Q_1_Q_r[] = "\200A\360\032\000\r!\240\001\340\010\016\210k\230\030\240\021\340\010\035\230S\240\003\2403\240a\330\010\014\210E\220\021\330\014\034\230A\230Q\330\014\024\220A\220Q\330\014\017\210v\220S\230\001\330\020\021\340\014\020\220\004\220F\230!\330\020\023\2203\220c\230\021\330\024%\240Q\330\025\030\230\003\2301\330\024!\240\021\330\024%\240Q\330\024\027\220r\230\034\320%8\270\001\330\010\017\210q"; +static const char __pyx_k_A_q_4wc_1D_4y_1_1D_1_Ja_4q_Q_Q_4[] = "\200A\330\010\027\220q\340\010\013\2104\210w\220c\230\021\330\014\033\2301\230D\240\001\330\014\020\220\t\230\021\340\010\013\2104\210y\230\003\2301\330\014\022\220)\2301\230D\240\001\330\014\020\220\013\2301\340\010\014\210J\220a\340\010\013\2104\210q\330\014\030\230\001\230\024\230Q\330\014\020\220\005\220Q\340\010\013\2104\210r\220\022\2204\220v\230S\240\001\330\014\017\210z\230\021\230$\230l\250%\250q\330\020\026\320\026(\250\001\320);\2704\270q\340\020\026\320\026(\250\001\250\021"; +static const char __pyx_k_AlignedSegment_refers_to_referen[] = "AlignedSegment refers to reference number {} that is larger than the number of references ({}) in the header"; +static const char __pyx_k_AlignmentFile_get_index_statisti[] = "AlignmentFile.get_index_statistics"; +static const char __pyx_k_AlignmentFile_get_reference_leng[] = "AlignmentFile.get_reference_length"; +static const char __pyx_k_AlignmentFile_get_reference_name[] = "AlignmentFile.get_reference_name"; +static const char __pyx_k_AlignmentFile_mapped_only_availa[] = "AlignmentFile.mapped only available in bam files"; +static const char __pyx_k_AlignmentHeader___setstate_cytho[] = "AlignmentHeader.__setstate_cython__"; +static const char __pyx_k_AlignmentHeader__from_text_and_l[] = "AlignmentHeader._from_text_and_lengths"; +static const char __pyx_k_AlignmentHeader_does_not_support[] = "AlignmentHeader does not support item assignment (use header.to_dict()"; +static const char __pyx_k_AlignmentHeader_get_reference_le[] = "AlignmentHeader.get_reference_length"; +static const char __pyx_k_AlignmentHeader_get_reference_na[] = "AlignmentHeader.get_reference_name"; +static const char __pyx_k_Cannot_add_extra_threads_when_ig[] = "Cannot add extra threads when \"ignore_truncation\" is True"; +static const char __pyx_k_Incompatible_checksums_0x_x_vs_0[] = "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))"; +static const char __pyx_k_IteratorColumnAllRefs___reduce_c[] = "IteratorColumnAllRefs.__reduce_cython__"; +static const char __pyx_k_IteratorColumnAllRefs___setstate[] = "IteratorColumnAllRefs.__setstate_cython__"; +static const char __pyx_k_IteratorColumnAll___reduce_cytho[] = "IteratorColumnAll.__reduce_cython__"; +static const char __pyx_k_IteratorColumnAll___setstate_cyt[] = "IteratorColumnAll.__setstate_cython__"; +static const char __pyx_k_IteratorColumnRegion___reduce_cy[] = "IteratorColumnRegion.__reduce_cython__"; +static const char __pyx_k_IteratorColumn___setstate_cython[] = "IteratorColumn.__setstate_cython__"; +static const char __pyx_k_IteratorRowAllRefs___reduce_cyth[] = "IteratorRowAllRefs.__reduce_cython__"; +static const char __pyx_k_IteratorRowAllRefs___setstate_cy[] = "IteratorRowAllRefs.__setstate_cython__"; +static const char __pyx_k_IteratorRowAll___setstate_cython[] = "IteratorRowAll.__setstate_cython__"; +static const char __pyx_k_IteratorRowHead___setstate_cytho[] = "IteratorRowHead.__setstate_cython__"; +static const char __pyx_k_IteratorRowRegion___reduce_cytho[] = "IteratorRowRegion.__reduce_cython__"; +static const char __pyx_k_IteratorRowRegion___setstate_cyt[] = "IteratorRowRegion.__setstate_cython__"; +static const char __pyx_k_IteratorRowSelection___reduce_cy[] = "IteratorRowSelection.__reduce_cython__"; +static const char __pyx_k_Note_that_Cython_is_deliberately[] = "Note that Cython is deliberately stricter than PEP-484 and rejects subclasses of builtin types. If you need to pass subclasses then set the 'annotation_typing' directive to False."; +static const char __pyx_k_Raw_iterator_set_up_without_regi[] = "Raw iterator set up without region cannot be reset"; +static const char __pyx_k_SAM_file_does_not_have_a_valid_h[] = "SAM? file does not have a valid header (mode='%s'), please provide reference_names and reference_lengths"; +static const char __pyx_k_access_from_StringIO_objects_not[] = "access from StringIO objects not supported"; +static const char __pyx_k_can_not_iterate_over_samfile_wit[] = "can not iterate over samfile without header"; +static const char __pyx_k_can_only_apply_IndexReads_on_bam[] = "can only apply IndexReads on bam files"; +static const char __pyx_k_cannot_create_AlignmentHeader_re[] = "cannot create AlignmentHeader, received NULL pointer"; +static const char __pyx_k_could_not_allocate_memory_of_siz[] = "could not allocate memory of size {}"; +static const char __pyx_k_either_supply_options_template_h[] = "either supply options `template`, `header`, `text` or both `reference_names` and `reference_lengths` for writing"; +static const char __pyx_k_failure_when_setting_reference_f[] = "failure when setting reference filename"; +static const char __pyx_k_fetching_by_region_is_not_availa[] = "fetching by region is not available for SAM files"; +static const char __pyx_k_file_does_not_have_a_valid_heade[] = "file does not have a valid header (mode='%s') - is it BAM/CRAM format?"; +static const char __pyx_k_file_has_no_sequences_defined_mo[] = "file has no sequences defined (mode='%s') - is it SAM/BAM format? Consider opening with check_sq=False"; +static const char __pyx_k_header_not_available_in_closed_f[] = "header not available in closed files"; +static const char __pyx_k_invalid_type_for_record_expected[] = "invalid type for record {}: {}, expected {}"; +static const char __pyx_k_mapping_information_not_recorded[] = "mapping information not recorded in index or index not available"; +static const char __pyx_k_multiple_iterators_not_implement[] = "multiple iterators not implemented for SAM files"; +static const char __pyx_k_multiple_s_lines_are_not_permitt[] = "multiple '%s' lines are not permitted"; +static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; +static const char __pyx_k_no_index_available_for_iteration[] = "no index available for iteration"; +static const char __pyx_k_not_enough_information_to_constr[] = "not enough information to construct header. Please provide template, header, text or reference_names/reference_lengths"; +static const char __pyx_k_number_of_reference_names_and_le[] = "number of reference names and lengths do not match"; +static const char __pyx_k_reference_id_i_out_of_range_0_ti[] = "reference_id %i out of range 0<=tid<%i"; +static const char __pyx_k_reference_sequence_for_tid_not_f[] = "reference sequence for '{}' (tid={}) not found"; +static const char __pyx_k_sam_write1_failed_with_error_cod[] = "sam_write1 failed with error code {}"; +static const char __pyx_k_self_b_self_htsfile_self_index_c[] = "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling"; +static const char __pyx_k_self_b_self_htsfile_self_index_s[] = "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling"; +static const char __pyx_k_self_htsfile_cannot_be_converted[] = "self.htsfile cannot be converted to a Python object for pickling"; +static const char __pyx_k_unable_to_read_header_informatio[] = "unable to read header information"; +static const char __pyx_k_unknown_stepper_option_s_in_Iter[] = "unknown stepper option `%s` in IteratorColumn"; +static const char __pyx_k_multiple_iterators_not_implement_2[] = "multiple_iterators not implemented for CRAM"; +/* #### Code section: decls ### */ +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags); /* proto */ +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_build_header_line(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_fields, PyObject *__pyx_v_record); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_2read_failure_reason(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_code); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_2__init__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths(CYTHON_UNUSED PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_text, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_text); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_header_dict); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths, PyObject *__pyx_v_text, PyObject *__pyx_v_add_sq_text); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_12__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_14__bool__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_16copy(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10references___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_tid); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_reference); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, int __pyx_v_tid); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_reference); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_34__setitem__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_key, CYTHON_UNUSED PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_36__getitem__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_key); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_38items(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_42keys(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_44values(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_46get(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_args); /* proto */ +static Py_ssize_t __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_48__len__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_50__contains__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_key); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_2has_index(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4check_index(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6_open(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_filepath_or_object, PyObject *__pyx_v_mode, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_template, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths, PyObject *__pyx_v_reference_filename, PyObject *__pyx_v_text, PyObject *__pyx_v_header, CYTHON_UNUSED PyObject *__pyx_v_port, PyObject *__pyx_v_add_sq_text, PyObject *__pyx_v_add_sam_header, CYTHON_UNUSED PyObject *__pyx_v_check_header, PyObject *__pyx_v_check_sq, PyObject *__pyx_v_index_filename, PyObject *__pyx_v_filepath_index, PyObject *__pyx_v_require_index, PyObject *__pyx_v_referencenames, PyObject *__pyx_v_referencelengths, PyObject *__pyx_v_duplicate_filehandle, PyObject *__pyx_v_ignore_truncation, PyObject *__pyx_v_format_options, PyObject *__pyx_v_threads); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8fetch(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_tid, PyObject *__pyx_v_until_eof, PyObject *__pyx_v_multiple_iterators, PyObject *__pyx_v_reference, PyObject *__pyx_v_end); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10head(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12mate(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_14pileup(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_reference, PyObject *__pyx_v_end, PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_16count(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_until_eof, PyObject *__pyx_v_read_callback, PyObject *__pyx_v_reference, PyObject *__pyx_v_end); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_quality_threshold, PyObject *__pyx_v_read_callback, PyObject *__pyx_v_reference, PyObject *__pyx_v_end); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_read_iterator); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_read_iterator); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_24close(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_26__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_28write(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_exc_type, CYTHON_UNUSED PyObject *__pyx_v_exc_value, CYTHON_UNUSED PyObject *__pyx_v_traceback); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6mapped___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_36__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_38__next__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, int __pyx_v_tid); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_tid); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10references___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_7lengths___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4text___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_48gettid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_50getrname(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_tid); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6header___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_2__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_tid, int __pyx_v_beg, int __pyx_v_stop, int __pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_6__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_n, int __pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_4__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_6__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_positions, int __pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len___get__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_8__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_12addReference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_tid, int __pyx_v_start, int __pyx_v_stop, int __pyx_v_truncate, int __pyx_v_multiple_iterators, CYTHON_UNUSED PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, CYTHON_UNUSED PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, CYTHON_UNUSED PyObject *__pyx_v_kwargs); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3tid___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3pos___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_14reference_base___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8genotype___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_11snp_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8coverage___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall___str__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_2build(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_4find(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, PyObject *__pyx_v_query_name); /* proto */ +static void __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_6__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_4__pyx_unpickle_SNPCall(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentHeader(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentFile(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowRegion(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowHead(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAll(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAllRefs(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowSelection(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnRegion(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAllRefs(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAll(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IndexedReads(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_SNPCall(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +/* #### Code section: late_includes ### */ +/* #### Code section: module_state ### */ +/* SmallCodeConfig */ +#ifndef CYTHON_SMALL_CODE +#if defined(__clang__) + #define CYTHON_SMALL_CODE +#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define CYTHON_SMALL_CODE __attribute__((cold)) +#else + #define CYTHON_SMALL_CODE +#endif +#endif + +typedef struct { + PyObject *__pyx_d; + PyObject *__pyx_b; + PyObject *__pyx_cython_runtime; + PyObject *__pyx_empty_tuple; + PyObject *__pyx_empty_bytes; + PyObject *__pyx_empty_unicode; + #ifdef __Pyx_CyFunction_USED + PyTypeObject *__pyx_CyFunctionType; + #endif + #ifdef __Pyx_FusedFunction_USED + PyTypeObject *__pyx_FusedFunctionType; + #endif + #ifdef __Pyx_Generator_USED + PyTypeObject *__pyx_GeneratorType; + #endif + #ifdef __Pyx_IterableCoroutine_USED + PyTypeObject *__pyx_IterableCoroutineType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineAwaitType; + #endif + #ifdef __Pyx_Coroutine_USED + PyTypeObject *__pyx_CoroutineType; + #endif + PyTypeObject *__pyx_ptype_7cpython_4type_type; + PyTypeObject *__pyx_ptype_7cpython_4bool_bool; + PyTypeObject *__pyx_ptype_7cpython_7complex_complex; + PyTypeObject *__pyx_ptype_7cpython_5array_array; + PyTypeObject *__pyx_ptype_5pysam_10libchtslib_HTSFile; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastaFile; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastqProxy; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastxRecord; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastxFile; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_FastqFile; + PyTypeObject *__pyx_ptype_5pysam_9libcfaidx_Fastafile; + PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache; + PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment; + PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn; + PyTypeObject *__pyx_ptype_5pysam_18libcalignedsegment_PileupRead; + PyObject *__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader; + PyObject *__pyx_type_5pysam_17libcalignmentfile_AlignmentFile; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRow; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorColumn; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll; + PyObject *__pyx_type_5pysam_17libcalignmentfile_IndexedReads; + PyObject *__pyx_type_5pysam_17libcalignmentfile_SNPCall; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads; + PyTypeObject *__pyx_ptype_5pysam_17libcalignmentfile_SNPCall; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_get; + __Pyx_CachedCFunction __pyx_umethod_PyDict_Type_pop; + int __pyx_k__10; + PyObject *__pyx_slice[1]; + PyObject *__pyx_tuple[16]; + PyObject *__pyx_codeobj_tab[166]; + PyObject *__pyx_string_tab[548]; + PyObject *__pyx_int_0; + PyObject *__pyx_int_1; + PyObject *__pyx_int_2; + PyObject *__pyx_int_7; + PyObject *__pyx_int_8; + PyObject *__pyx_int_13; + PyObject *__pyx_int_15; + PyObject *__pyx_int_1796; + PyObject *__pyx_int_8000; + PyObject *__pyx_int_18041500; + PyObject *__pyx_int_84615809; + PyObject *__pyx_int_239452417; + PyObject *__pyx_int_neg_1; + PyObject *__pyx_int_neg_2; +/* #### Code section: module_state_contents ### */ +/* CommonTypesMetaclass.module_state_decls */ +PyTypeObject *__pyx_CommonTypesMetaclassType; + +/* CachedMethodType.module_state_decls */ +#if CYTHON_COMPILING_IN_LIMITED_API +PyObject *__Pyx_CachedMethodType; +#endif + +/* CodeObjectCache.module_state_decls */ +struct __Pyx_CodeObjectCache __pyx_code_cache; + +/* #### Code section: module_state_end ### */ +} __pyx_mstatetype; + +#if CYTHON_USE_MODULE_STATE +#ifdef __cplusplus +namespace { +extern struct PyModuleDef __pyx_moduledef; +} /* anonymous namespace */ +#else +static struct PyModuleDef __pyx_moduledef; +#endif + +#define __pyx_mstate_global (__Pyx_PyModule_GetState(__Pyx_State_FindModule(&__pyx_moduledef))) + +#define __pyx_m (__Pyx_State_FindModule(&__pyx_moduledef)) +#else +static __pyx_mstatetype __pyx_mstate_global_static = +#ifdef __cplusplus + {}; +#else + {0}; +#endif +static __pyx_mstatetype * const __pyx_mstate_global = &__pyx_mstate_global_static; +#endif +/* #### Code section: constant_name_defines ### */ +#define __pyx_kp_u_ __pyx_string_tab[0] +#define __pyx_n_u_AH __pyx_string_tab[1] +#define __pyx_n_u_AN __pyx_string_tab[2] +#define __pyx_n_u_AS __pyx_string_tab[3] +#define __pyx_kp_u_AlignedSegment_refers_to_referen __pyx_string_tab[4] +#define __pyx_n_u_AlignmentFile __pyx_string_tab[5] +#define __pyx_n_u_AlignmentFile___enter __pyx_string_tab[6] +#define __pyx_n_u_AlignmentFile___exit __pyx_string_tab[7] +#define __pyx_n_u_AlignmentFile___reduce_cython __pyx_string_tab[8] +#define __pyx_n_u_AlignmentFile___setstate_cython __pyx_string_tab[9] +#define __pyx_n_u_AlignmentFile__open __pyx_string_tab[10] +#define __pyx_n_u_AlignmentFile_check_index __pyx_string_tab[11] +#define __pyx_n_u_AlignmentFile_close __pyx_string_tab[12] +#define __pyx_n_u_AlignmentFile_count __pyx_string_tab[13] +#define __pyx_n_u_AlignmentFile_count_coverage __pyx_string_tab[14] +#define __pyx_n_u_AlignmentFile_fetch __pyx_string_tab[15] +#define __pyx_n_u_AlignmentFile_find_introns __pyx_string_tab[16] +#define __pyx_n_u_AlignmentFile_find_introns_slow __pyx_string_tab[17] +#define __pyx_n_u_AlignmentFile_get_index_statisti __pyx_string_tab[18] +#define __pyx_n_u_AlignmentFile_get_reference_leng __pyx_string_tab[19] +#define __pyx_n_u_AlignmentFile_get_reference_name __pyx_string_tab[20] +#define __pyx_n_u_AlignmentFile_get_tid __pyx_string_tab[21] +#define __pyx_n_u_AlignmentFile_getrname __pyx_string_tab[22] +#define __pyx_n_u_AlignmentFile_gettid __pyx_string_tab[23] +#define __pyx_n_u_AlignmentFile_has_index __pyx_string_tab[24] +#define __pyx_n_u_AlignmentFile_head __pyx_string_tab[25] +#define __pyx_n_u_AlignmentFile_is_valid_tid __pyx_string_tab[26] +#define __pyx_kp_u_AlignmentFile_mapped_only_availa __pyx_string_tab[27] +#define __pyx_n_u_AlignmentFile_mate __pyx_string_tab[28] +#define __pyx_n_u_AlignmentFile_pileup __pyx_string_tab[29] +#define __pyx_n_u_AlignmentFile_write __pyx_string_tab[30] +#define __pyx_n_u_AlignmentHeader __pyx_string_tab[31] +#define __pyx_n_u_AlignmentHeader___reduce_cython __pyx_string_tab[32] +#define __pyx_n_u_AlignmentHeader___setstate_cytho __pyx_string_tab[33] +#define __pyx_n_u_AlignmentHeader__build_sequence __pyx_string_tab[34] +#define __pyx_n_u_AlignmentHeader__from_text_and_l __pyx_string_tab[35] +#define __pyx_n_u_AlignmentHeader_as_dict __pyx_string_tab[36] +#define __pyx_n_u_AlignmentHeader_copy __pyx_string_tab[37] +#define __pyx_kp_u_AlignmentHeader_does_not_support __pyx_string_tab[38] +#define __pyx_n_u_AlignmentHeader_from_dict __pyx_string_tab[39] +#define __pyx_n_u_AlignmentHeader_from_references __pyx_string_tab[40] +#define __pyx_n_u_AlignmentHeader_from_text __pyx_string_tab[41] +#define __pyx_n_u_AlignmentHeader_get __pyx_string_tab[42] +#define __pyx_n_u_AlignmentHeader_get_reference_le __pyx_string_tab[43] +#define __pyx_n_u_AlignmentHeader_get_reference_na __pyx_string_tab[44] +#define __pyx_n_u_AlignmentHeader_get_tid __pyx_string_tab[45] +#define __pyx_n_u_AlignmentHeader_is_valid_tid __pyx_string_tab[46] +#define __pyx_n_u_AlignmentHeader_items __pyx_string_tab[47] +#define __pyx_n_u_AlignmentHeader_iteritems __pyx_string_tab[48] +#define __pyx_n_u_AlignmentHeader_keys __pyx_string_tab[49] +#define __pyx_n_u_AlignmentHeader_to_dict __pyx_string_tab[50] +#define __pyx_n_u_AlignmentHeader_values __pyx_string_tab[51] +#define __pyx_n_u_AssertionError __pyx_string_tab[52] +#define __pyx_n_u_AttributeError __pyx_string_tab[53] +#define __pyx_n_u_BAM_CREF_SKIP __pyx_string_tab[54] +#define __pyx_n_u_BC __pyx_string_tab[55] +#define __pyx_n_u_CL __pyx_string_tab[56] +#define __pyx_n_u_CN __pyx_string_tab[57] +#define __pyx_n_u_CO __pyx_string_tab[58] +#define __pyx_kp_u_Can_t_seek __pyx_string_tab[59] +#define __pyx_kp_u_Cannot_add_extra_threads_when_ig __pyx_string_tab[60] +#define __pyx_kp_u_Closing_failed __pyx_string_tab[61] +#define __pyx_kp_u_Could_not_open_alignment_file __pyx_string_tab[62] +#define __pyx_kp_u_Could_not_open_index_file __pyx_string_tab[63] +#define __pyx_kp_u_Could_not_write_headers __pyx_string_tab[64] +#define __pyx_n_u_Counter __pyx_string_tab[65] +#define __pyx_n_u_DS __pyx_string_tab[66] +#define __pyx_n_u_DT __pyx_string_tab[67] +#define __pyx_n_u_FO __pyx_string_tab[68] +#define __pyx_n_u_GO __pyx_string_tab[69] +#define __pyx_n_u_HD __pyx_string_tab[70] +#define __pyx_n_u_ID __pyx_string_tab[71] +#define __pyx_n_u_IOError __pyx_string_tab[72] +#define __pyx_kp_u_I_O_operation_on_closed_file __pyx_string_tab[73] +#define __pyx_n_u_ImportError __pyx_string_tab[74] +#define __pyx_kp_u_Incompatible_checksums_0x_x_vs_0 __pyx_string_tab[75] +#define __pyx_n_u_IndexStats __pyx_string_tab[76] +#define __pyx_n_u_IndexedReads __pyx_string_tab[77] +#define __pyx_n_u_IndexedReads___reduce_cython __pyx_string_tab[78] +#define __pyx_n_u_IndexedReads___setstate_cython __pyx_string_tab[79] +#define __pyx_n_u_IndexedReads_build __pyx_string_tab[80] +#define __pyx_n_u_IndexedReads_find __pyx_string_tab[81] +#define __pyx_n_u_IteratorColumn __pyx_string_tab[82] +#define __pyx_n_u_IteratorColumnAll __pyx_string_tab[83] +#define __pyx_n_u_IteratorColumnAllRefs __pyx_string_tab[84] +#define __pyx_n_u_IteratorColumnAllRefs___reduce_c __pyx_string_tab[85] +#define __pyx_n_u_IteratorColumnAllRefs___setstate __pyx_string_tab[86] +#define __pyx_n_u_IteratorColumnAll___reduce_cytho __pyx_string_tab[87] +#define __pyx_n_u_IteratorColumnAll___setstate_cyt __pyx_string_tab[88] +#define __pyx_n_u_IteratorColumnRegion __pyx_string_tab[89] +#define __pyx_n_u_IteratorColumnRegion___reduce_cy __pyx_string_tab[90] +#define __pyx_n_u_IteratorColumnRegion___setstate __pyx_string_tab[91] +#define __pyx_n_u_IteratorColumn___reduce_cython __pyx_string_tab[92] +#define __pyx_n_u_IteratorColumn___setstate_cython __pyx_string_tab[93] +#define __pyx_n_u_IteratorColumn_addReference __pyx_string_tab[94] +#define __pyx_n_u_IteratorColumn_add_reference __pyx_string_tab[95] +#define __pyx_n_u_IteratorColumn_hasReference __pyx_string_tab[96] +#define __pyx_n_u_IteratorColumn_has_reference __pyx_string_tab[97] +#define __pyx_n_u_IteratorRow __pyx_string_tab[98] +#define __pyx_n_u_IteratorRowAll __pyx_string_tab[99] +#define __pyx_n_u_IteratorRowAllRefs __pyx_string_tab[100] +#define __pyx_n_u_IteratorRowAllRefs___reduce_cyth __pyx_string_tab[101] +#define __pyx_n_u_IteratorRowAllRefs___setstate_cy __pyx_string_tab[102] +#define __pyx_n_u_IteratorRowAllRefs_nextiter __pyx_string_tab[103] +#define __pyx_n_u_IteratorRowAll___reduce_cython __pyx_string_tab[104] +#define __pyx_n_u_IteratorRowAll___setstate_cython __pyx_string_tab[105] +#define __pyx_n_u_IteratorRowHead __pyx_string_tab[106] +#define __pyx_n_u_IteratorRowHead___reduce_cython __pyx_string_tab[107] +#define __pyx_n_u_IteratorRowHead___setstate_cytho __pyx_string_tab[108] +#define __pyx_n_u_IteratorRowRegion __pyx_string_tab[109] +#define __pyx_n_u_IteratorRowRegion___reduce_cytho __pyx_string_tab[110] +#define __pyx_n_u_IteratorRowRegion___setstate_cyt __pyx_string_tab[111] +#define __pyx_n_u_IteratorRowSelection __pyx_string_tab[112] +#define __pyx_n_u_IteratorRowSelection___reduce_cy __pyx_string_tab[113] +#define __pyx_n_u_IteratorRowSelection___setstate __pyx_string_tab[114] +#define __pyx_n_u_IteratorRow___reduce_cython __pyx_string_tab[115] +#define __pyx_n_u_IteratorRow___setstate_cython __pyx_string_tab[116] +#define __pyx_n_u_KNOWN_HEADER_FIELDS __pyx_string_tab[117] +#define __pyx_n_u_KS __pyx_string_tab[118] +#define __pyx_n_u_KeyError __pyx_string_tab[119] +#define __pyx_n_u_L __pyx_string_tab[120] +#define __pyx_n_u_LB __pyx_string_tab[121] +#define __pyx_n_u_LN __pyx_string_tab[122] +#define __pyx_n_u_M5 __pyx_string_tab[123] +#define __pyx_n_u_MAX_POS __pyx_string_tab[124] +#define __pyx_n_u_Mapping __pyx_string_tab[125] +#define __pyx_n_u_MemoryError __pyx_string_tab[126] +#define __pyx_n_u_N __pyx_string_tab[127] +#define __pyx_n_u_NotImplementedError __pyx_string_tab[128] +#define __pyx_kp_u_Note_that_Cython_is_deliberately __pyx_string_tab[129] +#define __pyx_n_u_OSError __pyx_string_tab[130] +#define __pyx_n_u_OrderedDict __pyx_string_tab[131] +#define __pyx_n_u_PG __pyx_string_tab[132] +#define __pyx_n_u_PI __pyx_string_tab[133] +#define __pyx_n_u_PL __pyx_string_tab[134] +#define __pyx_n_u_PM __pyx_string_tab[135] +#define __pyx_n_u_PN __pyx_string_tab[136] +#define __pyx_n_u_PP __pyx_string_tab[137] +#define __pyx_n_u_PU __pyx_string_tab[138] +#define __pyx_n_u_PickleError __pyx_string_tab[139] +#define __pyx_n_u_RG __pyx_string_tab[140] +#define __pyx_kp_u_Raw_iterator_set_up_without_regi __pyx_string_tab[141] +#define __pyx_kp_u_SAM_file_does_not_have_a_valid_h __pyx_string_tab[142] +#define __pyx_n_u_SM __pyx_string_tab[143] +#define __pyx_n_u_SN __pyx_string_tab[144] +#define __pyx_n_u_SNPCall __pyx_string_tab[145] +#define __pyx_n_u_SNPCall___reduce_cython __pyx_string_tab[146] +#define __pyx_n_u_SNPCall___setstate_cython __pyx_string_tab[147] +#define __pyx_n_u_SO __pyx_string_tab[148] +#define __pyx_n_u_SP __pyx_string_tab[149] +#define __pyx_kp_u_SQ __pyx_string_tab[150] +#define __pyx_n_u_SQ_2 __pyx_string_tab[151] +#define __pyx_kp_u_SQ_SN_LN __pyx_string_tab[152] +#define __pyx_n_u_SS __pyx_string_tab[153] +#define __pyx_n_u_Sequence __pyx_string_tab[154] +#define __pyx_n_u_StopIteration __pyx_string_tab[155] +#define __pyx_n_u_StringIO __pyx_string_tab[156] +#define __pyx_n_u_TP __pyx_string_tab[157] +#define __pyx_n_u_TypeError __pyx_string_tab[158] +#define __pyx_n_u_UR __pyx_string_tab[159] +#define __pyx_kp_u_Unable_to_reopen_file __pyx_string_tab[160] +#define __pyx_n_u_VALID_HEADERS __pyx_string_tab[161] +#define __pyx_n_u_VALID_HEADER_ORDER __pyx_string_tab[162] +#define __pyx_n_u_VALID_HEADER_TYPES __pyx_string_tab[163] +#define __pyx_n_u_VN __pyx_string_tab[164] +#define __pyx_n_u_ValueError __pyx_string_tab[165] +#define __pyx_kp_u__11 __pyx_string_tab[166] +#define __pyx_kp_u__12 __pyx_string_tab[167] +#define __pyx_kp_u__2 __pyx_string_tab[168] +#define __pyx_kp_u__3 __pyx_string_tab[169] +#define __pyx_kp_u__4 __pyx_string_tab[170] +#define __pyx_kp_u__5 __pyx_string_tab[171] +#define __pyx_kp_u__6 __pyx_string_tab[172] +#define __pyx_kp_u__7 __pyx_string_tab[173] +#define __pyx_kp_u__8 __pyx_string_tab[174] +#define __pyx_kp_b__9 __pyx_string_tab[175] +#define __pyx_kp_u_access_from_StringIO_objects_not __pyx_string_tab[176] +#define __pyx_n_u_addReference __pyx_string_tab[177] +#define __pyx_n_u_add_hts_options __pyx_string_tab[178] +#define __pyx_kp_u_add_note __pyx_string_tab[179] +#define __pyx_n_u_add_reference __pyx_string_tab[180] +#define __pyx_n_u_add_sam_header __pyx_string_tab[181] +#define __pyx_n_u_add_sq_text __pyx_string_tab[182] +#define __pyx_n_u_adjust_capq_threshold __pyx_string_tab[183] +#define __pyx_n_u_advance_all __pyx_string_tab[184] +#define __pyx_n_u_advance_nofilter __pyx_string_tab[185] +#define __pyx_n_u_advance_raw_all __pyx_string_tab[186] +#define __pyx_n_u_advance_raw_nofilter __pyx_string_tab[187] +#define __pyx_n_u_advance_samtools __pyx_string_tab[188] +#define __pyx_n_u_all __pyx_string_tab[189] +#define __pyx_n_u_all_2 __pyx_string_tab[190] +#define __pyx_n_u_append __pyx_string_tab[191] +#define __pyx_n_u_args __pyx_string_tab[192] +#define __pyx_n_u_array __pyx_string_tab[193] +#define __pyx_n_u_as_dict __pyx_string_tab[194] +#define __pyx_n_u_asyncio_coroutines __pyx_string_tab[195] +#define __pyx_n_u_b __pyx_string_tab[196] +#define __pyx_n_u_base_position __pyx_string_tab[197] +#define __pyx_n_u_beg __pyx_string_tab[198] +#define __pyx_n_u_bfile_name __pyx_string_tab[199] +#define __pyx_n_u_bindex_filename __pyx_string_tab[200] +#define __pyx_n_u_bool __pyx_string_tab[201] +#define __pyx_n_u_btext __pyx_string_tab[202] +#define __pyx_n_u_build __pyx_string_tab[203] +#define __pyx_n_u_build_header_line __pyx_string_tab[204] +#define __pyx_n_u_build_sequence_section __pyx_string_tab[205] +#define __pyx_n_u_c __pyx_string_tab[206] +#define __pyx_kp_u_can_not_iterate_over_samfile_wit __pyx_string_tab[207] +#define __pyx_kp_u_can_only_apply_IndexReads_on_bam __pyx_string_tab[208] +#define __pyx_kp_u_cannot_create_AlignmentHeader_re __pyx_string_tab[209] +#define __pyx_n_u_cfilename __pyx_string_tab[210] +#define __pyx_n_u_check_header __pyx_string_tab[211] +#define __pyx_n_u_check_index __pyx_string_tab[212] +#define __pyx_n_u_check_sq __pyx_string_tab[213] +#define __pyx_n_u_check_truncation __pyx_string_tab[214] +#define __pyx_n_u_cigar __pyx_string_tab[215] +#define __pyx_n_u_cigarstring __pyx_string_tab[216] +#define __pyx_n_u_cigartuples __pyx_string_tab[217] +#define __pyx_n_u_cindexname __pyx_string_tab[218] +#define __pyx_n_u_cinit __pyx_string_tab[219] +#define __pyx_n_u_class_getitem __pyx_string_tab[220] +#define __pyx_n_u_cline_in_traceback __pyx_string_tab[221] +#define __pyx_n_u_close __pyx_string_tab[222] +#define __pyx_n_u_closed __pyx_string_tab[223] +#define __pyx_n_u_cls __pyx_string_tab[224] +#define __pyx_n_u_cmode __pyx_string_tab[225] +#define __pyx_n_u_cnext __pyx_string_tab[226] +#define __pyx_n_u_code __pyx_string_tab[227] +#define __pyx_n_u_collections __pyx_string_tab[228] +#define __pyx_n_u_collections_abc __pyx_string_tab[229] +#define __pyx_n_u_compute_baq __pyx_string_tab[230] +#define __pyx_n_u_consensus_quality __pyx_string_tab[231] +#define __pyx_n_u_contains __pyx_string_tab[232] +#define __pyx_n_u_contig __pyx_string_tab[233] +#define __pyx_n_u_contig_length __pyx_string_tab[234] +#define __pyx_n_u_copy __pyx_string_tab[235] +#define __pyx_kp_u_could_not_allocate_bytes __pyx_string_tab[236] +#define __pyx_kp_u_could_not_allocate_memory_of_siz __pyx_string_tab[237] +#define __pyx_kp_u_could_not_create_header __pyx_string_tab[238] +#define __pyx_kp_u_could_not_open_alignment_file __pyx_string_tab[239] +#define __pyx_kp_u_could_not_parse_header __pyx_string_tab[240] +#define __pyx_n_u_count __pyx_string_tab[241] +#define __pyx_n_u_count_a __pyx_string_tab[242] +#define __pyx_n_u_count_c __pyx_string_tab[243] +#define __pyx_n_u_count_coverage __pyx_string_tab[244] +#define __pyx_n_u_count_g __pyx_string_tab[245] +#define __pyx_n_u_count_t __pyx_string_tab[246] +#define __pyx_n_u_counter __pyx_string_tab[247] +#define __pyx_n_u_coverage __pyx_string_tab[248] +#define __pyx_n_u_creference_filename __pyx_string_tab[249] +#define __pyx_n_u_ctext __pyx_string_tab[250] +#define __pyx_n_u_current_pos __pyx_string_tab[251] +#define __pyx_n_u_current_row __pyx_string_tab[252] +#define __pyx_n_u_data __pyx_string_tab[253] +#define __pyx_n_u_dealloc __pyx_string_tab[254] +#define __pyx_n_u_defaultdict __pyx_string_tab[255] +#define __pyx_n_u_dest __pyx_string_tab[256] +#define __pyx_n_u_dict __pyx_string_tab[257] +#define __pyx_n_u_dict_2 __pyx_string_tab[258] +#define __pyx_kp_u_disable __pyx_string_tab[259] +#define __pyx_n_u_duplicate_filehandle __pyx_string_tab[260] +#define __pyx_kp_u_either_supply_options_template_h __pyx_string_tab[261] +#define __pyx_kp_u_enable __pyx_string_tab[262] +#define __pyx_n_u_end __pyx_string_tab[263] +#define __pyx_n_u_enter __pyx_string_tab[264] +#define __pyx_n_u_enumerate __pyx_string_tab[265] +#define __pyx_kp_u_error_during_iteration __pyx_string_tab[266] +#define __pyx_kp_u_error_while_reading_file __pyx_string_tab[267] +#define __pyx_kp_u_error_while_reading_file_2 __pyx_string_tab[268] +#define __pyx_n_u_exc_type __pyx_string_tab[269] +#define __pyx_n_u_exc_value __pyx_string_tab[270] +#define __pyx_n_u_exit __pyx_string_tab[271] +#define __pyx_kp_u_failure_when_setting_reference_f __pyx_string_tab[272] +#define __pyx_n_u_fastafile __pyx_string_tab[273] +#define __pyx_n_u_fetch __pyx_string_tab[274] +#define __pyx_kp_u_fetch_called_on_bamfile_without __pyx_string_tab[275] +#define __pyx_kp_u_fetching_by_region_is_not_availa __pyx_string_tab[276] +#define __pyx_n_u_field __pyx_string_tab[277] +#define __pyx_n_u_fields __pyx_string_tab[278] +#define __pyx_kp_u_file_does_not_contain_alignment __pyx_string_tab[279] +#define __pyx_kp_u_file_does_not_have_a_valid_heade __pyx_string_tab[280] +#define __pyx_kp_u_file_has_no_sequences_defined_mo __pyx_string_tab[281] +#define __pyx_n_u_filename __pyx_string_tab[282] +#define __pyx_n_u_fileno __pyx_string_tab[283] +#define __pyx_n_u_filepath_index __pyx_string_tab[284] +#define __pyx_n_u_filepath_or_object __pyx_string_tab[285] +#define __pyx_n_u_fill_AlignmentHeader_from_list __pyx_string_tab[286] +#define __pyx_n_u_filter_method __pyx_string_tab[287] +#define __pyx_n_u_find __pyx_string_tab[288] +#define __pyx_n_u_find_introns __pyx_string_tab[289] +#define __pyx_n_u_find_introns_slow __pyx_string_tab[290] +#define __pyx_n_u_flag __pyx_string_tab[291] +#define __pyx_n_u_flag_filter __pyx_string_tab[292] +#define __pyx_n_u_flag_require __pyx_string_tab[293] +#define __pyx_n_u_format __pyx_string_tab[294] +#define __pyx_n_u_format_options __pyx_string_tab[295] +#define __pyx_n_u_free_pileup_iter __pyx_string_tab[296] +#define __pyx_n_u_from_dict __pyx_string_tab[297] +#define __pyx_n_u_from_references __pyx_string_tab[298] +#define __pyx_n_u_from_text __pyx_string_tab[299] +#define __pyx_n_u_from_text_and_lengths __pyx_string_tab[300] +#define __pyx_n_u_func __pyx_string_tab[301] +#define __pyx_kp_u_gc __pyx_string_tab[302] +#define __pyx_n_u_genome_loc __pyx_string_tab[303] +#define __pyx_n_u_genotype __pyx_string_tab[304] +#define __pyx_n_u_get __pyx_string_tab[305] +#define __pyx_n_u_getCurrent __pyx_string_tab[306] +#define __pyx_n_u_getSequence __pyx_string_tab[307] +#define __pyx_n_u_get_2 __pyx_string_tab[308] +#define __pyx_n_u_get_aligned_pairs __pyx_string_tab[309] +#define __pyx_n_u_get_index_statistics __pyx_string_tab[310] +#define __pyx_n_u_get_reference_length __pyx_string_tab[311] +#define __pyx_n_u_get_reference_name __pyx_string_tab[312] +#define __pyx_n_u_get_sequence __pyx_string_tab[313] +#define __pyx_n_u_get_tid __pyx_string_tab[314] +#define __pyx_n_u_getitem __pyx_string_tab[315] +#define __pyx_n_u_getrname __pyx_string_tab[316] +#define __pyx_n_u_getstate __pyx_string_tab[317] +#define __pyx_n_u_gettid __pyx_string_tab[318] +#define __pyx_n_u_h __pyx_string_tab[319] +#define __pyx_n_u_hasReference __pyx_string_tab[320] +#define __pyx_n_u_has_coord __pyx_string_tab[321] +#define __pyx_n_u_has_index __pyx_string_tab[322] +#define __pyx_n_u_has_reference __pyx_string_tab[323] +#define __pyx_n_u_hdr __pyx_string_tab[324] +#define __pyx_n_u_head __pyx_string_tab[325] +#define __pyx_n_u_header __pyx_string_tab[326] +#define __pyx_n_u_header_dict __pyx_string_tab[327] +#define __pyx_kp_u_header_line_with_invalid_type __pyx_string_tab[328] +#define __pyx_kp_u_header_line_without_s __pyx_string_tab[329] +#define __pyx_kp_u_header_not_available_in_closed_f __pyx_string_tab[330] +#define __pyx_n_u_idx __pyx_string_tab[331] +#define __pyx_n_u_ignore_orphans __pyx_string_tab[332] +#define __pyx_n_u_ignore_overlaps __pyx_string_tab[333] +#define __pyx_n_u_ignore_truncation __pyx_string_tab[334] +#define __pyx_kp_u_incomplete_sequence_information __pyx_string_tab[335] +#define __pyx_n_u_index __pyx_string_tab[336] +#define __pyx_n_u_index_filename __pyx_string_tab[337] +#define __pyx_n_u_init __pyx_string_tab[338] +#define __pyx_n_u_initializing __pyx_string_tab[339] +#define __pyx_n_u_int_array_template __pyx_string_tab[340] +#define __pyx_kp_u_interval_of_size_0 __pyx_string_tab[341] +#define __pyx_kp_u_interval_of_size_less_than_0 __pyx_string_tab[342] +#define __pyx_kp_u_invalid_file_opening_mode_s __pyx_string_tab[343] +#define __pyx_kp_u_invalid_type_for_record_expected __pyx_string_tab[344] +#define __pyx_n_u_io __pyx_string_tab[345] +#define __pyx_n_u_is_bam __pyx_string_tab[346] +#define __pyx_n_u_is_coroutine __pyx_string_tab[347] +#define __pyx_n_u_is_cram __pyx_string_tab[348] +#define __pyx_n_u_is_open __pyx_string_tab[349] +#define __pyx_n_u_is_valid_tid __pyx_string_tab[350] +#define __pyx_kp_u_isenabled __pyx_string_tab[351] +#define __pyx_n_u_islower __pyx_string_tab[352] +#define __pyx_n_u_isupper __pyx_string_tab[353] +#define __pyx_n_u_items __pyx_string_tab[354] +#define __pyx_n_u_iter __pyx_string_tab[355] +#define __pyx_n_u_iter_2 __pyx_string_tab[356] +#define __pyx_n_u_iterdata __pyx_string_tab[357] +#define __pyx_n_u_iteritems __pyx_string_tab[358] +#define __pyx_n_u_junc_start __pyx_string_tab[359] +#define __pyx_n_u_key __pyx_string_tab[360] +#define __pyx_n_u_keys __pyx_string_tab[361] +#define __pyx_n_u_kwargs __pyx_string_tab[362] +#define __pyx_n_u_l_text __pyx_string_tab[363] +#define __pyx_n_u_last_read_pos __pyx_string_tab[364] +#define __pyx_n_u_len __pyx_string_tab[365] +#define __pyx_n_u_length __pyx_string_tab[366] +#define __pyx_n_u_lengths __pyx_string_tab[367] +#define __pyx_n_u_line __pyx_string_tab[368] +#define __pyx_n_u_lines __pyx_string_tab[369] +#define __pyx_n_u_main __pyx_string_tab[370] +#define __pyx_n_u_make __pyx_string_tab[371] +#define __pyx_n_u_makeAlignmentHeader __pyx_string_tab[372] +#define __pyx_kp_u_malformatted_header_no_in_field __pyx_string_tab[373] +#define __pyx_n_u_map __pyx_string_tab[374] +#define __pyx_n_u_mapped __pyx_string_tab[375] +#define __pyx_kp_u_mapping_information_not_recorded __pyx_string_tab[376] +#define __pyx_n_u_mapping_quality __pyx_string_tab[377] +#define __pyx_n_u_match_or_deletion __pyx_string_tab[378] +#define __pyx_n_u_mate __pyx_string_tab[379] +#define __pyx_kp_u_mate_not_found __pyx_string_tab[380] +#define __pyx_kp_u_mate_s_is_unmapped __pyx_string_tab[381] +#define __pyx_n_u_max_depth __pyx_string_tab[382] +#define __pyx_n_u_max_rows __pyx_string_tab[383] +#define __pyx_n_u_min_base_quality __pyx_string_tab[384] +#define __pyx_n_u_min_mapping_quality __pyx_string_tab[385] +#define __pyx_n_u_mode __pyx_string_tab[386] +#define __pyx_n_u_module __pyx_string_tab[387] +#define __pyx_n_u_multiple_iterators __pyx_string_tab[388] +#define __pyx_kp_u_multiple_iterators_not_implement __pyx_string_tab[389] +#define __pyx_kp_u_multiple_iterators_not_implement_2 __pyx_string_tab[390] +#define __pyx_kp_u_multiple_s_lines_are_not_permitt __pyx_string_tab[391] +#define __pyx_n_u_n __pyx_string_tab[392] +#define __pyx_n_u_n_plp __pyx_string_tab[393] +#define __pyx_n_u_name __pyx_string_tab[394] +#define __pyx_n_u_name_2 __pyx_string_tab[395] +#define __pyx_n_u_namedtuple __pyx_string_tab[396] +#define __pyx_n_u_new __pyx_string_tab[397] +#define __pyx_n_u_next __pyx_string_tab[398] +#define __pyx_n_u_nextiter __pyx_string_tab[399] +#define __pyx_kp_u_no_default___reduce___due_to_non __pyx_string_tab[400] +#define __pyx_kp_u_no_index_available_for_fetch __pyx_string_tab[401] +#define __pyx_kp_u_no_index_available_for_iteration __pyx_string_tab[402] +#define __pyx_kp_u_no_index_available_for_pileup __pyx_string_tab[403] +#define __pyx_n_u_nofilter __pyx_string_tab[404] +#define __pyx_kp_u_not_enough_information_to_constr __pyx_string_tab[405] +#define __pyx_n_u_nreferences __pyx_string_tab[406] +#define __pyx_n_u_nt __pyx_string_tab[407] +#define __pyx_kp_u_number_of_reference_names_and_le __pyx_string_tab[408] +#define __pyx_n_u_op __pyx_string_tab[409] +#define __pyx_n_u_open __pyx_string_tab[410] +#define __pyx_n_u_os __pyx_string_tab[411] +#define __pyx_n_u_parse_region __pyx_string_tab[412] +#define __pyx_n_u_pickle __pyx_string_tab[413] +#define __pyx_n_u_pileup __pyx_string_tab[414] +#define __pyx_n_u_pileup_iter __pyx_string_tab[415] +#define __pyx_n_u_plp __pyx_string_tab[416] +#define __pyx_n_u_pop __pyx_string_tab[417] +#define __pyx_n_u_port __pyx_string_tab[418] +#define __pyx_n_u_pos __pyx_string_tab[419] +#define __pyx_n_u_positions __pyx_string_tab[420] +#define __pyx_n_u_pysam_libcalignmentfile __pyx_string_tab[421] +#define __pyx_kp_u_pysam_libcalignmentfile_pxd __pyx_string_tab[422] +#define __pyx_kp_u_pysam_libcalignmentfile_pyx __pyx_string_tab[423] +#define __pyx_n_u_pyx_PickleError __pyx_string_tab[424] +#define __pyx_n_u_pyx_checksum __pyx_string_tab[425] +#define __pyx_n_u_pyx_result __pyx_string_tab[426] +#define __pyx_n_u_pyx_state __pyx_string_tab[427] +#define __pyx_n_u_pyx_type __pyx_string_tab[428] +#define __pyx_n_u_pyx_unpickle_SNPCall __pyx_string_tab[429] +#define __pyx_n_u_pyx_unpickle_SNPCall__set_stat __pyx_string_tab[430] +#define __pyx_n_u_pyx_vtable __pyx_string_tab[431] +#define __pyx_n_u_qname __pyx_string_tab[432] +#define __pyx_n_u_qpos __pyx_string_tab[433] +#define __pyx_n_u_quality __pyx_string_tab[434] +#define __pyx_n_u_quality_threshold __pyx_string_tab[435] +#define __pyx_n_u_qualname __pyx_string_tab[436] +#define __pyx_n_u_query_name __pyx_string_tab[437] +#define __pyx_n_u_query_qualities __pyx_string_tab[438] +#define __pyx_n_u_r __pyx_string_tab[439] +#define __pyx_n_u_rU __pyx_string_tab[440] +#define __pyx_n_u_range __pyx_string_tab[441] +#define __pyx_n_u_rb __pyx_string_tab[442] +#define __pyx_n_u_rc __pyx_string_tab[443] +#define __pyx_n_u_re __pyx_string_tab[444] +#define __pyx_n_u_read __pyx_string_tab[445] +#define __pyx_n_u_read_callback __pyx_string_tab[446] +#define __pyx_n_u_read_failure_reason __pyx_string_tab[447] +#define __pyx_n_u_read_iterator __pyx_string_tab[448] +#define __pyx_n_u_read_loc __pyx_string_tab[449] +#define __pyx_kp_u_read_s_is_unpaired __pyx_string_tab[450] +#define __pyx_kp_u_read_s_not_found __pyx_string_tab[451] +#define __pyx_n_u_record __pyx_string_tab[452] +#define __pyx_n_u_redo_baq __pyx_string_tab[453] +#define __pyx_n_u_reduce __pyx_string_tab[454] +#define __pyx_n_u_reduce_cython __pyx_string_tab[455] +#define __pyx_n_u_reduce_ex __pyx_string_tab[456] +#define __pyx_n_u_ref __pyx_string_tab[457] +#define __pyx_n_u_reference __pyx_string_tab[458] +#define __pyx_n_u_reference_base __pyx_string_tab[459] +#define __pyx_n_u_reference_filename __pyx_string_tab[460] +#define __pyx_kp_u_reference_id_i_out_of_range_0_ti __pyx_string_tab[461] +#define __pyx_n_u_reference_lengths __pyx_string_tab[462] +#define __pyx_n_u_reference_names __pyx_string_tab[463] +#define __pyx_kp_u_reference_sequence_for_tid_not_f __pyx_string_tab[464] +#define __pyx_n_u_referencelengths __pyx_string_tab[465] +#define __pyx_n_u_referencenames __pyx_string_tab[466] +#define __pyx_n_u_references __pyx_string_tab[467] +#define __pyx_n_u_refpos __pyx_string_tab[468] +#define __pyx_n_u_region __pyx_string_tab[469] +#define __pyx_n_u_require_index __pyx_string_tab[470] +#define __pyx_n_u_res __pyx_string_tab[471] +#define __pyx_n_u_reset __pyx_string_tab[472] +#define __pyx_n_u_result __pyx_string_tab[473] +#define __pyx_n_u_results __pyx_string_tab[474] +#define __pyx_n_u_ret __pyx_string_tab[475] +#define __pyx_n_u_rstart __pyx_string_tab[476] +#define __pyx_n_u_rstop __pyx_string_tab[477] +#define __pyx_n_u_rtid __pyx_string_tab[478] +#define __pyx_kp_u_s __pyx_string_tab[479] +#define __pyx_kp_u_sam_write1_failed_with_error_cod __pyx_string_tab[480] +#define __pyx_n_u_samfile __pyx_string_tab[481] +#define __pyx_n_u_samtools __pyx_string_tab[482] +#define __pyx_n_u_self __pyx_string_tab[483] +#define __pyx_kp_u_self_b_self_htsfile_self_index_c __pyx_string_tab[484] +#define __pyx_kp_u_self_b_self_htsfile_self_index_s __pyx_string_tab[485] +#define __pyx_kp_u_self_htsfile_cannot_be_converted __pyx_string_tab[486] +#define __pyx_n_u_seq __pyx_string_tab[487] +#define __pyx_n_u_set_name __pyx_string_tab[488] +#define __pyx_n_u_setitem __pyx_string_tab[489] +#define __pyx_n_u_setstate __pyx_string_tab[490] +#define __pyx_n_u_setstate_cython __pyx_string_tab[491] +#define __pyx_n_u_setup_iterator __pyx_string_tab[492] +#define __pyx_n_u_setup_raw_rest_iterator __pyx_string_tab[493] +#define __pyx_n_u_snp_quality __pyx_string_tab[494] +#define __pyx_n_u_spec __pyx_string_tab[495] +#define __pyx_n_u_split __pyx_string_tab[496] +#define __pyx_n_u_splitlines __pyx_string_tab[497] +#define __pyx_n_u_sq __pyx_string_tab[498] +#define __pyx_n_u_start __pyx_string_tab[499] +#define __pyx_n_u_start_2 __pyx_string_tab[500] +#define __pyx_n_u_startswith __pyx_string_tab[501] +#define __pyx_n_u_state __pyx_string_tab[502] +#define __pyx_n_u_stepper __pyx_string_tab[503] +#define __pyx_n_u_stop __pyx_string_tab[504] +#define __pyx_n_u_stop_2 __pyx_string_tab[505] +#define __pyx_n_u_str __pyx_string_tab[506] +#define __pyx_kp_u_stringsource __pyx_string_tab[507] +#define __pyx_n_u_strip __pyx_string_tab[508] +#define __pyx_n_u_sum __pyx_string_tab[509] +#define __pyx_n_u_super __pyx_string_tab[510] +#define __pyx_n_u_t __pyx_string_tab[511] +#define __pyx_n_u_tell __pyx_string_tab[512] +#define __pyx_n_u_template __pyx_string_tab[513] +#define __pyx_n_u_test __pyx_string_tab[514] +#define __pyx_n_u_text __pyx_string_tab[515] +#define __pyx_n_u_threads __pyx_string_tab[516] +#define __pyx_n_u_threshold __pyx_string_tab[517] +#define __pyx_n_u_tid __pyx_string_tab[518] +#define __pyx_n_u_to_dict __pyx_string_tab[519] +#define __pyx_n_u_total __pyx_string_tab[520] +#define __pyx_n_u_traceback __pyx_string_tab[521] +#define __pyx_n_u_truncate __pyx_string_tab[522] +#define __pyx_kp_u_truncated_file __pyx_string_tab[523] +#define __pyx_kp_u_unable_to_open_index_file __pyx_string_tab[524] +#define __pyx_kp_u_unable_to_open_index_file_s __pyx_string_tab[525] +#define __pyx_kp_u_unable_to_read_header_informatio __pyx_string_tab[526] +#define __pyx_kp_u_unknown_reference __pyx_string_tab[527] +#define __pyx_kp_u_unknown_stepper_option_s_in_Iter __pyx_string_tab[528] +#define __pyx_n_u_unmapped __pyx_string_tab[529] +#define __pyx_n_u_until_eof __pyx_string_tab[530] +#define __pyx_n_u_update __pyx_string_tab[531] +#define __pyx_n_u_use_setstate __pyx_string_tab[532] +#define __pyx_n_u_value __pyx_string_tab[533] +#define __pyx_n_u_values __pyx_string_tab[534] +#define __pyx_n_u_w __pyx_string_tab[535] +#define __pyx_n_u_warn __pyx_string_tab[536] +#define __pyx_n_u_warnings __pyx_string_tab[537] +#define __pyx_n_u_wb __pyx_string_tab[538] +#define __pyx_n_u_wb0 __pyx_string_tab[539] +#define __pyx_n_u_wbu __pyx_string_tab[540] +#define __pyx_n_u_wc __pyx_string_tab[541] +#define __pyx_n_u_wh __pyx_string_tab[542] +#define __pyx_n_u_write __pyx_string_tab[543] +#define __pyx_kp_u_wrong_sequence_information_in_s __pyx_string_tab[544] +#define __pyx_n_u_x __pyx_string_tab[545] +#define __pyx_n_u_y __pyx_string_tab[546] +#define __pyx_n_u_zip __pyx_string_tab[547] +/* #### Code section: module_state_clear ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_clear(PyObject *m) { + __pyx_mstatetype *clear_module_state = __Pyx_PyModule_GetState(m); + if (!clear_module_state) return 0; + Py_CLEAR(clear_module_state->__pyx_d); + Py_CLEAR(clear_module_state->__pyx_b); + Py_CLEAR(clear_module_state->__pyx_cython_runtime); + Py_CLEAR(clear_module_state->__pyx_empty_tuple); + Py_CLEAR(clear_module_state->__pyx_empty_bytes); + Py_CLEAR(clear_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_CLEAR(clear_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_CLEAR(clear_module_state->__pyx_FusedFunctionType); + #endif + #if CYTHON_PEP489_MULTI_PHASE_INIT + __Pyx_State_RemoveModule(NULL); + #endif + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_4type_type); + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_4bool_bool); + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_7complex_complex); + Py_CLEAR(clear_module_state->__pyx_ptype_7cpython_5array_array); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_10libchtslib_HTSFile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_FastaFile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_FastqProxy); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_FastxRecord); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_FastxFile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_FastqFile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_9libcfaidx_Fastafile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_18libcalignedsegment_PileupRead); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_AlignmentFile); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRow); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumn); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_IndexedReads); + Py_CLEAR(clear_module_state->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall); + Py_CLEAR(clear_module_state->__pyx_type_5pysam_17libcalignmentfile_SNPCall); + for (int i=0; i<1; ++i) { Py_CLEAR(clear_module_state->__pyx_slice[i]); } + for (int i=0; i<16; ++i) { Py_CLEAR(clear_module_state->__pyx_tuple[i]); } + for (int i=0; i<166; ++i) { Py_CLEAR(clear_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<548; ++i) { Py_CLEAR(clear_module_state->__pyx_string_tab[i]); } + Py_CLEAR(clear_module_state->__pyx_int_0); + Py_CLEAR(clear_module_state->__pyx_int_1); + Py_CLEAR(clear_module_state->__pyx_int_2); + Py_CLEAR(clear_module_state->__pyx_int_7); + Py_CLEAR(clear_module_state->__pyx_int_8); + Py_CLEAR(clear_module_state->__pyx_int_13); + Py_CLEAR(clear_module_state->__pyx_int_15); + Py_CLEAR(clear_module_state->__pyx_int_1796); + Py_CLEAR(clear_module_state->__pyx_int_8000); + Py_CLEAR(clear_module_state->__pyx_int_18041500); + Py_CLEAR(clear_module_state->__pyx_int_84615809); + Py_CLEAR(clear_module_state->__pyx_int_239452417); + Py_CLEAR(clear_module_state->__pyx_int_neg_1); + Py_CLEAR(clear_module_state->__pyx_int_neg_2); + return 0; +} +#endif +/* #### Code section: module_state_traverse ### */ +#if CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __pyx_m_traverse(PyObject *m, visitproc visit, void *arg) { + __pyx_mstatetype *traverse_module_state = __Pyx_PyModule_GetState(m); + if (!traverse_module_state) return 0; + Py_VISIT(traverse_module_state->__pyx_d); + Py_VISIT(traverse_module_state->__pyx_b); + Py_VISIT(traverse_module_state->__pyx_cython_runtime); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_tuple); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_bytes); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_empty_unicode); + #ifdef __Pyx_CyFunction_USED + Py_VISIT(traverse_module_state->__pyx_CyFunctionType); + #endif + #ifdef __Pyx_FusedFunction_USED + Py_VISIT(traverse_module_state->__pyx_FusedFunctionType); + #endif + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_4type_type); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_4bool_bool); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_7complex_complex); + Py_VISIT(traverse_module_state->__pyx_ptype_7cpython_5array_array); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_10libchtslib_HTSFile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_FastaFile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_FastqProxy); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_FastxRecord); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_FastxFile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_FastqFile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_9libcfaidx_Fastafile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_18libcalignedsegment_PileupRead); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_AlignmentFile); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRow); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumn); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_IndexedReads); + Py_VISIT(traverse_module_state->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall); + Py_VISIT(traverse_module_state->__pyx_type_5pysam_17libcalignmentfile_SNPCall); + for (int i=0; i<1; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_slice[i]); } + for (int i=0; i<16; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_tuple[i]); } + for (int i=0; i<166; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_codeobj_tab[i]); } + for (int i=0; i<548; ++i) { __Pyx_VISIT_CONST(traverse_module_state->__pyx_string_tab[i]); } + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_0); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_1); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_2); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_7); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_8); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_13); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_15); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_1796); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_8000); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_18041500); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_84615809); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_239452417); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_neg_1); + __Pyx_VISIT_CONST(traverse_module_state->__pyx_int_neg_2); + return 0; +} +#endif +/* #### Code section: module_code ### */ + +/* "cpython/complex.pxd":20 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4real_real(PyComplexObject *__pyx_v_self) { + double __pyx_r; + + /* "cpython/complex.pxd":23 + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: + * return self.cval.real # <<<<<<<<<<<<<< + * + * # unavailable in limited API +*/ + __pyx_r = __pyx_v_self->cval.real; + goto __pyx_L0; + + /* "cpython/complex.pxd":20 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double real(self) noexcept: +*/ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/complex.pxd":26 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE double __pyx_f_7cpython_7complex_7complex_4imag_imag(PyComplexObject *__pyx_v_self) { + double __pyx_r; + + /* "cpython/complex.pxd":29 + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: + * return self.cval.imag # <<<<<<<<<<<<<< + * + * # PyTypeObject PyComplex_Type +*/ + __pyx_r = __pyx_v_self->cval.imag; + goto __pyx_L0; + + /* "cpython/complex.pxd":26 + * + * # unavailable in limited API + * @property # <<<<<<<<<<<<<< + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline double imag(self) noexcept: +*/ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/contextvars.pxd":115 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject *__pyx_f_7cpython_11contextvars_get_value(PyObject *__pyx_v_var, struct __pyx_opt_args_7cpython_11contextvars_get_value *__pyx_optional_args) { + + /* "cpython/contextvars.pxd":116 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the default value of the context variable, +*/ + PyObject *__pyx_v_default_value = ((PyObject *)Py_None); + PyObject *__pyx_v_value; + PyObject *__pyx_v_pyvalue = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_value", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_default_value = __pyx_optional_args->default_value; + } + } + + /* "cpython/contextvars.pxd":121 + * or None if no such value or default was found. + * """ + * cdef PyObject *value = NULL # <<<<<<<<<<<<<< + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: +*/ + __pyx_v_value = NULL; + + /* "cpython/contextvars.pxd":122 + * """ + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) # <<<<<<<<<<<<<< + * if value is NULL: + * # context variable does not have a default +*/ + __pyx_t_1 = PyContextVar_Get(__pyx_v_var, NULL, (&__pyx_v_value)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 122, __pyx_L1_error) + + /* "cpython/contextvars.pxd":123 + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: # <<<<<<<<<<<<<< + * # context variable does not have a default + * pyvalue = default_value +*/ + __pyx_t_2 = (__pyx_v_value == NULL); + if (__pyx_t_2) { + + /* "cpython/contextvars.pxd":125 + * if value is NULL: + * # context variable does not have a default + * pyvalue = default_value # <<<<<<<<<<<<<< + * else: + * # value or default value of context variable +*/ + __Pyx_INCREF(__pyx_v_default_value); + __pyx_v_pyvalue = __pyx_v_default_value; + + /* "cpython/contextvars.pxd":123 + * cdef PyObject *value = NULL + * PyContextVar_Get(var, NULL, &value) + * if value is NULL: # <<<<<<<<<<<<<< + * # context variable does not have a default + * pyvalue = default_value +*/ + goto __pyx_L3; + } + + /* "cpython/contextvars.pxd":128 + * else: + * # value or default value of context variable + * pyvalue = value # <<<<<<<<<<<<<< + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue +*/ + /*else*/ { + __pyx_t_3 = ((PyObject *)__pyx_v_value); + __Pyx_INCREF(__pyx_t_3); + __pyx_v_pyvalue = __pyx_t_3; + __pyx_t_3 = 0; + + /* "cpython/contextvars.pxd":129 + * # value or default value of context variable + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' # <<<<<<<<<<<<<< + * return pyvalue + * +*/ + Py_XDECREF(__pyx_v_value); + } + __pyx_L3:; + + /* "cpython/contextvars.pxd":130 + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pyvalue); + __pyx_r = __pyx_v_pyvalue; + goto __pyx_L0; + + /* "cpython/contextvars.pxd":115 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_AddTraceback("cpython.contextvars.get_value", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pyvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "cpython/contextvars.pxd":133 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value_no_default(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + +#if !CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE PyObject *__pyx_f_7cpython_11contextvars_get_value_no_default(PyObject *__pyx_v_var, struct __pyx_opt_args_7cpython_11contextvars_get_value_no_default *__pyx_optional_args) { + + /* "cpython/contextvars.pxd":134 + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") + * cdef inline object get_value_no_default(var, default_value=None): # <<<<<<<<<<<<<< + * """Return a new reference to the value of the context variable, + * or the provided default value if no such value was found. +*/ + PyObject *__pyx_v_default_value = ((PyObject *)Py_None); + PyObject *__pyx_v_value; + PyObject *__pyx_v_pyvalue = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("get_value_no_default", 0); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_default_value = __pyx_optional_args->default_value; + } + } + + /* "cpython/contextvars.pxd":140 + * Ignores the default value of the context variable, if any. + * """ + * cdef PyObject *value = NULL # <<<<<<<<<<<<<< + * PyContextVar_Get(var, default_value, &value) + * # value of context variable or 'default_value' +*/ + __pyx_v_value = NULL; + + /* "cpython/contextvars.pxd":141 + * """ + * cdef PyObject *value = NULL + * PyContextVar_Get(var, default_value, &value) # <<<<<<<<<<<<<< + * # value of context variable or 'default_value' + * pyvalue = value +*/ + __pyx_t_1 = PyContextVar_Get(__pyx_v_var, ((PyObject *)__pyx_v_default_value), (&__pyx_v_value)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(1, 141, __pyx_L1_error) + + /* "cpython/contextvars.pxd":143 + * PyContextVar_Get(var, default_value, &value) + * # value of context variable or 'default_value' + * pyvalue = value # <<<<<<<<<<<<<< + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_value); + __Pyx_INCREF(__pyx_t_2); + __pyx_v_pyvalue = __pyx_t_2; + __pyx_t_2 = 0; + + /* "cpython/contextvars.pxd":144 + * # value of context variable or 'default_value' + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' # <<<<<<<<<<<<<< + * return pyvalue +*/ + Py_XDECREF(__pyx_v_value); + + /* "cpython/contextvars.pxd":145 + * pyvalue = value + * Py_XDECREF(value) # PyContextVar_Get() returned an owned reference as 'PyObject*' + * return pyvalue # <<<<<<<<<<<<<< +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_pyvalue); + __pyx_r = __pyx_v_pyvalue; + goto __pyx_L0; + + /* "cpython/contextvars.pxd":133 + * + * + * @_cython.c_compile_guard("!CYTHON_COMPILING_IN_LIMITED_API") # <<<<<<<<<<<<<< + * cdef inline object get_value_no_default(var, default_value=None): + * """Return a new reference to the value of the context variable, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("cpython.contextvars.get_value_no_default", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_pyvalue); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +#endif /*!(#if !CYTHON_COMPILING_IN_LIMITED_API)*/ + +/* "array.pxd":104 + * __data_union data + * + * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fulfill the PEP. +*/ + +/* Python wrapper */ +CYTHON_UNUSED static int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ +CYTHON_UNUSED static int __pyx_pw_7cpython_5array_5array_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_7cpython_5array_5array___getbuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_7cpython_5array_5array___getbuffer__(arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info, CYTHON_UNUSED int __pyx_v_flags) { + PyObject *__pyx_v_item_count = NULL; + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + char *__pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + char __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + if (unlikely(__pyx_v_info == NULL)) { + PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); + return -1; + } + __Pyx_RefNannySetupContext("__getbuffer__", 0); + __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(__pyx_v_info->obj); + + /* "array.pxd":109 + * # In particular strided access is always provided regardless + * # of flags + * item_count = Py_SIZE(self) # <<<<<<<<<<<<<< + * + * info.suboffsets = NULL +*/ + __pyx_t_1 = PyLong_FromSsize_t(Py_SIZE(((PyObject *)__pyx_v_self))); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 109, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_item_count = __pyx_t_1; + __pyx_t_1 = 0; + + /* "array.pxd":111 + * item_count = Py_SIZE(self) + * + * info.suboffsets = NULL # <<<<<<<<<<<<<< + * info.buf = self.data.as_chars + * info.readonly = 0 +*/ + __pyx_v_info->suboffsets = NULL; + + /* "array.pxd":112 + * + * info.suboffsets = NULL + * info.buf = self.data.as_chars # <<<<<<<<<<<<<< + * info.readonly = 0 + * info.ndim = 1 +*/ + __pyx_t_2 = __pyx_v_self->data.as_chars; + __pyx_v_info->buf = __pyx_t_2; + + /* "array.pxd":113 + * info.suboffsets = NULL + * info.buf = self.data.as_chars + * info.readonly = 0 # <<<<<<<<<<<<<< + * info.ndim = 1 + * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) +*/ + __pyx_v_info->readonly = 0; + + /* "array.pxd":114 + * info.buf = self.data.as_chars + * info.readonly = 0 + * info.ndim = 1 # <<<<<<<<<<<<<< + * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * info.len = info.itemsize * item_count +*/ + __pyx_v_info->ndim = 1; + + /* "array.pxd":115 + * info.readonly = 0 + * info.ndim = 1 + * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) # <<<<<<<<<<<<<< + * info.len = info.itemsize * item_count + * +*/ + __pyx_t_3 = __pyx_v_self->ob_descr->itemsize; + __pyx_v_info->itemsize = __pyx_t_3; + + /* "array.pxd":116 + * info.ndim = 1 + * info.itemsize = self.ob_descr.itemsize # e.g. sizeof(float) + * info.len = info.itemsize * item_count # <<<<<<<<<<<<<< + * + * info.shape = PyObject_Malloc(sizeof(Py_ssize_t) + 2) +*/ + __pyx_t_1 = PyLong_FromSsize_t(__pyx_v_info->itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_v_item_count); if (unlikely(!__pyx_t_4)) __PYX_ERR(2, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_4); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 116, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_info->len = __pyx_t_5; + + /* "array.pxd":118 + * info.len = info.itemsize * item_count + * + * info.shape = PyObject_Malloc(sizeof(Py_ssize_t) + 2) # <<<<<<<<<<<<<< + * if not info.shape: + * raise MemoryError() +*/ + __pyx_v_info->shape = ((Py_ssize_t *)PyObject_Malloc(((sizeof(Py_ssize_t)) + 2))); + + /* "array.pxd":119 + * + * info.shape = PyObject_Malloc(sizeof(Py_ssize_t) + 2) + * if not info.shape: # <<<<<<<<<<<<<< + * raise MemoryError() + * info.shape[0] = item_count # constant regardless of resizing +*/ + __pyx_t_6 = (!(__pyx_v_info->shape != 0)); + if (unlikely(__pyx_t_6)) { + + /* "array.pxd":120 + * info.shape = PyObject_Malloc(sizeof(Py_ssize_t) + 2) + * if not info.shape: + * raise MemoryError() # <<<<<<<<<<<<<< + * info.shape[0] = item_count # constant regardless of resizing + * info.strides = &info.itemsize +*/ + PyErr_NoMemory(); __PYX_ERR(2, 120, __pyx_L1_error) + + /* "array.pxd":119 + * + * info.shape = PyObject_Malloc(sizeof(Py_ssize_t) + 2) + * if not info.shape: # <<<<<<<<<<<<<< + * raise MemoryError() + * info.shape[0] = item_count # constant regardless of resizing +*/ + } + + /* "array.pxd":121 + * if not info.shape: + * raise MemoryError() + * info.shape[0] = item_count # constant regardless of resizing # <<<<<<<<<<<<<< + * info.strides = &info.itemsize + * +*/ + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_item_count); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(2, 121, __pyx_L1_error) + (__pyx_v_info->shape[0]) = __pyx_t_5; + + /* "array.pxd":122 + * raise MemoryError() + * info.shape[0] = item_count # constant regardless of resizing + * info.strides = &info.itemsize # <<<<<<<<<<<<<< + * + * info.format = (info.shape + 1) +*/ + __pyx_v_info->strides = (&__pyx_v_info->itemsize); + + /* "array.pxd":124 + * info.strides = &info.itemsize + * + * info.format = (info.shape + 1) # <<<<<<<<<<<<<< + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 +*/ + __pyx_v_info->format = ((char *)(__pyx_v_info->shape + 1)); + + /* "array.pxd":125 + * + * info.format = (info.shape + 1) + * info.format[0] = self.ob_descr.typecode # <<<<<<<<<<<<<< + * info.format[1] = 0 + * info.obj = self +*/ + __pyx_t_7 = __pyx_v_self->ob_descr->typecode; + (__pyx_v_info->format[0]) = __pyx_t_7; + + /* "array.pxd":126 + * info.format = (info.shape + 1) + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 # <<<<<<<<<<<<<< + * info.obj = self + * +*/ + (__pyx_v_info->format[1]) = 0; + + /* "array.pxd":127 + * info.format[0] = self.ob_descr.typecode + * info.format[1] = 0 + * info.obj = self # <<<<<<<<<<<<<< + * + * def __releasebuffer__(self, Py_buffer* info): +*/ + __Pyx_INCREF((PyObject *)__pyx_v_self); + __Pyx_GIVEREF((PyObject *)__pyx_v_self); + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); + __pyx_v_info->obj = ((PyObject *)__pyx_v_self); + + /* "array.pxd":104 + * __data_union data + * + * def __getbuffer__(self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< + * # This implementation of getbuffer is geared towards Cython + * # requirements, and does not yet fulfill the PEP. +*/ + + /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_AddTraceback("cpython.array.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + if (__pyx_v_info->obj != NULL) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + goto __pyx_L2; + __pyx_L0:; + if (__pyx_v_info->obj == Py_None) { + __Pyx_GOTREF(__pyx_v_info->obj); + __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; + } + __pyx_L2:; + __Pyx_XDECREF(__pyx_v_item_count); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":129 + * info.obj = self + * + * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< + * PyObject_Free(info.shape) + * +*/ + +/* Python wrapper */ +CYTHON_UNUSED static void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ +CYTHON_UNUSED static void __pyx_pw_7cpython_5array_5array_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_7cpython_5array_5array_2__releasebuffer__(((arrayobject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_7cpython_5array_5array_2__releasebuffer__(CYTHON_UNUSED arrayobject *__pyx_v_self, Py_buffer *__pyx_v_info) { + + /* "array.pxd":130 + * + * def __releasebuffer__(self, Py_buffer* info): + * PyObject_Free(info.shape) # <<<<<<<<<<<<<< + * + * array newarrayobject(PyTypeObject* type, Py_ssize_t size, arraydescr *descr) +*/ + PyObject_Free(__pyx_v_info->shape); + + /* "array.pxd":129 + * info.obj = self + * + * def __releasebuffer__(self, Py_buffer* info): # <<<<<<<<<<<<<< + * PyObject_Free(info.shape) + * +*/ + + /* function exit code */ +} + +/* "array.pxd":141 + * + * + * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< + * """ fast creation of a new array, given a template array. + * type will be same as template. +*/ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_clone(arrayobject *__pyx_v_template, Py_ssize_t __pyx_v_length, int __pyx_v_zero) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("clone", 0); + + /* "array.pxd":145 + * type will be same as template. + * if zero is true, new array will be initialized with zeroes.""" + * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) # <<<<<<<<<<<<<< + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) +*/ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_template)), __pyx_v_length, __pyx_v_template->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 145, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":146 + * if zero is true, new array will be initialized with zeroes.""" + * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: # <<<<<<<<<<<<<< + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op +*/ + if (__pyx_v_zero) { + } else { + __pyx_t_2 = __pyx_v_zero; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = (((PyObject *)__pyx_v_op) != Py_None); + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "array.pxd":147 + * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * +*/ + (void)(memset(__pyx_v_op->data.as_chars, 0, (__pyx_v_length * __pyx_v_op->ob_descr->itemsize))); + + /* "array.pxd":146 + * if zero is true, new array will be initialized with zeroes.""" + * cdef array op = newarrayobject(Py_TYPE(template), length, template.ob_descr) + * if zero and op is not None: # <<<<<<<<<<<<<< + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op +*/ + } + + /* "array.pxd":148 + * if zero and op is not None: + * memset(op.data.as_chars, 0, length * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline array copy(array self): +*/ + __Pyx_XDECREF((PyObject *)__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_op); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + /* "array.pxd":141 + * + * + * cdef inline array clone(array template, Py_ssize_t length, bint zero): # <<<<<<<<<<<<<< + * """ fast creation of a new array, given a template array. + * type will be same as template. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.clone", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":150 + * return op + * + * cdef inline array copy(array self): # <<<<<<<<<<<<<< + * """ make a copy of an array. """ + * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) +*/ + +static CYTHON_INLINE arrayobject *__pyx_f_7cpython_5array_copy(arrayobject *__pyx_v_self) { + arrayobject *__pyx_v_op = 0; + arrayobject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("copy", 0); + + /* "array.pxd":152 + * cdef inline array copy(array self): + * """ make a copy of an array. """ + * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) # <<<<<<<<<<<<<< + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op +*/ + __pyx_t_1 = ((PyObject *)newarrayobject(Py_TYPE(((PyObject *)__pyx_v_self)), Py_SIZE(((PyObject *)__pyx_v_self)), __pyx_v_self->ob_descr)); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_op = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "array.pxd":153 + * """ make a copy of an array. """ + * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) # <<<<<<<<<<<<<< + * return op + * +*/ + (void)(memcpy(__pyx_v_op->data.as_chars, __pyx_v_self->data.as_chars, (Py_SIZE(((PyObject *)__pyx_v_op)) * __pyx_v_op->ob_descr->itemsize))); + + /* "array.pxd":154 + * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) + * memcpy(op.data.as_chars, self.data.as_chars, Py_SIZE(op) * op.ob_descr.itemsize) + * return op # <<<<<<<<<<<<<< + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: +*/ + __Pyx_XDECREF((PyObject *)__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_op); + __pyx_r = __pyx_v_op; + goto __pyx_L0; + + /* "array.pxd":150 + * return op + * + * cdef inline array copy(array self): # <<<<<<<<<<<<<< + * """ make a copy of an array. """ + * cdef array op = newarrayobject(Py_TYPE(self), Py_SIZE(self), self.ob_descr) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("cpython.array.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_op); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "array.pxd":156 + * return op + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< + * """ efficient appending of new stuff of same type + * (e.g. of same array type) +*/ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend_buffer(arrayobject *__pyx_v_self, char *__pyx_v_stuff, Py_ssize_t __pyx_v_n) { + Py_ssize_t __pyx_v_itemsize; + Py_ssize_t __pyx_v_origsize; + int __pyx_r; + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "array.pxd":160 + * (e.g. of same array type) + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize # <<<<<<<<<<<<<< + * cdef Py_ssize_t origsize = Py_SIZE(self) + * resize_smart(self, origsize + n) +*/ + __pyx_t_1 = __pyx_v_self->ob_descr->itemsize; + __pyx_v_itemsize = __pyx_t_1; + + /* "array.pxd":161 + * n: number of elements (not number of bytes!) """ + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t origsize = Py_SIZE(self) # <<<<<<<<<<<<<< + * resize_smart(self, origsize + n) + * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) +*/ + __pyx_v_origsize = Py_SIZE(((PyObject *)__pyx_v_self)); + + /* "array.pxd":162 + * cdef Py_ssize_t itemsize = self.ob_descr.itemsize + * cdef Py_ssize_t origsize = Py_SIZE(self) + * resize_smart(self, origsize + n) # <<<<<<<<<<<<<< + * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) + * return 0 +*/ + __pyx_t_1 = resize_smart(__pyx_v_self, (__pyx_v_origsize + __pyx_v_n)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(2, 162, __pyx_L1_error) + + /* "array.pxd":163 + * cdef Py_ssize_t origsize = Py_SIZE(self) + * resize_smart(self, origsize + n) + * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) # <<<<<<<<<<<<<< + * return 0 + * +*/ + (void)(memcpy((__pyx_v_self->data.as_chars + (__pyx_v_origsize * __pyx_v_itemsize)), __pyx_v_stuff, (__pyx_v_n * __pyx_v_itemsize))); + + /* "array.pxd":164 + * resize_smart(self, origsize + n) + * memcpy(self.data.as_chars + origsize * itemsize, stuff, n * itemsize) + * return 0 # <<<<<<<<<<<<<< + * + * cdef inline int extend(array self, array other) except -1: +*/ + __pyx_r = 0; + goto __pyx_L0; + + /* "array.pxd":156 + * return op + * + * cdef inline int extend_buffer(array self, char* stuff, Py_ssize_t n) except -1: # <<<<<<<<<<<<<< + * """ efficient appending of new stuff of same type + * (e.g. of same array type) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend_buffer", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "array.pxd":166 + * return 0 + * + * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: +*/ + +static CYTHON_INLINE int __pyx_f_7cpython_5array_extend(arrayobject *__pyx_v_self, arrayobject *__pyx_v_other) { + int __pyx_r; + int __pyx_t_1; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + + /* "array.pxd":168 + * cdef inline int extend(array self, array other) except -1: + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) +*/ + __pyx_t_1 = (__pyx_v_self->ob_descr->typecode != __pyx_v_other->ob_descr->typecode); + if (__pyx_t_1) { + + /* "array.pxd":169 + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() # <<<<<<<<<<<<<< + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * +*/ + __pyx_t_2 = PyErr_BadArgument(); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(2, 169, __pyx_L1_error) + + /* "array.pxd":168 + * cdef inline int extend(array self, array other) except -1: + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: # <<<<<<<<<<<<<< + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) +*/ + } + + /* "array.pxd":170 + * if self.ob_descr.typecode != other.ob_descr.typecode: + * PyErr_BadArgument() + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) # <<<<<<<<<<<<<< + * + * cdef inline void zero(array self) noexcept: +*/ + __pyx_t_2 = __pyx_f_7cpython_5array_extend_buffer(__pyx_v_self, __pyx_v_other->data.as_chars, Py_SIZE(((PyObject *)__pyx_v_other))); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(2, 170, __pyx_L1_error) + __pyx_r = __pyx_t_2; + goto __pyx_L0; + + /* "array.pxd":166 + * return 0 + * + * cdef inline int extend(array self, array other) except -1: # <<<<<<<<<<<<<< + * """ extend array with data from another array; types must match. """ + * if self.ob_descr.typecode != other.ob_descr.typecode: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_AddTraceback("cpython.array.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + return __pyx_r; +} + +/* "array.pxd":172 + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + * cdef inline void zero(array self) noexcept: # <<<<<<<<<<<<<< + * """ set all elements of array to zero. """ + * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) +*/ + +static CYTHON_INLINE void __pyx_f_7cpython_5array_zero(arrayobject *__pyx_v_self) { + + /* "array.pxd":174 + * cdef inline void zero(array self) noexcept: + * """ set all elements of array to zero. """ + * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) # <<<<<<<<<<<<<< +*/ + (void)(memset(__pyx_v_self->data.as_chars, 0, (Py_SIZE(((PyObject *)__pyx_v_self)) * __pyx_v_self->ob_descr->itemsize))); + + /* "array.pxd":172 + * return extend_buffer(self, other.data.as_chars, Py_SIZE(other)) + * + * cdef inline void zero(array self) noexcept: # <<<<<<<<<<<<<< + * """ set all elements of array to zero. """ + * memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize) +*/ + + /* function exit code */ +} + +/* "pysam/libcalignmentfile.pyx":142 + * + * + * def build_header_line(fields, record): # <<<<<<<<<<<<<< + * '''build a header line from `fields` dictionary for `record`''' + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_1build_header_line(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_build_header_line, "build_header_line(fields, record)\n\nbuild a header line from `fields` dictionary for `record`"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_1build_header_line = {"build_header_line", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_1build_header_line, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_build_header_line}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_1build_header_line(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_fields = 0; + PyObject *__pyx_v_record = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build_header_line (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_fields,&__pyx_mstate_global->__pyx_n_u_record,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 142, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 142, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 142, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "build_header_line", 0) < 0) __PYX_ERR(0, 142, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("build_header_line", 1, 2, 2, i); __PYX_ERR(0, 142, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 2)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 142, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 142, __pyx_L3_error) + } + __pyx_v_fields = values[0]; + __pyx_v_record = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("build_header_line", 1, 2, 2, __pyx_nargs); __PYX_ERR(0, 142, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.build_header_line", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_build_header_line(__pyx_self, __pyx_v_fields, __pyx_v_record); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_build_header_line(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_fields, PyObject *__pyx_v_record) { + PyObject *__pyx_v_line = NULL; + PyObject *__pyx_v_key = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + size_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9[3]; + PyObject *(*__pyx_t_10)(PyObject *); + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])) + __Pyx_RefNannySetupContext("build_header_line", 0); + __Pyx_TraceStartFunc("build_header_line", __pyx_f[0], 142, 0, 0, 0, __PYX_ERR(0, 142, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":146 + * + * # TODO: add checking for field and sort order + * line = ["@%s" % record] # <<<<<<<<<<<<<< + * # comment + * if record == "CO": +*/ + __pyx_t_1 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_s, __pyx_v_record); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyList_SET_ITEM(__pyx_t_2, 0, __pyx_t_1) != (0)) __PYX_ERR(0, 146, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_v_line = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":148 + * line = ["@%s" % record] + * # comment + * if record == "CO": # <<<<<<<<<<<<<< + * line.append(fields) + * # user tags +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_record, __pyx_mstate_global->__pyx_n_u_CO, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 148, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":149 + * # comment + * if record == "CO": + * line.append(fields) # <<<<<<<<<<<<<< + * # user tags + * elif record.islower(): +*/ + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_line, __pyx_v_fields); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 149, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":148 + * line = ["@%s" % record] + * # comment + * if record == "CO": # <<<<<<<<<<<<<< + * line.append(fields) + * # user tags +*/ + goto __pyx_L3; + } + + /* "pysam/libcalignmentfile.pyx":151 + * line.append(fields) + * # user tags + * elif record.islower(): # <<<<<<<<<<<<<< + * for key in sorted(fields): + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + __pyx_t_1 = __pyx_v_record; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_islower, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 151, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":152 + * # user tags + * elif record.islower(): + * for key in sorted(fields): # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * # defined tags +*/ + __pyx_t_2 = PySequence_List(__pyx_v_fields); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((PyList_Sort(__pyx_t_2) < 0))) __PYX_ERR(0, 152, __pyx_L1_error) + __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 152, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_2 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_6); + ++__pyx_t_6; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":153 + * elif record.islower(): + * for key in sorted(fields): + * line.append("%s:%s" % (key, str(fields[key]))) # <<<<<<<<<<<<<< + * # defined tags + * else: +*/ + __pyx_t_2 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_key), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_v_fields, __pyx_v_key); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_Unicode(__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_9[0] = __pyx_t_2; + __pyx_t_9[1] = __pyx_mstate_global->__pyx_kp_u_; + __pyx_t_9[2] = __pyx_t_8; + __pyx_t_7 = __Pyx_PyUnicode_Join(__pyx_t_9, 3, __Pyx_PyUnicode_GET_LENGTH(__pyx_t_2) + 1 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_8), 127 | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_2) | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_8)); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_line, __pyx_t_7); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 153, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":152 + * # user tags + * elif record.islower(): + * for key in sorted(fields): # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * # defined tags +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":151 + * line.append(fields) + * # user tags + * elif record.islower(): # <<<<<<<<<<<<<< + * for key in sorted(fields): + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + goto __pyx_L3; + } + + /* "pysam/libcalignmentfile.pyx":157 + * else: + * # write fields of the specification + * for key in VALID_HEADER_ORDER[record]: # <<<<<<<<<<<<<< + * if key in fields: + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + /*else*/ { + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_ORDER); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 157, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_record); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 157, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (likely(PyList_CheckExact(__pyx_t_7)) || PyTuple_CheckExact(__pyx_t_7)) { + __pyx_t_1 = __pyx_t_7; __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 157, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 157, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 157, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_7 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 157, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_6)); + #else + __pyx_t_7 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 157, __pyx_L1_error) + } else { + __pyx_t_7 = __pyx_t_10(__pyx_t_1); + if (unlikely(!__pyx_t_7)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 157, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_7); + __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_7); + __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":158 + * # write fields of the specification + * for key in VALID_HEADER_ORDER[record]: + * if key in fields: # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * # write user fields +*/ + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(__pyx_v_key, __pyx_v_fields, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 158, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":159 + * for key in VALID_HEADER_ORDER[record]: + * if key in fields: + * line.append("%s:%s" % (key, str(fields[key]))) # <<<<<<<<<<<<<< + * # write user fields + * for key in fields: +*/ + __pyx_t_7 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_key), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_v_fields, __pyx_v_key); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_2 = __Pyx_PyObject_Unicode(__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_9[0] = __pyx_t_7; + __pyx_t_9[1] = __pyx_mstate_global->__pyx_kp_u_; + __pyx_t_9[2] = __pyx_t_2; + __pyx_t_8 = __Pyx_PyUnicode_Join(__pyx_t_9, 3, __Pyx_PyUnicode_GET_LENGTH(__pyx_t_7) + 1 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_2), 127 | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_7) | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_2)); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_line, __pyx_t_8); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 159, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "pysam/libcalignmentfile.pyx":158 + * # write fields of the specification + * for key in VALID_HEADER_ORDER[record]: + * if key in fields: # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * # write user fields +*/ + } + + /* "pysam/libcalignmentfile.pyx":157 + * else: + * # write fields of the specification + * for key in VALID_HEADER_ORDER[record]: # <<<<<<<<<<<<<< + * if key in fields: + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":161 + * line.append("%s:%s" % (key, str(fields[key]))) + * # write user fields + * for key in fields: # <<<<<<<<<<<<<< + * if not key.isupper(): + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + if (likely(PyList_CheckExact(__pyx_v_fields)) || PyTuple_CheckExact(__pyx_v_fields)) { + __pyx_t_1 = __pyx_v_fields; __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_fields); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 161, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 161, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_8 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_6)); + #else + __pyx_t_8 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 161, __pyx_L1_error) + } else { + __pyx_t_8 = __pyx_t_10(__pyx_t_1); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 161, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_8); + __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_8); + __pyx_t_8 = 0; + + /* "pysam/libcalignmentfile.pyx":162 + * # write user fields + * for key in fields: + * if not key.isupper(): # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * +*/ + __pyx_t_2 = __pyx_v_key; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_isupper, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 162, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 162, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_11 = (!__pyx_t_3); + if (__pyx_t_11) { + + /* "pysam/libcalignmentfile.pyx":163 + * for key in fields: + * if not key.isupper(): + * line.append("%s:%s" % (key, str(fields[key]))) # <<<<<<<<<<<<<< + * + * return "\t".join(line) +*/ + __pyx_t_8 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_key), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_fields, __pyx_v_key); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_Unicode(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9[0] = __pyx_t_8; + __pyx_t_9[1] = __pyx_mstate_global->__pyx_kp_u_; + __pyx_t_9[2] = __pyx_t_7; + __pyx_t_2 = __Pyx_PyUnicode_Join(__pyx_t_9, 3, __Pyx_PyUnicode_GET_LENGTH(__pyx_t_8) + 1 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_7), 127 | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_8) | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_7)); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_line, __pyx_t_2); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 163, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":162 + * # write user fields + * for key in fields: + * if not key.isupper(): # <<<<<<<<<<<<<< + * line.append("%s:%s" % (key, str(fields[key]))) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":161 + * line.append("%s:%s" % (key, str(fields[key]))) + * # write user fields + * for key in fields: # <<<<<<<<<<<<<< + * if not key.isupper(): + * line.append("%s:%s" % (key, str(fields[key]))) +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + __pyx_L3:; + + /* "pysam/libcalignmentfile.pyx":165 + * line.append("%s:%s" % (key, str(fields[key]))) + * + * return "\t".join(line) # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__2, __pyx_v_line); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 165, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 69, 0, __PYX_ERR(0, 165, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":142 + * + * + * def build_header_line(fields, record): # <<<<<<<<<<<<<< + * '''build a header line from `fields` dictionary for `record`''' + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 142, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.build_header_line", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_line); + __Pyx_XDECREF(__pyx_v_key); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":168 + * + * + * cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr): # <<<<<<<<<<<<<< + * if not hdr: + * raise ValueError('cannot create AlignmentHeader, received NULL pointer') +*/ + +static struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(bam_hdr_t *__pyx_v_hdr) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_header = 0; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[1])) + __Pyx_RefNannySetupContext("makeAlignmentHeader", 0); + __Pyx_TraceStartFunc("makeAlignmentHeader", __pyx_f[0], 168, 0, 0, 0, __PYX_ERR(0, 168, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":169 + * + * cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr): + * if not hdr: # <<<<<<<<<<<<<< + * raise ValueError('cannot create AlignmentHeader, received NULL pointer') + * +*/ + __pyx_t_1 = (!(__pyx_v_hdr != 0)); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":170 + * cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr): + * if not hdr: + * raise ValueError('cannot create AlignmentHeader, received NULL pointer') # <<<<<<<<<<<<<< + * + * # check: is AlignmetHeader.__cinit__ called? +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_cannot_create_AlignmentHeader_re}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 170, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 170, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":169 + * + * cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr): + * if not hdr: # <<<<<<<<<<<<<< + * raise ValueError('cannot create AlignmentHeader, received NULL pointer') + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":173 + * + * # check: is AlignmetHeader.__cinit__ called? + * cdef AlignmentHeader header = AlignmentHeader.__new__(AlignmentHeader) # <<<<<<<<<<<<<< + * header.ptr = hdr + * +*/ + __pyx_t_2 = ((PyObject *)__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentHeader(((PyTypeObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader), __pyx_mstate_global->__pyx_empty_tuple, NULL)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 173, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_2); + __pyx_v_header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":174 + * # check: is AlignmetHeader.__cinit__ called? + * cdef AlignmentHeader header = AlignmentHeader.__new__(AlignmentHeader) + * header.ptr = hdr # <<<<<<<<<<<<<< + * + * return header +*/ + __pyx_v_header->ptr = __pyx_v_hdr; + + /* "pysam/libcalignmentfile.pyx":176 + * header.ptr = hdr + * + * return header # <<<<<<<<<<<<<< + * + * def read_failure_reason(code): +*/ + __Pyx_XDECREF((PyObject *)__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_header); + __pyx_r = __pyx_v_header; + __Pyx_TraceReturnValue((PyObject *)__pyx_r, 16, 0, __PYX_ERR(0, 176, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":168 + * + * + * cdef AlignmentHeader makeAlignmentHeader(bam_hdr_t *hdr): # <<<<<<<<<<<<<< + * if not hdr: + * raise ValueError('cannot create AlignmentHeader, received NULL pointer') +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 168, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.makeAlignmentHeader", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_header); + __Pyx_XGIVEREF((PyObject *)__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":178 + * return header + * + * def read_failure_reason(code): # <<<<<<<<<<<<<< + * if code == -2: + * return 'truncated file' +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_3read_failure_reason(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_2read_failure_reason, "read_failure_reason(code)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_3read_failure_reason = {"read_failure_reason", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_3read_failure_reason, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_2read_failure_reason}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_3read_failure_reason(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_code = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("read_failure_reason (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_code,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 178, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 178, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "read_failure_reason", 0) < 0) __PYX_ERR(0, 178, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("read_failure_reason", 1, 1, 1, i); __PYX_ERR(0, 178, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 178, __pyx_L3_error) + } + __pyx_v_code = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("read_failure_reason", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 178, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.read_failure_reason", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_2read_failure_reason(__pyx_self, __pyx_v_code); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_2read_failure_reason(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_code) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])) + __Pyx_RefNannySetupContext("read_failure_reason", 0); + __Pyx_TraceStartFunc("read_failure_reason", __pyx_f[0], 178, 0, 0, 0, __PYX_ERR(0, 178, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":179 + * + * def read_failure_reason(code): + * if code == -2: # <<<<<<<<<<<<<< + * return 'truncated file' + * else: +*/ + __pyx_t_1 = (__Pyx_PyLong_BoolEqObjC(__pyx_v_code, __pyx_mstate_global->__pyx_int_neg_2, -2L, 0)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 179, __pyx_L1_error) + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":180 + * def read_failure_reason(code): + * if code == -2: + * return 'truncated file' # <<<<<<<<<<<<<< + * else: + * return "error {} while reading file".format(code) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_mstate_global->__pyx_kp_u_truncated_file); + __pyx_r = __pyx_mstate_global->__pyx_kp_u_truncated_file; + __Pyx_TraceReturnValue(__pyx_r, 5, 0, __PYX_ERR(0, 180, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":179 + * + * def read_failure_reason(code): + * if code == -2: # <<<<<<<<<<<<<< + * return 'truncated file' + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":182 + * return 'truncated file' + * else: + * return "error {} while reading file".format(code) # <<<<<<<<<<<<<< + * + * +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __pyx_mstate_global->__pyx_kp_u_error_while_reading_file; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v_code}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 182, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 7, 0, __PYX_ERR(0, 182, __pyx_L1_error)); + goto __pyx_L0; + } + + /* "pysam/libcalignmentfile.pyx":178 + * return header + * + * def read_failure_reason(code): # <<<<<<<<<<<<<< + * if code == -2: + * return 'truncated file' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 178, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.read_failure_reason", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":187 + * # the following should be class-method for VariantHeader, but cdef @classmethods + * # are not implemented in cython. + * cdef int fill_AlignmentHeader_from_list(bam_hdr_t *dest, # <<<<<<<<<<<<<< + * reference_names, + * reference_lengths, +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_fill_AlignmentHeader_from_list(CYTHON_UNUSED bam_hdr_t *__pyx_v_dest, CYTHON_UNUSED PyObject *__pyx_v_reference_names, CYTHON_UNUSED PyObject *__pyx_v_reference_lengths, struct __pyx_opt_args_5pysam_17libcalignmentfile_fill_AlignmentHeader_from_list *__pyx_optional_args) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[3])) + __Pyx_TraceStartFunc("fill_AlignmentHeader_from_list", __pyx_f[0], 187, 0, 0, 0, __PYX_ERR(0, 187, __pyx_L1_error)); + if (__pyx_optional_args) { + } + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 0, 0, __PYX_ERR(0, 187, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 187, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.fill_AlignmentHeader_from_list", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":228 + * + * # See makeVariantHeader for C constructor + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.ptr = NULL + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, __pyx_nargs); return -1; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return -1; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__cinit__", __pyx_kwds); return -1;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[4])) + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 228, 0, 0, 0, __PYX_ERR(0, 228, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":229 + * # See makeVariantHeader for C constructor + * def __cinit__(self): + * self.ptr = NULL # <<<<<<<<<<<<<< + * + * # Python constructor +*/ + __pyx_v_self->ptr = NULL; + + /* "pysam/libcalignmentfile.pyx":228 + * + * # See makeVariantHeader for C constructor + * def __cinit__(self): # <<<<<<<<<<<<<< + * self.ptr = NULL + * +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 228, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 228, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":232 + * + * # Python constructor + * def __init__(self): # <<<<<<<<<<<<<< + * self.ptr = bam_hdr_init() + * if self.ptr is NULL: +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_3__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__init__", 1, 0, 0, __pyx_nargs); return -1; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return -1; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__init__", __pyx_kwds); return -1;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_2__init__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_2__init__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[5])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 232, 0, 0, 0, __PYX_ERR(0, 232, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":233 + * # Python constructor + * def __init__(self): + * self.ptr = bam_hdr_init() # <<<<<<<<<<<<<< + * if self.ptr is NULL: + * raise MemoryError("could not create header") +*/ + __pyx_v_self->ptr = bam_hdr_init(); + + /* "pysam/libcalignmentfile.pyx":234 + * def __init__(self): + * self.ptr = bam_hdr_init() + * if self.ptr is NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not create header") + * +*/ + __pyx_t_1 = (__pyx_v_self->ptr == NULL); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":235 + * self.ptr = bam_hdr_init() + * if self.ptr is NULL: + * raise MemoryError("could not create header") # <<<<<<<<<<<<<< + * + * @classmethod +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_4 = __pyx_builtin_MemoryError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_could_not_create_header}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 235, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 235, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":234 + * def __init__(self): + * self.ptr = bam_hdr_init() + * if self.ptr is NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not create header") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":232 + * + * # Python constructor + * def __init__(self): # <<<<<<<<<<<<<< + * self.ptr = bam_hdr_init() + * if self.ptr is NULL: +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 232, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 232, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":237 + * raise MemoryError("could not create header") + * + * @classmethod # <<<<<<<<<<<<<< + * def _from_text_and_lengths(cls, text, reference_names, reference_lengths): + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths, "AlignmentHeader._from_text_and_lengths(cls, text, reference_names, reference_lengths)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths = {"_from_text_and_lengths", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_text = 0; + PyObject *__pyx_v_reference_names = 0; + PyObject *__pyx_v_reference_lengths = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_from_text_and_lengths (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_text,&__pyx_mstate_global->__pyx_n_u_reference_names,&__pyx_mstate_global->__pyx_n_u_reference_lengths,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 237, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 237, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 237, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 237, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_from_text_and_lengths", 0) < 0) __PYX_ERR(0, 237, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_from_text_and_lengths", 1, 3, 3, i); __PYX_ERR(0, 237, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 237, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 237, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 237, __pyx_L3_error) + } + __pyx_v_text = values[0]; + __pyx_v_reference_names = values[1]; + __pyx_v_reference_lengths = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_from_text_and_lengths", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 237, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader._from_text_and_lengths", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths(((PyTypeObject*)__pyx_v_cls), __pyx_v_text, __pyx_v_reference_names, __pyx_v_reference_lengths); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths(CYTHON_UNUSED PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_text, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self = 0; + char *__pyx_v_ctext; + int __pyx_v_l_text; + int __pyx_v_n; + int __pyx_v_x; + PyObject *__pyx_v_btext = NULL; + PyObject *__pyx_v_name = NULL; + PyObject *__pyx_7genexpr__pyx_v_ref = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_t_5; + char *__pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + PyObject *(*__pyx_t_12)(PyObject *); + int __pyx_t_13; + PyObject *__pyx_t_14 = NULL; + int32_t __pyx_t_15; + uint32_t __pyx_t_16; + char const *__pyx_t_17; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])) + __Pyx_RefNannySetupContext("_from_text_and_lengths", 0); + __Pyx_TraceStartFunc("_from_text_and_lengths", __pyx_f[0], 237, 0, 0, 0, __PYX_ERR(0, 237, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_reference_names); + + /* "pysam/libcalignmentfile.pyx":240 + * def _from_text_and_lengths(cls, text, reference_names, reference_lengths): + * + * cdef AlignmentHeader self = AlignmentHeader() # <<<<<<<<<<<<<< + * cdef char *ctext + * cdef int l_text +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 240, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_v_self = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":244 + * cdef int l_text + * cdef int n, x + * if text is not None: # <<<<<<<<<<<<<< + * btext = force_bytes(text) + * ctext = btext +*/ + __pyx_t_5 = (__pyx_v_text != Py_None); + if (__pyx_t_5) { + + /* "pysam/libcalignmentfile.pyx":245 + * cdef int n, x + * if text is not None: + * btext = force_bytes(text) # <<<<<<<<<<<<<< + * ctext = btext + * l_text = len(btext) +*/ + __pyx_t_1 = __pyx_f_5pysam_9libcutils_force_bytes(__pyx_v_text, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 245, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_btext = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":246 + * if text is not None: + * btext = force_bytes(text) + * ctext = btext # <<<<<<<<<<<<<< + * l_text = len(btext) + * self.ptr.text = calloc(l_text + 1, sizeof(char)) +*/ + if (unlikely(__pyx_v_btext == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 246, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_PyBytes_AsWritableString(__pyx_v_btext); if (unlikely((!__pyx_t_6) && PyErr_Occurred())) __PYX_ERR(0, 246, __pyx_L1_error) + __pyx_v_ctext = __pyx_t_6; + + /* "pysam/libcalignmentfile.pyx":247 + * btext = force_bytes(text) + * ctext = btext + * l_text = len(btext) # <<<<<<<<<<<<<< + * self.ptr.text = calloc(l_text + 1, sizeof(char)) + * if self.ptr.text == NULL: +*/ + if (unlikely(__pyx_v_btext == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(0, 247, __pyx_L1_error) + } + __pyx_t_7 = __Pyx_PyBytes_GET_SIZE(__pyx_v_btext); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 247, __pyx_L1_error) + __pyx_v_l_text = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":248 + * ctext = btext + * l_text = len(btext) + * self.ptr.text = calloc(l_text + 1, sizeof(char)) # <<<<<<<<<<<<<< + * if self.ptr.text == NULL: + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) +*/ + __pyx_v_self->ptr->text = ((char *)calloc((__pyx_v_l_text + 1), (sizeof(char)))); + + /* "pysam/libcalignmentfile.pyx":249 + * l_text = len(btext) + * self.ptr.text = calloc(l_text + 1, sizeof(char)) + * if self.ptr.text == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) + * self.ptr.l_text = l_text +*/ + __pyx_t_5 = (__pyx_v_self->ptr->text == NULL); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":250 + * self.ptr.text = calloc(l_text + 1, sizeof(char)) + * if self.ptr.text == NULL: + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) # <<<<<<<<<<<<<< + * self.ptr.l_text = l_text + * memcpy(self.ptr.text, ctext, l_text + 1) +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_2 = __pyx_builtin_MemoryError; + __pyx_t_9 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_bytes; + __Pyx_INCREF(__pyx_t_9); + __pyx_t_10 = __Pyx_PyLong_From_long((__pyx_v_l_text + 1)); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, __pyx_t_10}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __pyx_t_10 = __Pyx_PyLong_FromSize_t((sizeof(char))); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_3, __pyx_t_8, __pyx_t_10}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_4, (3-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 250, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":249 + * l_text = len(btext) + * self.ptr.text = calloc(l_text + 1, sizeof(char)) + * if self.ptr.text == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) + * self.ptr.l_text = l_text +*/ + } + + /* "pysam/libcalignmentfile.pyx":251 + * if self.ptr.text == NULL: + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) + * self.ptr.l_text = l_text # <<<<<<<<<<<<<< + * memcpy(self.ptr.text, ctext, l_text + 1) + * +*/ + __pyx_v_self->ptr->l_text = __pyx_v_l_text; + + /* "pysam/libcalignmentfile.pyx":252 + * raise MemoryError("could not allocate {} bytes".format(l_text + 1), sizeof(char)) + * self.ptr.l_text = l_text + * memcpy(self.ptr.text, ctext, l_text + 1) # <<<<<<<<<<<<<< + * + * if reference_names and reference_lengths: +*/ + (void)(memcpy(__pyx_v_self->ptr->text, __pyx_v_ctext, (__pyx_v_l_text + 1))); + + /* "pysam/libcalignmentfile.pyx":244 + * cdef int l_text + * cdef int n, x + * if text is not None: # <<<<<<<<<<<<<< + * btext = force_bytes(text) + * ctext = btext +*/ + } + + /* "pysam/libcalignmentfile.pyx":254 + * memcpy(self.ptr.text, ctext, l_text + 1) + * + * if reference_names and reference_lengths: # <<<<<<<<<<<<<< + * reference_names = [force_bytes(ref) for ref in reference_names] + * +*/ + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_v_reference_names); if (unlikely((__pyx_t_11 < 0))) __PYX_ERR(0, 254, __pyx_L1_error) + if (__pyx_t_11) { + } else { + __pyx_t_5 = __pyx_t_11; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_v_reference_lengths); if (unlikely((__pyx_t_11 < 0))) __PYX_ERR(0, 254, __pyx_L1_error) + __pyx_t_5 = __pyx_t_11; + __pyx_L6_bool_binop_done:; + if (__pyx_t_5) { + + /* "pysam/libcalignmentfile.pyx":255 + * + * if reference_names and reference_lengths: + * reference_names = [force_bytes(ref) for ref in reference_names] # <<<<<<<<<<<<<< + * + * self.ptr.n_targets = len(reference_names) +*/ + { /* enter inner scope */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 255, __pyx_L10_error) + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyList_CheckExact(__pyx_v_reference_names)) || PyTuple_CheckExact(__pyx_v_reference_names)) { + __pyx_t_2 = __pyx_v_reference_names; __Pyx_INCREF(__pyx_t_2); + __pyx_t_7 = 0; + __pyx_t_12 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_reference_names); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 255, __pyx_L10_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_12 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 255, __pyx_L10_error) + } + for (;;) { + if (likely(!__pyx_t_12)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 255, __pyx_L10_error) + #endif + if (__pyx_t_7 >= __pyx_temp) break; + } + __pyx_t_10 = __Pyx_PyList_GetItemRef(__pyx_t_2, __pyx_t_7); + ++__pyx_t_7; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 255, __pyx_L10_error) + #endif + if (__pyx_t_7 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_10 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_7)); + #else + __pyx_t_10 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_7); + #endif + ++__pyx_t_7; + } + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 255, __pyx_L10_error) + } else { + __pyx_t_10 = __pyx_t_12(__pyx_t_2); + if (unlikely(!__pyx_t_10)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 255, __pyx_L10_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_10); + __Pyx_XDECREF_SET(__pyx_7genexpr__pyx_v_ref, __pyx_t_10); + __pyx_t_10 = 0; + __pyx_t_10 = __pyx_f_5pysam_9libcutils_force_bytes(__pyx_7genexpr__pyx_v_ref, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 255, __pyx_L10_error) + __Pyx_GOTREF(__pyx_t_10); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_10))) __PYX_ERR(0, 255, __pyx_L10_error) + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_ref); __pyx_7genexpr__pyx_v_ref = 0; + goto __pyx_L14_exit_scope; + __pyx_L10_error:; + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_ref); __pyx_7genexpr__pyx_v_ref = 0; + goto __pyx_L1_error; + __pyx_L14_exit_scope:; + } /* exit inner scope */ + __Pyx_DECREF_SET(__pyx_v_reference_names, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":257 + * reference_names = [force_bytes(ref) for ref in reference_names] + * + * self.ptr.n_targets = len(reference_names) # <<<<<<<<<<<<<< + * + * n = sum([len(reference_names) + 1]) +*/ + __pyx_t_7 = PyObject_Length(__pyx_v_reference_names); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 257, __pyx_L1_error) + __pyx_v_self->ptr->n_targets = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":259 + * self.ptr.n_targets = len(reference_names) + * + * n = sum([len(reference_names) + 1]) # <<<<<<<<<<<<<< + * self.ptr.target_name = calloc(n, sizeof(char*)) + * if self.ptr.target_name == NULL: +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_sum); + __pyx_t_10 = __pyx_builtin_sum; + __pyx_t_7 = PyObject_Length(__pyx_v_reference_names); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 259, __pyx_L1_error) + __pyx_t_8 = PyLong_FromSsize_t((__pyx_t_7 + 1)); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 259, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_8); + if (__Pyx_PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_8) != (0)) __PYX_ERR(0, 259, __pyx_L1_error); + __pyx_t_8 = 0; + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_10, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 259, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_13 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 259, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_n = __pyx_t_13; + + /* "pysam/libcalignmentfile.pyx":260 + * + * n = sum([len(reference_names) + 1]) + * self.ptr.target_name = calloc(n, sizeof(char*)) # <<<<<<<<<<<<<< + * if self.ptr.target_name == NULL: + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *))) +*/ + __pyx_v_self->ptr->target_name = ((char **)calloc(__pyx_v_n, (sizeof(char *)))); + + /* "pysam/libcalignmentfile.pyx":261 + * n = sum([len(reference_names) + 1]) + * self.ptr.target_name = calloc(n, sizeof(char*)) + * if self.ptr.target_name == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *))) + * +*/ + __pyx_t_5 = (__pyx_v_self->ptr->target_name == NULL); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":262 + * self.ptr.target_name = calloc(n, sizeof(char*)) + * if self.ptr.target_name == NULL: + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *))) # <<<<<<<<<<<<<< + * + * self.ptr.target_len = calloc(n, sizeof(uint32_t)) +*/ + __pyx_t_10 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_3 = __pyx_builtin_MemoryError; + __pyx_t_8 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_bytes; + __Pyx_INCREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_n); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 262, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_14 = __Pyx_PyLong_FromSize_t((sizeof(char *))); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 262, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_t_9, __pyx_t_14}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_4, (3-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 262, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, __pyx_t_2}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 262, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 262, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":261 + * n = sum([len(reference_names) + 1]) + * self.ptr.target_name = calloc(n, sizeof(char*)) + * if self.ptr.target_name == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *))) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":264 + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(char *))) + * + * self.ptr.target_len = calloc(n, sizeof(uint32_t)) # <<<<<<<<<<<<<< + * if self.ptr.target_len == NULL: + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t))) +*/ + __pyx_v_self->ptr->target_len = ((uint32_t *)calloc(__pyx_v_n, (sizeof(uint32_t)))); + + /* "pysam/libcalignmentfile.pyx":265 + * + * self.ptr.target_len = calloc(n, sizeof(uint32_t)) + * if self.ptr.target_len == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t))) + * +*/ + __pyx_t_5 = (__pyx_v_self->ptr->target_len == NULL); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":266 + * self.ptr.target_len = calloc(n, sizeof(uint32_t)) + * if self.ptr.target_len == NULL: + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t))) # <<<<<<<<<<<<<< + * + * for x from 0 <= x < self.ptr.n_targets: +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_2 = __pyx_builtin_MemoryError; + __pyx_t_14 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_bytes; + __Pyx_INCREF(__pyx_t_14); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_n); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 266, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_8 = __Pyx_PyLong_FromSize_t((sizeof(uint32_t))); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 266, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_14, __pyx_t_9, __pyx_t_8}; + __pyx_t_10 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_4, (3-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 266, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + } + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_10}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 266, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 266, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":265 + * + * self.ptr.target_len = calloc(n, sizeof(uint32_t)) + * if self.ptr.target_len == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t))) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":268 + * raise MemoryError("could not allocate {} bytes".format(n, sizeof(uint32_t))) + * + * for x from 0 <= x < self.ptr.n_targets: # <<<<<<<<<<<<<< + * self.ptr.target_len[x] = reference_lengths[x] + * name = reference_names[x] +*/ + __pyx_t_15 = __pyx_v_self->ptr->n_targets; + for (__pyx_v_x = 0; __pyx_v_x < __pyx_t_15; __pyx_v_x++) { + + /* "pysam/libcalignmentfile.pyx":269 + * + * for x from 0 <= x < self.ptr.n_targets: + * self.ptr.target_len[x] = reference_lengths[x] # <<<<<<<<<<<<<< + * name = reference_names[x] + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_reference_lengths, __pyx_v_x, int, 1, __Pyx_PyLong_From_int, 0, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 269, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_16 = __Pyx_PyLong_As_uint32_t(__pyx_t_1); if (unlikely((__pyx_t_16 == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 269, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + (__pyx_v_self->ptr->target_len[__pyx_v_x]) = __pyx_t_16; + + /* "pysam/libcalignmentfile.pyx":270 + * for x from 0 <= x < self.ptr.n_targets: + * self.ptr.target_len[x] = reference_lengths[x] + * name = reference_names[x] # <<<<<<<<<<<<<< + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) + * if self.ptr.target_name[x] == NULL: +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_reference_names, __pyx_v_x, int, 1, __Pyx_PyLong_From_int, 0, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 270, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_name, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":271 + * self.ptr.target_len[x] = reference_lengths[x] + * name = reference_names[x] + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) # <<<<<<<<<<<<<< + * if self.ptr.target_name[x] == NULL: + * raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char))) +*/ + __pyx_t_7 = PyObject_Length(__pyx_v_name); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 271, __pyx_L1_error) + (__pyx_v_self->ptr->target_name[__pyx_v_x]) = ((char *)calloc((__pyx_t_7 + 1), (sizeof(char)))); + + /* "pysam/libcalignmentfile.pyx":272 + * name = reference_names[x] + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) + * if self.ptr.target_name[x] == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char))) + * strncpy(self.ptr.target_name[x], name, len(name)) +*/ + __pyx_t_5 = ((__pyx_v_self->ptr->target_name[__pyx_v_x]) == NULL); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":273 + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) + * if self.ptr.target_name[x] == NULL: + * raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char))) # <<<<<<<<<<<<<< + * strncpy(self.ptr.target_name[x], name, len(name)) + * +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_10 = __pyx_builtin_MemoryError; + __pyx_t_8 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_bytes; + __Pyx_INCREF(__pyx_t_8); + __pyx_t_7 = PyObject_Length(__pyx_v_name); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 273, __pyx_L1_error) + __pyx_t_9 = PyLong_FromSsize_t((__pyx_t_7 + 1)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_14 = __Pyx_PyLong_FromSize_t((sizeof(char))); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_t_9, __pyx_t_14}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_4, (3-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_10, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 273, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 273, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":272 + * name = reference_names[x] + * self.ptr.target_name[x] = calloc(len(name) + 1, sizeof(char)) + * if self.ptr.target_name[x] == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char))) + * strncpy(self.ptr.target_name[x], name, len(name)) +*/ + } + + /* "pysam/libcalignmentfile.pyx":274 + * if self.ptr.target_name[x] == NULL: + * raise MemoryError("could not allocate {} bytes".format(len(name) + 1, sizeof(char))) + * strncpy(self.ptr.target_name[x], name, len(name)) # <<<<<<<<<<<<<< + * + * return self +*/ + __pyx_t_17 = __Pyx_PyObject_AsString(__pyx_v_name); if (unlikely((!__pyx_t_17) && PyErr_Occurred())) __PYX_ERR(0, 274, __pyx_L1_error) + __pyx_t_7 = PyObject_Length(__pyx_v_name); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 274, __pyx_L1_error) + (void)(strncpy((__pyx_v_self->ptr->target_name[__pyx_v_x]), __pyx_t_17, __pyx_t_7)); + } + + /* "pysam/libcalignmentfile.pyx":254 + * memcpy(self.ptr.text, ctext, l_text + 1) + * + * if reference_names and reference_lengths: # <<<<<<<<<<<<<< + * reference_names = [force_bytes(ref) for ref in reference_names] + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":276 + * strncpy(self.ptr.target_name[x], name, len(name)) + * + * return self # <<<<<<<<<<<<<< + * + * @classmethod +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 191, 0, __PYX_ERR(0, 276, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":237 + * raise MemoryError("could not create header") + * + * @classmethod # <<<<<<<<<<<<<< + * def _from_text_and_lengths(cls, text, reference_names, reference_lengths): + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 237, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader._from_text_and_lengths", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_self); + __Pyx_XDECREF(__pyx_v_btext); + __Pyx_XDECREF(__pyx_v_name); + __Pyx_XDECREF(__pyx_7genexpr__pyx_v_ref); + __Pyx_XDECREF(__pyx_v_reference_names); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":278 + * return self + * + * @classmethod # <<<<<<<<<<<<<< + * def from_text(cls, text): + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text, "AlignmentHeader.from_text(cls, text)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text = {"from_text", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_text = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_text (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_text,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 278, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 278, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "from_text", 0) < 0) __PYX_ERR(0, 278, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("from_text", 1, 1, 1, i); __PYX_ERR(0, 278, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 278, __pyx_L3_error) + } + __pyx_v_text = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_text", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 278, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_text", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text(((PyTypeObject*)__pyx_v_cls), __pyx_v_text); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_text) { + PyObject *__pyx_v_reference_names = NULL; + PyObject *__pyx_v_reference_lengths = NULL; + PyObject *__pyx_v_line = NULL; + PyObject *__pyx_v_fields = NULL; + PyObject *__pyx_8genexpr1__pyx_v_x = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + Py_ssize_t __pyx_t_4; + PyObject *(*__pyx_t_5)(PyObject *); + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + Py_ssize_t __pyx_t_12; + PyObject *(*__pyx_t_13)(PyObject *); + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *__pyx_t_17 = NULL; + int __pyx_t_18; + int __pyx_t_19; + PyObject *__pyx_t_20 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])) + __Pyx_RefNannySetupContext("from_text", 0); + __Pyx_TraceStartFunc("from_text", __pyx_f[0], 278, 0, 0, 0, __PYX_ERR(0, 278, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":281 + * def from_text(cls, text): + * + * reference_names, reference_lengths = [], [] # <<<<<<<<<<<<<< + * for line in text.splitlines(): + * if line.startswith("@SQ"): +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 281, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_reference_names = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_v_reference_lengths = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":282 + * + * reference_names, reference_lengths = [], [] + * for line in text.splitlines(): # <<<<<<<<<<<<<< + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) +*/ + __pyx_t_1 = __pyx_v_text; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_splitlines, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1); + __pyx_t_4 = 0; + __pyx_t_5 = NULL; + } else { + __pyx_t_4 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 282, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_5)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 282, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + __pyx_t_2 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_4); + ++__pyx_t_4; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 282, __pyx_L1_error) + #endif + if (__pyx_t_4 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_4)); + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_4); + #endif + ++__pyx_t_4; + } + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 282, __pyx_L1_error) + } else { + __pyx_t_2 = __pyx_t_5(__pyx_t_1); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 282, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_line, __pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":283 + * reference_names, reference_lengths = [], [] + * for line in text.splitlines(): + * if line.startswith("@SQ"): # <<<<<<<<<<<<<< + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: +*/ + __pyx_t_6 = __pyx_v_line; + __Pyx_INCREF(__pyx_t_6); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_mstate_global->__pyx_kp_u_SQ}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_startswith, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 283, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 283, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_7) { + + /* "pysam/libcalignmentfile.pyx":284 + * for line in text.splitlines(): + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) # <<<<<<<<<<<<<< + * try: + * reference_names.append(fields["SN"]) +*/ + __pyx_t_6 = NULL; + __Pyx_INCREF((PyObject *)(&PyDict_Type)); + __pyx_t_8 = ((PyObject *)(&PyDict_Type)); + { /* enter inner scope */ + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = __pyx_v_line; + __Pyx_INCREF(__pyx_t_11); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_11, __pyx_mstate_global->__pyx_kp_u__2}; + __pyx_t_10 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_split, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_10); + } + __pyx_t_11 = __Pyx_PyObject_GetSlice(__pyx_t_10, 1, 0, NULL, NULL, &__pyx_mstate_global->__pyx_slice[0], 1, 0, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (likely(PyList_CheckExact(__pyx_t_11)) || PyTuple_CheckExact(__pyx_t_11)) { + __pyx_t_10 = __pyx_t_11; __Pyx_INCREF(__pyx_t_10); + __pyx_t_12 = 0; + __pyx_t_13 = NULL; + } else { + __pyx_t_12 = -1; __pyx_t_10 = PyObject_GetIter(__pyx_t_11); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_13 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_10); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 284, __pyx_L8_error) + } + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + for (;;) { + if (likely(!__pyx_t_13)) { + if (likely(PyList_CheckExact(__pyx_t_10))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_10); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 284, __pyx_L8_error) + #endif + if (__pyx_t_12 >= __pyx_temp) break; + } + __pyx_t_11 = __Pyx_PyList_GetItemRef(__pyx_t_10, __pyx_t_12); + ++__pyx_t_12; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_10); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 284, __pyx_L8_error) + #endif + if (__pyx_t_12 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_11 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_10, __pyx_t_12)); + #else + __pyx_t_11 = __Pyx_PySequence_ITEM(__pyx_t_10, __pyx_t_12); + #endif + ++__pyx_t_12; + } + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 284, __pyx_L8_error) + } else { + __pyx_t_11 = __pyx_t_13(__pyx_t_10); + if (unlikely(!__pyx_t_11)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 284, __pyx_L8_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_11); + __Pyx_XDECREF_SET(__pyx_8genexpr1__pyx_v_x, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_8genexpr1__pyx_v_x, __pyx_mstate_global->__pyx_n_u_split); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_14 = __Pyx_PyObject_Call(__pyx_t_11, __pyx_mstate_global->__pyx_tuple[0], NULL); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(__Pyx_ListComp_Append(__pyx_t_9, (PyObject*)__pyx_t_14))) __PYX_ERR(0, 284, __pyx_L8_error) + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + } + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_x); __pyx_8genexpr1__pyx_v_x = 0; + goto __pyx_L12_exit_scope; + __pyx_L8_error:; + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_x); __pyx_8genexpr1__pyx_v_x = 0; + goto __pyx_L1_error; + __pyx_L12_exit_scope:; + } /* exit inner scope */ + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_t_9}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 284, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_2)); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":285 + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(int(fields["LN"])) +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":286 + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: + * reference_names.append(fields["SN"]) # <<<<<<<<<<<<<< + * reference_lengths.append(int(fields["LN"])) + * except KeyError: +*/ + __pyx_t_2 = __Pyx_PyDict_GetItem(__pyx_v_fields, __pyx_mstate_global->__pyx_n_u_SN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 286, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_18 = __Pyx_PyList_Append(__pyx_v_reference_names, __pyx_t_2); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 286, __pyx_L13_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":287 + * try: + * reference_names.append(fields["SN"]) + * reference_lengths.append(int(fields["LN"])) # <<<<<<<<<<<<<< + * except KeyError: + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) +*/ + __pyx_t_2 = __Pyx_PyDict_GetItem(__pyx_v_fields, __pyx_mstate_global->__pyx_n_u_LN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 287, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_8 = __Pyx_PyNumber_Int(__pyx_t_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 287, __pyx_L13_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_18 = __Pyx_PyList_Append(__pyx_v_reference_lengths, __pyx_t_8); if (unlikely(__pyx_t_18 == ((int)-1))) __PYX_ERR(0, 287, __pyx_L13_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + + /* "pysam/libcalignmentfile.pyx":285 + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(int(fields["LN"])) +*/ + } + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_XDECREF(__pyx_t_17); __pyx_t_17 = 0; + goto __pyx_L20_try_end; + __pyx_L13_error:; + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_TraceException(__pyx_lineno, 0, 0); + + /* "pysam/libcalignmentfile.pyx":288 + * reference_names.append(fields["SN"]) + * reference_lengths.append(int(fields["LN"])) + * except KeyError: # <<<<<<<<<<<<<< + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) + * except ValueError: +*/ + __pyx_t_19 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_KeyError); + if (__pyx_t_19) { + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_text", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_TraceExceptionHandled(0); + if (__Pyx_GetException(&__pyx_t_8, &__pyx_t_2, &__pyx_t_9) < 0) __PYX_ERR(0, 288, __pyx_L15_except_error) + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_TraceExceptionDone(); + + /* "pysam/libcalignmentfile.pyx":289 + * reference_lengths.append(int(fields["LN"])) + * except KeyError: + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) # <<<<<<<<<<<<<< + * except ValueError: + * raise ValueError("wrong sequence information in '%s'" % str(fields)) +*/ + __pyx_t_10 = NULL; + __Pyx_INCREF(__pyx_builtin_KeyError); + __pyx_t_14 = __pyx_builtin_KeyError; + __pyx_t_11 = __Pyx_PyObject_Unicode(__pyx_v_fields); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 289, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_20 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_incomplete_sequence_information, __pyx_t_11); if (unlikely(!__pyx_t_20)) __PYX_ERR(0, 289, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_20); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_10, __pyx_t_20}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_14, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 289, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(0, 289, __pyx_L15_except_error) + } + + /* "pysam/libcalignmentfile.pyx":290 + * except KeyError: + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) + * except ValueError: # <<<<<<<<<<<<<< + * raise ValueError("wrong sequence information in '%s'" % str(fields)) + * +*/ + __pyx_t_19 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_ValueError); + if (__pyx_t_19) { + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_text", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_TraceExceptionHandled(0); + if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_2, &__pyx_t_8) < 0) __PYX_ERR(0, 290, __pyx_L15_except_error) + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_TraceExceptionDone(); + + /* "pysam/libcalignmentfile.pyx":291 + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) + * except ValueError: + * raise ValueError("wrong sequence information in '%s'" % str(fields)) # <<<<<<<<<<<<<< + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) +*/ + __pyx_t_14 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_20 = __pyx_builtin_ValueError; + __pyx_t_10 = __Pyx_PyObject_Unicode(__pyx_v_fields); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 291, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_wrong_sequence_information_in_s, __pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 291, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_14, __pyx_t_11}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_20, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_20); __pyx_t_20 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 291, __pyx_L15_except_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(0, 291, __pyx_L15_except_error) + } + goto __pyx_L15_except_error; + + /* "pysam/libcalignmentfile.pyx":285 + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(int(fields["LN"])) +*/ + __pyx_L15_except_error:; + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_ExceptionReset(__pyx_t_15, __pyx_t_16, __pyx_t_17); + goto __pyx_L1_error; + __pyx_L20_try_end:; + } + + /* "pysam/libcalignmentfile.pyx":283 + * reference_names, reference_lengths = [], [] + * for line in text.splitlines(): + * if line.startswith("@SQ"): # <<<<<<<<<<<<<< + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) + * try: +*/ + } + + /* "pysam/libcalignmentfile.pyx":282 + * + * reference_names, reference_lengths = [], [] + * for line in text.splitlines(): # <<<<<<<<<<<<<< + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":293 + * raise ValueError("wrong sequence information in '%s'" % str(fields)) + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) # <<<<<<<<<<<<<< + * + * @classmethod +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = ((PyObject *)__pyx_v_cls); + __Pyx_INCREF(__pyx_t_8); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[4] = {__pyx_t_8, __pyx_v_text, __pyx_v_reference_names, __pyx_v_reference_lengths}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_from_text_and_lengths, __pyx_callargs+__pyx_t_3, (4-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 293, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 65, 0, __PYX_ERR(0, 293, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":278 + * return self + * + * @classmethod # <<<<<<<<<<<<<< + * def from_text(cls, text): + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_20); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 278, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_text", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_reference_names); + __Pyx_XDECREF(__pyx_v_reference_lengths); + __Pyx_XDECREF(__pyx_v_line); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_8genexpr1__pyx_v_x); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":295 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_dict(cls, header_dict): + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict, "AlignmentHeader.from_dict(cls, header_dict)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict = {"from_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_header_dict = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_dict (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_header_dict,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 295, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 295, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "from_dict", 0) < 0) __PYX_ERR(0, 295, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("from_dict", 1, 1, 1, i); __PYX_ERR(0, 295, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 295, __pyx_L3_error) + } + __pyx_v_header_dict = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_dict", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 295, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict(((PyTypeObject*)__pyx_v_cls), __pyx_v_header_dict); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_header_dict) { + PyObject *__pyx_v_lines = 0; + PyObject *__pyx_v_record = NULL; + PyObject *__pyx_v_data = NULL; + PyObject *__pyx_v_fields = NULL; + PyObject *__pyx_v_text = NULL; + PyObject *__pyx_v_reference_names = NULL; + PyObject *__pyx_v_reference_lengths = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + Py_ssize_t __pyx_t_3; + PyObject *(*__pyx_t_4)(PyObject *); + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + size_t __pyx_t_13; + int __pyx_t_14; + Py_ssize_t __pyx_t_15; + PyObject *(*__pyx_t_16)(PyObject *); + PyObject *(*__pyx_t_17)(PyObject *); + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + PyObject *__pyx_t_20 = NULL; + int __pyx_t_21; + PyObject *__pyx_t_22 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])) + __Pyx_RefNannySetupContext("from_dict", 0); + __Pyx_TraceStartFunc("from_dict", __pyx_f[0], 295, 0, 0, 0, __PYX_ERR(0, 295, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":298 + * def from_dict(cls, header_dict): + * + * cdef list lines = [] # <<<<<<<<<<<<<< + * # first: defined tags + * for record in VALID_HEADERS: +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 298, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_lines = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":300 + * cdef list lines = [] + * # first: defined tags + * for record in VALID_HEADERS: # <<<<<<<<<<<<<< + * if record in header_dict: + * data = header_dict[record] +*/ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_VALID_HEADERS); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 300, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_2 = __pyx_t_1; __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 300, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 300, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 300, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + __pyx_t_1 = __Pyx_PyList_GetItemRef(__pyx_t_2, __pyx_t_3); + ++__pyx_t_3; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 300, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3)); + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_3); + #endif + ++__pyx_t_3; + } + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 300, __pyx_L1_error) + } else { + __pyx_t_1 = __pyx_t_4(__pyx_t_2); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 300, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_record, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":301 + * # first: defined tags + * for record in VALID_HEADERS: + * if record in header_dict: # <<<<<<<<<<<<<< + * data = header_dict[record] + * if not isinstance(data, VALID_HEADER_TYPES[record]): +*/ + __pyx_t_5 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_v_header_dict, Py_EQ)); if (unlikely((__pyx_t_5 < 0))) __PYX_ERR(0, 301, __pyx_L1_error) + if (__pyx_t_5) { + + /* "pysam/libcalignmentfile.pyx":302 + * for record in VALID_HEADERS: + * if record in header_dict: + * data = header_dict[record] # <<<<<<<<<<<<<< + * if not isinstance(data, VALID_HEADER_TYPES[record]): + * raise ValueError( +*/ + __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_header_dict, __pyx_v_record); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 302, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_data, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":303 + * if record in header_dict: + * data = header_dict[record] + * if not isinstance(data, VALID_HEADER_TYPES[record]): # <<<<<<<<<<<<<< + * raise ValueError( + * "invalid type for record {}: {}, expected {}".format( +*/ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 303, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_record); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 303, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = PyObject_IsInstance(__pyx_v_data, __pyx_t_6); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 303, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_7 = (!__pyx_t_5); + if (unlikely(__pyx_t_7)) { + + /* "pysam/libcalignmentfile.pyx":304 + * data = header_dict[record] + * if not isinstance(data, VALID_HEADER_TYPES[record]): + * raise ValueError( # <<<<<<<<<<<<<< + * "invalid type for record {}: {}, expected {}".format( + * record, type(data), VALID_HEADER_TYPES[record])) +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_8 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":305 + * if not isinstance(data, VALID_HEADER_TYPES[record]): + * raise ValueError( + * "invalid type for record {}: {}, expected {}".format( # <<<<<<<<<<<<<< + * record, type(data), VALID_HEADER_TYPES[record])) + * if isinstance(data, Mapping): +*/ + __pyx_t_10 = __pyx_mstate_global->__pyx_kp_u_invalid_type_for_record_expected; + __Pyx_INCREF(__pyx_t_10); + + /* "pysam/libcalignmentfile.pyx":306 + * raise ValueError( + * "invalid type for record {}: {}, expected {}".format( + * record, type(data), VALID_HEADER_TYPES[record])) # <<<<<<<<<<<<<< + * if isinstance(data, Mapping): + * lines.append(build_header_line(data, record)) +*/ + __Pyx_GetModuleGlobalName(__pyx_t_11, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 306, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_12 = __Pyx_PyObject_GetItem(__pyx_t_11, __pyx_v_record); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 306, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_13 = 0; + { + PyObject *__pyx_callargs[4] = {__pyx_t_10, __pyx_v_record, ((PyObject *)Py_TYPE(__pyx_v_data)), __pyx_t_12}; + __pyx_t_9 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_13, (4-__pyx_t_13) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 305, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + } + __pyx_t_13 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_t_9}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_13, (2-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 304, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(0, 304, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":303 + * if record in header_dict: + * data = header_dict[record] + * if not isinstance(data, VALID_HEADER_TYPES[record]): # <<<<<<<<<<<<<< + * raise ValueError( + * "invalid type for record {}: {}, expected {}".format( +*/ + } + + /* "pysam/libcalignmentfile.pyx":307 + * "invalid type for record {}: {}, expected {}".format( + * record, type(data), VALID_HEADER_TYPES[record])) + * if isinstance(data, Mapping): # <<<<<<<<<<<<<< + * lines.append(build_header_line(data, record)) + * else: +*/ + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyObject_IsInstance(__pyx_v_data, __pyx_t_6); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 307, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_7) { + + /* "pysam/libcalignmentfile.pyx":308 + * record, type(data), VALID_HEADER_TYPES[record])) + * if isinstance(data, Mapping): + * lines.append(build_header_line(data, record)) # <<<<<<<<<<<<<< + * else: + * for fields in header_dict[record]: +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_build_header_line); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 308, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_13 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_9))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_9); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_9); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_9, __pyx__function); + __pyx_t_13 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_v_data, __pyx_v_record}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_9, __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 308, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_lines, __pyx_t_6); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 308, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":307 + * "invalid type for record {}: {}, expected {}".format( + * record, type(data), VALID_HEADER_TYPES[record])) + * if isinstance(data, Mapping): # <<<<<<<<<<<<<< + * lines.append(build_header_line(data, record)) + * else: +*/ + goto __pyx_L7; + } + + /* "pysam/libcalignmentfile.pyx":310 + * lines.append(build_header_line(data, record)) + * else: + * for fields in header_dict[record]: # <<<<<<<<<<<<<< + * lines.append(build_header_line(fields, record)) + * +*/ + /*else*/ { + __pyx_t_6 = __Pyx_PyObject_GetItem(__pyx_v_header_dict, __pyx_v_record); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 310, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (likely(PyList_CheckExact(__pyx_t_6)) || PyTuple_CheckExact(__pyx_t_6)) { + __pyx_t_9 = __pyx_t_6; __Pyx_INCREF(__pyx_t_9); + __pyx_t_15 = 0; + __pyx_t_16 = NULL; + } else { + __pyx_t_15 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 310, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_16 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 310, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + for (;;) { + if (likely(!__pyx_t_16)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 310, __pyx_L1_error) + #endif + if (__pyx_t_15 >= __pyx_temp) break; + } + __pyx_t_6 = __Pyx_PyList_GetItemRef(__pyx_t_9, __pyx_t_15); + ++__pyx_t_15; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 310, __pyx_L1_error) + #endif + if (__pyx_t_15 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_15)); + #else + __pyx_t_6 = __Pyx_PySequence_ITEM(__pyx_t_9, __pyx_t_15); + #endif + ++__pyx_t_15; + } + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 310, __pyx_L1_error) + } else { + __pyx_t_6 = __pyx_t_16(__pyx_t_9); + if (unlikely(!__pyx_t_6)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 310, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_fields, __pyx_t_6); + __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":311 + * else: + * for fields in header_dict[record]: + * lines.append(build_header_line(fields, record)) # <<<<<<<<<<<<<< + * + * # then: user tags (lower case), sorted alphabetically +*/ + __pyx_t_8 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_build_header_line); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 311, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_13 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_1))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_1); + assert(__pyx_t_8); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_1); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_1, __pyx__function); + __pyx_t_13 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_8, __pyx_v_fields, __pyx_v_record}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_1, __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 311, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_lines, __pyx_t_6); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 311, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":310 + * lines.append(build_header_line(data, record)) + * else: + * for fields in header_dict[record]: # <<<<<<<<<<<<<< + * lines.append(build_header_line(fields, record)) + * +*/ + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + __pyx_L7:; + + /* "pysam/libcalignmentfile.pyx":301 + * # first: defined tags + * for record in VALID_HEADERS: + * if record in header_dict: # <<<<<<<<<<<<<< + * data = header_dict[record] + * if not isinstance(data, VALID_HEADER_TYPES[record]): +*/ + } + + /* "pysam/libcalignmentfile.pyx":300 + * cdef list lines = [] + * # first: defined tags + * for record in VALID_HEADERS: # <<<<<<<<<<<<<< + * if record in header_dict: + * data = header_dict[record] +*/ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":314 + * + * # then: user tags (lower case), sorted alphabetically + * for record, data in sorted(header_dict.items()): # <<<<<<<<<<<<<< + * if record in VALID_HEADERS: + * continue +*/ + __pyx_t_9 = __pyx_v_header_dict; + __Pyx_INCREF(__pyx_t_9); + __pyx_t_13 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_items, __pyx_callargs+__pyx_t_13, (1-__pyx_t_13) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_9 = PySequence_List(__pyx_t_2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely((PyList_Sort(__pyx_t_9) < 0))) __PYX_ERR(0, 314, __pyx_L1_error) + __pyx_t_2 = __pyx_t_9; __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + for (;;) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 314, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + __pyx_t_9 = __Pyx_PyList_GetItemRef(__pyx_t_2, __pyx_t_3); + ++__pyx_t_3; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if ((likely(PyTuple_CheckExact(__pyx_t_9))) || (PyList_CheckExact(__pyx_t_9))) { + PyObject* sequence = __pyx_t_9; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 314, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_6); + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_1); + } else { + __pyx_t_6 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_1); + } + #else + __pyx_t_6 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_1 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + #endif + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_8 = PyObject_GetIter(__pyx_t_9); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 314, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_17 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_8); + index = 0; __pyx_t_6 = __pyx_t_17(__pyx_t_8); if (unlikely(!__pyx_t_6)) goto __pyx_L14_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + index = 1; __pyx_t_1 = __pyx_t_17(__pyx_t_8); if (unlikely(!__pyx_t_1)) goto __pyx_L14_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_17(__pyx_t_8), 2) < 0) __PYX_ERR(0, 314, __pyx_L1_error) + __pyx_t_17 = NULL; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L15_unpacking_done; + __pyx_L14_unpacking_failed:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_17 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 314, __pyx_L1_error) + __pyx_L15_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_record, __pyx_t_6); + __pyx_t_6 = 0; + __Pyx_XDECREF_SET(__pyx_v_data, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":315 + * # then: user tags (lower case), sorted alphabetically + * for record, data in sorted(header_dict.items()): + * if record in VALID_HEADERS: # <<<<<<<<<<<<<< + * continue + * if isinstance(data, Mapping): +*/ + __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_VALID_HEADERS); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 315, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_t_9, Py_EQ)); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 315, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_7) { + + /* "pysam/libcalignmentfile.pyx":316 + * for record, data in sorted(header_dict.items()): + * if record in VALID_HEADERS: + * continue # <<<<<<<<<<<<<< + * if isinstance(data, Mapping): + * lines.append(build_header_line(data, record)) +*/ + goto __pyx_L12_continue; + + /* "pysam/libcalignmentfile.pyx":315 + * # then: user tags (lower case), sorted alphabetically + * for record, data in sorted(header_dict.items()): + * if record in VALID_HEADERS: # <<<<<<<<<<<<<< + * continue + * if isinstance(data, Mapping): +*/ + } + + /* "pysam/libcalignmentfile.pyx":317 + * if record in VALID_HEADERS: + * continue + * if isinstance(data, Mapping): # <<<<<<<<<<<<<< + * lines.append(build_header_line(data, record)) + * else: +*/ + __Pyx_GetModuleGlobalName(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 317, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_7 = PyObject_IsInstance(__pyx_v_data, __pyx_t_9); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 317, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (__pyx_t_7) { + + /* "pysam/libcalignmentfile.pyx":318 + * continue + * if isinstance(data, Mapping): + * lines.append(build_header_line(data, record)) # <<<<<<<<<<<<<< + * else: + * for fields in header_dict[record]: +*/ + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_mstate_global->__pyx_n_u_build_header_line); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 318, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_13 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_13 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_v_data, __pyx_v_record}; + __pyx_t_9 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 318, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + } + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_lines, __pyx_t_9); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 318, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":317 + * if record in VALID_HEADERS: + * continue + * if isinstance(data, Mapping): # <<<<<<<<<<<<<< + * lines.append(build_header_line(data, record)) + * else: +*/ + goto __pyx_L17; + } + + /* "pysam/libcalignmentfile.pyx":320 + * lines.append(build_header_line(data, record)) + * else: + * for fields in header_dict[record]: # <<<<<<<<<<<<<< + * lines.append(build_header_line(fields, record)) + * +*/ + /*else*/ { + __pyx_t_9 = __Pyx_PyObject_GetItem(__pyx_v_header_dict, __pyx_v_record); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (likely(PyList_CheckExact(__pyx_t_9)) || PyTuple_CheckExact(__pyx_t_9)) { + __pyx_t_6 = __pyx_t_9; __Pyx_INCREF(__pyx_t_6); + __pyx_t_15 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_15 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_t_9); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 320, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 320, __pyx_L1_error) + #endif + if (__pyx_t_15 >= __pyx_temp) break; + } + __pyx_t_9 = __Pyx_PyList_GetItemRef(__pyx_t_6, __pyx_t_15); + ++__pyx_t_15; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 320, __pyx_L1_error) + #endif + if (__pyx_t_15 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_15)); + #else + __pyx_t_9 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_15); + #endif + ++__pyx_t_15; + } + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 320, __pyx_L1_error) + } else { + __pyx_t_9 = __pyx_t_4(__pyx_t_6); + if (unlikely(!__pyx_t_9)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 320, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_9); + __Pyx_XDECREF_SET(__pyx_v_fields, __pyx_t_9); + __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":321 + * else: + * for fields in header_dict[record]: + * lines.append(build_header_line(fields, record)) # <<<<<<<<<<<<<< + * + * text = "\n".join(lines) + "\n" +*/ + __pyx_t_1 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_build_header_line); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_13 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_13 = 0; + } + #endif + { + PyObject *__pyx_callargs[3] = {__pyx_t_1, __pyx_v_fields, __pyx_v_record}; + __pyx_t_9 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + } + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_lines, __pyx_t_9); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 321, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":320 + * lines.append(build_header_line(data, record)) + * else: + * for fields in header_dict[record]: # <<<<<<<<<<<<<< + * lines.append(build_header_line(fields, record)) + * +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __pyx_L17:; + + /* "pysam/libcalignmentfile.pyx":314 + * + * # then: user tags (lower case), sorted alphabetically + * for record, data in sorted(header_dict.items()): # <<<<<<<<<<<<<< + * if record in VALID_HEADERS: + * continue +*/ + __pyx_L12_continue:; + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":323 + * lines.append(build_header_line(fields, record)) + * + * text = "\n".join(lines) + "\n" # <<<<<<<<<<<<<< + * + * reference_names, reference_lengths = [], [] +*/ + __pyx_t_2 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__3, __pyx_v_lines); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 323, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = __Pyx_PyUnicode_ConcatInPlace(__pyx_t_2, __pyx_mstate_global->__pyx_kp_u__3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 323, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_text = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":325 + * text = "\n".join(lines) + "\n" + * + * reference_names, reference_lengths = [], [] # <<<<<<<<<<<<<< + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: +*/ + __pyx_t_6 = PyList_New(0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 325, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 325, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_reference_names = ((PyObject*)__pyx_t_6); + __pyx_t_6 = 0; + __pyx_v_reference_lengths = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":326 + * + * reference_names, reference_lengths = [], [] + * if "SQ" in header_dict: # <<<<<<<<<<<<<< + * for fields in header_dict["SQ"]: + * try: +*/ + __pyx_t_7 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_v_header_dict, Py_EQ)); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 326, __pyx_L1_error) + if (__pyx_t_7) { + + /* "pysam/libcalignmentfile.pyx":327 + * reference_names, reference_lengths = [], [] + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: # <<<<<<<<<<<<<< + * try: + * reference_names.append(fields["SN"]) +*/ + __pyx_t_2 = __Pyx_PyObject_Dict_GetItem(__pyx_v_header_dict, __pyx_mstate_global->__pyx_n_u_SQ_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_6 = __pyx_t_2; __Pyx_INCREF(__pyx_t_6); + __pyx_t_3 = 0; + __pyx_t_4 = NULL; + } else { + __pyx_t_3 = -1; __pyx_t_6 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 327, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_4 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 327, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_4)) { + if (likely(PyList_CheckExact(__pyx_t_6))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 327, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + __pyx_t_2 = __Pyx_PyList_GetItemRef(__pyx_t_6, __pyx_t_3); + ++__pyx_t_3; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_6); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 327, __pyx_L1_error) + #endif + if (__pyx_t_3 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_6, __pyx_t_3)); + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_6, __pyx_t_3); + #endif + ++__pyx_t_3; + } + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 327, __pyx_L1_error) + } else { + __pyx_t_2 = __pyx_t_4(__pyx_t_6); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 327, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_fields, __pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":328 + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(fields["LN"]) +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_18, &__pyx_t_19, &__pyx_t_20); + __Pyx_XGOTREF(__pyx_t_18); + __Pyx_XGOTREF(__pyx_t_19); + __Pyx_XGOTREF(__pyx_t_20); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":329 + * for fields in header_dict["SQ"]: + * try: + * reference_names.append(fields["SN"]) # <<<<<<<<<<<<<< + * reference_lengths.append(fields["LN"]) + * except KeyError: +*/ + __pyx_t_2 = __Pyx_PyObject_Dict_GetItem(__pyx_v_fields, __pyx_mstate_global->__pyx_n_u_SN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 329, __pyx_L25_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_reference_names, __pyx_t_2); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 329, __pyx_L25_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":330 + * try: + * reference_names.append(fields["SN"]) + * reference_lengths.append(fields["LN"]) # <<<<<<<<<<<<<< + * except KeyError: + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) +*/ + __pyx_t_2 = __Pyx_PyObject_Dict_GetItem(__pyx_v_fields, __pyx_mstate_global->__pyx_n_u_LN); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 330, __pyx_L25_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = __Pyx_PyList_Append(__pyx_v_reference_lengths, __pyx_t_2); if (unlikely(__pyx_t_14 == ((int)-1))) __PYX_ERR(0, 330, __pyx_L25_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":328 + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(fields["LN"]) +*/ + } + __Pyx_XDECREF(__pyx_t_18); __pyx_t_18 = 0; + __Pyx_XDECREF(__pyx_t_19); __pyx_t_19 = 0; + __Pyx_XDECREF(__pyx_t_20); __pyx_t_20 = 0; + goto __pyx_L32_try_end; + __pyx_L25_error:; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_TraceException(__pyx_lineno, 0, 0); + + /* "pysam/libcalignmentfile.pyx":331 + * reference_names.append(fields["SN"]) + * reference_lengths.append(fields["LN"]) + * except KeyError: # <<<<<<<<<<<<<< + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) + * +*/ + __pyx_t_21 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_KeyError); + if (__pyx_t_21) { + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_TraceExceptionHandled(0); + if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_9, &__pyx_t_8) < 0) __PYX_ERR(0, 331, __pyx_L27_except_error) + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_TraceExceptionDone(); + + /* "pysam/libcalignmentfile.pyx":332 + * reference_lengths.append(fields["LN"]) + * except KeyError: + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) # <<<<<<<<<<<<<< + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) +*/ + __pyx_t_12 = NULL; + __Pyx_INCREF(__pyx_builtin_KeyError); + __pyx_t_10 = __pyx_builtin_KeyError; + __pyx_t_11 = __Pyx_PyObject_Unicode(__pyx_v_fields); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 332, __pyx_L27_except_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_22 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_incomplete_sequence_information, __pyx_t_11); if (unlikely(!__pyx_t_22)) __PYX_ERR(0, 332, __pyx_L27_except_error) + __Pyx_GOTREF(__pyx_t_22); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_13 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_12, __pyx_t_22}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_10, __pyx_callargs+__pyx_t_13, (2-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_22); __pyx_t_22 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 332, __pyx_L27_except_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 332, __pyx_L27_except_error) + } + goto __pyx_L27_except_error; + + /* "pysam/libcalignmentfile.pyx":328 + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: + * try: # <<<<<<<<<<<<<< + * reference_names.append(fields["SN"]) + * reference_lengths.append(fields["LN"]) +*/ + __pyx_L27_except_error:; + __Pyx_XGIVEREF(__pyx_t_18); + __Pyx_XGIVEREF(__pyx_t_19); + __Pyx_XGIVEREF(__pyx_t_20); + __Pyx_ExceptionReset(__pyx_t_18, __pyx_t_19, __pyx_t_20); + goto __pyx_L1_error; + __pyx_L32_try_end:; + } + + /* "pysam/libcalignmentfile.pyx":327 + * reference_names, reference_lengths = [], [] + * if "SQ" in header_dict: + * for fields in header_dict["SQ"]: # <<<<<<<<<<<<<< + * try: + * reference_names.append(fields["SN"]) +*/ + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":326 + * + * reference_names, reference_lengths = [], [] + * if "SQ" in header_dict: # <<<<<<<<<<<<<< + * for fields in header_dict["SQ"]: + * try: +*/ + } + + /* "pysam/libcalignmentfile.pyx":334 + * raise KeyError("incomplete sequence information in '%s'" % str(fields)) + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) # <<<<<<<<<<<<<< + * + * @classmethod +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = ((PyObject *)__pyx_v_cls); + __Pyx_INCREF(__pyx_t_8); + __pyx_t_13 = 0; + { + PyObject *__pyx_callargs[4] = {__pyx_t_8, __pyx_v_text, __pyx_v_reference_names, __pyx_v_reference_lengths}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_from_text_and_lengths, __pyx_callargs+__pyx_t_13, (4-__pyx_t_13) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + __Pyx_TraceReturnValue(__pyx_r, 138, 0, __PYX_ERR(0, 334, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":295 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_dict(cls, header_dict): + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_22); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 295, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_lines); + __Pyx_XDECREF(__pyx_v_record); + __Pyx_XDECREF(__pyx_v_data); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_text); + __Pyx_XDECREF(__pyx_v_reference_names); + __Pyx_XDECREF(__pyx_v_reference_lengths); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":336 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references, "AlignmentHeader.from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references = {"from_references", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references(PyObject *__pyx_v_cls, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference_names = 0; + PyObject *__pyx_v_reference_lengths = 0; + PyObject *__pyx_v_text = 0; + PyObject *__pyx_v_add_sq_text = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[4] = {0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("from_references (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference_names,&__pyx_mstate_global->__pyx_n_u_reference_lengths,&__pyx_mstate_global->__pyx_n_u_text,&__pyx_mstate_global->__pyx_n_u_add_sq_text,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 336, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "from_references", 0) < 0) __PYX_ERR(0, 336, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":337 + * + * @classmethod + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): # <<<<<<<<<<<<<< + * + * if len(reference_names) != len(reference_lengths): +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_True)); + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("from_references", 0, 2, 4, i); __PYX_ERR(0, 336, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 336, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 336, __pyx_L3_error) + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 336, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_True)); + } + __pyx_v_reference_names = values[0]; + __pyx_v_reference_lengths = values[1]; + __pyx_v_text = values[2]; + __pyx_v_add_sq_text = values[3]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("from_references", 0, 2, 4, __pyx_nargs); __PYX_ERR(0, 336, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_references", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references(((PyTypeObject*)__pyx_v_cls), __pyx_v_reference_names, __pyx_v_reference_lengths, __pyx_v_text, __pyx_v_add_sq_text); + + /* "pysam/libcalignmentfile.pyx":336 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references(PyTypeObject *__pyx_v_cls, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths, PyObject *__pyx_v_text, PyObject *__pyx_v_add_sq_text) { + PyObject *__pyx_8genexpr2__pyx_v_x = NULL; + PyObject *__pyx_8genexpr2__pyx_v_y = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *(*__pyx_t_13)(PyObject *); + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])) + __Pyx_RefNannySetupContext("from_references", 0); + __Pyx_TraceStartFunc("from_references", __pyx_f[0], 336, 0, 0, 0, __PYX_ERR(0, 336, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_text); + + /* "pysam/libcalignmentfile.pyx":339 + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * + * if len(reference_names) != len(reference_lengths): # <<<<<<<<<<<<<< + * raise ValueError("number of reference names and lengths do not match") + * +*/ + __pyx_t_1 = PyObject_Length(__pyx_v_reference_names); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 339, __pyx_L1_error) + __pyx_t_2 = PyObject_Length(__pyx_v_reference_lengths); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 339, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_1 != __pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":340 + * + * if len(reference_names) != len(reference_lengths): + * raise ValueError("number of reference names and lengths do not match") # <<<<<<<<<<<<<< + * + * # optionally, if there is no text, add a SAM compatible header to output file. +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_6 = __pyx_builtin_ValueError; + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_number_of_reference_names_and_le}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 340, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 340, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":339 + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * + * if len(reference_names) != len(reference_lengths): # <<<<<<<<<<<<<< + * raise ValueError("number of reference names and lengths do not match") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":343 + * + * # optionally, if there is no text, add a SAM compatible header to output file. + * if text is None and add_sq_text: # <<<<<<<<<<<<<< + * text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip( + * reference_names, reference_lengths)]) +*/ + __pyx_t_8 = (__pyx_v_text == Py_None); + if (__pyx_t_8) { + } else { + __pyx_t_3 = __pyx_t_8; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_v_add_sq_text); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 343, __pyx_L1_error) + __pyx_t_3 = __pyx_t_8; + __pyx_L5_bool_binop_done:; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":344 + * # optionally, if there is no text, add a SAM compatible header to output file. + * if text is None and add_sq_text: + * text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip( # <<<<<<<<<<<<<< + * reference_names, reference_lengths)]) + * +*/ + { /* enter inner scope */ + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_zip); + __pyx_t_9 = __pyx_builtin_zip; + + /* "pysam/libcalignmentfile.pyx":345 + * if text is None and add_sq_text: + * text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip( + * reference_names, reference_lengths)]) # <<<<<<<<<<<<<< + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) +*/ + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_5, __pyx_v_reference_names, __pyx_v_reference_lengths}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_9, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_6); + } + + /* "pysam/libcalignmentfile.pyx":344 + * # optionally, if there is no text, add a SAM compatible header to output file. + * if text is None and add_sq_text: + * text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip( # <<<<<<<<<<<<<< + * reference_names, reference_lengths)]) + * +*/ + if (likely(PyList_CheckExact(__pyx_t_6)) || PyTuple_CheckExact(__pyx_t_6)) { + __pyx_t_9 = __pyx_t_6; __Pyx_INCREF(__pyx_t_9); + __pyx_t_2 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_2 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 344, __pyx_L9_error) + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 344, __pyx_L9_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + __pyx_t_6 = __Pyx_PyList_GetItemRef(__pyx_t_9, __pyx_t_2); + ++__pyx_t_2; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 344, __pyx_L9_error) + #endif + if (__pyx_t_2 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_2)); + #else + __pyx_t_6 = __Pyx_PySequence_ITEM(__pyx_t_9, __pyx_t_2); + #endif + ++__pyx_t_2; + } + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 344, __pyx_L9_error) + } else { + __pyx_t_6 = __pyx_t_10(__pyx_t_9); + if (unlikely(!__pyx_t_6)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 344, __pyx_L9_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_6); + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 344, __pyx_L9_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_11); + } else { + __pyx_t_5 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_XGOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_XGOTREF(__pyx_t_11); + } + #else + __pyx_t_5 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_11 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_12 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_13 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_12); + index = 0; __pyx_t_5 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_5)) goto __pyx_L12_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 1; __pyx_t_11 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_11)) goto __pyx_L12_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_13(__pyx_t_12), 2) < 0) __PYX_ERR(0, 344, __pyx_L9_error) + __pyx_t_13 = NULL; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + goto __pyx_L13_unpacking_done; + __pyx_L12_unpacking_failed:; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_13 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 344, __pyx_L9_error) + __pyx_L13_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_x, __pyx_t_5); + __pyx_t_5 = 0; + __Pyx_XDECREF_SET(__pyx_8genexpr2__pyx_v_y, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_11 = __pyx_mstate_global->__pyx_kp_u_SQ_SN_LN; + __Pyx_INCREF(__pyx_t_11); + __pyx_t_7 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_11, __pyx_8genexpr2__pyx_v_x, __pyx_8genexpr2__pyx_v_y}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_7, (3-__pyx_t_7) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_GOTREF(__pyx_t_6); + } + if (unlikely(__Pyx_ListComp_Append(__pyx_t_4, (PyObject*)__pyx_t_6))) __PYX_ERR(0, 344, __pyx_L9_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); __pyx_8genexpr2__pyx_v_x = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); __pyx_8genexpr2__pyx_v_y = 0; + goto __pyx_L15_exit_scope; + __pyx_L9_error:; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); __pyx_8genexpr2__pyx_v_x = 0; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); __pyx_8genexpr2__pyx_v_y = 0; + goto __pyx_L1_error; + __pyx_L15_exit_scope:; + } /* exit inner scope */ + __pyx_t_9 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__4, __pyx_t_4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 344, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF_SET(__pyx_v_text, __pyx_t_9); + __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":343 + * + * # optionally, if there is no text, add a SAM compatible header to output file. + * if text is None and add_sq_text: # <<<<<<<<<<<<<< + * text = "".join(["@SQ\tSN:{}\tLN:{}\n".format(x, y) for x, y in zip( + * reference_names, reference_lengths)]) +*/ + } + + /* "pysam/libcalignmentfile.pyx":347 + * reference_names, reference_lengths)]) + * + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_cls); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = 0; + { + PyObject *__pyx_callargs[4] = {__pyx_t_4, __pyx_v_text, __pyx_v_reference_names, __pyx_v_reference_lengths}; + __pyx_t_9 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_from_text_and_lengths, __pyx_callargs+__pyx_t_7, (4-__pyx_t_7) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 347, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + } + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; + __Pyx_TraceReturnValue(__pyx_r, 38, 0, __PYX_ERR(0, 347, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":336 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 336, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.from_references", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_x); + __Pyx_XDECREF(__pyx_8genexpr2__pyx_v_y); + __Pyx_XDECREF(__pyx_v_text); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":349 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * bam_hdr_destroy(self.ptr) + * self.ptr = NULL +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_13__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_13__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_12__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_12__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[10])) + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 349, 0, 0, 0, __PYX_ERR(0, 349, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":350 + * + * def __dealloc__(self): + * bam_hdr_destroy(self.ptr) # <<<<<<<<<<<<<< + * self.ptr = NULL + * +*/ + bam_hdr_destroy(__pyx_v_self->ptr); + + /* "pysam/libcalignmentfile.pyx":351 + * def __dealloc__(self): + * bam_hdr_destroy(self.ptr) + * self.ptr = NULL # <<<<<<<<<<<<<< + * + * def __bool__(self): +*/ + __pyx_v_self->ptr = NULL; + + /* "pysam/libcalignmentfile.pyx":349 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * bam_hdr_destroy(self.ptr) + * self.ptr = NULL +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 349, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 349, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.AlignmentHeader.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); +} + +/* "pysam/libcalignmentfile.pyx":353 + * self.ptr = NULL + * + * def __bool__(self): # <<<<<<<<<<<<<< + * return self.ptr != NULL + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_15__bool__(PyObject *__pyx_v_self); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_15__bool__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__bool__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_14__bool__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_14__bool__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[11])) + __Pyx_TraceStartFunc("__bool__", __pyx_f[0], 353, 0, 0, 0, __PYX_ERR(0, 353, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":354 + * + * def __bool__(self): + * return self.ptr != NULL # <<<<<<<<<<<<<< + * + * def copy(self): +*/ + __pyx_r = (__pyx_v_self->ptr != NULL); + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 1, 0, __PYX_ERR(0, 354, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":353 + * self.ptr = NULL + * + * def __bool__(self): # <<<<<<<<<<<<<< + * return self.ptr != NULL + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 353, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__bool__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":356 + * return self.ptr != NULL + * + * def copy(self): # <<<<<<<<<<<<<< + * return makeAlignmentHeader(bam_hdr_dup(self.ptr)) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_17copy(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_16copy, "AlignmentHeader.copy(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_17copy = {"copy", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_17copy, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_16copy}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_17copy(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("copy (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("copy", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("copy", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_16copy(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_16copy(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[12])) + __Pyx_RefNannySetupContext("copy", 0); + __Pyx_TraceStartFunc("copy", __pyx_f[0], 356, 0, 0, 0, __PYX_ERR(0, 356, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":357 + * + * def copy(self): + * return makeAlignmentHeader(bam_hdr_dup(self.ptr)) # <<<<<<<<<<<<<< + * + * property nreferences: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((PyObject *)__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(bam_hdr_dup(__pyx_v_self->ptr))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 357, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 357, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":356 + * return self.ptr != NULL + * + * def copy(self): # <<<<<<<<<<<<<< + * return makeAlignmentHeader(bam_hdr_dup(self.ptr)) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 356, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":363 + * + * This is a read-only attribute.""" + * def __get__(self): # <<<<<<<<<<<<<< + * return self.ptr.n_targets + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[13])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 363, 0, 0, 0, __PYX_ERR(0, 363, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":364 + * This is a read-only attribute.""" + * def __get__(self): + * return self.ptr.n_targets # <<<<<<<<<<<<<< + * + * property references: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int32_t(__pyx_v_self->ptr->n_targets); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 364, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 364, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":363 + * + * This is a read-only attribute.""" + * def __get__(self): # <<<<<<<<<<<<<< + * return self.ptr.n_targets + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 363, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.nreferences.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":369 + * """tuple with the names of :term:`reference` sequences. This is a + * read-only attribute""" + * def __get__(self): # <<<<<<<<<<<<<< + * t = [] + * cdef int x +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_10references_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_10references_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10references___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_10references___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_v_t = NULL; + int __pyx_v_x; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int32_t __pyx_t_2; + int32_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[14])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 369, 0, 0, 0, __PYX_ERR(0, 369, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":370 + * read-only attribute""" + * def __get__(self): + * t = [] # <<<<<<<<<<<<<< + * cdef int x + * for x in range(self.ptr.n_targets): +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 370, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_t = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":372 + * t = [] + * cdef int x + * for x in range(self.ptr.n_targets): # <<<<<<<<<<<<<< + * t.append(charptr_to_str(self.ptr.target_name[x])) + * return tuple(t) +*/ + __pyx_t_2 = __pyx_v_self->ptr->n_targets; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_x = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":373 + * cdef int x + * for x in range(self.ptr.n_targets): + * t.append(charptr_to_str(self.ptr.target_name[x])) # <<<<<<<<<<<<<< + * return tuple(t) + * +*/ + __pyx_t_1 = __pyx_f_5pysam_9libcutils_charptr_to_str((__pyx_v_self->ptr->target_name[__pyx_v_x]), NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 373, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyList_Append(__pyx_v_t, __pyx_t_1); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 373, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "pysam/libcalignmentfile.pyx":374 + * for x in range(self.ptr.n_targets): + * t.append(charptr_to_str(self.ptr.target_name[x])) + * return tuple(t) # <<<<<<<<<<<<<< + * + * property lengths: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_AsTuple(__pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 374, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 20, 0, __PYX_ERR(0, 374, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":369 + * """tuple with the names of :term:`reference` sequences. This is a + * read-only attribute""" + * def __get__(self): # <<<<<<<<<<<<<< + * t = [] + * cdef int x +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 369, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.references.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_t); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":381 + * :attr:`pysam.AlignmentFile.references` + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * t = [] + * cdef int x +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_v_t = NULL; + int __pyx_v_x; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int32_t __pyx_t_2; + int32_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[15])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 381, 0, 0, 0, __PYX_ERR(0, 381, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":382 + * """ + * def __get__(self): + * t = [] # <<<<<<<<<<<<<< + * cdef int x + * for x in range(self.ptr.n_targets): +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 382, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_t = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":384 + * t = [] + * cdef int x + * for x in range(self.ptr.n_targets): # <<<<<<<<<<<<<< + * t.append(self.ptr.target_len[x]) + * return tuple(t) +*/ + __pyx_t_2 = __pyx_v_self->ptr->n_targets; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_x = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":385 + * cdef int x + * for x in range(self.ptr.n_targets): + * t.append(self.ptr.target_len[x]) # <<<<<<<<<<<<<< + * return tuple(t) + * +*/ + __pyx_t_1 = __Pyx_PyLong_From_uint32_t((__pyx_v_self->ptr->target_len[__pyx_v_x])); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 385, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyList_Append(__pyx_v_t, __pyx_t_1); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 385, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "pysam/libcalignmentfile.pyx":386 + * for x in range(self.ptr.n_targets): + * t.append(self.ptr.target_len[x]) + * return tuple(t) # <<<<<<<<<<<<<< + * + * def _build_sequence_section(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyList_AsTuple(__pyx_v_t); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 386, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 18, 0, __PYX_ERR(0, 386, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":381 + * :attr:`pysam.AlignmentFile.references` + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * t = [] + * cdef int x +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 381, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.lengths.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_t); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":388 + * return tuple(t) + * + * def _build_sequence_section(self): # <<<<<<<<<<<<<< + * """return sequence section of header. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section, "AlignmentHeader._build_sequence_section(self)\n\nreturn sequence section of header.\n\nThe sequence section is built from the list of reference names and\nlengths stored in the BAM-file and not from any @SQ entries that\nare part of the header's text section."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section = {"_build_sequence_section", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_build_sequence_section (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("_build_sequence_section", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("_build_sequence_section", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + int __pyx_v_x; + PyObject *__pyx_v_text = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int32_t __pyx_t_2; + int32_t __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + int __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[16])) + __Pyx_RefNannySetupContext("_build_sequence_section", 0); + __Pyx_TraceStartFunc("_build_sequence_section", __pyx_f[0], 388, 0, 0, 0, __PYX_ERR(0, 388, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":397 + * + * cdef int x + * text = [] # <<<<<<<<<<<<<< + * for x in range(self.ptr.n_targets): + * text.append("@SQ\tSN:{}\tLN:{}\n".format( +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 397, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_text = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":398 + * cdef int x + * text = [] + * for x in range(self.ptr.n_targets): # <<<<<<<<<<<<<< + * text.append("@SQ\tSN:{}\tLN:{}\n".format( + * force_str(self.ptr.target_name[x]), +*/ + __pyx_t_2 = __pyx_v_self->ptr->n_targets; + __pyx_t_3 = __pyx_t_2; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_x = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":399 + * text = [] + * for x in range(self.ptr.n_targets): + * text.append("@SQ\tSN:{}\tLN:{}\n".format( # <<<<<<<<<<<<<< + * force_str(self.ptr.target_name[x]), + * self.ptr.target_len[x])) +*/ + __pyx_t_5 = __pyx_mstate_global->__pyx_kp_u_SQ_SN_LN; + __Pyx_INCREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":400 + * for x in range(self.ptr.n_targets): + * text.append("@SQ\tSN:{}\tLN:{}\n".format( + * force_str(self.ptr.target_name[x]), # <<<<<<<<<<<<<< + * self.ptr.target_len[x])) + * return "".join(text) +*/ + __pyx_t_6 = __Pyx_PyBytes_FromString((__pyx_v_self->ptr->target_name[__pyx_v_x])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 400, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __pyx_f_5pysam_9libcutils_force_str(__pyx_t_6, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 400, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":401 + * text.append("@SQ\tSN:{}\tLN:{}\n".format( + * force_str(self.ptr.target_name[x]), + * self.ptr.target_len[x])) # <<<<<<<<<<<<<< + * return "".join(text) + * +*/ + __pyx_t_6 = __Pyx_PyLong_From_uint32_t((__pyx_v_self->ptr->target_len[__pyx_v_x])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 401, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_5, __pyx_t_7, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_8, (3-__pyx_t_8) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 399, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":399 + * text = [] + * for x in range(self.ptr.n_targets): + * text.append("@SQ\tSN:{}\tLN:{}\n".format( # <<<<<<<<<<<<<< + * force_str(self.ptr.target_name[x]), + * self.ptr.target_len[x])) +*/ + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_text, __pyx_t_1); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(0, 399, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "pysam/libcalignmentfile.pyx":402 + * force_str(self.ptr.target_name[x]), + * self.ptr.target_len[x])) + * return "".join(text) # <<<<<<<<<<<<<< + * + * def to_dict(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__4, __pyx_v_text); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 402, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 28, 0, __PYX_ERR(0, 402, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":388 + * return tuple(t) + * + * def _build_sequence_section(self): # <<<<<<<<<<<<<< + * """return sequence section of header. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 388, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader._build_sequence_section", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_text); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":404 + * return "".join(text) + * + * def to_dict(self): # <<<<<<<<<<<<<< + * """return two-level dictionary with header information from the file. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict, "AlignmentHeader.to_dict(self)\n\nreturn two-level dictionary with header information from the file.\n\nThe first level contains the record (``HD``, ``SQ``, etc) and\nthe second level contains the fields (``VN``, ``LN``, etc).\n\nThe parser is validating and will raise an AssertionError if\nif encounters any record or field tags that are not part of\nthe SAM specification. Use the\n:attr:`pysam.AlignmentFile.text` attribute to get the unparsed\nheader.\n\nThe parsing follows the SAM format specification with the\nexception of the ``CL`` field. This option will consume the\nrest of a header line irrespective of any additional fields.\nThis behaviour has been added to accommodate command line\noptions that contain characters that are not valid field\nseparators.\n\nIf no @SQ entries are within the text section of the header,\nthis will be automatically added from the reference names and\nlengths stored in the binary part of the header."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict = {"to_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("to_dict (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("to_dict", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("to_dict", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_v_result = NULL; + PyObject *__pyx_v_t = NULL; + PyObject *__pyx_v_line = NULL; + PyObject *__pyx_v_fields = NULL; + PyObject *__pyx_v_record = NULL; + PyObject *__pyx_v_x = NULL; + PyObject *__pyx_v_idx = NULL; + PyObject *__pyx_v_field = NULL; + PyObject *__pyx_v_key = NULL; + PyObject *__pyx_v_value = NULL; + PyObject *__pyx_v_sq = NULL; + PyObject *__pyx_v_ref = NULL; + PyObject *__pyx_v_length = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *(*__pyx_t_7)(PyObject *); + int __pyx_t_8; + int __pyx_t_9; + PyObject *__pyx_t_10[5]; + int __pyx_t_11; + Py_ssize_t __pyx_t_12; + PyObject *(*__pyx_t_13)(PyObject *); + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *(*__pyx_t_17)(PyObject *); + PyObject *__pyx_t_18 = NULL; + PyObject *__pyx_t_19 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[17])) + __Pyx_RefNannySetupContext("to_dict", 0); + __Pyx_TraceStartFunc("to_dict", __pyx_f[0], 404, 0, 0, 0, __PYX_ERR(0, 404, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":427 + * lengths stored in the binary part of the header. + * """ + * result = collections.OrderedDict() # <<<<<<<<<<<<<< + * + * # convert to python string +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_collections); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_OrderedDict); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_result = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":430 + * + * # convert to python string + * t = self.__str__() # <<<<<<<<<<<<<< + * for line in t.split("\n"): + * line = line.strip(' \0') +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_str, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 430, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_t = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":431 + * # convert to python string + * t = self.__str__() + * for line in t.split("\n"): # <<<<<<<<<<<<<< + * line = line.strip(' \0') + * if not line: +*/ + __pyx_t_4 = __pyx_v_t; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u__3}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_split, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 431, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_4 = __pyx_t_1; __Pyx_INCREF(__pyx_t_4); + __pyx_t_6 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 431, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 431, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 431, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_1 = __Pyx_PyList_GetItemRef(__pyx_t_4, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 431, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_6)); + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_4, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 431, __pyx_L1_error) + } else { + __pyx_t_1 = __pyx_t_7(__pyx_t_4); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 431, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_line, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":432 + * t = self.__str__() + * for line in t.split("\n"): + * line = line.strip(' \0') # <<<<<<<<<<<<<< + * if not line: + * continue +*/ + __pyx_t_2 = __pyx_v_line; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u__5}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_strip, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 432, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF_SET(__pyx_v_line, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":433 + * for line in t.split("\n"): + * line = line.strip(' \0') + * if not line: # <<<<<<<<<<<<<< + * continue + * assert line.startswith("@"), \ +*/ + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_v_line); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 433, __pyx_L1_error) + __pyx_t_9 = (!__pyx_t_8); + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":434 + * line = line.strip(' \0') + * if not line: + * continue # <<<<<<<<<<<<<< + * assert line.startswith("@"), \ + * "header line without '@': '%s'" % line +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":433 + * for line in t.split("\n"): + * line = line.strip(' \0') + * if not line: # <<<<<<<<<<<<<< + * continue + * assert line.startswith("@"), \ +*/ + } + + /* "pysam/libcalignmentfile.pyx":435 + * if not line: + * continue + * assert line.startswith("@"), \ # <<<<<<<<<<<<<< + * "header line without '@': '%s'" % line + * fields = line[1:].split("\t") +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_2 = __pyx_v_line; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u__6}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_startswith, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 435, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_9)) { + + /* "pysam/libcalignmentfile.pyx":436 + * continue + * assert line.startswith("@"), \ + * "header line without '@': '%s'" % line # <<<<<<<<<<<<<< + * fields = line[1:].split("\t") + * record = fields[0] +*/ + __pyx_t_1 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_header_line_without_s, __pyx_v_line); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 436, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_builtin_AssertionError, __pyx_t_1, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 435, __pyx_L1_error) + } + } + #else + if ((1)); else __PYX_ERR(0, 435, __pyx_L1_error) + #endif + + /* "pysam/libcalignmentfile.pyx":437 + * assert line.startswith("@"), \ + * "header line without '@': '%s'" % line + * fields = line[1:].split("\t") # <<<<<<<<<<<<<< + * record = fields[0] + * assert record in VALID_HEADER_TYPES, \ +*/ + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_line, 1, 0, NULL, NULL, &__pyx_mstate_global->__pyx_slice[0], 1, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 437, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u__2}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_split, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 437, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_XDECREF_SET(__pyx_v_fields, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":438 + * "header line without '@': '%s'" % line + * fields = line[1:].split("\t") + * record = fields[0] # <<<<<<<<<<<<<< + * assert record in VALID_HEADER_TYPES, \ + * "header line with invalid type '%s': '%s'" % (record, line) +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_fields, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 438, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_record, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":439 + * fields = line[1:].split("\t") + * record = fields[0] + * assert record in VALID_HEADER_TYPES, \ # <<<<<<<<<<<<<< + * "header line with invalid type '%s': '%s'" % (record, line) + * +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 439, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_9 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_t_1, Py_EQ)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 439, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_9)) { + + /* "pysam/libcalignmentfile.pyx":440 + * record = fields[0] + * assert record in VALID_HEADER_TYPES, \ + * "header line with invalid type '%s': '%s'" % (record, line) # <<<<<<<<<<<<<< + * + * # treat comments +*/ + __pyx_t_1 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_record), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_FormatSimpleAndDecref(PyObject_Str(__pyx_v_line), __pyx_mstate_global->__pyx_empty_unicode); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_10[0] = __pyx_mstate_global->__pyx_kp_u_header_line_with_invalid_type; + __pyx_t_10[1] = __pyx_t_1; + __pyx_t_10[2] = __pyx_mstate_global->__pyx_kp_u__7; + __pyx_t_10[3] = __pyx_t_3; + __pyx_t_10[4] = __pyx_mstate_global->__pyx_kp_u__8; + __pyx_t_2 = __Pyx_PyUnicode_Join(__pyx_t_10, 5, 31 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_1) + 4 + __Pyx_PyUnicode_GET_LENGTH(__pyx_t_3) + 1, 127 | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_1) | __Pyx_PyUnicode_MAX_CHAR_VALUE(__pyx_t_3)); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 440, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_builtin_AssertionError, __pyx_t_2, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 439, __pyx_L1_error) + } + } + #else + if ((1)); else __PYX_ERR(0, 439, __pyx_L1_error) + #endif + + /* "pysam/libcalignmentfile.pyx":443 + * + * # treat comments + * if record == "CO": # <<<<<<<<<<<<<< + * if record not in result: + * result[record] = [] +*/ + __pyx_t_9 = (__Pyx_PyUnicode_Equals(__pyx_v_record, __pyx_mstate_global->__pyx_n_u_CO, Py_EQ)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 443, __pyx_L1_error) + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":444 + * # treat comments + * if record == "CO": + * if record not in result: # <<<<<<<<<<<<<< + * result[record] = [] + * result[record].append("\t".join( fields[1:])) +*/ + __pyx_t_9 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_v_result, Py_NE)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 444, __pyx_L1_error) + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":445 + * if record == "CO": + * if record not in result: + * result[record] = [] # <<<<<<<<<<<<<< + * result[record].append("\t".join( fields[1:])) + * continue +*/ + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 445, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((PyObject_SetItem(__pyx_v_result, __pyx_v_record, __pyx_t_2) < 0))) __PYX_ERR(0, 445, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":444 + * # treat comments + * if record == "CO": + * if record not in result: # <<<<<<<<<<<<<< + * result[record] = [] + * result[record].append("\t".join( fields[1:])) +*/ + } + + /* "pysam/libcalignmentfile.pyx":446 + * if record not in result: + * result[record] = [] + * result[record].append("\t".join( fields[1:])) # <<<<<<<<<<<<<< + * continue + * # the following is clumsy as generators do not work? +*/ + __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_result, __pyx_v_record); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 446, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_GetSlice(__pyx_v_fields, 1, 0, NULL, NULL, &__pyx_mstate_global->__pyx_slice[0], 1, 0, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 446, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 446, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_11 = __Pyx_PyObject_Append(__pyx_t_2, __pyx_t_1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 446, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":447 + * result[record] = [] + * result[record].append("\t".join( fields[1:])) + * continue # <<<<<<<<<<<<<< + * # the following is clumsy as generators do not work? + * x = {} +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":443 + * + * # treat comments + * if record == "CO": # <<<<<<<<<<<<<< + * if record not in result: + * result[record] = [] +*/ + } + + /* "pysam/libcalignmentfile.pyx":449 + * continue + * # the following is clumsy as generators do not work? + * x = {} # <<<<<<<<<<<<<< + * + * for idx, field in enumerate(fields[1:]): +*/ + __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 449, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_x, ((PyObject*)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":451 + * x = {} + * + * for idx, field in enumerate(fields[1:]): # <<<<<<<<<<<<<< + * if ":" not in field: + * raise ValueError("malformatted header: no ':' in field" ) +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_0); + __pyx_t_1 = __pyx_mstate_global->__pyx_int_0; + __pyx_t_2 = __Pyx_PyObject_GetSlice(__pyx_v_fields, 1, 0, NULL, NULL, &__pyx_mstate_global->__pyx_slice[0], 1, 0, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 451, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); + __pyx_t_12 = 0; + __pyx_t_13 = NULL; + } else { + __pyx_t_12 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 451, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_13 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_3); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 451, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_13)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 451, __pyx_L1_error) + #endif + if (__pyx_t_12 >= __pyx_temp) break; + } + __pyx_t_2 = __Pyx_PyList_GetItemRef(__pyx_t_3, __pyx_t_12); + ++__pyx_t_12; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_3); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 451, __pyx_L1_error) + #endif + if (__pyx_t_12 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_12)); + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_3, __pyx_t_12); + #endif + ++__pyx_t_12; + } + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 451, __pyx_L1_error) + } else { + __pyx_t_2 = __pyx_t_13(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 451, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_field, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_INCREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_AddObjC(__pyx_t_1, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 451, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); + __pyx_t_1 = __pyx_t_2; + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":452 + * + * for idx, field in enumerate(fields[1:]): + * if ":" not in field: # <<<<<<<<<<<<<< + * raise ValueError("malformatted header: no ':' in field" ) + * key, value = field.split(":", 1) +*/ + __pyx_t_9 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_kp_u_, __pyx_v_field, Py_NE)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 452, __pyx_L1_error) + if (unlikely(__pyx_t_9)) { + + /* "pysam/libcalignmentfile.pyx":453 + * for idx, field in enumerate(fields[1:]): + * if ":" not in field: + * raise ValueError("malformatted header: no ':' in field" ) # <<<<<<<<<<<<<< + * key, value = field.split(":", 1) + * if key in ("CL",): +*/ + __pyx_t_14 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_15 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_14, __pyx_mstate_global->__pyx_kp_u_malformatted_header_no_in_field}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_15, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 453, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 453, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":452 + * + * for idx, field in enumerate(fields[1:]): + * if ":" not in field: # <<<<<<<<<<<<<< + * raise ValueError("malformatted header: no ':' in field" ) + * key, value = field.split(":", 1) +*/ + } + + /* "pysam/libcalignmentfile.pyx":454 + * if ":" not in field: + * raise ValueError("malformatted header: no ':' in field" ) + * key, value = field.split(":", 1) # <<<<<<<<<<<<<< + * if key in ("CL",): + * # special treatment for command line +*/ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_field, __pyx_mstate_global->__pyx_n_u_split); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_15 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[0], NULL); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if ((likely(PyTuple_CheckExact(__pyx_t_15))) || (PyList_CheckExact(__pyx_t_15))) { + PyObject* sequence = __pyx_t_15; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 454, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_14 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_14); + } else { + __pyx_t_2 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + __pyx_t_14 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_14); + } + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + #endif + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_16 = PyObject_GetIter(__pyx_t_15); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 454, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_17 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_16); + index = 0; __pyx_t_2 = __pyx_t_17(__pyx_t_16); if (unlikely(!__pyx_t_2)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_2); + index = 1; __pyx_t_14 = __pyx_t_17(__pyx_t_16); if (unlikely(!__pyx_t_14)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_14); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_17(__pyx_t_16), 2) < 0) __PYX_ERR(0, 454, __pyx_L1_error) + __pyx_t_17 = NULL; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + goto __pyx_L12_unpacking_done; + __pyx_L11_unpacking_failed:; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __pyx_t_17 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 454, __pyx_L1_error) + __pyx_L12_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_2); + __pyx_t_2 = 0; + __Pyx_XDECREF_SET(__pyx_v_value, __pyx_t_14); + __pyx_t_14 = 0; + + /* "pysam/libcalignmentfile.pyx":455 + * raise ValueError("malformatted header: no ':' in field" ) + * key, value = field.split(":", 1) + * if key in ("CL",): # <<<<<<<<<<<<<< + * # special treatment for command line + * # statements (CL). These might contain +*/ + __Pyx_INCREF(__pyx_v_key); + __pyx_t_15 = __pyx_v_key; + __pyx_t_9 = (__Pyx_PyUnicode_Equals(__pyx_t_15, __pyx_mstate_global->__pyx_n_u_CL, Py_EQ)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 455, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_8 = __pyx_t_9; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":462 + * # header. Thus, in contravention to the + * # SAM API, consume the rest of the line. + * key, value = "\t".join(fields[idx+1:]).split(":", 1) # <<<<<<<<<<<<<< + * x[key] = KNOWN_HEADER_FIELDS[record][key](value) + * break +*/ + __pyx_t_15 = __Pyx_PyLong_AddObjC(__pyx_v_idx, __pyx_mstate_global->__pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_14 = __Pyx_PyObject_GetSlice(__pyx_v_fields, 0, 0, &__pyx_t_15, NULL, NULL, 0, 0, 1); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__2, __pyx_t_14); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __pyx_t_14 = PyUnicode_Split(((PyObject*)__pyx_t_15), __Pyx_NoneAsNull(__pyx_mstate_global->__pyx_kp_u_), 1); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (1) { + PyObject* sequence = __pyx_t_14; + Py_ssize_t size = __Pyx_PyList_GET_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 462, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_15 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_15); + __pyx_t_2 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_2); + #else + __pyx_t_15 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_2 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 462, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + } + __Pyx_DECREF_SET(__pyx_v_key, __pyx_t_15); + __pyx_t_15 = 0; + __Pyx_DECREF_SET(__pyx_v_value, __pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":463 + * # SAM API, consume the rest of the line. + * key, value = "\t".join(fields[idx+1:]).split(":", 1) + * x[key] = KNOWN_HEADER_FIELDS[record][key](value) # <<<<<<<<<<<<<< + * break + * +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_15, __pyx_mstate_global->__pyx_n_u_KNOWN_HEADER_FIELDS); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_16 = __Pyx_PyObject_GetItem(__pyx_t_15, __pyx_v_record); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_15 = __Pyx_PyObject_GetItem(__pyx_t_16, __pyx_v_key); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_15))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_15); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_15); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_15, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_value}; + __pyx_t_14 = __Pyx_PyObject_FastCall(__pyx_t_15, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + } + if (unlikely((PyDict_SetItem(__pyx_v_x, __pyx_v_key, __pyx_t_14) < 0))) __PYX_ERR(0, 463, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + + /* "pysam/libcalignmentfile.pyx":464 + * key, value = "\t".join(fields[idx+1:]).split(":", 1) + * x[key] = KNOWN_HEADER_FIELDS[record][key](value) + * break # <<<<<<<<<<<<<< + * + * # interpret type of known header record tags, default to str +*/ + goto __pyx_L9_break; + + /* "pysam/libcalignmentfile.pyx":455 + * raise ValueError("malformatted header: no ':' in field" ) + * key, value = field.split(":", 1) + * if key in ("CL",): # <<<<<<<<<<<<<< + * # special treatment for command line + * # statements (CL). These might contain +*/ + } + + /* "pysam/libcalignmentfile.pyx":467 + * + * # interpret type of known header record tags, default to str + * x[key] = KNOWN_HEADER_FIELDS[record].get(key, str)(value) # <<<<<<<<<<<<<< + * + * if VALID_HEADER_TYPES[record] == Mapping: +*/ + __pyx_t_15 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_18, __pyx_mstate_global->__pyx_n_u_KNOWN_HEADER_FIELDS); if (unlikely(!__pyx_t_18)) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_18); + __pyx_t_19 = __Pyx_PyObject_GetItem(__pyx_t_18, __pyx_v_record); if (unlikely(!__pyx_t_19)) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_19); + __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; + __pyx_t_16 = __pyx_t_19; + __Pyx_INCREF(__pyx_t_16); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_16, __pyx_v_key, ((PyObject *)(&PyUnicode_Type))}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_19); __pyx_t_19 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_15); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_15); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_15, __pyx_v_value}; + __pyx_t_14 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + } + if (unlikely((PyDict_SetItem(__pyx_v_x, __pyx_v_key, __pyx_t_14) < 0))) __PYX_ERR(0, 467, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + + /* "pysam/libcalignmentfile.pyx":451 + * x = {} + * + * for idx, field in enumerate(fields[1:]): # <<<<<<<<<<<<<< + * if ":" not in field: + * raise ValueError("malformatted header: no ':' in field" ) +*/ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L14_for_end; + __pyx_L9_break:; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + goto __pyx_L14_for_end; + __pyx_L14_for_end:; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":469 + * x[key] = KNOWN_HEADER_FIELDS[record].get(key, str)(value) + * + * if VALID_HEADER_TYPES[record] == Mapping: # <<<<<<<<<<<<<< + * if record in result: + * raise ValueError( +*/ + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_record); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_14 = PyObject_RichCompare(__pyx_t_3, __pyx_t_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_14); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_14); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 469, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":470 + * + * if VALID_HEADER_TYPES[record] == Mapping: + * if record in result: # <<<<<<<<<<<<<< + * raise ValueError( + * "multiple '%s' lines are not permitted" % record) +*/ + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_v_result, Py_EQ)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 470, __pyx_L1_error) + if (unlikely(__pyx_t_8)) { + + /* "pysam/libcalignmentfile.pyx":471 + * if VALID_HEADER_TYPES[record] == Mapping: + * if record in result: + * raise ValueError( # <<<<<<<<<<<<<< + * "multiple '%s' lines are not permitted" % record) + * +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_3 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":472 + * if record in result: + * raise ValueError( + * "multiple '%s' lines are not permitted" % record) # <<<<<<<<<<<<<< + * + * result[record] = x +*/ + __pyx_t_2 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_multiple_s_lines_are_not_permitt, __pyx_v_record); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 472, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_t_2}; + __pyx_t_14 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 471, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + } + __Pyx_Raise(__pyx_t_14, 0, 0, 0); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __PYX_ERR(0, 471, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":470 + * + * if VALID_HEADER_TYPES[record] == Mapping: + * if record in result: # <<<<<<<<<<<<<< + * raise ValueError( + * "multiple '%s' lines are not permitted" % record) +*/ + } + + /* "pysam/libcalignmentfile.pyx":474 + * "multiple '%s' lines are not permitted" % record) + * + * result[record] = x # <<<<<<<<<<<<<< + * elif VALID_HEADER_TYPES[record] == Sequence: + * if record not in result: result[record] = [] +*/ + if (unlikely((PyObject_SetItem(__pyx_v_result, __pyx_v_record, __pyx_v_x) < 0))) __PYX_ERR(0, 474, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":469 + * x[key] = KNOWN_HEADER_FIELDS[record].get(key, str)(value) + * + * if VALID_HEADER_TYPES[record] == Mapping: # <<<<<<<<<<<<<< + * if record in result: + * raise ValueError( +*/ + goto __pyx_L15; + } + + /* "pysam/libcalignmentfile.pyx":475 + * + * result[record] = x + * elif VALID_HEADER_TYPES[record] == Sequence: # <<<<<<<<<<<<<< + * if record not in result: result[record] = [] + * result[record].append(x) +*/ + __Pyx_GetModuleGlobalName(__pyx_t_14, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_3 = __Pyx_PyObject_GetItem(__pyx_t_14, __pyx_v_record); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_14, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_2 = PyObject_RichCompare(__pyx_t_3, __pyx_t_14, Py_EQ); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 475, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":476 + * result[record] = x + * elif VALID_HEADER_TYPES[record] == Sequence: + * if record not in result: result[record] = [] # <<<<<<<<<<<<<< + * result[record].append(x) + * +*/ + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_v_record, __pyx_v_result, Py_NE)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + if (__pyx_t_8) { + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely((PyObject_SetItem(__pyx_v_result, __pyx_v_record, __pyx_t_2) < 0))) __PYX_ERR(0, 476, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } + + /* "pysam/libcalignmentfile.pyx":477 + * elif VALID_HEADER_TYPES[record] == Sequence: + * if record not in result: result[record] = [] + * result[record].append(x) # <<<<<<<<<<<<<< + * + * # if there are no SQ lines in the header, add the +*/ + __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_v_result, __pyx_v_record); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 477, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_11 = __Pyx_PyObject_Append(__pyx_t_2, __pyx_v_x); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 477, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":475 + * + * result[record] = x + * elif VALID_HEADER_TYPES[record] == Sequence: # <<<<<<<<<<<<<< + * if record not in result: result[record] = [] + * result[record].append(x) +*/ + } + __pyx_L15:; + + /* "pysam/libcalignmentfile.pyx":431 + * # convert to python string + * t = self.__str__() + * for line in t.split("\n"): # <<<<<<<<<<<<<< + * line = line.strip(' \0') + * if not line: +*/ + __pyx_L3_continue:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":488 + * # the SQ information is not part of the textual header + * # and thus are missing from the output. See issue 84. + * if "SQ" not in result: # <<<<<<<<<<<<<< + * sq = [] + * for ref, length in zip(self.references, self.lengths): +*/ + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_v_result, Py_NE)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 488, __pyx_L1_error) + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":489 + * # and thus are missing from the output. See issue 84. + * if "SQ" not in result: + * sq = [] # <<<<<<<<<<<<<< + * for ref, length in zip(self.references, self.lengths): + * sq.append({'LN': length, 'SN': ref }) +*/ + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 489, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_sq = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":490 + * if "SQ" not in result: + * sq = [] + * for ref, length in zip(self.references, self.lengths): # <<<<<<<<<<<<<< + * sq.append({'LN': length, 'SN': ref }) + * result["SQ"] = sq +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_zip); + __pyx_t_14 = __pyx_builtin_zip; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_references); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_lengths); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_t_3, __pyx_t_1}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_14, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { + __pyx_t_14 = __pyx_t_4; __Pyx_INCREF(__pyx_t_14); + __pyx_t_6 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_14 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_14); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 490, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_14))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_14); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 490, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GetItemRef(__pyx_t_14, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_14); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 490, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_14, __pyx_t_6)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_14, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 490, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_7(__pyx_t_14); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 490, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 490, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_3); + } else { + __pyx_t_1 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + } + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_2 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 490, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_17 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); + index = 0; __pyx_t_1 = __pyx_t_17(__pyx_t_2); if (unlikely(!__pyx_t_1)) goto __pyx_L22_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_3 = __pyx_t_17(__pyx_t_2); if (unlikely(!__pyx_t_3)) goto __pyx_L22_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_17(__pyx_t_2), 2) < 0) __PYX_ERR(0, 490, __pyx_L1_error) + __pyx_t_17 = NULL; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + goto __pyx_L23_unpacking_done; + __pyx_L22_unpacking_failed:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_17 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 490, __pyx_L1_error) + __pyx_L23_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_ref, __pyx_t_1); + __pyx_t_1 = 0; + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); + __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":491 + * sq = [] + * for ref, length in zip(self.references, self.lengths): + * sq.append({'LN': length, 'SN': ref }) # <<<<<<<<<<<<<< + * result["SQ"] = sq + * +*/ + __pyx_t_4 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 491, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (PyDict_SetItem(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_LN, __pyx_v_length) < 0) __PYX_ERR(0, 491, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_SN, __pyx_v_ref) < 0) __PYX_ERR(0, 491, __pyx_L1_error) + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_sq, __pyx_t_4); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 491, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":490 + * if "SQ" not in result: + * sq = [] + * for ref, length in zip(self.references, self.lengths): # <<<<<<<<<<<<<< + * sq.append({'LN': length, 'SN': ref }) + * result["SQ"] = sq +*/ + } + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + + /* "pysam/libcalignmentfile.pyx":492 + * for ref, length in zip(self.references, self.lengths): + * sq.append({'LN': length, 'SN': ref }) + * result["SQ"] = sq # <<<<<<<<<<<<<< + * + * return result +*/ + if (unlikely((PyObject_SetItem(__pyx_v_result, __pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_v_sq) < 0))) __PYX_ERR(0, 492, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":488 + * # the SQ information is not part of the textual header + * # and thus are missing from the output. See issue 84. + * if "SQ" not in result: # <<<<<<<<<<<<<< + * sq = [] + * for ref, length in zip(self.references, self.lengths): +*/ + } + + /* "pysam/libcalignmentfile.pyx":494 + * result["SQ"] = sq + * + * return result # <<<<<<<<<<<<<< + * + * def as_dict(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_result); + __pyx_r = __pyx_v_result; + __Pyx_TraceReturnValue(__pyx_r, 205, 0, __PYX_ERR(0, 494, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":404 + * return "".join(text) + * + * def to_dict(self): # <<<<<<<<<<<<<< + * """return two-level dictionary with header information from the file. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_19); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 404, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.to_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_t); + __Pyx_XDECREF(__pyx_v_line); + __Pyx_XDECREF(__pyx_v_fields); + __Pyx_XDECREF(__pyx_v_record); + __Pyx_XDECREF(__pyx_v_x); + __Pyx_XDECREF(__pyx_v_idx); + __Pyx_XDECREF(__pyx_v_field); + __Pyx_XDECREF(__pyx_v_key); + __Pyx_XDECREF(__pyx_v_value); + __Pyx_XDECREF(__pyx_v_sq); + __Pyx_XDECREF(__pyx_v_ref); + __Pyx_XDECREF(__pyx_v_length); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":496 + * return result + * + * def as_dict(self): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`to_dict()` instead""" + * return self.to_dict() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict, "AlignmentHeader.as_dict(self)\n\ndeprecated, use :meth:`to_dict()` instead"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict = {"as_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("as_dict (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("as_dict", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("as_dict", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[18])) + __Pyx_RefNannySetupContext("as_dict", 0); + __Pyx_TraceStartFunc("as_dict", __pyx_f[0], 496, 0, 0, 0, __PYX_ERR(0, 496, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":498 + * def as_dict(self): + * """deprecated, use :meth:`to_dict()` instead""" + * return self.to_dict() # <<<<<<<<<<<<<< + * + * def get_reference_name(self, tid): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 498, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 498, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":496 + * return result + * + * def as_dict(self): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`to_dict()` instead""" + * return self.to_dict() +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 496, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.as_dict", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":500 + * return self.to_dict() + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * if tid == -1: + * return None +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name, "AlignmentHeader.get_reference_name(self, tid)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name = {"get_reference_name", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_tid = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_reference_name (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_tid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 500, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 500, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_reference_name", 0) < 0) __PYX_ERR(0, 500, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_reference_name", 1, 1, 1, i); __PYX_ERR(0, 500, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 500, __pyx_L3_error) + } + __pyx_v_tid = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_reference_name", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 500, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_reference_name", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v_tid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_tid) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[19])) + __Pyx_RefNannySetupContext("get_reference_name", 0); + __Pyx_TraceStartFunc("get_reference_name", __pyx_f[0], 500, 0, 0, 0, __PYX_ERR(0, 500, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":501 + * + * def get_reference_name(self, tid): + * if tid == -1: # <<<<<<<<<<<<<< + * return None + * if not 0 <= tid < self.ptr.n_targets: +*/ + __pyx_t_1 = (__Pyx_PyLong_BoolEqObjC(__pyx_v_tid, __pyx_mstate_global->__pyx_int_neg_1, -1L, 0)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 501, __pyx_L1_error) + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":502 + * def get_reference_name(self, tid): + * if tid == -1: + * return None # <<<<<<<<<<<<<< + * if not 0 <= tid < self.ptr.n_targets: + * raise ValueError("reference_id %i out of range 0<=tid<%i" % +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":501 + * + * def get_reference_name(self, tid): + * if tid == -1: # <<<<<<<<<<<<<< + * return None + * if not 0 <= tid < self.ptr.n_targets: +*/ + } + + /* "pysam/libcalignmentfile.pyx":503 + * if tid == -1: + * return None + * if not 0 <= tid < self.ptr.n_targets: # <<<<<<<<<<<<<< + * raise ValueError("reference_id %i out of range 0<=tid<%i" % + * (tid, self.ptr.n_targets)) +*/ + __pyx_t_2 = PyObject_RichCompare(__pyx_mstate_global->__pyx_int_0, __pyx_v_tid, Py_LE); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 503, __pyx_L1_error) + if (__Pyx_PyObject_IsTrue(__pyx_t_2)) { + __Pyx_DECREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyLong_From_int32_t(__pyx_v_self->ptr->n_targets); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 503, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = PyObject_RichCompare(__pyx_v_tid, __pyx_t_3, Py_LT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 503, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 503, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_4 = (!__pyx_t_1); + if (unlikely(__pyx_t_4)) { + + /* "pysam/libcalignmentfile.pyx":504 + * return None + * if not 0 <= tid < self.ptr.n_targets: + * raise ValueError("reference_id %i out of range 0<=tid<%i" % # <<<<<<<<<<<<<< + * (tid, self.ptr.n_targets)) + * return charptr_to_str(self.ptr.target_name[tid]) +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":505 + * if not 0 <= tid < self.ptr.n_targets: + * raise ValueError("reference_id %i out of range 0<=tid<%i" % + * (tid, self.ptr.n_targets)) # <<<<<<<<<<<<<< + * return charptr_to_str(self.ptr.target_name[tid]) + * +*/ + __pyx_t_6 = __Pyx_PyLong_From_int32_t(__pyx_v_self->ptr->n_targets); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 505, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 505, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_INCREF(__pyx_v_tid); + __Pyx_GIVEREF(__pyx_v_tid); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_tid) != (0)) __PYX_ERR(0, 505, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_6) != (0)) __PYX_ERR(0, 505, __pyx_L1_error); + __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":504 + * return None + * if not 0 <= tid < self.ptr.n_targets: + * raise ValueError("reference_id %i out of range 0<=tid<%i" % # <<<<<<<<<<<<<< + * (tid, self.ptr.n_targets)) + * return charptr_to_str(self.ptr.target_name[tid]) +*/ + __pyx_t_6 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_reference_id_i_out_of_range_0_ti, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 504, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 504, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 504, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":503 + * if tid == -1: + * return None + * if not 0 <= tid < self.ptr.n_targets: # <<<<<<<<<<<<<< + * raise ValueError("reference_id %i out of range 0<=tid<%i" % + * (tid, self.ptr.n_targets)) +*/ + } + + /* "pysam/libcalignmentfile.pyx":506 + * raise ValueError("reference_id %i out of range 0<=tid<%i" % + * (tid, self.ptr.n_targets)) + * return charptr_to_str(self.ptr.target_name[tid]) # <<<<<<<<<<<<<< + * + * def get_reference_length(self, reference): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_v_tid); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 506, __pyx_L1_error) + __pyx_t_2 = __pyx_f_5pysam_9libcutils_charptr_to_str((__pyx_v_self->ptr->target_name[__pyx_t_9]), NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 506, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 24, 0, __PYX_ERR(0, 506, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":500 + * return self.to_dict() + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * if tid == -1: + * return None +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 500, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_reference_name", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":508 + * return charptr_to_str(self.ptr.target_name[tid]) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * cdef int tid = self.get_tid(reference) + * if tid < 0: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length, "AlignmentHeader.get_reference_length(self, reference)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length = {"get_reference_length", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_reference_length (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 508, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 508, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_reference_length", 0) < 0) __PYX_ERR(0, 508, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_reference_length", 1, 1, 1, i); __PYX_ERR(0, 508, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 508, __pyx_L3_error) + } + __pyx_v_reference = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_reference_length", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 508, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_reference_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v_reference); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_reference) { + int __pyx_v_tid; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[20])) + __Pyx_RefNannySetupContext("get_reference_length", 0); + __Pyx_TraceStartFunc("get_reference_length", __pyx_f[0], 508, 0, 0, 0, __PYX_ERR(0, 508, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":509 + * + * def get_reference_length(self, reference): + * cdef int tid = self.get_tid(reference) # <<<<<<<<<<<<<< + * if tid < 0: + * raise KeyError("unknown reference {}".format(reference)) +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_reference}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_tid, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 509, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_4 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 509, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_tid = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":510 + * def get_reference_length(self, reference): + * cdef int tid = self.get_tid(reference) + * if tid < 0: # <<<<<<<<<<<<<< + * raise KeyError("unknown reference {}".format(reference)) + * else: +*/ + __pyx_t_5 = (__pyx_v_tid < 0); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":511 + * cdef int tid = self.get_tid(reference) + * if tid < 0: + * raise KeyError("unknown reference {}".format(reference)) # <<<<<<<<<<<<<< + * else: + * return self.ptr.target_len[tid] +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_KeyError); + __pyx_t_6 = __pyx_builtin_KeyError; + __pyx_t_8 = __pyx_mstate_global->__pyx_kp_u_unknown_reference; + __Pyx_INCREF(__pyx_t_8); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_v_reference}; + __pyx_t_7 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 511, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + } + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_7}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 511, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 511, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":510 + * def get_reference_length(self, reference): + * cdef int tid = self.get_tid(reference) + * if tid < 0: # <<<<<<<<<<<<<< + * raise KeyError("unknown reference {}".format(reference)) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":513 + * raise KeyError("unknown reference {}".format(reference)) + * else: + * return self.ptr.target_len[tid] # <<<<<<<<<<<<<< + * + * def is_valid_tid(self, int tid): +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_uint32_t((__pyx_v_self->ptr->target_len[__pyx_v_tid])); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 513, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 17, 0, __PYX_ERR(0, 513, __pyx_L1_error)); + goto __pyx_L0; + } + + /* "pysam/libcalignmentfile.pyx":508 + * return charptr_to_str(self.ptr.target_name[tid]) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * cdef int tid = self.get_tid(reference) + * if tid < 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 508, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_reference_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":515 + * return self.ptr.target_len[tid] + * + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid, "AlignmentHeader.is_valid_tid(self, int tid)\n\nreturn True if the numerical :term:`tid` is valid; False otherwise.\n\nNote that the unmapped tid code (-1) counts as an invalid."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid = {"is_valid_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + int __pyx_v_tid; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_valid_tid (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_tid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 515, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 515, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "is_valid_tid", 0) < 0) __PYX_ERR(0, 515, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("is_valid_tid", 1, 1, 1, i); __PYX_ERR(0, 515, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 515, __pyx_L3_error) + } + __pyx_v_tid = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_tid == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 515, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("is_valid_tid", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 515, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.is_valid_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v_tid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, int __pyx_v_tid) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[21])) + __Pyx_RefNannySetupContext("is_valid_tid", 0); + __Pyx_TraceStartFunc("is_valid_tid", __pyx_f[0], 515, 0, 0, 0, __PYX_ERR(0, 515, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":521 + * Note that the unmapped tid code (-1) counts as an invalid. + * """ + * return 0 <= tid < self.ptr.n_targets # <<<<<<<<<<<<<< + * + * def get_tid(self, reference): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = (0 <= __pyx_v_tid); + if (__pyx_t_1) { + __pyx_t_1 = (__pyx_v_tid < __pyx_v_self->ptr->n_targets); + } + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 521, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 521, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":515 + * return self.ptr.target_len[tid] + * + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 515, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.is_valid_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":523 + * return 0 <= tid < self.ptr.n_targets + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid, "AlignmentHeader.get_tid(self, reference)\n\nreturn the numerical :term:`tid` corresponding to\n:term:`reference`\n\nreturns -1 if reference is not known."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid = {"get_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_tid (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 523, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 523, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_tid", 0) < 0) __PYX_ERR(0, 523, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_tid", 1, 1, 1, i); __PYX_ERR(0, 523, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 523, __pyx_L3_error) + } + __pyx_v_reference = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_tid", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 523, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v_reference); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_reference) { + int __pyx_v_tid; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + char const *__pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[22])) + __Pyx_RefNannySetupContext("get_tid", 0); + __Pyx_TraceStartFunc("get_tid", __pyx_f[0], 523, 0, 0, 0, __PYX_ERR(0, 523, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_reference); + + /* "pysam/libcalignmentfile.pyx":530 + * returns -1 if reference is not known. + * """ + * reference = force_bytes(reference) # <<<<<<<<<<<<<< + * tid = bam_name2id(self.ptr, reference) + * if tid < -1: +*/ + __pyx_t_1 = __pyx_f_5pysam_9libcutils_force_bytes(__pyx_v_reference, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 530, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF_SET(__pyx_v_reference, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":531 + * """ + * reference = force_bytes(reference) + * tid = bam_name2id(self.ptr, reference) # <<<<<<<<<<<<<< + * if tid < -1: + * raise ValueError('could not parse header') +*/ + __pyx_t_2 = __Pyx_PyObject_AsString(__pyx_v_reference); if (unlikely((!__pyx_t_2) && PyErr_Occurred())) __PYX_ERR(0, 531, __pyx_L1_error) + __pyx_v_tid = bam_name2id(__pyx_v_self->ptr, __pyx_t_2); + + /* "pysam/libcalignmentfile.pyx":532 + * reference = force_bytes(reference) + * tid = bam_name2id(self.ptr, reference) + * if tid < -1: # <<<<<<<<<<<<<< + * raise ValueError('could not parse header') + * return tid +*/ + __pyx_t_3 = (__pyx_v_tid < -1L); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":533 + * tid = bam_name2id(self.ptr, reference) + * if tid < -1: + * raise ValueError('could not parse header') # <<<<<<<<<<<<<< + * return tid + * +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_could_not_parse_header}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 533, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 533, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":532 + * reference = force_bytes(reference) + * tid = bam_name2id(self.ptr, reference) + * if tid < -1: # <<<<<<<<<<<<<< + * raise ValueError('could not parse header') + * return tid +*/ + } + + /* "pysam/libcalignmentfile.pyx":534 + * if tid < -1: + * raise ValueError('could not parse header') + * return tid # <<<<<<<<<<<<<< + * + * def __str__(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_tid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 534, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 19, 0, __PYX_ERR(0, 534, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":523 + * return 0 <= tid < self.ptr.n_targets + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 523, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_reference); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":536 + * return tid + * + * def __str__(self): # <<<<<<<<<<<<<< + * '''string with the full contents of the :term:`sam file` header as a + * string. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_33__str__(PyObject *__pyx_v_self); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__, "AlignmentHeader.__str__(self)\n\nstring with the full contents of the :term:`sam file` header as a\nstring.\n\nIf no @SQ entries are within the text section of the header,\nthis will be automatically added from the reference names and\nlengths stored in the binary part of the header.\n\nSee :attr:`pysam.AlignmentFile.header.to_dict()` to get a parsed\nrepresentation of the header."); +#if CYTHON_UPDATE_DESCRIPTOR_DOC +struct wrapperbase __pyx_wrapperbase_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__; +#endif +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_33__str__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_v_text = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[23])) + __Pyx_RefNannySetupContext("__str__", 0); + __Pyx_TraceStartFunc("__str__", __pyx_f[0], 536, 0, 0, 0, __PYX_ERR(0, 536, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":547 + * representation of the header. + * ''' + * text = from_string_and_size(self.ptr.text, self.ptr.l_text) # <<<<<<<<<<<<<< + * if "@SQ" not in text: + * text += "\n" + self._build_sequence_section() +*/ + __pyx_t_1 = __pyx_f_5pysam_9libcutils_from_string_and_size(__pyx_v_self->ptr->text, __pyx_v_self->ptr->l_text); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 547, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_text = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":548 + * ''' + * text = from_string_and_size(self.ptr.text, self.ptr.l_text) + * if "@SQ" not in text: # <<<<<<<<<<<<<< + * text += "\n" + self._build_sequence_section() + * return text +*/ + __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_kp_u_SQ, __pyx_v_text, Py_NE)); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 548, __pyx_L1_error) + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":549 + * text = from_string_and_size(self.ptr.text, self.ptr.l_text) + * if "@SQ" not in text: + * text += "\n" + self._build_sequence_section() # <<<<<<<<<<<<<< + * return text + * +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_build_sequence_section, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 549, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_3 = PyNumber_Add(__pyx_mstate_global->__pyx_kp_u__3, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 549, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyNumber_InPlaceAdd(__pyx_v_text, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 549, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_text, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":548 + * ''' + * text = from_string_and_size(self.ptr.text, self.ptr.l_text) + * if "@SQ" not in text: # <<<<<<<<<<<<<< + * text += "\n" + self._build_sequence_section() + * return text +*/ + } + + /* "pysam/libcalignmentfile.pyx":550 + * if "@SQ" not in text: + * text += "\n" + self._build_sequence_section() + * return text # <<<<<<<<<<<<<< + * + * # dictionary access methods, for backwards compatibility. +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_text); + __pyx_r = __pyx_v_text; + __Pyx_TraceReturnValue(__pyx_r, 20, 0, __PYX_ERR(0, 550, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":536 + * return tid + * + * def __str__(self): # <<<<<<<<<<<<<< + * '''string with the full contents of the :term:`sam file` header as a + * string. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 536, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_text); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":553 + * + * # dictionary access methods, for backwards compatibility. + * def __setitem__(self, key, value): # <<<<<<<<<<<<<< + * raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()") + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_35__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_35__setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key, PyObject *__pyx_v_value) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_34__setitem__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), ((PyObject *)__pyx_v_key), ((PyObject *)__pyx_v_value)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_34__setitem__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_key, CYTHON_UNUSED PyObject *__pyx_v_value) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[24])) + __Pyx_RefNannySetupContext("__setitem__", 0); + __Pyx_TraceStartFunc("__setitem__", __pyx_f[0], 553, 0, 0, 0, __PYX_ERR(0, 553, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":554 + * # dictionary access methods, for backwards compatibility. + * def __setitem__(self, key, value): + * raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()") # <<<<<<<<<<<<<< + * + * def __getitem__(self, key): +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_TypeError); + __pyx_t_3 = __pyx_builtin_TypeError; + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_AlignmentHeader_does_not_support}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 554, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 554, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":553 + * + * # dictionary access methods, for backwards compatibility. + * def __setitem__(self, key, value): # <<<<<<<<<<<<<< + * raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()") + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 553, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":556 + * raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()") + * + * def __getitem__(self, key): # <<<<<<<<<<<<<< + * return self.to_dict().__getitem__(key) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_37__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_37__getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_key) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_36__getitem__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), ((PyObject *)__pyx_v_key)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_36__getitem__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_key) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[25])) + __Pyx_RefNannySetupContext("__getitem__", 0); + __Pyx_TraceStartFunc("__getitem__", __pyx_f[0], 556, 0, 0, 0, __PYX_ERR(0, 556, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":557 + * + * def __getitem__(self, key): + * return self.to_dict().__getitem__(key) # <<<<<<<<<<<<<< + * + * def items(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 557, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_key}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_getitem, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 557, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 557, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":556 + * raise TypeError("AlignmentHeader does not support item assignment (use header.to_dict()") + * + * def __getitem__(self, key): # <<<<<<<<<<<<<< + * return self.to_dict().__getitem__(key) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 556, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":559 + * return self.to_dict().__getitem__(key) + * + * def items(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_39items(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_38items, "AlignmentHeader.items(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_39items = {"items", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_39items, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_38items}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_39items(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("items (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("items", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("items", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_38items(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_38items(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[26])) + __Pyx_RefNannySetupContext("items", 0); + __Pyx_TraceStartFunc("items", __pyx_f[0], 559, 0, 0, 0, __PYX_ERR(0, 559, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":560 + * + * def items(self): + * return self.to_dict().items() # <<<<<<<<<<<<<< + * + * # PY2 compatibility +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 560, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_items, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 560, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 560, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":559 + * return self.to_dict().__getitem__(key) + * + * def items(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 559, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.items", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":563 + * + * # PY2 compatibility + * def iteritems(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems, "AlignmentHeader.iteritems(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems = {"iteritems", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("iteritems (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("iteritems", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("iteritems", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[27])) + __Pyx_RefNannySetupContext("iteritems", 0); + __Pyx_TraceStartFunc("iteritems", __pyx_f[0], 563, 0, 0, 0, __PYX_ERR(0, 563, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":564 + * # PY2 compatibility + * def iteritems(self): + * return self.to_dict().items() # <<<<<<<<<<<<<< + * + * def keys(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 564, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_items, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 564, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 564, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":563 + * + * # PY2 compatibility + * def iteritems(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 563, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.iteritems", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":566 + * return self.to_dict().items() + * + * def keys(self): # <<<<<<<<<<<<<< + * return self.to_dict().keys() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_43keys(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_42keys, "AlignmentHeader.keys(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_43keys = {"keys", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_43keys, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_42keys}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_43keys(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("keys (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("keys", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("keys", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_42keys(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_42keys(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[28])) + __Pyx_RefNannySetupContext("keys", 0); + __Pyx_TraceStartFunc("keys", __pyx_f[0], 566, 0, 0, 0, __PYX_ERR(0, 566, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":567 + * + * def keys(self): + * return self.to_dict().keys() # <<<<<<<<<<<<<< + * + * def values(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 567, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_keys, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 567, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 567, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":566 + * return self.to_dict().items() + * + * def keys(self): # <<<<<<<<<<<<<< + * return self.to_dict().keys() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 566, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.keys", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":569 + * return self.to_dict().keys() + * + * def values(self): # <<<<<<<<<<<<<< + * return self.to_dict().values() + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_45values(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_44values, "AlignmentHeader.values(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_45values = {"values", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_45values, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_44values}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_45values(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("values (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("values", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("values", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_44values(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_44values(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[29])) + __Pyx_RefNannySetupContext("values", 0); + __Pyx_TraceStartFunc("values", __pyx_f[0], 569, 0, 0, 0, __PYX_ERR(0, 569, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":570 + * + * def values(self): + * return self.to_dict().values() # <<<<<<<<<<<<<< + * + * def get(self, *args): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 570, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_values, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 570, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 570, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":569 + * return self.to_dict().keys() + * + * def values(self): # <<<<<<<<<<<<<< + * return self.to_dict().values() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 569, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.values", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":572 + * return self.to_dict().values() + * + * def get(self, *args): # <<<<<<<<<<<<<< + * return self.to_dict().get(*args) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_47get(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_46get, "AlignmentHeader.get(self, *args)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_47get = {"get", (PyCFunction)(void(*)(void))(PyCFunctionWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_47get, METH_VARARGS|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_46get}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_47get(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_args = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get", __pyx_kwds); return NULL;} + __Pyx_INCREF(__pyx_args); + __pyx_v_args = __pyx_args; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_46get(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v_args); + + /* function exit code */ + __Pyx_DECREF(__pyx_v_args); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_46get(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_args) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[30])) + __Pyx_RefNannySetupContext("get", 0); + __Pyx_TraceStartFunc("get", __pyx_f[0], 572, 0, 0, 0, __PYX_ERR(0, 572, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":573 + * + * def get(self, *args): + * return self.to_dict().get(*args) # <<<<<<<<<<<<<< + * + * def __len__(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 573, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_mstate_global->__pyx_n_u_get); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 573, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_v_args, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 573, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 573, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":572 + * return self.to_dict().values() + * + * def get(self, *args): # <<<<<<<<<<<<<< + * return self.to_dict().get(*args) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 572, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.get", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":575 + * return self.to_dict().get(*args) + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self.to_dict().__len__() + * +*/ + +/* Python wrapper */ +static Py_ssize_t __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + Py_ssize_t __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_48__len__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static Py_ssize_t __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_48__len__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + Py_ssize_t __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[31])) + __Pyx_RefNannySetupContext("__len__", 0); + __Pyx_TraceStartFunc("__len__", __pyx_f[0], 575, 0, 0, 0, __PYX_ERR(0, 575, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":576 + * + * def __len__(self): + * return self.to_dict().__len__() # <<<<<<<<<<<<<< + * + * def __contains__(self, key): +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 576, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_len, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 576, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_t_1); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 576, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_6; + __Pyx_TraceReturnCValue(__pyx_r, PyLong_FromSsize_t, 1, 0, __PYX_ERR(0, 576, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":575 + * return self.to_dict().get(*args) + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self.to_dict().__len__() + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 575, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__len__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":578 + * return self.to_dict().__len__() + * + * def __contains__(self, key): # <<<<<<<<<<<<<< + * return self.to_dict().__contains__(key) + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_51__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_key); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_51__contains__(PyObject *__pyx_v_self, PyObject *__pyx_v_key) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__contains__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_50__contains__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), ((PyObject *)__pyx_v_key)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_50__contains__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, PyObject *__pyx_v_key) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[32])) + __Pyx_RefNannySetupContext("__contains__", 0); + __Pyx_TraceStartFunc("__contains__", __pyx_f[0], 578, 0, 0, 0, __PYX_ERR(0, 578, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":579 + * + * def __contains__(self, key): + * return self.to_dict().__contains__(key) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_to_dict, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_key}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_contains, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 579, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_6 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 579, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_6; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 1, 0, __PYX_ERR(0, 579, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":578 + * return self.to_dict().__len__() + * + * def __contains__(self, key): # <<<<<<<<<<<<<< + * return self.to_dict().__contains__(key) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 578, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__contains__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__, "AlignmentHeader.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[33])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__, "AlignmentHeader.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[34])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentHeader.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":738 + * """ + * + * def __cinit__(self, *args, **kwargs): # <<<<<<<<<<<<<< + * self.htsfile = NULL + * self.filename = None +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v_args = 0; + PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return -1; + if (__pyx_kwds_len > 0) { + if (unlikely(__Pyx_CheckKeywordStrings("__cinit__", __pyx_kwds) == -1)) return -1; + __pyx_v_kwargs = __Pyx_KwargsAsDict_VARARGS(__pyx_kwds, __pyx_kwvalues); + if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + } else { + __pyx_v_kwargs = PyDict_New(); + if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + } + __Pyx_INCREF(__pyx_args); + __pyx_v_args = __pyx_args; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_args, __pyx_v_kwargs); + + /* function exit code */ + __Pyx_DECREF(__pyx_v_args); + __Pyx_DECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[35])) + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 738, 0, 0, 0, __PYX_ERR(0, 738, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_args); + + /* "pysam/libcalignmentfile.pyx":739 + * + * def __cinit__(self, *args, **kwargs): + * self.htsfile = NULL # <<<<<<<<<<<<<< + * self.filename = None + * self.mode = None +*/ + __pyx_v_self->__pyx_base.htsfile = NULL; + + /* "pysam/libcalignmentfile.pyx":740 + * def __cinit__(self, *args, **kwargs): + * self.htsfile = NULL + * self.filename = None # <<<<<<<<<<<<<< + * self.mode = None + * self.threads = 1 +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.filename); + __Pyx_DECREF(__pyx_v_self->__pyx_base.filename); + __pyx_v_self->__pyx_base.filename = Py_None; + + /* "pysam/libcalignmentfile.pyx":741 + * self.htsfile = NULL + * self.filename = None + * self.mode = None # <<<<<<<<<<<<<< + * self.threads = 1 + * self.is_stream = False +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.mode); + __Pyx_DECREF(__pyx_v_self->__pyx_base.mode); + __pyx_v_self->__pyx_base.mode = Py_None; + + /* "pysam/libcalignmentfile.pyx":742 + * self.filename = None + * self.mode = None + * self.threads = 1 # <<<<<<<<<<<<<< + * self.is_stream = False + * self.is_remote = False +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_1); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_1); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.threads); + __Pyx_DECREF(__pyx_v_self->__pyx_base.threads); + __pyx_v_self->__pyx_base.threads = __pyx_mstate_global->__pyx_int_1; + + /* "pysam/libcalignmentfile.pyx":743 + * self.mode = None + * self.threads = 1 + * self.is_stream = False # <<<<<<<<<<<<<< + * self.is_remote = False + * self.index = NULL +*/ + __pyx_v_self->__pyx_base.is_stream = 0; + + /* "pysam/libcalignmentfile.pyx":744 + * self.threads = 1 + * self.is_stream = False + * self.is_remote = False # <<<<<<<<<<<<<< + * self.index = NULL + * +*/ + __pyx_v_self->__pyx_base.is_remote = 0; + + /* "pysam/libcalignmentfile.pyx":745 + * self.is_stream = False + * self.is_remote = False + * self.index = NULL # <<<<<<<<<<<<<< + * + * if "filename" in kwargs: +*/ + __pyx_v_self->index = NULL; + + /* "pysam/libcalignmentfile.pyx":747 + * self.index = NULL + * + * if "filename" in kwargs: # <<<<<<<<<<<<<< + * args = [kwargs["filename"]] + * del kwargs["filename"] +*/ + __pyx_t_1 = (__Pyx_PyDict_ContainsTF(__pyx_mstate_global->__pyx_n_u_filename, __pyx_v_kwargs, Py_EQ)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 747, __pyx_L1_error) + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":748 + * + * if "filename" in kwargs: + * args = [kwargs["filename"]] # <<<<<<<<<<<<<< + * del kwargs["filename"] + * +*/ + __pyx_t_2 = __Pyx_PyDict_GetItem(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_filename); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyList_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyList_SET_ITEM(__pyx_t_3, 0, __pyx_t_2) != (0)) __PYX_ERR(0, 748, __pyx_L1_error); + __pyx_t_2 = 0; + __Pyx_DECREF_SET(__pyx_v_args, __pyx_t_3); + __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":749 + * if "filename" in kwargs: + * args = [kwargs["filename"]] + * del kwargs["filename"] # <<<<<<<<<<<<<< + * + * self._open(*args, **kwargs) +*/ + if (unlikely((PyDict_DelItem(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_filename) < 0))) __PYX_ERR(0, 749, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":747 + * self.index = NULL + * + * if "filename" in kwargs: # <<<<<<<<<<<<<< + * args = [kwargs["filename"]] + * del kwargs["filename"] +*/ + } + + /* "pysam/libcalignmentfile.pyx":751 + * del kwargs["filename"] + * + * self._open(*args, **kwargs) # <<<<<<<<<<<<<< + * + * # allocate memory for iterator +*/ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_open); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 751, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PySequence_Tuple(__pyx_v_args); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 751, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = PyDict_Copy(__pyx_v_kwargs); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 751, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 751, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":754 + * + * # allocate memory for iterator + * self.b = calloc(1, sizeof(bam1_t)) # <<<<<<<<<<<<<< + * if self.b == NULL: + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) +*/ + __pyx_v_self->b = ((bam1_t *)calloc(1, (sizeof(bam1_t)))); + + /* "pysam/libcalignmentfile.pyx":755 + * # allocate memory for iterator + * self.b = calloc(1, sizeof(bam1_t)) + * if self.b == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) + * +*/ + __pyx_t_1 = (__pyx_v_self->b == NULL); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":756 + * self.b = calloc(1, sizeof(bam1_t)) + * if self.b == NULL: + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) # <<<<<<<<<<<<<< + * + * def has_index(self): +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_2 = __pyx_builtin_MemoryError; + __pyx_t_6 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_memory_of_siz; + __Pyx_INCREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_FromSize_t((sizeof(bam1_t))); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 756, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_t_7}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 756, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 756, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 756, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":755 + * # allocate memory for iterator + * self.b = calloc(1, sizeof(bam1_t)) + * if self.b == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":738 + * """ + * + * def __cinit__(self, *args, **kwargs): # <<<<<<<<<<<<<< + * self.htsfile = NULL + * self.filename = None +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 738, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 738, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_args); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":758 + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) + * + * def has_index(self): # <<<<<<<<<<<<<< + * """return true if htsfile has an existing (and opened) index. + * """ +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_3has_index(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_2has_index, "AlignmentFile.has_index(self)\n\nreturn true if htsfile has an existing (and opened) index.\n "); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_3has_index = {"has_index", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_3has_index, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_2has_index}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_3has_index(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("has_index (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("has_index", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("has_index", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_2has_index(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_2has_index(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[36])) + __Pyx_RefNannySetupContext("has_index", 0); + __Pyx_TraceStartFunc("has_index", __pyx_f[0], 758, 0, 0, 0, __PYX_ERR(0, 758, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":761 + * """return true if htsfile has an existing (and opened) index. + * """ + * return self.index != NULL # <<<<<<<<<<<<<< + * + * def check_index(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyBool_FromLong((__pyx_v_self->index != NULL)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 761, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 761, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":758 + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) + * + * def has_index(self): # <<<<<<<<<<<<<< + * """return true if htsfile has an existing (and opened) index. + * """ +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 758, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.has_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":763 + * return self.index != NULL + * + * def check_index(self): # <<<<<<<<<<<<<< + * """return True if index is present. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_5check_index(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_4check_index, "AlignmentFile.check_index(self)\n\nreturn True if index is present.\n\nRaises\n------\n\nAttributeError\n if htsfile is :term:`SAM` formatted and thus has no index.\n\nValueError\n if htsfile is closed or index could not be opened."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_5check_index = {"check_index", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_5check_index, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_4check_index}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_5check_index(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("check_index (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("check_index", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("check_index", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4check_index(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4check_index(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[37])) + __Pyx_RefNannySetupContext("check_index", 0); + __Pyx_TraceStartFunc("check_index", __pyx_f[0], 763, 0, 0, 0, __PYX_ERR(0, 763, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":776 + * """ + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * if not self.is_bam and not self.is_cram: +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 776, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 776, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":777 + * + * if not self.is_open: + * raise ValueError("I/O operation on closed file") # <<<<<<<<<<<<<< + * if not self.is_bam and not self.is_cram: + * raise AttributeError( +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 777, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 777, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":776 + * """ + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * if not self.is_bam and not self.is_cram: +*/ + } + + /* "pysam/libcalignmentfile.pyx":778 + * if not self.is_open: + * raise ValueError("I/O operation on closed file") + * if not self.is_bam and not self.is_cram: # <<<<<<<<<<<<<< + * raise AttributeError( + * "AlignmentFile.mapped only available in bam files") +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 778, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 778, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = (!__pyx_t_2); + if (__pyx_t_7) { + } else { + __pyx_t_3 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 778, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 778, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = (!__pyx_t_7); + __pyx_t_3 = __pyx_t_2; + __pyx_L5_bool_binop_done:; + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":779 + * raise ValueError("I/O operation on closed file") + * if not self.is_bam and not self.is_cram: + * raise AttributeError( # <<<<<<<<<<<<<< + * "AlignmentFile.mapped only available in bam files") + * if self.index == NULL: +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_AttributeError); + __pyx_t_4 = __pyx_builtin_AttributeError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_AlignmentFile_mapped_only_availa}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 779, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 779, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":778 + * if not self.is_open: + * raise ValueError("I/O operation on closed file") + * if not self.is_bam and not self.is_cram: # <<<<<<<<<<<<<< + * raise AttributeError( + * "AlignmentFile.mapped only available in bam files") +*/ + } + + /* "pysam/libcalignmentfile.pyx":781 + * raise AttributeError( + * "AlignmentFile.mapped only available in bam files") + * if self.index == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "mapping information not recorded in index " +*/ + __pyx_t_3 = (__pyx_v_self->index == NULL); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":782 + * "AlignmentFile.mapped only available in bam files") + * if self.index == NULL: + * raise ValueError( # <<<<<<<<<<<<<< + * "mapping information not recorded in index " + * "or index not available") +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_mapping_information_not_recorded}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 782, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 782, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":781 + * raise AttributeError( + * "AlignmentFile.mapped only available in bam files") + * if self.index == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "mapping information not recorded in index " +*/ + } + + /* "pysam/libcalignmentfile.pyx":785 + * "mapping information not recorded in index " + * "or index not available") + * return True # <<<<<<<<<<<<<< + * + * def _open(self, +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_True); + __pyx_r = Py_True; + __Pyx_TraceReturnValue(__pyx_r, 30, 0, __PYX_ERR(0, 785, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":763 + * return self.index != NULL + * + * def check_index(self): # <<<<<<<<<<<<<< + * """return True if index is present. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 763, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.check_index", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":787 + * return True + * + * def _open(self, # <<<<<<<<<<<<<< + * filepath_or_object, + * mode=None, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_6_open, "AlignmentFile._open(self, filepath_or_object, mode=None, AlignmentFile template=None, reference_names=None, reference_lengths=None, reference_filename=None, text=None, header=None, port=None, add_sq_text=True, add_sam_header=True, check_header=True, check_sq=True, index_filename=None, filepath_index=None, require_index=False, referencenames=None, referencelengths=None, duplicate_filehandle=True, ignore_truncation=False, format_options=None, threads=1)\n\nopen a sam, bam or cram formatted file.\n\nIf _open is called on an existing file, the current file\nwill be closed and a new file will be opened."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_7_open = {"_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_6_open}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7_open(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_filepath_or_object = 0; + PyObject *__pyx_v_mode = 0; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_template = 0; + PyObject *__pyx_v_reference_names = 0; + PyObject *__pyx_v_reference_lengths = 0; + PyObject *__pyx_v_reference_filename = 0; + PyObject *__pyx_v_text = 0; + PyObject *__pyx_v_header = 0; + CYTHON_UNUSED PyObject *__pyx_v_port = 0; + PyObject *__pyx_v_add_sq_text = 0; + PyObject *__pyx_v_add_sam_header = 0; + CYTHON_UNUSED PyObject *__pyx_v_check_header = 0; + PyObject *__pyx_v_check_sq = 0; + PyObject *__pyx_v_index_filename = 0; + PyObject *__pyx_v_filepath_index = 0; + PyObject *__pyx_v_require_index = 0; + PyObject *__pyx_v_referencenames = 0; + PyObject *__pyx_v_referencelengths = 0; + PyObject *__pyx_v_duplicate_filehandle = 0; + PyObject *__pyx_v_ignore_truncation = 0; + PyObject *__pyx_v_format_options = 0; + PyObject *__pyx_v_threads = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("_open (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_filepath_or_object,&__pyx_mstate_global->__pyx_n_u_mode,&__pyx_mstate_global->__pyx_n_u_template,&__pyx_mstate_global->__pyx_n_u_reference_names,&__pyx_mstate_global->__pyx_n_u_reference_lengths,&__pyx_mstate_global->__pyx_n_u_reference_filename,&__pyx_mstate_global->__pyx_n_u_text,&__pyx_mstate_global->__pyx_n_u_header,&__pyx_mstate_global->__pyx_n_u_port,&__pyx_mstate_global->__pyx_n_u_add_sq_text,&__pyx_mstate_global->__pyx_n_u_add_sam_header,&__pyx_mstate_global->__pyx_n_u_check_header,&__pyx_mstate_global->__pyx_n_u_check_sq,&__pyx_mstate_global->__pyx_n_u_index_filename,&__pyx_mstate_global->__pyx_n_u_filepath_index,&__pyx_mstate_global->__pyx_n_u_require_index,&__pyx_mstate_global->__pyx_n_u_referencenames,&__pyx_mstate_global->__pyx_n_u_referencelengths,&__pyx_mstate_global->__pyx_n_u_duplicate_filehandle,&__pyx_mstate_global->__pyx_n_u_ignore_truncation,&__pyx_mstate_global->__pyx_n_u_format_options,&__pyx_mstate_global->__pyx_n_u_threads,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 787, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 22: + values[21] = __Pyx_ArgRef_FASTCALL(__pyx_args, 21); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[21])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 21: + values[20] = __Pyx_ArgRef_FASTCALL(__pyx_args, 20); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[20])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 20: + values[19] = __Pyx_ArgRef_FASTCALL(__pyx_args, 19); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[19])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 19: + values[18] = __Pyx_ArgRef_FASTCALL(__pyx_args, 18); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[18])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 18: + values[17] = __Pyx_ArgRef_FASTCALL(__pyx_args, 17); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[17])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 17: + values[16] = __Pyx_ArgRef_FASTCALL(__pyx_args, 16); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[16])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 16: + values[15] = __Pyx_ArgRef_FASTCALL(__pyx_args, 15); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[15])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 15: + values[14] = __Pyx_ArgRef_FASTCALL(__pyx_args, 14); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[14])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 14: + values[13] = __Pyx_ArgRef_FASTCALL(__pyx_args, 13); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[13])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 13: + values[12] = __Pyx_ArgRef_FASTCALL(__pyx_args, 12); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[12])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 12: + values[11] = __Pyx_ArgRef_FASTCALL(__pyx_args, 11); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[11])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 11: + values[10] = __Pyx_ArgRef_FASTCALL(__pyx_args, 10); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[10])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 10: + values[9] = __Pyx_ArgRef_FASTCALL(__pyx_args, 9); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[9])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 9: + values[8] = __Pyx_ArgRef_FASTCALL(__pyx_args, 8); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[8])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "_open", 0) < 0) __PYX_ERR(0, 787, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":789 + * def _open(self, + * filepath_or_object, + * mode=None, # <<<<<<<<<<<<<< + * AlignmentFile template=None, + * reference_names=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":790 + * filepath_or_object, + * mode=None, + * AlignmentFile template=None, # <<<<<<<<<<<<<< + * reference_names=None, + * reference_lengths=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef((PyObject *)((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":791 + * mode=None, + * AlignmentFile template=None, + * reference_names=None, # <<<<<<<<<<<<<< + * reference_lengths=None, + * reference_filename=None, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":792 + * AlignmentFile template=None, + * reference_names=None, + * reference_lengths=None, # <<<<<<<<<<<<<< + * reference_filename=None, + * text=None, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":793 + * reference_names=None, + * reference_lengths=None, + * reference_filename=None, # <<<<<<<<<<<<<< + * text=None, + * header=None, +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":794 + * reference_lengths=None, + * reference_filename=None, + * text=None, # <<<<<<<<<<<<<< + * header=None, + * port=None, +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":795 + * reference_filename=None, + * text=None, + * header=None, # <<<<<<<<<<<<<< + * port=None, + * add_sq_text=True, +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":796 + * text=None, + * header=None, + * port=None, # <<<<<<<<<<<<<< + * add_sq_text=True, + * add_sam_header=True, +*/ + if (!values[8]) values[8] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":797 + * header=None, + * port=None, + * add_sq_text=True, # <<<<<<<<<<<<<< + * add_sam_header=True, + * check_header=True, +*/ + if (!values[9]) values[9] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":798 + * port=None, + * add_sq_text=True, + * add_sam_header=True, # <<<<<<<<<<<<<< + * check_header=True, + * check_sq=True, +*/ + if (!values[10]) values[10] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":799 + * add_sq_text=True, + * add_sam_header=True, + * check_header=True, # <<<<<<<<<<<<<< + * check_sq=True, + * index_filename=None, +*/ + if (!values[11]) values[11] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":800 + * add_sam_header=True, + * check_header=True, + * check_sq=True, # <<<<<<<<<<<<<< + * index_filename=None, + * filepath_index=None, +*/ + if (!values[12]) values[12] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":801 + * check_header=True, + * check_sq=True, + * index_filename=None, # <<<<<<<<<<<<<< + * filepath_index=None, + * require_index=False, +*/ + if (!values[13]) values[13] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":802 + * check_sq=True, + * index_filename=None, + * filepath_index=None, # <<<<<<<<<<<<<< + * require_index=False, + * referencenames=None, +*/ + if (!values[14]) values[14] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":803 + * index_filename=None, + * filepath_index=None, + * require_index=False, # <<<<<<<<<<<<<< + * referencenames=None, + * referencelengths=None, +*/ + if (!values[15]) values[15] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":804 + * filepath_index=None, + * require_index=False, + * referencenames=None, # <<<<<<<<<<<<<< + * referencelengths=None, + * duplicate_filehandle=True, +*/ + if (!values[16]) values[16] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":805 + * require_index=False, + * referencenames=None, + * referencelengths=None, # <<<<<<<<<<<<<< + * duplicate_filehandle=True, + * ignore_truncation=False, +*/ + if (!values[17]) values[17] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":806 + * referencenames=None, + * referencelengths=None, + * duplicate_filehandle=True, # <<<<<<<<<<<<<< + * ignore_truncation=False, + * format_options=None, +*/ + if (!values[18]) values[18] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":807 + * referencelengths=None, + * duplicate_filehandle=True, + * ignore_truncation=False, # <<<<<<<<<<<<<< + * format_options=None, + * threads=1): +*/ + if (!values[19]) values[19] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":808 + * duplicate_filehandle=True, + * ignore_truncation=False, + * format_options=None, # <<<<<<<<<<<<<< + * threads=1): + * '''open a sam, bam or cram formatted file. +*/ + if (!values[20]) values[20] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[21]) values[21] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_int_1)); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("_open", 0, 1, 22, i); __PYX_ERR(0, 787, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 22: + values[21] = __Pyx_ArgRef_FASTCALL(__pyx_args, 21); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[21])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 21: + values[20] = __Pyx_ArgRef_FASTCALL(__pyx_args, 20); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[20])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 20: + values[19] = __Pyx_ArgRef_FASTCALL(__pyx_args, 19); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[19])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 19: + values[18] = __Pyx_ArgRef_FASTCALL(__pyx_args, 18); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[18])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 18: + values[17] = __Pyx_ArgRef_FASTCALL(__pyx_args, 17); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[17])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 17: + values[16] = __Pyx_ArgRef_FASTCALL(__pyx_args, 16); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[16])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 16: + values[15] = __Pyx_ArgRef_FASTCALL(__pyx_args, 15); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[15])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 15: + values[14] = __Pyx_ArgRef_FASTCALL(__pyx_args, 14); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[14])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 14: + values[13] = __Pyx_ArgRef_FASTCALL(__pyx_args, 13); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[13])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 13: + values[12] = __Pyx_ArgRef_FASTCALL(__pyx_args, 12); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[12])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 12: + values[11] = __Pyx_ArgRef_FASTCALL(__pyx_args, 11); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[11])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 11: + values[10] = __Pyx_ArgRef_FASTCALL(__pyx_args, 10); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[10])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 10: + values[9] = __Pyx_ArgRef_FASTCALL(__pyx_args, 9); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[9])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 9: + values[8] = __Pyx_ArgRef_FASTCALL(__pyx_args, 8); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[8])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 787, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 787, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + + /* "pysam/libcalignmentfile.pyx":789 + * def _open(self, + * filepath_or_object, + * mode=None, # <<<<<<<<<<<<<< + * AlignmentFile template=None, + * reference_names=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":790 + * filepath_or_object, + * mode=None, + * AlignmentFile template=None, # <<<<<<<<<<<<<< + * reference_names=None, + * reference_lengths=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef((PyObject *)((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":791 + * mode=None, + * AlignmentFile template=None, + * reference_names=None, # <<<<<<<<<<<<<< + * reference_lengths=None, + * reference_filename=None, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":792 + * AlignmentFile template=None, + * reference_names=None, + * reference_lengths=None, # <<<<<<<<<<<<<< + * reference_filename=None, + * text=None, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":793 + * reference_names=None, + * reference_lengths=None, + * reference_filename=None, # <<<<<<<<<<<<<< + * text=None, + * header=None, +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":794 + * reference_lengths=None, + * reference_filename=None, + * text=None, # <<<<<<<<<<<<<< + * header=None, + * port=None, +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":795 + * reference_filename=None, + * text=None, + * header=None, # <<<<<<<<<<<<<< + * port=None, + * add_sq_text=True, +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":796 + * text=None, + * header=None, + * port=None, # <<<<<<<<<<<<<< + * add_sq_text=True, + * add_sam_header=True, +*/ + if (!values[8]) values[8] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":797 + * header=None, + * port=None, + * add_sq_text=True, # <<<<<<<<<<<<<< + * add_sam_header=True, + * check_header=True, +*/ + if (!values[9]) values[9] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":798 + * port=None, + * add_sq_text=True, + * add_sam_header=True, # <<<<<<<<<<<<<< + * check_header=True, + * check_sq=True, +*/ + if (!values[10]) values[10] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":799 + * add_sq_text=True, + * add_sam_header=True, + * check_header=True, # <<<<<<<<<<<<<< + * check_sq=True, + * index_filename=None, +*/ + if (!values[11]) values[11] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":800 + * add_sam_header=True, + * check_header=True, + * check_sq=True, # <<<<<<<<<<<<<< + * index_filename=None, + * filepath_index=None, +*/ + if (!values[12]) values[12] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":801 + * check_header=True, + * check_sq=True, + * index_filename=None, # <<<<<<<<<<<<<< + * filepath_index=None, + * require_index=False, +*/ + if (!values[13]) values[13] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":802 + * check_sq=True, + * index_filename=None, + * filepath_index=None, # <<<<<<<<<<<<<< + * require_index=False, + * referencenames=None, +*/ + if (!values[14]) values[14] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":803 + * index_filename=None, + * filepath_index=None, + * require_index=False, # <<<<<<<<<<<<<< + * referencenames=None, + * referencelengths=None, +*/ + if (!values[15]) values[15] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":804 + * filepath_index=None, + * require_index=False, + * referencenames=None, # <<<<<<<<<<<<<< + * referencelengths=None, + * duplicate_filehandle=True, +*/ + if (!values[16]) values[16] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":805 + * require_index=False, + * referencenames=None, + * referencelengths=None, # <<<<<<<<<<<<<< + * duplicate_filehandle=True, + * ignore_truncation=False, +*/ + if (!values[17]) values[17] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":806 + * referencenames=None, + * referencelengths=None, + * duplicate_filehandle=True, # <<<<<<<<<<<<<< + * ignore_truncation=False, + * format_options=None, +*/ + if (!values[18]) values[18] = __Pyx_NewRef(((PyObject *)Py_True)); + + /* "pysam/libcalignmentfile.pyx":807 + * referencelengths=None, + * duplicate_filehandle=True, + * ignore_truncation=False, # <<<<<<<<<<<<<< + * format_options=None, + * threads=1): +*/ + if (!values[19]) values[19] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":808 + * duplicate_filehandle=True, + * ignore_truncation=False, + * format_options=None, # <<<<<<<<<<<<<< + * threads=1): + * '''open a sam, bam or cram formatted file. +*/ + if (!values[20]) values[20] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[21]) values[21] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_int_1)); + } + __pyx_v_filepath_or_object = values[0]; + __pyx_v_mode = values[1]; + __pyx_v_template = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[2]); + __pyx_v_reference_names = values[3]; + __pyx_v_reference_lengths = values[4]; + __pyx_v_reference_filename = values[5]; + __pyx_v_text = values[6]; + __pyx_v_header = values[7]; + __pyx_v_port = values[8]; + __pyx_v_add_sq_text = values[9]; + __pyx_v_add_sam_header = values[10]; + __pyx_v_check_header = values[11]; + __pyx_v_check_sq = values[12]; + __pyx_v_index_filename = values[13]; + __pyx_v_filepath_index = values[14]; + __pyx_v_require_index = values[15]; + __pyx_v_referencenames = values[16]; + __pyx_v_referencelengths = values[17]; + __pyx_v_duplicate_filehandle = values[18]; + __pyx_v_ignore_truncation = values[19]; + __pyx_v_format_options = values[20]; + __pyx_v_threads = values[21]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("_open", 0, 1, 22, __pyx_nargs); __PYX_ERR(0, 787, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile._open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_template), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "template", 0))) __PYX_ERR(0, 790, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6_open(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_filepath_or_object, __pyx_v_mode, __pyx_v_template, __pyx_v_reference_names, __pyx_v_reference_lengths, __pyx_v_reference_filename, __pyx_v_text, __pyx_v_header, __pyx_v_port, __pyx_v_add_sq_text, __pyx_v_add_sam_header, __pyx_v_check_header, __pyx_v_check_sq, __pyx_v_index_filename, __pyx_v_filepath_index, __pyx_v_require_index, __pyx_v_referencenames, __pyx_v_referencelengths, __pyx_v_duplicate_filehandle, __pyx_v_ignore_truncation, __pyx_v_format_options, __pyx_v_threads); + + /* "pysam/libcalignmentfile.pyx":787 + * return True + * + * def _open(self, # <<<<<<<<<<<<<< + * filepath_or_object, + * mode=None, +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6_open(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_filepath_or_object, PyObject *__pyx_v_mode, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_template, PyObject *__pyx_v_reference_names, PyObject *__pyx_v_reference_lengths, PyObject *__pyx_v_reference_filename, PyObject *__pyx_v_text, PyObject *__pyx_v_header, CYTHON_UNUSED PyObject *__pyx_v_port, PyObject *__pyx_v_add_sq_text, PyObject *__pyx_v_add_sam_header, CYTHON_UNUSED PyObject *__pyx_v_check_header, PyObject *__pyx_v_check_sq, PyObject *__pyx_v_index_filename, PyObject *__pyx_v_filepath_index, PyObject *__pyx_v_require_index, PyObject *__pyx_v_referencenames, PyObject *__pyx_v_referencelengths, PyObject *__pyx_v_duplicate_filehandle, PyObject *__pyx_v_ignore_truncation, PyObject *__pyx_v_format_options, PyObject *__pyx_v_threads) { + char *__pyx_v_cfilename; + char *__pyx_v_creference_filename; + char *__pyx_v_cindexname; + CYTHON_UNUSED char *__pyx_v_cmode; + bam_hdr_t *__pyx_v_hdr; + int __pyx_v_ret; + PyObject *__pyx_v_filename = NULL; + CYTHON_UNUSED PyObject *__pyx_v_bfile_name = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + char *__pyx_t_10; + int __pyx_t_11; + htsFile *__pyx_t_12; + struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno __pyx_t_13; + PyObject *__pyx_t_14 = NULL; + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + Py_ssize_t __pyx_t_17; + char const *__pyx_t_18; + bam_hdr_t *__pyx_t_19; + int64_t __pyx_t_20; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[38])) + __Pyx_RefNannySetupContext("_open", 0); + __Pyx_TraceStartFunc("_open", __pyx_f[0], 787, 0, 0, 0, __PYX_ERR(0, 787, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_mode); + __Pyx_INCREF(__pyx_v_reference_names); + __Pyx_INCREF(__pyx_v_reference_lengths); + __Pyx_INCREF(__pyx_v_reference_filename); + + /* "pysam/libcalignmentfile.pyx":816 + * + * ''' + * cdef char *cfilename = NULL # <<<<<<<<<<<<<< + * cdef char *creference_filename = NULL + * cdef char *cindexname = NULL +*/ + __pyx_v_cfilename = NULL; + + /* "pysam/libcalignmentfile.pyx":817 + * ''' + * cdef char *cfilename = NULL + * cdef char *creference_filename = NULL # <<<<<<<<<<<<<< + * cdef char *cindexname = NULL + * cdef char *cmode = NULL +*/ + __pyx_v_creference_filename = NULL; + + /* "pysam/libcalignmentfile.pyx":818 + * cdef char *cfilename = NULL + * cdef char *creference_filename = NULL + * cdef char *cindexname = NULL # <<<<<<<<<<<<<< + * cdef char *cmode = NULL + * cdef bam_hdr_t * hdr = NULL +*/ + __pyx_v_cindexname = NULL; + + /* "pysam/libcalignmentfile.pyx":819 + * cdef char *creference_filename = NULL + * cdef char *cindexname = NULL + * cdef char *cmode = NULL # <<<<<<<<<<<<<< + * cdef bam_hdr_t * hdr = NULL + * cdef int ret +*/ + __pyx_v_cmode = NULL; + + /* "pysam/libcalignmentfile.pyx":820 + * cdef char *cindexname = NULL + * cdef char *cmode = NULL + * cdef bam_hdr_t * hdr = NULL # <<<<<<<<<<<<<< + * cdef int ret + * +*/ + __pyx_v_hdr = NULL; + + /* "pysam/libcalignmentfile.pyx":823 + * cdef int ret + * + * if threads > 1 and ignore_truncation: # <<<<<<<<<<<<<< + * # This won't raise errors if reaching a truncated alignment, + * # because bgzf_mt_reader in htslib does not deal with +*/ + __pyx_t_2 = PyObject_RichCompare(__pyx_v_threads, __pyx_mstate_global->__pyx_int_1, Py_GT); __Pyx_XGOTREF(__pyx_t_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 823, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 823, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_ignore_truncation); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 823, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":829 + * # to bgzf_read (https://github.com/samtools/htslib/blob/1.7/bgzf.c#L888) + * # Better to avoid this (for now) than to produce seemingly correct results. + * raise ValueError('Cannot add extra threads when "ignore_truncation" is True') # <<<<<<<<<<<<<< + * self.threads = threads + * +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_Cannot_add_extra_threads_when_ig}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 829, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 829, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":823 + * cdef int ret + * + * if threads > 1 and ignore_truncation: # <<<<<<<<<<<<<< + * # This won't raise errors if reaching a truncated alignment, + * # because bgzf_mt_reader in htslib does not deal with +*/ + } + + /* "pysam/libcalignmentfile.pyx":830 + * # Better to avoid this (for now) than to produce seemingly correct results. + * raise ValueError('Cannot add extra threads when "ignore_truncation" is True') + * self.threads = threads # <<<<<<<<<<<<<< + * + * # for backwards compatibility: +*/ + __Pyx_INCREF(__pyx_v_threads); + __Pyx_GIVEREF(__pyx_v_threads); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.threads); + __Pyx_DECREF(__pyx_v_self->__pyx_base.threads); + __pyx_v_self->__pyx_base.threads = __pyx_v_threads; + + /* "pysam/libcalignmentfile.pyx":833 + * + * # for backwards compatibility: + * if referencenames is not None: # <<<<<<<<<<<<<< + * reference_names = referencenames + * if referencelengths is not None: +*/ + __pyx_t_1 = (__pyx_v_referencenames != Py_None); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":834 + * # for backwards compatibility: + * if referencenames is not None: + * reference_names = referencenames # <<<<<<<<<<<<<< + * if referencelengths is not None: + * reference_lengths = referencelengths +*/ + __Pyx_INCREF(__pyx_v_referencenames); + __Pyx_DECREF_SET(__pyx_v_reference_names, __pyx_v_referencenames); + + /* "pysam/libcalignmentfile.pyx":833 + * + * # for backwards compatibility: + * if referencenames is not None: # <<<<<<<<<<<<<< + * reference_names = referencenames + * if referencelengths is not None: +*/ + } + + /* "pysam/libcalignmentfile.pyx":835 + * if referencenames is not None: + * reference_names = referencenames + * if referencelengths is not None: # <<<<<<<<<<<<<< + * reference_lengths = referencelengths + * +*/ + __pyx_t_1 = (__pyx_v_referencelengths != Py_None); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":836 + * reference_names = referencenames + * if referencelengths is not None: + * reference_lengths = referencelengths # <<<<<<<<<<<<<< + * + * # close a previously opened file +*/ + __Pyx_INCREF(__pyx_v_referencelengths); + __Pyx_DECREF_SET(__pyx_v_reference_lengths, __pyx_v_referencelengths); + + /* "pysam/libcalignmentfile.pyx":835 + * if referencenames is not None: + * reference_names = referencenames + * if referencelengths is not None: # <<<<<<<<<<<<<< + * reference_lengths = referencelengths + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":839 + * + * # close a previously opened file + * if self.is_open: # <<<<<<<<<<<<<< + * self.close() + * +*/ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 839, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 839, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":840 + * # close a previously opened file + * if self.is_open: + * self.close() # <<<<<<<<<<<<<< + * + * # autodetection for read +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_close, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 840, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":839 + * + * # close a previously opened file + * if self.is_open: # <<<<<<<<<<<<<< + * self.close() + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":843 + * + * # autodetection for read + * if mode is None: # <<<<<<<<<<<<<< + * mode = "r" + * +*/ + __pyx_t_1 = (__pyx_v_mode == Py_None); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":844 + * # autodetection for read + * if mode is None: + * mode = "r" # <<<<<<<<<<<<<< + * + * if add_sam_header and mode == "w": +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_n_u_r); + __Pyx_DECREF_SET(__pyx_v_mode, __pyx_mstate_global->__pyx_n_u_r); + + /* "pysam/libcalignmentfile.pyx":843 + * + * # autodetection for read + * if mode is None: # <<<<<<<<<<<<<< + * mode = "r" + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":846 + * mode = "r" + * + * if add_sam_header and mode == "w": # <<<<<<<<<<<<<< + * mode = "wh" + * +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_add_sam_header); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 846, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_mode, __pyx_mstate_global->__pyx_n_u_w, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 846, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L11_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":847 + * + * if add_sam_header and mode == "w": + * mode = "wh" # <<<<<<<<<<<<<< + * + * assert mode in ("r", "w", "rb", "wb", "wh", +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_n_u_wh); + __Pyx_DECREF_SET(__pyx_v_mode, __pyx_mstate_global->__pyx_n_u_wh); + + /* "pysam/libcalignmentfile.pyx":846 + * mode = "r" + * + * if add_sam_header and mode == "w": # <<<<<<<<<<<<<< + * mode = "wh" + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":849 + * mode = "wh" + * + * assert mode in ("r", "w", "rb", "wb", "wh", # <<<<<<<<<<<<<< + * "wbu", "rU", "wb0", + * "rc", "wc"), \ +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __Pyx_INCREF(__pyx_v_mode); + __pyx_t_2 = __pyx_v_mode; + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_r, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_w, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_rb, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_wb, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_wh, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_wbu, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_rU, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_wb0, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_rc, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_wc, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 849, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L13_bool_binop_done:; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __pyx_t_1; + if (unlikely(!__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":852 + * "wbu", "rU", "wb0", + * "rc", "wc"), \ + * "invalid file opening mode `%s`" % mode # <<<<<<<<<<<<<< + * + * self.duplicate_filehandle = duplicate_filehandle +*/ + __pyx_t_2 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_invalid_file_opening_mode_s, __pyx_v_mode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 852, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_Raise(__pyx_builtin_AssertionError, __pyx_t_2, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 849, __pyx_L1_error) + } + } + #else + if ((1)); else __PYX_ERR(0, 849, __pyx_L1_error) + #endif + + /* "pysam/libcalignmentfile.pyx":854 + * "invalid file opening mode `%s`" % mode + * + * self.duplicate_filehandle = duplicate_filehandle # <<<<<<<<<<<<<< + * + * # StringIO not supported +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_duplicate_filehandle); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 854, __pyx_L1_error) + __pyx_v_self->__pyx_base.duplicate_filehandle = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":857 + * + * # StringIO not supported + * if isinstance(filepath_or_object, StringIO): # <<<<<<<<<<<<<< + * raise NotImplementedError( + * "access from StringIO objects not supported") +*/ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_StringIO); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 857, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_IsInstance(__pyx_v_filepath_or_object, __pyx_t_2); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 857, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":858 + * # StringIO not supported + * if isinstance(filepath_or_object, StringIO): + * raise NotImplementedError( # <<<<<<<<<<<<<< + * "access from StringIO objects not supported") + * # reading from a file descriptor +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_NotImplementedError); + __pyx_t_4 = __pyx_builtin_NotImplementedError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_access_from_StringIO_objects_not}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 858, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 858, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":857 + * + * # StringIO not supported + * if isinstance(filepath_or_object, StringIO): # <<<<<<<<<<<<<< + * raise NotImplementedError( + * "access from StringIO objects not supported") +*/ + } + + /* "pysam/libcalignmentfile.pyx":861 + * "access from StringIO objects not supported") + * # reading from a file descriptor + * elif isinstance(filepath_or_object, int): # <<<<<<<<<<<<<< + * self.filename = filepath_or_object + * filename = None +*/ + __pyx_t_3 = PyLong_Check(__pyx_v_filepath_or_object); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":862 + * # reading from a file descriptor + * elif isinstance(filepath_or_object, int): + * self.filename = filepath_or_object # <<<<<<<<<<<<<< + * filename = None + * self.is_remote = False +*/ + __Pyx_INCREF(__pyx_v_filepath_or_object); + __Pyx_GIVEREF(__pyx_v_filepath_or_object); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.filename); + __Pyx_DECREF(__pyx_v_self->__pyx_base.filename); + __pyx_v_self->__pyx_base.filename = __pyx_v_filepath_or_object; + + /* "pysam/libcalignmentfile.pyx":863 + * elif isinstance(filepath_or_object, int): + * self.filename = filepath_or_object + * filename = None # <<<<<<<<<<<<<< + * self.is_remote = False + * self.is_stream = True +*/ + __Pyx_INCREF(Py_None); + __pyx_v_filename = ((PyObject*)Py_None); + + /* "pysam/libcalignmentfile.pyx":864 + * self.filename = filepath_or_object + * filename = None + * self.is_remote = False # <<<<<<<<<<<<<< + * self.is_stream = True + * # reading from a File object or other object with fileno +*/ + __pyx_v_self->__pyx_base.is_remote = 0; + + /* "pysam/libcalignmentfile.pyx":865 + * filename = None + * self.is_remote = False + * self.is_stream = True # <<<<<<<<<<<<<< + * # reading from a File object or other object with fileno + * elif hasattr(filepath_or_object, "fileno"): +*/ + __pyx_v_self->__pyx_base.is_stream = 1; + + /* "pysam/libcalignmentfile.pyx":861 + * "access from StringIO objects not supported") + * # reading from a file descriptor + * elif isinstance(filepath_or_object, int): # <<<<<<<<<<<<<< + * self.filename = filepath_or_object + * filename = None +*/ + goto __pyx_L23; + } + + /* "pysam/libcalignmentfile.pyx":867 + * self.is_stream = True + * # reading from a File object or other object with fileno + * elif hasattr(filepath_or_object, "fileno"): # <<<<<<<<<<<<<< + * if filepath_or_object.closed: + * raise ValueError('I/O operation on closed file') +*/ + __pyx_t_3 = __Pyx_HasAttr(__pyx_v_filepath_or_object, __pyx_mstate_global->__pyx_n_u_fileno); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 867, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":868 + * # reading from a File object or other object with fileno + * elif hasattr(filepath_or_object, "fileno"): + * if filepath_or_object.closed: # <<<<<<<<<<<<<< + * raise ValueError('I/O operation on closed file') + * self.filename = filepath_or_object +*/ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_filepath_or_object, __pyx_mstate_global->__pyx_n_u_closed); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 868, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 868, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":869 + * elif hasattr(filepath_or_object, "fileno"): + * if filepath_or_object.closed: + * raise ValueError('I/O operation on closed file') # <<<<<<<<<<<<<< + * self.filename = filepath_or_object + * # .name can be TextIOWrapper +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 869, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 869, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":868 + * # reading from a File object or other object with fileno + * elif hasattr(filepath_or_object, "fileno"): + * if filepath_or_object.closed: # <<<<<<<<<<<<<< + * raise ValueError('I/O operation on closed file') + * self.filename = filepath_or_object +*/ + } + + /* "pysam/libcalignmentfile.pyx":870 + * if filepath_or_object.closed: + * raise ValueError('I/O operation on closed file') + * self.filename = filepath_or_object # <<<<<<<<<<<<<< + * # .name can be TextIOWrapper + * try: +*/ + __Pyx_INCREF(__pyx_v_filepath_or_object); + __Pyx_GIVEREF(__pyx_v_filepath_or_object); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.filename); + __Pyx_DECREF(__pyx_v_self->__pyx_base.filename); + __pyx_v_self->__pyx_base.filename = __pyx_v_filepath_or_object; + + /* "pysam/libcalignmentfile.pyx":872 + * self.filename = filepath_or_object + * # .name can be TextIOWrapper + * try: # <<<<<<<<<<<<<< + * filename = encode_filename(str(filepath_or_object.name)) + * cfilename = filename +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":873 + * # .name can be TextIOWrapper + * try: + * filename = encode_filename(str(filepath_or_object.name)) # <<<<<<<<<<<<<< + * cfilename = filename + * except AttributeError: +*/ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_filepath_or_object, __pyx_mstate_global->__pyx_n_u_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 873, __pyx_L25_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyObject_Unicode(__pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 873, __pyx_L25_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __pyx_f_5pysam_9libcutils_encode_filename(__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 873, __pyx_L25_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_filename = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":874 + * try: + * filename = encode_filename(str(filepath_or_object.name)) + * cfilename = filename # <<<<<<<<<<<<<< + * except AttributeError: + * filename = None +*/ + if (unlikely(__pyx_v_filename == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 874, __pyx_L25_error) + } + __pyx_t_10 = __Pyx_PyBytes_AsWritableString(__pyx_v_filename); if (unlikely((!__pyx_t_10) && PyErr_Occurred())) __PYX_ERR(0, 874, __pyx_L25_error) + __pyx_v_cfilename = __pyx_t_10; + + /* "pysam/libcalignmentfile.pyx":872 + * self.filename = filepath_or_object + * # .name can be TextIOWrapper + * try: # <<<<<<<<<<<<<< + * filename = encode_filename(str(filepath_or_object.name)) + * cfilename = filename +*/ + } + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L30_try_end; + __pyx_L25_error:; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_TraceException(__pyx_lineno, 0, 0); + + /* "pysam/libcalignmentfile.pyx":875 + * filename = encode_filename(str(filepath_or_object.name)) + * cfilename = filename + * except AttributeError: # <<<<<<<<<<<<<< + * filename = None + * self.is_remote = False +*/ + __pyx_t_11 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_AttributeError); + if (__pyx_t_11) { + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile._open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_TraceExceptionHandled(0); + if (__Pyx_GetException(&__pyx_t_2, &__pyx_t_5, &__pyx_t_4) < 0) __PYX_ERR(0, 875, __pyx_L27_except_error) + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_4); + __Pyx_TraceExceptionDone(); + + /* "pysam/libcalignmentfile.pyx":876 + * cfilename = filename + * except AttributeError: + * filename = None # <<<<<<<<<<<<<< + * self.is_remote = False + * self.is_stream = True +*/ + __Pyx_INCREF(Py_None); + __Pyx_XDECREF_SET(__pyx_v_filename, ((PyObject*)Py_None)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L26_exception_handled; + } + goto __pyx_L27_except_error; + + /* "pysam/libcalignmentfile.pyx":872 + * self.filename = filepath_or_object + * # .name can be TextIOWrapper + * try: # <<<<<<<<<<<<<< + * filename = encode_filename(str(filepath_or_object.name)) + * cfilename = filename +*/ + __pyx_L27_except_error:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + goto __pyx_L1_error; + __pyx_L26_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_ExceptionReset(__pyx_t_7, __pyx_t_8, __pyx_t_9); + __pyx_L30_try_end:; + } + + /* "pysam/libcalignmentfile.pyx":877 + * except AttributeError: + * filename = None + * self.is_remote = False # <<<<<<<<<<<<<< + * self.is_stream = True + * # what remains is a filename +*/ + __pyx_v_self->__pyx_base.is_remote = 0; + + /* "pysam/libcalignmentfile.pyx":878 + * filename = None + * self.is_remote = False + * self.is_stream = True # <<<<<<<<<<<<<< + * # what remains is a filename + * else: +*/ + __pyx_v_self->__pyx_base.is_stream = 1; + + /* "pysam/libcalignmentfile.pyx":867 + * self.is_stream = True + * # reading from a File object or other object with fileno + * elif hasattr(filepath_or_object, "fileno"): # <<<<<<<<<<<<<< + * if filepath_or_object.closed: + * raise ValueError('I/O operation on closed file') +*/ + goto __pyx_L23; + } + + /* "pysam/libcalignmentfile.pyx":881 + * # what remains is a filename + * else: + * self.filename = filename = encode_filename(filepath_or_object) # <<<<<<<<<<<<<< + * cfilename = filename + * self.is_remote = hisremote(cfilename) +*/ + /*else*/ { + __pyx_t_4 = __pyx_f_5pysam_9libcutils_encode_filename(__pyx_v_filepath_or_object); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 881, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.filename); + __Pyx_DECREF(__pyx_v_self->__pyx_base.filename); + __pyx_v_self->__pyx_base.filename = __pyx_t_4; + __Pyx_INCREF(__pyx_t_4); + __pyx_v_filename = ((PyObject*)__pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":882 + * else: + * self.filename = filename = encode_filename(filepath_or_object) + * cfilename = filename # <<<<<<<<<<<<<< + * self.is_remote = hisremote(cfilename) + * self.is_stream = self.filename == b'-' +*/ + if (unlikely(__pyx_v_filename == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 882, __pyx_L1_error) + } + __pyx_t_10 = __Pyx_PyBytes_AsWritableString(__pyx_v_filename); if (unlikely((!__pyx_t_10) && PyErr_Occurred())) __PYX_ERR(0, 882, __pyx_L1_error) + __pyx_v_cfilename = __pyx_t_10; + + /* "pysam/libcalignmentfile.pyx":883 + * self.filename = filename = encode_filename(filepath_or_object) + * cfilename = filename + * self.is_remote = hisremote(cfilename) # <<<<<<<<<<<<<< + * self.is_stream = self.filename == b'-' + * +*/ + __pyx_v_self->__pyx_base.is_remote = hisremote(__pyx_v_cfilename); + + /* "pysam/libcalignmentfile.pyx":884 + * cfilename = filename + * self.is_remote = hisremote(cfilename) + * self.is_stream = self.filename == b'-' # <<<<<<<<<<<<<< + * + * # for htslib, wbu seems to not work +*/ + __pyx_t_4 = PyObject_RichCompare(__pyx_v_self->__pyx_base.filename, __pyx_mstate_global->__pyx_kp_b__9, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 884, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 884, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_self->__pyx_base.is_stream = __pyx_t_3; + } + __pyx_L23:; + + /* "pysam/libcalignmentfile.pyx":887 + * + * # for htslib, wbu seems to not work + * if mode == "wbu": # <<<<<<<<<<<<<< + * mode = "wb0" + * +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_mode, __pyx_mstate_global->__pyx_n_u_wbu, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 887, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":888 + * # for htslib, wbu seems to not work + * if mode == "wbu": + * mode = "wb0" # <<<<<<<<<<<<<< + * + * self.mode = force_bytes(mode) +*/ + __Pyx_INCREF(__pyx_mstate_global->__pyx_n_u_wb0); + __Pyx_DECREF_SET(__pyx_v_mode, __pyx_mstate_global->__pyx_n_u_wb0); + + /* "pysam/libcalignmentfile.pyx":887 + * + * # for htslib, wbu seems to not work + * if mode == "wbu": # <<<<<<<<<<<<<< + * mode = "wb0" + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":890 + * mode = "wb0" + * + * self.mode = force_bytes(mode) # <<<<<<<<<<<<<< + * self.reference_filename = reference_filename = encode_filename( + * reference_filename) +*/ + __pyx_t_4 = __pyx_f_5pysam_9libcutils_force_bytes(__pyx_v_mode, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 890, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.mode); + __Pyx_DECREF(__pyx_v_self->__pyx_base.mode); + __pyx_v_self->__pyx_base.mode = __pyx_t_4; + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":891 + * + * self.mode = force_bytes(mode) + * self.reference_filename = reference_filename = encode_filename( # <<<<<<<<<<<<<< + * reference_filename) + * +*/ + __pyx_t_4 = __pyx_f_5pysam_9libcutils_encode_filename(__pyx_v_reference_filename); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 891, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->reference_filename); + __Pyx_DECREF(__pyx_v_self->reference_filename); + __pyx_v_self->reference_filename = __pyx_t_4; + __Pyx_INCREF(__pyx_t_4); + __Pyx_DECREF_SET(__pyx_v_reference_filename, __pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":894 + * reference_filename) + * + * if mode[0] == 'w': # <<<<<<<<<<<<<< + * # open file for writing + * +*/ + __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_mode, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 894, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_w, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 894, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":897 + * # open file for writing + * + * if not (template or header or text or (reference_names and reference_lengths)): # <<<<<<<<<<<<<< + * raise ValueError( + * "either supply options `template`, `header`, `text` or both `reference_names` " +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_template)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 897, __pyx_L1_error) + if (!__pyx_t_1) { + } else { + __pyx_t_3 = __pyx_t_1; + goto __pyx_L36_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_header); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 897, __pyx_L1_error) + if (!__pyx_t_1) { + } else { + __pyx_t_3 = __pyx_t_1; + goto __pyx_L36_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_text); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 897, __pyx_L1_error) + if (!__pyx_t_1) { + } else { + __pyx_t_3 = __pyx_t_1; + goto __pyx_L36_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_reference_names); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 897, __pyx_L1_error) + if (__pyx_t_1) { + } else { + __pyx_t_3 = __pyx_t_1; + goto __pyx_L36_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_reference_lengths); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 897, __pyx_L1_error) + __pyx_t_3 = __pyx_t_1; + __pyx_L36_bool_binop_done:; + __pyx_t_1 = (!__pyx_t_3); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":898 + * + * if not (template or header or text or (reference_names and reference_lengths)): + * raise ValueError( # <<<<<<<<<<<<<< + * "either supply options `template`, `header`, `text` or both `reference_names` " + * "and `reference_lengths` for writing") +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_2 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_either_supply_options_template_h}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 898, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 898, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":897 + * # open file for writing + * + * if not (template or header or text or (reference_names and reference_lengths)): # <<<<<<<<<<<<<< + * raise ValueError( + * "either supply options `template`, `header`, `text` or both `reference_names` " +*/ + } + + /* "pysam/libcalignmentfile.pyx":902 + * "and `reference_lengths` for writing") + * + * if template: # <<<<<<<<<<<<<< + * # header is copied, though at the moment not strictly + * # necessary as AlignmentHeader is immutable. +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_template)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 902, __pyx_L1_error) + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":905 + * # header is copied, though at the moment not strictly + * # necessary as AlignmentHeader is immutable. + * self.header = template.header.copy() # <<<<<<<<<<<<<< + * elif isinstance(header, AlignmentHeader): + * self.header = header.copy() +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_template->header); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_copy, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 905, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 905, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":902 + * "and `reference_lengths` for writing") + * + * if template: # <<<<<<<<<<<<<< + * # header is copied, though at the moment not strictly + * # necessary as AlignmentHeader is immutable. +*/ + goto __pyx_L41; + } + + /* "pysam/libcalignmentfile.pyx":906 + * # necessary as AlignmentHeader is immutable. + * self.header = template.header.copy() + * elif isinstance(header, AlignmentHeader): # <<<<<<<<<<<<<< + * self.header = header.copy() + * elif isinstance(header, Mapping): +*/ + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_header, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":907 + * self.header = template.header.copy() + * elif isinstance(header, AlignmentHeader): + * self.header = header.copy() # <<<<<<<<<<<<<< + * elif isinstance(header, Mapping): + * self.header = AlignmentHeader.from_dict(header) +*/ + __pyx_t_2 = __pyx_v_header; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_copy, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 907, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 907, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":906 + * # necessary as AlignmentHeader is immutable. + * self.header = template.header.copy() + * elif isinstance(header, AlignmentHeader): # <<<<<<<<<<<<<< + * self.header = header.copy() + * elif isinstance(header, Mapping): +*/ + goto __pyx_L41; + } + + /* "pysam/libcalignmentfile.pyx":908 + * elif isinstance(header, AlignmentHeader): + * self.header = header.copy() + * elif isinstance(header, Mapping): # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: +*/ + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 908, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyObject_IsInstance(__pyx_v_header, __pyx_t_4); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 908, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":909 + * self.header = header.copy() + * elif isinstance(header, Mapping): + * self.header = AlignmentHeader.from_dict(header) # <<<<<<<<<<<<<< + * elif reference_names and reference_lengths: + * self.header = AlignmentHeader.from_references( +*/ + __pyx_t_2 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_header}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_from_dict, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 909, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 909, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":908 + * elif isinstance(header, AlignmentHeader): + * self.header = header.copy() + * elif isinstance(header, Mapping): # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: +*/ + goto __pyx_L41; + } + + /* "pysam/libcalignmentfile.pyx":910 + * elif isinstance(header, Mapping): + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_references( + * reference_names, +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_names); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 910, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L42_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_lengths); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 910, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L42_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":911 + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: + * self.header = AlignmentHeader.from_references( # <<<<<<<<<<<<<< + * reference_names, + * reference_lengths, +*/ + __pyx_t_2 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __Pyx_INCREF(__pyx_t_2); + + /* "pysam/libcalignmentfile.pyx":915 + * reference_lengths, + * add_sq_text=add_sq_text, + * text=text) # <<<<<<<<<<<<<< + * elif text: + * self.header = AlignmentHeader.from_text(text) +*/ + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[3 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_2, __pyx_v_reference_names, __pyx_v_reference_lengths}; + __pyx_t_5 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 911, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_add_sq_text, __pyx_v_add_sq_text, __pyx_t_5, __pyx_callargs+3, 0) < 0) __PYX_ERR(0, 911, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_text, __pyx_v_text, __pyx_t_5, __pyx_callargs+3, 1) < 0) __PYX_ERR(0, 911, __pyx_L1_error) + __pyx_t_4 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_from_references, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_5); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 911, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + + /* "pysam/libcalignmentfile.pyx":911 + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: + * self.header = AlignmentHeader.from_references( # <<<<<<<<<<<<<< + * reference_names, + * reference_lengths, +*/ + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 911, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":910 + * elif isinstance(header, Mapping): + * self.header = AlignmentHeader.from_dict(header) + * elif reference_names and reference_lengths: # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_references( + * reference_names, +*/ + goto __pyx_L41; + } + + /* "pysam/libcalignmentfile.pyx":916 + * add_sq_text=add_sq_text, + * text=text) + * elif text: # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_text(text) + * else: +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_text); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 916, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":917 + * text=text) + * elif text: + * self.header = AlignmentHeader.from_text(text) # <<<<<<<<<<<<<< + * else: + * raise ValueError("not enough information to construct header. Please provide template, " +*/ + __pyx_t_5 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_v_text}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_from_text, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 917, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 917, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":916 + * add_sq_text=add_sq_text, + * text=text) + * elif text: # <<<<<<<<<<<<<< + * self.header = AlignmentHeader.from_text(text) + * else: +*/ + goto __pyx_L41; + } + + /* "pysam/libcalignmentfile.pyx":919 + * self.header = AlignmentHeader.from_text(text) + * else: + * raise ValueError("not enough information to construct header. Please provide template, " # <<<<<<<<<<<<<< + * "header, text or reference_names/reference_lengths") + * self.htsfile = self._open_htsfile() +*/ + /*else*/ { + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_2 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_not_enough_information_to_constr}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 919, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 919, __pyx_L1_error) + } + __pyx_L41:; + + /* "pysam/libcalignmentfile.pyx":921 + * raise ValueError("not enough information to construct header. Please provide template, " + * "header, text or reference_names/reference_lengths") + * self.htsfile = self._open_htsfile() # <<<<<<<<<<<<<< + * + * if self.htsfile == NULL: +*/ + __pyx_t_12 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._open_htsfile(((struct __pyx_obj_5pysam_10libchtslib_HTSFile *)__pyx_v_self)); if (unlikely(__pyx_t_12 == ((htsFile *)0) && PyErr_Occurred())) __PYX_ERR(0, 921, __pyx_L1_error) + __pyx_v_self->__pyx_base.htsfile = __pyx_t_12; + + /* "pysam/libcalignmentfile.pyx":923 + * self.htsfile = self._open_htsfile() + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.htsfile == NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":924 + * + * if self.htsfile == NULL: + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open alignment file", filename) + * else: +*/ + __pyx_t_1 = (errno != 0); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":925 + * if self.htsfile == NULL: + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) # <<<<<<<<<<<<<< + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) +*/ + __pyx_t_13.__pyx_n = 1; + __pyx_t_13.filename = __pyx_v_filename; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Could_not_open_alignment_file, &__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 925, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 925, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":924 + * + * if self.htsfile == NULL: + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open alignment file", filename) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":927 + * raise OSError_from_errno("Could not open alignment file", filename) + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) # <<<<<<<<<<<<<< + * if format_options and len(format_options): + * self.add_hts_options(format_options) +*/ + /*else*/ { + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_15 = __pyx_mstate_global->__pyx_kp_u_could_not_open_alignment_file; + __Pyx_INCREF(__pyx_t_15); + __pyx_t_16 = __pyx_f_5pysam_9libcutils_force_str(__pyx_v_filename, NULL); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 927, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_15, __pyx_t_16}; + __pyx_t_14 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 927, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + } + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_14}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 927, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 927, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":923 + * self.htsfile = self._open_htsfile() + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) +*/ + } + + /* "pysam/libcalignmentfile.pyx":928 + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) + * if format_options and len(format_options): # <<<<<<<<<<<<<< + * self.add_hts_options(format_options) + * # set filename with reference sequences. If no filename +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_format_options); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 928, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L47_bool_binop_done; + } + __pyx_t_17 = PyObject_Length(__pyx_v_format_options); if (unlikely(__pyx_t_17 == ((Py_ssize_t)-1))) __PYX_ERR(0, 928, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_17 != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L47_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":929 + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) + * if format_options and len(format_options): + * self.add_hts_options(format_options) # <<<<<<<<<<<<<< + * # set filename with reference sequences. If no filename + * # is given, the CRAM reference arrays will be built from +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_v_format_options}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_add_hts_options, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 929, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":928 + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) + * if format_options and len(format_options): # <<<<<<<<<<<<<< + * self.add_hts_options(format_options) + * # set filename with reference sequences. If no filename +*/ + } + + /* "pysam/libcalignmentfile.pyx":933 + * # is given, the CRAM reference arrays will be built from + * # the @SQ header in the header + * if "c" in mode and reference_filename: # <<<<<<<<<<<<<< + * if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0): + * raise ValueError("failure when setting reference filename") +*/ + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_c, __pyx_v_mode, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 933, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L50_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_filename); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 933, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L50_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":934 + * # the @SQ header in the header + * if "c" in mode and reference_filename: + * if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0): # <<<<<<<<<<<<<< + * raise ValueError("failure when setting reference filename") + * +*/ + __pyx_t_18 = __Pyx_PyObject_AsString(__pyx_v_self->reference_filename); if (unlikely((!__pyx_t_18) && PyErr_Occurred())) __PYX_ERR(0, 934, __pyx_L1_error) + __pyx_t_1 = (hts_set_fai_filename(__pyx_v_self->__pyx_base.htsfile, __pyx_t_18) != 0); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":935 + * if "c" in mode and reference_filename: + * if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0): + * raise ValueError("failure when setting reference filename") # <<<<<<<<<<<<<< + * + * # write header to htsfile +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_14 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_failure_when_setting_reference_f}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_14, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 935, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 935, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":934 + * # the @SQ header in the header + * if "c" in mode and reference_filename: + * if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0): # <<<<<<<<<<<<<< + * raise ValueError("failure when setting reference filename") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":933 + * # is given, the CRAM reference arrays will be built from + * # the @SQ header in the header + * if "c" in mode and reference_filename: # <<<<<<<<<<<<<< + * if (hts_set_fai_filename(self.htsfile, self.reference_filename) != 0): + * raise ValueError("failure when setting reference filename") +*/ + } + + /* "pysam/libcalignmentfile.pyx":938 + * + * # write header to htsfile + * if "b" in mode or "c" in mode or "h" in mode: # <<<<<<<<<<<<<< + * hdr = self.header.ptr + * with nogil: +*/ + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_b, __pyx_v_mode, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 938, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L54_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_c, __pyx_v_mode, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 938, __pyx_L1_error) + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L54_bool_binop_done; + } + __pyx_t_3 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_h, __pyx_v_mode, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 938, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L54_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":939 + * # write header to htsfile + * if "b" in mode or "c" in mode or "h" in mode: + * hdr = self.header.ptr # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_hdr_write(self.htsfile, hdr) +*/ + __pyx_t_19 = __pyx_v_self->header->ptr; + __pyx_v_hdr = __pyx_t_19; + + /* "pysam/libcalignmentfile.pyx":940 + * if "b" in mode or "c" in mode or "h" in mode: + * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_hdr_write(self.htsfile, hdr) + * if ret < 0: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":941 + * hdr = self.header.ptr + * with nogil: + * ret = sam_hdr_write(self.htsfile, hdr) # <<<<<<<<<<<<<< + * if ret < 0: + * raise OSError_from_errno("Could not write headers", filename) +*/ + __pyx_v_ret = sam_hdr_write(__pyx_v_self->__pyx_base.htsfile, __pyx_v_hdr); + } + + /* "pysam/libcalignmentfile.pyx":940 + * if "b" in mode or "c" in mode or "h" in mode: + * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_hdr_write(self.htsfile, hdr) + * if ret < 0: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L59; + } + __pyx_L59:; + } + } + + /* "pysam/libcalignmentfile.pyx":942 + * with nogil: + * ret = sam_hdr_write(self.htsfile, hdr) + * if ret < 0: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not write headers", filename) + * +*/ + __pyx_t_1 = (__pyx_v_ret < 0); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":943 + * ret = sam_hdr_write(self.htsfile, hdr) + * if ret < 0: + * raise OSError_from_errno("Could not write headers", filename) # <<<<<<<<<<<<<< + * + * elif mode[0] == "r": +*/ + __pyx_t_13.__pyx_n = 1; + __pyx_t_13.filename = __pyx_v_filename; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Could_not_write_headers, &__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 943, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 943, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":942 + * with nogil: + * ret = sam_hdr_write(self.htsfile, hdr) + * if ret < 0: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not write headers", filename) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":938 + * + * # write header to htsfile + * if "b" in mode or "c" in mode or "h" in mode: # <<<<<<<<<<<<<< + * hdr = self.header.ptr + * with nogil: +*/ + } + + /* "pysam/libcalignmentfile.pyx":894 + * reference_filename) + * + * if mode[0] == 'w': # <<<<<<<<<<<<<< + * # open file for writing + * +*/ + goto __pyx_L34; + } + + /* "pysam/libcalignmentfile.pyx":945 + * raise OSError_from_errno("Could not write headers", filename) + * + * elif mode[0] == "r": # <<<<<<<<<<<<<< + * # open file for reading + * self.htsfile = self._open_htsfile() +*/ + __pyx_t_4 = __Pyx_GetItemInt(__pyx_v_mode, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 945, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_r, Py_EQ)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 945, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":947 + * elif mode[0] == "r": + * # open file for reading + * self.htsfile = self._open_htsfile() # <<<<<<<<<<<<<< + * + * if self.htsfile == NULL: +*/ + __pyx_t_12 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._open_htsfile(((struct __pyx_obj_5pysam_10libchtslib_HTSFile *)__pyx_v_self)); if (unlikely(__pyx_t_12 == ((htsFile *)0) && PyErr_Occurred())) __PYX_ERR(0, 947, __pyx_L1_error) + __pyx_v_self->__pyx_base.htsfile = __pyx_t_12; + + /* "pysam/libcalignmentfile.pyx":949 + * self.htsfile = self._open_htsfile() + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.htsfile == NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":950 + * + * if self.htsfile == NULL: + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open alignment file", filename) + * else: +*/ + __pyx_t_1 = (errno != 0); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":951 + * if self.htsfile == NULL: + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) # <<<<<<<<<<<<<< + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) +*/ + __pyx_t_13.__pyx_n = 1; + __pyx_t_13.filename = __pyx_v_filename; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Could_not_open_alignment_file, &__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 951, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 951, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":950 + * + * if self.htsfile == NULL: + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open alignment file", filename) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":953 + * raise OSError_from_errno("Could not open alignment file", filename) + * else: + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) # <<<<<<<<<<<<<< + * + * if self.htsfile.format.category != sequence_data: +*/ + /*else*/ { + __pyx_t_14 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_16 = __pyx_mstate_global->__pyx_kp_u_could_not_open_alignment_file; + __Pyx_INCREF(__pyx_t_16); + __pyx_t_15 = __pyx_f_5pysam_9libcutils_force_str(__pyx_v_filename, NULL); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 953, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_16, __pyx_t_15}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 953, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_14, __pyx_t_2}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 953, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 953, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":949 + * self.htsfile = self._open_htsfile() + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open alignment file", filename) +*/ + } + + /* "pysam/libcalignmentfile.pyx":955 + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) + * + * if self.htsfile.format.category != sequence_data: # <<<<<<<<<<<<<< + * raise ValueError("file does not contain alignment data") + * +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.htsfile->format.category != sequence_data); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":956 + * + * if self.htsfile.format.category != sequence_data: + * raise ValueError("file does not contain alignment data") # <<<<<<<<<<<<<< + * + * if format_options and len(format_options): +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_2 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_file_does_not_contain_alignment}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 956, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 956, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":955 + * raise ValueError("could not open alignment file `{}`".format(force_str(filename))) + * + * if self.htsfile.format.category != sequence_data: # <<<<<<<<<<<<<< + * raise ValueError("file does not contain alignment data") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":958 + * raise ValueError("file does not contain alignment data") + * + * if format_options and len(format_options): # <<<<<<<<<<<<<< + * self.add_hts_options(format_options) + * +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_format_options); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 958, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L65_bool_binop_done; + } + __pyx_t_17 = PyObject_Length(__pyx_v_format_options); if (unlikely(__pyx_t_17 == ((Py_ssize_t)-1))) __PYX_ERR(0, 958, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_17 != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L65_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":959 + * + * if format_options and len(format_options): + * self.add_hts_options(format_options) # <<<<<<<<<<<<<< + * + * self.check_truncation(ignore_truncation) +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_format_options}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_add_hts_options, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 959, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":958 + * raise ValueError("file does not contain alignment data") + * + * if format_options and len(format_options): # <<<<<<<<<<<<<< + * self.add_hts_options(format_options) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":961 + * self.add_hts_options(format_options) + * + * self.check_truncation(ignore_truncation) # <<<<<<<<<<<<<< + * + * # bam/cram files require a valid header +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_ignore_truncation}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_check_truncation, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 961, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":964 + * + * # bam/cram files require a valid header + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * with nogil: + * hdr = sam_hdr_read(self.htsfile) +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 964, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 964, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L68_bool_binop_done; + } + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 964, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 964, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = __pyx_t_3; + __pyx_L68_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":965 + * # bam/cram files require a valid header + * if self.is_bam or self.is_cram: + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":966 + * if self.is_bam or self.is_cram: + * with nogil: + * hdr = sam_hdr_read(self.htsfile) # <<<<<<<<<<<<<< + * if hdr == NULL: + * raise ValueError( +*/ + __pyx_v_hdr = sam_hdr_read(__pyx_v_self->__pyx_base.htsfile); + } + + /* "pysam/libcalignmentfile.pyx":965 + * # bam/cram files require a valid header + * if self.is_bam or self.is_cram: + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L72; + } + __pyx_L72:; + } + } + + /* "pysam/libcalignmentfile.pyx":967 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "file does not have a valid header (mode='%s') " +*/ + __pyx_t_1 = (__pyx_v_hdr == NULL); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":968 + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: + * raise ValueError( # <<<<<<<<<<<<<< + * "file does not have a valid header (mode='%s') " + * "- is it BAM/CRAM format?" % mode) +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":970 + * raise ValueError( + * "file does not have a valid header (mode='%s') " + * "- is it BAM/CRAM format?" % mode) # <<<<<<<<<<<<<< + * self.header = makeAlignmentHeader(hdr) + * else: +*/ + __pyx_t_14 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_file_does_not_have_a_valid_heade, __pyx_v_mode); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 970, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_14}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 968, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 968, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":967 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "file does not have a valid header (mode='%s') " +*/ + } + + /* "pysam/libcalignmentfile.pyx":971 + * "file does not have a valid header (mode='%s') " + * "- is it BAM/CRAM format?" % mode) + * self.header = makeAlignmentHeader(hdr) # <<<<<<<<<<<<<< + * else: + * # in sam files a header is optional. If not given, +*/ + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(__pyx_v_hdr)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 971, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":964 + * + * # bam/cram files require a valid header + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * with nogil: + * hdr = sam_hdr_read(self.htsfile) +*/ + goto __pyx_L67; + } + + /* "pysam/libcalignmentfile.pyx":976 + * # user may provide reference names and lengths to built + * # an on-the-fly header. + * if reference_names and reference_lengths: # <<<<<<<<<<<<<< + * # build header from a target names and lengths + * self.header = AlignmentHeader.from_references( +*/ + /*else*/ { + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_names); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 976, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L75_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_lengths); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 976, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L75_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":978 + * if reference_names and reference_lengths: + * # build header from a target names and lengths + * self.header = AlignmentHeader.from_references( # <<<<<<<<<<<<<< + * reference_names=reference_names, + * reference_lengths=reference_lengths, +*/ + __pyx_t_5 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader); + __Pyx_INCREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":982 + * reference_lengths=reference_lengths, + * add_sq_text=add_sq_text, + * text=text) # <<<<<<<<<<<<<< + * else: + * with nogil: +*/ + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 4 : 0)] = {__pyx_t_5, NULL}; + __pyx_t_14 = __Pyx_MakeVectorcallBuilderKwds(4); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 978, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference_names, __pyx_v_reference_names, __pyx_t_14, __pyx_callargs+1, 0) < 0) __PYX_ERR(0, 978, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference_lengths, __pyx_v_reference_lengths, __pyx_t_14, __pyx_callargs+1, 1) < 0) __PYX_ERR(0, 978, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_add_sq_text, __pyx_v_add_sq_text, __pyx_t_14, __pyx_callargs+1, 2) < 0) __PYX_ERR(0, 978, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_text, __pyx_v_text, __pyx_t_14, __pyx_callargs+1, 3) < 0) __PYX_ERR(0, 978, __pyx_L1_error) + __pyx_t_4 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_from_references, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_14); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 978, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + + /* "pysam/libcalignmentfile.pyx":978 + * if reference_names and reference_lengths: + * # build header from a target names and lengths + * self.header = AlignmentHeader.from_references( # <<<<<<<<<<<<<< + * reference_names=reference_names, + * reference_lengths=reference_lengths, +*/ + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader))))) __PYX_ERR(0, 978, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":976 + * # user may provide reference names and lengths to built + * # an on-the-fly header. + * if reference_names and reference_lengths: # <<<<<<<<<<<<<< + * # build header from a target names and lengths + * self.header = AlignmentHeader.from_references( +*/ + goto __pyx_L74; + } + + /* "pysam/libcalignmentfile.pyx":984 + * text=text) + * else: + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + /*else*/ { + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":985 + * else: + * with nogil: + * hdr = sam_hdr_read(self.htsfile) # <<<<<<<<<<<<<< + * if hdr == NULL: + * raise ValueError( +*/ + __pyx_v_hdr = sam_hdr_read(__pyx_v_self->__pyx_base.htsfile); + } + + /* "pysam/libcalignmentfile.pyx":984 + * text=text) + * else: + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L79; + } + __pyx_L79:; + } + } + + /* "pysam/libcalignmentfile.pyx":986 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "SAM? file does not have a valid header (mode='%s'), " +*/ + __pyx_t_1 = (__pyx_v_hdr == NULL); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":987 + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: + * raise ValueError( # <<<<<<<<<<<<<< + * "SAM? file does not have a valid header (mode='%s'), " + * "please provide reference_names and reference_lengths") +*/ + __pyx_t_14 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_14, __pyx_mstate_global->__pyx_kp_u_SAM_file_does_not_have_a_valid_h}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 987, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 987, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":986 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "SAM? file does not have a valid header (mode='%s'), " +*/ + } + + /* "pysam/libcalignmentfile.pyx":990 + * "SAM? file does not have a valid header (mode='%s'), " + * "please provide reference_names and reference_lengths") + * self.header = makeAlignmentHeader(hdr) # <<<<<<<<<<<<<< + * + * # set filename with reference sequences +*/ + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(__pyx_v_hdr)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 990, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + } + __pyx_L74:; + } + __pyx_L67:; + + /* "pysam/libcalignmentfile.pyx":993 + * + * # set filename with reference sequences + * if self.is_cram and reference_filename: # <<<<<<<<<<<<<< + * creference_filename = self.reference_filename + * hts_set_opt(self.htsfile, +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 993, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 993, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L82_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_reference_filename); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 993, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L82_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":994 + * # set filename with reference sequences + * if self.is_cram and reference_filename: + * creference_filename = self.reference_filename # <<<<<<<<<<<<<< + * hts_set_opt(self.htsfile, + * CRAM_OPT_REFERENCE, +*/ + __pyx_t_10 = __Pyx_PyObject_AsWritableString(__pyx_v_self->reference_filename); if (unlikely((!__pyx_t_10) && PyErr_Occurred())) __PYX_ERR(0, 994, __pyx_L1_error) + __pyx_v_creference_filename = __pyx_t_10; + + /* "pysam/libcalignmentfile.pyx":995 + * if self.is_cram and reference_filename: + * creference_filename = self.reference_filename + * hts_set_opt(self.htsfile, # <<<<<<<<<<<<<< + * CRAM_OPT_REFERENCE, + * creference_filename) +*/ + (void)(hts_set_opt(__pyx_v_self->__pyx_base.htsfile, CRAM_OPT_REFERENCE, __pyx_v_creference_filename)); + + /* "pysam/libcalignmentfile.pyx":993 + * + * # set filename with reference sequences + * if self.is_cram and reference_filename: # <<<<<<<<<<<<<< + * creference_filename = self.reference_filename + * hts_set_opt(self.htsfile, +*/ + } + + /* "pysam/libcalignmentfile.pyx":999 + * creference_filename) + * + * if check_sq and self.header.nreferences == 0: # <<<<<<<<<<<<<< + * raise ValueError( + * ("file has no sequences defined (mode='%s') - " +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_check_sq); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 999, __pyx_L1_error) + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L85_bool_binop_done; + } + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 999, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = (__Pyx_PyLong_BoolEqObjC(__pyx_t_4, __pyx_mstate_global->__pyx_int_0, 0, 0)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 999, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = __pyx_t_3; + __pyx_L85_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1000 + * + * if check_sq and self.header.nreferences == 0: + * raise ValueError( # <<<<<<<<<<<<<< + * ("file has no sequences defined (mode='%s') - " + * "is it SAM/BAM format? Consider opening with " +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_14 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":1003 + * ("file has no sequences defined (mode='%s') - " + * "is it SAM/BAM format? Consider opening with " + * "check_sq=False") % mode) # <<<<<<<<<<<<<< + * + * if self.is_bam or self.is_cram: +*/ + __pyx_t_2 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_file_has_no_sequences_defined_mo, __pyx_v_mode); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1003, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_2}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_14, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1000, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1000, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":999 + * creference_filename) + * + * if check_sq and self.header.nreferences == 0: # <<<<<<<<<<<<<< + * raise ValueError( + * ("file has no sequences defined (mode='%s') - " +*/ + } + + /* "pysam/libcalignmentfile.pyx":1005 + * "check_sq=False") % mode) + * + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * self.index_filename = index_filename or filepath_index + * if self.index_filename: +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1005, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1005, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L88_bool_binop_done; + } + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1005, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1005, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_1 = __pyx_t_3; + __pyx_L88_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1006 + * + * if self.is_bam or self.is_cram: + * self.index_filename = index_filename or filepath_index # <<<<<<<<<<<<<< + * if self.index_filename: + * cindexname = bfile_name = encode_filename(self.index_filename) +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_index_filename); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1006, __pyx_L1_error) + if (!__pyx_t_1) { + } else { + __Pyx_INCREF(__pyx_v_index_filename); + __pyx_t_4 = __pyx_v_index_filename; + goto __pyx_L90_bool_binop_done; + } + __Pyx_INCREF(__pyx_v_filepath_index); + __pyx_t_4 = __pyx_v_filepath_index; + __pyx_L90_bool_binop_done:; + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF(__pyx_v_self->__pyx_base.index_filename); + __Pyx_DECREF(__pyx_v_self->__pyx_base.index_filename); + __pyx_v_self->__pyx_base.index_filename = __pyx_t_4; + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1007 + * if self.is_bam or self.is_cram: + * self.index_filename = index_filename or filepath_index + * if self.index_filename: # <<<<<<<<<<<<<< + * cindexname = bfile_name = encode_filename(self.index_filename) + * +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_self->__pyx_base.index_filename); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1007, __pyx_L1_error) + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1008 + * self.index_filename = index_filename or filepath_index + * if self.index_filename: + * cindexname = bfile_name = encode_filename(self.index_filename) # <<<<<<<<<<<<<< + * + * if cfilename or cindexname: +*/ + __pyx_t_4 = __pyx_v_self->__pyx_base.index_filename; + __Pyx_INCREF(__pyx_t_4); + __pyx_t_14 = __pyx_f_5pysam_9libcutils_encode_filename(__pyx_t_4); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 1008, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_14); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(__pyx_t_14 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 1008, __pyx_L1_error) + } + __pyx_t_10 = __Pyx_PyBytes_AsWritableString(__pyx_t_14); if (unlikely((!__pyx_t_10) && PyErr_Occurred())) __PYX_ERR(0, 1008, __pyx_L1_error) + __pyx_v_cindexname = __pyx_t_10; + __Pyx_INCREF(__pyx_t_14); + __pyx_v_bfile_name = ((PyObject*)__pyx_t_14); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + + /* "pysam/libcalignmentfile.pyx":1007 + * if self.is_bam or self.is_cram: + * self.index_filename = index_filename or filepath_index + * if self.index_filename: # <<<<<<<<<<<<<< + * cindexname = bfile_name = encode_filename(self.index_filename) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1010 + * cindexname = bfile_name = encode_filename(self.index_filename) + * + * if cfilename or cindexname: # <<<<<<<<<<<<<< + * with nogil: + * self.index = sam_index_load3(self.htsfile, cfilename, cindexname, +*/ + __pyx_t_3 = (__pyx_v_cfilename != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L94_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_cindexname != 0); + __pyx_t_1 = __pyx_t_3; + __pyx_L94_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1011 + * + * if cfilename or cindexname: + * with nogil: # <<<<<<<<<<<<<< + * self.index = sam_index_load3(self.htsfile, cfilename, cindexname, + * HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL) +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1012 + * if cfilename or cindexname: + * with nogil: + * self.index = sam_index_load3(self.htsfile, cfilename, cindexname, # <<<<<<<<<<<<<< + * HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL) + * +*/ + __pyx_v_self->index = sam_index_load3(__pyx_v_self->__pyx_base.htsfile, __pyx_v_cfilename, __pyx_v_cindexname, (HTS_IDX_SAVE_REMOTE | HTS_IDX_SILENT_FAIL)); + } + + /* "pysam/libcalignmentfile.pyx":1011 + * + * if cfilename or cindexname: + * with nogil: # <<<<<<<<<<<<<< + * self.index = sam_index_load3(self.htsfile, cfilename, cindexname, + * HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL) +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L98; + } + __pyx_L98:; + } + } + + /* "pysam/libcalignmentfile.pyx":1015 + * HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL) + * + * if not self.index and (cindexname or require_index): # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open index file", self.index_filename) +*/ + __pyx_t_3 = (!(__pyx_v_self->index != 0)); + if (__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L100_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_cindexname != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_1 = __pyx_t_3; + goto __pyx_L100_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_require_index); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1015, __pyx_L1_error) + __pyx_t_1 = __pyx_t_3; + __pyx_L100_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1016 + * + * if not self.index and (cindexname or require_index): + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open index file", self.index_filename) + * else: +*/ + __pyx_t_1 = (errno != 0); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1017 + * if not self.index and (cindexname or require_index): + * if errno: + * raise OSError_from_errno("Could not open index file", self.index_filename) # <<<<<<<<<<<<<< + * else: + * raise IOError('unable to open index file `%s`' % self.index_filename) +*/ + __pyx_t_14 = __pyx_v_self->__pyx_base.index_filename; + __Pyx_INCREF(__pyx_t_14); + __pyx_t_13.__pyx_n = 1; + __pyx_t_13.filename = __pyx_t_14; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Could_not_open_index_file, &__pyx_t_13); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1017, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1017, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1016 + * + * if not self.index and (cindexname or require_index): + * if errno: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Could not open index file", self.index_filename) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1019 + * raise OSError_from_errno("Could not open index file", self.index_filename) + * else: + * raise IOError('unable to open index file `%s`' % self.index_filename) # <<<<<<<<<<<<<< + * + * elif require_index: +*/ + /*else*/ { + __pyx_t_14 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_2 = __pyx_builtin_IOError; + __pyx_t_5 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_unable_to_open_index_file_s, __pyx_v_self->__pyx_base.index_filename); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1019, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_14, __pyx_t_5}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1019, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1019, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1015 + * HTS_IDX_SAVE_REMOTE|HTS_IDX_SILENT_FAIL) + * + * if not self.index and (cindexname or require_index): # <<<<<<<<<<<<<< + * if errno: + * raise OSError_from_errno("Could not open index file", self.index_filename) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1010 + * cindexname = bfile_name = encode_filename(self.index_filename) + * + * if cfilename or cindexname: # <<<<<<<<<<<<<< + * with nogil: + * self.index = sam_index_load3(self.htsfile, cfilename, cindexname, +*/ + goto __pyx_L93; + } + + /* "pysam/libcalignmentfile.pyx":1021 + * raise IOError('unable to open index file `%s`' % self.index_filename) + * + * elif require_index: # <<<<<<<<<<<<<< + * raise IOError('unable to open index file') + * +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_require_index); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1021, __pyx_L1_error) + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1022 + * + * elif require_index: + * raise IOError('unable to open index file') # <<<<<<<<<<<<<< + * + * # save start of data section +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_5 = __pyx_builtin_IOError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_unable_to_open_index_file}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1022, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1022, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1021 + * raise IOError('unable to open index file `%s`' % self.index_filename) + * + * elif require_index: # <<<<<<<<<<<<<< + * raise IOError('unable to open index file') + * +*/ + } + __pyx_L93:; + + /* "pysam/libcalignmentfile.pyx":1025 + * + * # save start of data section + * if not self.is_stream: # <<<<<<<<<<<<<< + * self.start_offset = self.tell() + * +*/ + __pyx_t_1 = (!__pyx_v_self->__pyx_base.is_stream); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1026 + * # save start of data section + * if not self.is_stream: + * self.start_offset = self.tell() # <<<<<<<<<<<<<< + * + * def fetch(self, +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_tell, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1026, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __pyx_t_20 = __Pyx_PyLong_As_int64_t(__pyx_t_4); if (unlikely((__pyx_t_20 == ((int64_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1026, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_self->__pyx_base.start_offset = __pyx_t_20; + + /* "pysam/libcalignmentfile.pyx":1025 + * + * # save start of data section + * if not self.is_stream: # <<<<<<<<<<<<<< + * self.start_offset = self.tell() + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1005 + * "check_sq=False") % mode) + * + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * self.index_filename = index_filename or filepath_index + * if self.index_filename: +*/ + } + + /* "pysam/libcalignmentfile.pyx":945 + * raise OSError_from_errno("Could not write headers", filename) + * + * elif mode[0] == "r": # <<<<<<<<<<<<<< + * # open file for reading + * self.htsfile = self._open_htsfile() +*/ + } + __pyx_L34:; + + /* "pysam/libcalignmentfile.pyx":787 + * return True + * + * def _open(self, # <<<<<<<<<<<<<< + * filepath_or_object, + * mode=None, +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 787, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_14); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 787, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile._open", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_filename); + __Pyx_XDECREF(__pyx_v_bfile_name); + __Pyx_XDECREF(__pyx_v_mode); + __Pyx_XDECREF(__pyx_v_reference_names); + __Pyx_XDECREF(__pyx_v_reference_lengths); + __Pyx_XDECREF(__pyx_v_reference_filename); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1028 + * self.start_offset = self.tell() + * + * def fetch(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_9fetch(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_8fetch, "AlignmentFile.fetch(self, contig=None, start=None, stop=None, region=None, tid=None, until_eof=False, multiple_iterators=False, reference=None, end=None)\n\nfetch reads aligned in a :term:`region`.\n\nSee :meth:`~pysam.HTSFile.parse_region` for more information\non how genomic regions can be specified. :term:`reference` and\n`end` are also accepted for backward compatibility as synonyms\nfor :term:`contig` and `stop`, respectively.\n\nWithout a `contig` or `region` all mapped reads in the file\nwill be fetched. The reads will be returned ordered by reference\nsequence, which will not necessarily be the order within the\nfile. This mode of iteration still requires an index. If there is\nno index, use `until_eof=True`.\n\nIf only `contig` is set, all reads aligned to `contig`\nwill be fetched.\n\nA :term:`SAM` file does not allow random access. If `region`\nor `contig` are given, an exception is raised.\n\nParameters\n----------\n\nuntil_eof : bool\n\n If `until_eof` is True, all reads from the current file\n position will be returned in order as they are within the\n file. Using this option will also fetch unmapped reads.\n\nmultiple_iterators : bool\n\n If `multiple_iterators` is True, multiple\n iterators on the same file can be used at the same time. The\n iterator returned will receive its own copy of a filehandle to\n the file effectively re-opening the file. Re-opening a file\n creates some overhead, so beware.\n\nReturns\n-------\n\n An iterator over a collection of reads. : IteratorRow\n\nRaises\n------\n\nValueError\n if the genomic coordinates are out of range or invalid or the\n file does not permit random access to genomic coordinates."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_9fetch = {"fetch", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_9fetch, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_8fetch}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_9fetch(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_contig = 0; + PyObject *__pyx_v_start = 0; + PyObject *__pyx_v_stop = 0; + PyObject *__pyx_v_region = 0; + PyObject *__pyx_v_tid = 0; + PyObject *__pyx_v_until_eof = 0; + PyObject *__pyx_v_multiple_iterators = 0; + PyObject *__pyx_v_reference = 0; + PyObject *__pyx_v_end = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("fetch (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_contig,&__pyx_mstate_global->__pyx_n_u_start,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_region,&__pyx_mstate_global->__pyx_n_u_tid,&__pyx_mstate_global->__pyx_n_u_until_eof,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,&__pyx_mstate_global->__pyx_n_u_reference,&__pyx_mstate_global->__pyx_n_u_end,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1028, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 9: + values[8] = __Pyx_ArgRef_FASTCALL(__pyx_args, 8); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[8])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "fetch", 0) < 0) __PYX_ERR(0, 1028, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":1029 + * + * def fetch(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1030 + * def fetch(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1031 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * tid=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1032 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * tid=None, + * until_eof=False, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1033 + * stop=None, + * region=None, + * tid=None, # <<<<<<<<<<<<<< + * until_eof=False, + * multiple_iterators=False, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1034 + * region=None, + * tid=None, + * until_eof=False, # <<<<<<<<<<<<<< + * multiple_iterators=False, + * reference=None, +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":1035 + * tid=None, + * until_eof=False, + * multiple_iterators=False, # <<<<<<<<<<<<<< + * reference=None, + * end=None): +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":1036 + * until_eof=False, + * multiple_iterators=False, + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * """fetch reads aligned in a :term:`region`. +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1037 + * multiple_iterators=False, + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * """fetch reads aligned in a :term:`region`. + * +*/ + if (!values[8]) values[8] = __Pyx_NewRef(((PyObject *)Py_None)); + } else { + switch (__pyx_nargs) { + case 9: + values[8] = __Pyx_ArgRef_FASTCALL(__pyx_args, 8); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[8])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1028, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + + /* "pysam/libcalignmentfile.pyx":1029 + * + * def fetch(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1030 + * def fetch(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1031 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * tid=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1032 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * tid=None, + * until_eof=False, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1033 + * stop=None, + * region=None, + * tid=None, # <<<<<<<<<<<<<< + * until_eof=False, + * multiple_iterators=False, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1034 + * region=None, + * tid=None, + * until_eof=False, # <<<<<<<<<<<<<< + * multiple_iterators=False, + * reference=None, +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":1035 + * tid=None, + * until_eof=False, + * multiple_iterators=False, # <<<<<<<<<<<<<< + * reference=None, + * end=None): +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_False)); + + /* "pysam/libcalignmentfile.pyx":1036 + * until_eof=False, + * multiple_iterators=False, + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * """fetch reads aligned in a :term:`region`. +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1037 + * multiple_iterators=False, + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * """fetch reads aligned in a :term:`region`. + * +*/ + if (!values[8]) values[8] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_contig = values[0]; + __pyx_v_start = values[1]; + __pyx_v_stop = values[2]; + __pyx_v_region = values[3]; + __pyx_v_tid = values[4]; + __pyx_v_until_eof = values[5]; + __pyx_v_multiple_iterators = values[6]; + __pyx_v_reference = values[7]; + __pyx_v_end = values[8]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("fetch", 0, 0, 9, __pyx_nargs); __PYX_ERR(0, 1028, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.fetch", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8fetch(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region, __pyx_v_tid, __pyx_v_until_eof, __pyx_v_multiple_iterators, __pyx_v_reference, __pyx_v_end); + + /* "pysam/libcalignmentfile.pyx":1028 + * self.start_offset = self.tell() + * + * def fetch(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8fetch(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_tid, PyObject *__pyx_v_until_eof, PyObject *__pyx_v_multiple_iterators, PyObject *__pyx_v_reference, PyObject *__pyx_v_end) { + int __pyx_v_rtid; + int __pyx_v_rstart; + int __pyx_v_rstop; + int __pyx_v_has_coord; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *(*__pyx_t_10)(PyObject *); + int __pyx_t_11; + int __pyx_t_12; + int __pyx_t_13; + int __pyx_t_14; + int __pyx_t_15; + PyObject *__pyx_t_16 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[39])) + __Pyx_RefNannySetupContext("fetch", 0); + __Pyx_TraceStartFunc("fetch", __pyx_f[0], 1028, 0, 0, 0, __PYX_ERR(0, 1028, __pyx_L1_error)); + __Pyx_INCREF(__pyx_v_multiple_iterators); + + /* "pysam/libcalignmentfile.pyx":1089 + * cdef int rtid, rstart, rstop, has_coord + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError( "I/O operation on closed file" ) + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1089, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1089, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1090 + * + * if not self.is_open: + * raise ValueError( "I/O operation on closed file" ) # <<<<<<<<<<<<<< + * + * has_coord, rtid, rstart, rstop = self.parse_region( +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1090, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1090, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1089 + * cdef int rtid, rstart, rstop, has_coord + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError( "I/O operation on closed file" ) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1092 + * raise ValueError( "I/O operation on closed file" ) + * + * has_coord, rtid, rstart, rstop = self.parse_region( # <<<<<<<<<<<<<< + * contig, start, stop, region, tid, + * end=end, reference=reference) +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":1094 + * has_coord, rtid, rstart, rstop = self.parse_region( + * contig, start, stop, region, tid, + * end=end, reference=reference) # <<<<<<<<<<<<<< + * + * # Turn of re-opening if htsfile is a stream +*/ + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[6 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_5, __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region, __pyx_v_tid}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_end, __pyx_v_end, __pyx_t_4, __pyx_callargs+6, 0) < 0) __PYX_ERR(0, 1092, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference, __pyx_v_reference, __pyx_t_4, __pyx_callargs+6, 1) < 0) __PYX_ERR(0, 1092, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_parse_region, __pyx_callargs+__pyx_t_6, (6-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 4)) { + if (size > 4) __Pyx_RaiseTooManyValuesError(4); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 1092, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 2); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 3); + __Pyx_INCREF(__pyx_t_8); + } else { + __pyx_t_4 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_PyList_GetItemRef(sequence, 2); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyList_GetItemRef(sequence, 3); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_8); + } + #else + { + Py_ssize_t i; + PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_5,&__pyx_t_7,&__pyx_t_8}; + for (i=0; i < 4; i++) { + PyObject* item = __Pyx_PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_GOTREF(item); + *(temps[i]) = item; + } + } + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_5,&__pyx_t_7,&__pyx_t_8}; + __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); + for (index=0; index < 4; index++) { + PyObject* item = __pyx_t_10(__pyx_t_9); if (unlikely(!item)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(item); + *(temps[index]) = item; + } + if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 4) < 0) __PYX_ERR(0, 1092, __pyx_L1_error) + __pyx_t_10 = NULL; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 1092, __pyx_L1_error) + __pyx_L5_unpacking_done:; + } + + /* "pysam/libcalignmentfile.pyx":1092 + * raise ValueError( "I/O operation on closed file" ) + * + * has_coord, rtid, rstart, rstop = self.parse_region( # <<<<<<<<<<<<<< + * contig, start, stop, region, tid, + * end=end, reference=reference) +*/ + __pyx_t_11 = __Pyx_PyLong_As_int(__pyx_t_4); if (unlikely((__pyx_t_11 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = __Pyx_PyLong_As_int(__pyx_t_5); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_13 = __Pyx_PyLong_As_int(__pyx_t_7); if (unlikely((__pyx_t_13 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_14 = __Pyx_PyLong_As_int(__pyx_t_8); if (unlikely((__pyx_t_14 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1092, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_has_coord = __pyx_t_11; + __pyx_v_rtid = __pyx_t_12; + __pyx_v_rstart = __pyx_t_13; + __pyx_v_rstop = __pyx_t_14; + + /* "pysam/libcalignmentfile.pyx":1097 + * + * # Turn of re-opening if htsfile is a stream + * if self.is_stream: # <<<<<<<<<<<<<< + * multiple_iterators = False + * +*/ + if (__pyx_v_self->__pyx_base.is_stream) { + + /* "pysam/libcalignmentfile.pyx":1098 + * # Turn of re-opening if htsfile is a stream + * if self.is_stream: + * multiple_iterators = False # <<<<<<<<<<<<<< + * + * if self.is_bam or self.is_cram: +*/ + __Pyx_INCREF(Py_False); + __Pyx_DECREF_SET(__pyx_v_multiple_iterators, Py_False); + + /* "pysam/libcalignmentfile.pyx":1097 + * + * # Turn of re-opening if htsfile is a stream + * if self.is_stream: # <<<<<<<<<<<<<< + * multiple_iterators = False + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1100 + * multiple_iterators = False + * + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * if not until_eof and not self.is_remote: + * if not self.has_index(): +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1100, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L8_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1100, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1100, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __pyx_t_2; + __pyx_L8_bool_binop_done:; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1101 + * + * if self.is_bam or self.is_cram: + * if not until_eof and not self.is_remote: # <<<<<<<<<<<<<< + * if not self.has_index(): + * raise ValueError( +*/ + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_until_eof); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1101, __pyx_L1_error) + __pyx_t_15 = (!__pyx_t_2); + if (__pyx_t_15) { + } else { + __pyx_t_3 = __pyx_t_15; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_15 = (!__pyx_v_self->__pyx_base.is_remote); + __pyx_t_3 = __pyx_t_15; + __pyx_L11_bool_binop_done:; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1102 + * if self.is_bam or self.is_cram: + * if not until_eof and not self.is_remote: + * if not self.has_index(): # <<<<<<<<<<<<<< + * raise ValueError( + * "fetch called on bamfile without index") +*/ + __pyx_t_8 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_8); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1102, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1102, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_15 = (!__pyx_t_3); + if (unlikely(__pyx_t_15)) { + + /* "pysam/libcalignmentfile.pyx":1103 + * if not until_eof and not self.is_remote: + * if not self.has_index(): + * raise ValueError( # <<<<<<<<<<<<<< + * "fetch called on bamfile without index") + * +*/ + __pyx_t_8 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_7 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_mstate_global->__pyx_kp_u_fetch_called_on_bamfile_without}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1103, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1103, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1102 + * if self.is_bam or self.is_cram: + * if not until_eof and not self.is_remote: + * if not self.has_index(): # <<<<<<<<<<<<<< + * raise ValueError( + * "fetch called on bamfile without index") +*/ + } + + /* "pysam/libcalignmentfile.pyx":1101 + * + * if self.is_bam or self.is_cram: + * if not until_eof and not self.is_remote: # <<<<<<<<<<<<<< + * if not self.has_index(): + * raise ValueError( +*/ + } + + /* "pysam/libcalignmentfile.pyx":1106 + * "fetch called on bamfile without index") + * + * if has_coord: # <<<<<<<<<<<<<< + * return IteratorRowRegion( + * self, rtid, rstart, rstop, +*/ + __pyx_t_15 = (__pyx_v_has_coord != 0); + if (__pyx_t_15) { + + /* "pysam/libcalignmentfile.pyx":1107 + * + * if has_coord: + * return IteratorRowRegion( # <<<<<<<<<<<<<< + * self, rtid, rstart, rstop, + * multiple_iterators=multiple_iterators) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_7 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_8 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + + /* "pysam/libcalignmentfile.pyx":1108 + * if has_coord: + * return IteratorRowRegion( + * self, rtid, rstart, rstop, # <<<<<<<<<<<<<< + * multiple_iterators=multiple_iterators) + * else: +*/ + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_rtid); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_rstart); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_rstop); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + + /* "pysam/libcalignmentfile.pyx":1109 + * return IteratorRowRegion( + * self, rtid, rstart, rstop, + * multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * else: + * if until_eof: +*/ + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[5 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_7, ((PyObject *)__pyx_v_self), __pyx_t_5, __pyx_t_4, __pyx_t_9}; + __pyx_t_16 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 1107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_16, __pyx_callargs+5, 0) < 0) __PYX_ERR(0, 1107, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_8, __pyx_callargs+__pyx_t_6, (5-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_16); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1107, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 63, 0, __PYX_ERR(0, 1107, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1106 + * "fetch called on bamfile without index") + * + * if has_coord: # <<<<<<<<<<<<<< + * return IteratorRowRegion( + * self, rtid, rstart, rstop, +*/ + } + + /* "pysam/libcalignmentfile.pyx":1111 + * multiple_iterators=multiple_iterators) + * else: + * if until_eof: # <<<<<<<<<<<<<< + * return IteratorRowAll( + * self, +*/ + /*else*/ { + __pyx_t_15 = __Pyx_PyObject_IsTrue(__pyx_v_until_eof); if (unlikely((__pyx_t_15 < 0))) __PYX_ERR(0, 1111, __pyx_L1_error) + if (__pyx_t_15) { + + /* "pysam/libcalignmentfile.pyx":1112 + * else: + * if until_eof: + * return IteratorRowAll( # <<<<<<<<<<<<<< + * self, + * multiple_iterators=multiple_iterators) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + __pyx_t_16 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + + /* "pysam/libcalignmentfile.pyx":1114 + * return IteratorRowAll( + * self, + * multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * else: + * # AH: check - reason why no multiple_iterators for +*/ + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_8, ((PyObject *)__pyx_v_self)}; + __pyx_t_9 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_9, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 1112, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_16, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_9); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1112, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 74, 0, __PYX_ERR(0, 1112, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1111 + * multiple_iterators=multiple_iterators) + * else: + * if until_eof: # <<<<<<<<<<<<<< + * return IteratorRowAll( + * self, +*/ + } + + /* "pysam/libcalignmentfile.pyx":1118 + * # AH: check - reason why no multiple_iterators for + * # AllRefs? + * return IteratorRowAllRefs( # <<<<<<<<<<<<<< + * self, + * multiple_iterators=multiple_iterators) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_16 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs); + __pyx_t_9 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs); + + /* "pysam/libcalignmentfile.pyx":1120 + * return IteratorRowAllRefs( + * self, + * multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * else: + * if has_coord: +*/ + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_16, ((PyObject *)__pyx_v_self)}; + __pyx_t_8 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1118, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_8, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 1118, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_9, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_8); + __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1118, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 80, 0, __PYX_ERR(0, 1118, __pyx_L1_error)); + goto __pyx_L0; + } + } + + /* "pysam/libcalignmentfile.pyx":1100 + * multiple_iterators = False + * + * if self.is_bam or self.is_cram: # <<<<<<<<<<<<<< + * if not until_eof and not self.is_remote: + * if not self.has_index(): +*/ + } + + /* "pysam/libcalignmentfile.pyx":1122 + * multiple_iterators=multiple_iterators) + * else: + * if has_coord: # <<<<<<<<<<<<<< + * raise ValueError( + * "fetching by region is not available for SAM files") +*/ + /*else*/ { + __pyx_t_15 = (__pyx_v_has_coord != 0); + if (unlikely(__pyx_t_15)) { + + /* "pysam/libcalignmentfile.pyx":1123 + * else: + * if has_coord: + * raise ValueError( # <<<<<<<<<<<<<< + * "fetching by region is not available for SAM files") + * +*/ + __pyx_t_9 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_8 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_9, __pyx_mstate_global->__pyx_kp_u_fetching_by_region_is_not_availa}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1123, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1123, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1122 + * multiple_iterators=multiple_iterators) + * else: + * if has_coord: # <<<<<<<<<<<<<< + * raise ValueError( + * "fetching by region is not available for SAM files") +*/ + } + + /* "pysam/libcalignmentfile.pyx":1126 + * "fetching by region is not available for SAM files") + * + * if multiple_iterators == True: # <<<<<<<<<<<<<< + * raise ValueError( + * "multiple iterators not implemented for SAM files") +*/ + __pyx_t_1 = PyObject_RichCompare(__pyx_v_multiple_iterators, Py_True, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1126, __pyx_L1_error) + __pyx_t_15 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_15 < 0))) __PYX_ERR(0, 1126, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(__pyx_t_15)) { + + /* "pysam/libcalignmentfile.pyx":1127 + * + * if multiple_iterators == True: + * raise ValueError( # <<<<<<<<<<<<<< + * "multiple iterators not implemented for SAM files") + * +*/ + __pyx_t_8 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_9 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_mstate_global->__pyx_kp_u_multiple_iterators_not_implement}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_9, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1127, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1127, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1126 + * "fetching by region is not available for SAM files") + * + * if multiple_iterators == True: # <<<<<<<<<<<<<< + * raise ValueError( + * "multiple iterators not implemented for SAM files") +*/ + } + + /* "pysam/libcalignmentfile.pyx":1130 + * "multiple iterators not implemented for SAM files") + * + * return IteratorRowAll(self, # <<<<<<<<<<<<<< + * multiple_iterators=multiple_iterators) + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_9 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + __pyx_t_8 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll); + + /* "pysam/libcalignmentfile.pyx":1131 + * + * return IteratorRowAll(self, + * multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * def head(self, n, multiple_iterators=True): +*/ + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_9, ((PyObject *)__pyx_v_self)}; + __pyx_t_16 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 1130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_16, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 1130, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_8, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_16); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1130, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 100, 0, __PYX_ERR(0, 1130, __pyx_L1_error)); + goto __pyx_L0; + } + + /* "pysam/libcalignmentfile.pyx":1028 + * self.start_offset = self.tell() + * + * def fetch(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1028, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.fetch", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_multiple_iterators); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1133 + * multiple_iterators=multiple_iterators) + * + * def head(self, n, multiple_iterators=True): # <<<<<<<<<<<<<< + * '''return an iterator over the first n alignments. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11head(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_10head, "AlignmentFile.head(self, n, multiple_iterators=True)\n\nreturn an iterator over the first n alignments.\n\nThis iterator is is useful for inspecting the bam-file.\n\nParameters\n----------\n\nmultiple_iterators : bool\n\n is set to True by default in order to\n avoid changing the current file position.\n\nReturns\n-------\n\n an iterator over a collection of reads : IteratorRowHead"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_11head = {"head", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11head, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_10head}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11head(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_n = 0; + PyObject *__pyx_v_multiple_iterators = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("head (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_n,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1133, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1133, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1133, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "head", 0) < 0) __PYX_ERR(0, 1133, __pyx_L3_error) + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_True)); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("head", 0, 1, 2, i); __PYX_ERR(0, 1133, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1133, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1133, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_True)); + } + __pyx_v_n = values[0]; + __pyx_v_multiple_iterators = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("head", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 1133, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.head", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10head(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_n, __pyx_v_multiple_iterators); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10head(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_n, PyObject *__pyx_v_multiple_iterators) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[40])) + __Pyx_RefNannySetupContext("head", 0); + __Pyx_TraceStartFunc("head", __pyx_f[0], 1133, 0, 0, 0, __PYX_ERR(0, 1133, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1152 + * + * ''' + * return IteratorRowHead(self, n, # <<<<<<<<<<<<<< + * multiple_iterators=multiple_iterators) + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead); + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead); + + /* "pysam/libcalignmentfile.pyx":1153 + * ''' + * return IteratorRowHead(self, n, + * multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * def mate(self, AlignedSegment read): +*/ + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[3 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_2, ((PyObject *)__pyx_v_self), __pyx_v_n}; + __pyx_t_5 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1152, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_5, __pyx_callargs+3, 0) < 0) __PYX_ERR(0, 1152, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_3, __pyx_callargs+__pyx_t_4, (3-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_5); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1152, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 2, 0, __PYX_ERR(0, 1152, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1133 + * multiple_iterators=multiple_iterators) + * + * def head(self, n, multiple_iterators=True): # <<<<<<<<<<<<<< + * '''return an iterator over the first n alignments. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1133, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.head", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1155 + * multiple_iterators=multiple_iterators) + * + * def mate(self, AlignedSegment read): # <<<<<<<<<<<<<< + * '''return the mate of :class:`pysam.AlignedSegment` `read`. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_13mate(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_12mate, "AlignmentFile.mate(self, AlignedSegment read)\n\nreturn the mate of :class:`pysam.AlignedSegment` `read`.\n\n.. note::\n\n Calling this method will change the file position.\n This might interfere with any iterators that have\n not re-opened the file.\n\n.. note::\n\n This method is too slow for high-throughput processing.\n If a read needs to be processed with its mate, work\n from a read name sorted file or, better, cache reads.\n\nReturns\n-------\n\nthe mate : AlignedSegment\n\nRaises\n------\n\nValueError\n if the read is unpaired or the mate is unmapped"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_13mate = {"mate", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_13mate, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_12mate}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_13mate(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("mate (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_read,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1155, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1155, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "mate", 0) < 0) __PYX_ERR(0, 1155, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("mate", 1, 1, 1, i); __PYX_ERR(0, 1155, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1155, __pyx_L3_error) + } + __pyx_v_read = ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("mate", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1155, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.mate", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment, 1, "read", 0))) __PYX_ERR(0, 1155, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12mate(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_read); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12mate(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read) { + uint32_t __pyx_v_flag; + int __pyx_v_x; + PyObject *__pyx_v_mate = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + uint16_t __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + PyObject *(*__pyx_t_11)(PyObject *); + int __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[41])) + __Pyx_RefNannySetupContext("mate", 0); + __Pyx_TraceStartFunc("mate", __pyx_f[0], 1155, 0, 0, 0, __PYX_ERR(0, 1155, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1182 + * + * ''' + * cdef uint32_t flag = read._delegate.core.flag # <<<<<<<<<<<<<< + * + * if flag & BAM_FPAIRED == 0: +*/ + __pyx_t_1 = __pyx_v_read->_delegate->core.flag; + __pyx_v_flag = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":1184 + * cdef uint32_t flag = read._delegate.core.flag + * + * if flag & BAM_FPAIRED == 0: # <<<<<<<<<<<<<< + * raise ValueError("read %s: is unpaired" % + * (read.query_name)) +*/ + __pyx_t_2 = ((__pyx_v_flag & BAM_FPAIRED) == 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":1185 + * + * if flag & BAM_FPAIRED == 0: + * raise ValueError("read %s: is unpaired" % # <<<<<<<<<<<<<< + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":1186 + * if flag & BAM_FPAIRED == 0: + * raise ValueError("read %s: is unpaired" % + * (read.query_name)) # <<<<<<<<<<<<<< + * if flag & BAM_FMUNMAP != 0: + * raise ValueError("mate %s: is unmapped" % +*/ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_query_name); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1186, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "pysam/libcalignmentfile.pyx":1185 + * + * if flag & BAM_FPAIRED == 0: + * raise ValueError("read %s: is unpaired" % # <<<<<<<<<<<<<< + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: +*/ + __pyx_t_7 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_read_s_is_unpaired, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1185, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_7}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1185, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 1185, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1184 + * cdef uint32_t flag = read._delegate.core.flag + * + * if flag & BAM_FPAIRED == 0: # <<<<<<<<<<<<<< + * raise ValueError("read %s: is unpaired" % + * (read.query_name)) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1187 + * raise ValueError("read %s: is unpaired" % + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: # <<<<<<<<<<<<<< + * raise ValueError("mate %s: is unmapped" % + * (read.query_name)) +*/ + __pyx_t_2 = ((__pyx_v_flag & BAM_FMUNMAP) != 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":1188 + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: + * raise ValueError("mate %s: is unmapped" % # <<<<<<<<<<<<<< + * (read.query_name)) + * +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_7 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":1189 + * if flag & BAM_FMUNMAP != 0: + * raise ValueError("mate %s: is unmapped" % + * (read.query_name)) # <<<<<<<<<<<<<< + * + * # xor flags to get the other mate +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_query_name); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1189, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "pysam/libcalignmentfile.pyx":1188 + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: + * raise ValueError("mate %s: is unmapped" % # <<<<<<<<<<<<<< + * (read.query_name)) + * +*/ + __pyx_t_6 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_mate_s_is_unmapped, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1188, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_t_6}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1188, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 1188, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1187 + * raise ValueError("read %s: is unpaired" % + * (read.query_name)) + * if flag & BAM_FMUNMAP != 0: # <<<<<<<<<<<<<< + * raise ValueError("mate %s: is unmapped" % + * (read.query_name)) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1192 + * + * # xor flags to get the other mate + * cdef int x = BAM_FREAD1 + BAM_FREAD2 # <<<<<<<<<<<<<< + * flag = (flag ^ x) & x + * +*/ + __pyx_v_x = (BAM_FREAD1 + BAM_FREAD2); + + /* "pysam/libcalignmentfile.pyx":1193 + * # xor flags to get the other mate + * cdef int x = BAM_FREAD1 + BAM_FREAD2 + * flag = (flag ^ x) & x # <<<<<<<<<<<<<< + * + * # Make sure to use a separate file to jump around +*/ + __pyx_v_flag = ((__pyx_v_flag ^ __pyx_v_x) & __pyx_v_x); + + /* "pysam/libcalignmentfile.pyx":1201 + * # could thus be made much quicker, for example + * # by using tell and seek. + * for mate in self.fetch( # <<<<<<<<<<<<<< + * read._delegate.core.mpos, + * read._delegate.core.mpos + 1, +*/ + __pyx_t_7 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_7); + + /* "pysam/libcalignmentfile.pyx":1202 + * # by using tell and seek. + * for mate in self.fetch( + * read._delegate.core.mpos, # <<<<<<<<<<<<<< + * read._delegate.core.mpos + 1, + * tid=read._delegate.core.mtid, +*/ + __pyx_t_6 = __Pyx_PyLong_From_int32_t(__pyx_v_read->_delegate->core.mpos); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1202, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "pysam/libcalignmentfile.pyx":1203 + * for mate in self.fetch( + * read._delegate.core.mpos, + * read._delegate.core.mpos + 1, # <<<<<<<<<<<<<< + * tid=read._delegate.core.mtid, + * multiple_iterators=True): +*/ + __pyx_t_5 = __Pyx_PyLong_From_long((__pyx_v_read->_delegate->core.mpos + 1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1203, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":1204 + * read._delegate.core.mpos, + * read._delegate.core.mpos + 1, + * tid=read._delegate.core.mtid, # <<<<<<<<<<<<<< + * multiple_iterators=True): + * if mate.flag & flag != 0 and \ +*/ + __pyx_t_4 = __Pyx_PyLong_From_int32_t(__pyx_v_read->_delegate->core.mtid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1204, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "pysam/libcalignmentfile.pyx":1205 + * read._delegate.core.mpos + 1, + * tid=read._delegate.core.mtid, + * multiple_iterators=True): # <<<<<<<<<<<<<< + * if mate.flag & flag != 0 and \ + * mate.query_name == read.query_name: +*/ + __pyx_t_8 = 0; + { + PyObject *__pyx_callargs[3 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_7, __pyx_t_6, __pyx_t_5}; + __pyx_t_9 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_tid, __pyx_t_4, __pyx_t_9, __pyx_callargs+3, 0) < 0) __PYX_ERR(0, 1201, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, Py_True, __pyx_t_9, __pyx_callargs+3, 1) < 0) __PYX_ERR(0, 1201, __pyx_L1_error) + __pyx_t_3 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_fetch, __pyx_callargs+__pyx_t_8, (3-__pyx_t_8) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_9); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + + /* "pysam/libcalignmentfile.pyx":1201 + * # could thus be made much quicker, for example + * # by using tell and seek. + * for mate in self.fetch( # <<<<<<<<<<<<<< + * read._delegate.core.mpos, + * read._delegate.core.mpos + 1, +*/ + if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { + __pyx_t_9 = __pyx_t_3; __Pyx_INCREF(__pyx_t_9); + __pyx_t_10 = 0; + __pyx_t_11 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1201, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1201, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + for (;;) { + if (likely(!__pyx_t_11)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1201, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + __pyx_t_3 = __Pyx_PyList_GetItemRef(__pyx_t_9, __pyx_t_10); + ++__pyx_t_10; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1201, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10)); + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(__pyx_t_9, __pyx_t_10); + #endif + ++__pyx_t_10; + } + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1201, __pyx_L1_error) + } else { + __pyx_t_3 = __pyx_t_11(__pyx_t_9); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1201, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_3); + __Pyx_XDECREF_SET(__pyx_v_mate, __pyx_t_3); + __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":1206 + * tid=read._delegate.core.mtid, + * multiple_iterators=True): + * if mate.flag & flag != 0 and \ # <<<<<<<<<<<<<< + * mate.query_name == read.query_name: + * break +*/ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_mate, __pyx_mstate_global->__pyx_n_u_flag); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyLong_From_uint32_t(__pyx_v_flag); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyNumber_And(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = (__Pyx_PyLong_BoolNeObjC(__pyx_t_5, __pyx_mstate_global->__pyx_int_0, 0, 0)); if (unlikely((__pyx_t_12 < 0))) __PYX_ERR(0, 1206, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_12) { + } else { + __pyx_t_2 = __pyx_t_12; + goto __pyx_L8_bool_binop_done; + } + + /* "pysam/libcalignmentfile.pyx":1207 + * multiple_iterators=True): + * if mate.flag & flag != 0 and \ + * mate.query_name == read.query_name: # <<<<<<<<<<<<<< + * break + * else: +*/ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_mate, __pyx_mstate_global->__pyx_n_u_query_name); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1207, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_query_name); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1207, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_5, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1207, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_12 < 0))) __PYX_ERR(0, 1207, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_2 = __pyx_t_12; + __pyx_L8_bool_binop_done:; + + /* "pysam/libcalignmentfile.pyx":1206 + * tid=read._delegate.core.mtid, + * multiple_iterators=True): + * if mate.flag & flag != 0 and \ # <<<<<<<<<<<<<< + * mate.query_name == read.query_name: + * break +*/ + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":1208 + * if mate.flag & flag != 0 and \ + * mate.query_name == read.query_name: + * break # <<<<<<<<<<<<<< + * else: + * raise ValueError("mate not found") +*/ + goto __pyx_L6_break; + + /* "pysam/libcalignmentfile.pyx":1206 + * tid=read._delegate.core.mtid, + * multiple_iterators=True): + * if mate.flag & flag != 0 and \ # <<<<<<<<<<<<<< + * mate.query_name == read.query_name: + * break +*/ + } + + /* "pysam/libcalignmentfile.pyx":1201 + * # could thus be made much quicker, for example + * # by using tell and seek. + * for mate in self.fetch( # <<<<<<<<<<<<<< + * read._delegate.core.mpos, + * read._delegate.core.mpos + 1, +*/ + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L10_for_else; + __pyx_L6_break:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L11_for_end; + /*else*/ { + __pyx_L10_for_else:; + + /* "pysam/libcalignmentfile.pyx":1210 + * break + * else: + * raise ValueError("mate not found") # <<<<<<<<<<<<<< + * + * return mate +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_mate_not_found}; + __pyx_t_9 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1210, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + } + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __PYX_ERR(0, 1210, __pyx_L1_error) + } + __pyx_L11_for_end:; + + /* "pysam/libcalignmentfile.pyx":1212 + * raise ValueError("mate not found") + * + * return mate # <<<<<<<<<<<<<< + * + * def pileup(self, +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_mate); + __pyx_r = __pyx_v_mate; + __Pyx_TraceReturnValue(__pyx_r, 82, 0, __PYX_ERR(0, 1212, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1155 + * multiple_iterators=multiple_iterators) + * + * def mate(self, AlignedSegment read): # <<<<<<<<<<<<<< + * '''return the mate of :class:`pysam.AlignedSegment` `read`. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1155, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.mate", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_mate); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1214 + * return mate + * + * def pileup(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_15pileup(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_14pileup, "AlignmentFile.pileup(self, contig=None, start=None, stop=None, region=None, reference=None, end=None, **kwargs)\n\nperform a :term:`pileup` within a :term:`region`. The region is\nspecified by :term:`contig`, `start` and `stop` (using\n0-based indexing). :term:`reference` and `end` are also accepted for\nbackward compatibility as synonyms for :term:`contig` and `stop`,\nrespectively. Alternatively, a samtools 'region' string\ncan be supplied.\n\nWithout 'contig' or 'region' all reads will be used for the\npileup. The reads will be returned ordered by\n:term:`contig` sequence, which will not necessarily be the\norder within the file.\n\nNote that :term:`SAM` formatted files do not allow random\naccess. In these files, if a 'region' or 'contig' are\ngiven an exception is raised.\n\n.. note::\n\n 'all' reads which overlap the region are returned. The\n first base returned will be the first base of the first\n read 'not' necessarily the first base of the region used\n in the query.\n\nParameters\n----------\n\ntruncate : bool\n\n By default, the samtools pileup engine outputs all reads\n overlapping a region. If truncate is True and a region is\n given, only columns in the exact region specified are\n returned.\n\nmax_depth : int\n Maximum read depth permitted. The default limit is '8000'.\n\nstepper : string\n The stepper controls how the iterator advances.\n Possible options for the stepper are\n\n ``all``\n skip reads in which any of the following flags are set:\n BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL, BAM_FDUP\n\n ``nofilter``\n uses every single read turning off any filtering.\n\n ``samtools``\n same filter and read processing as in samtools\n pileup. For full compatibility, this requires a\n 'fastafile' to be given. The following options all pertain\n to filtering of the ``samtools`` stepper.\n\nfastafile : :class:`~pysam.FastaFile` object.\n\n This is required for some of the steppers.\n""\nignore_overlaps: bool\n\n If set to True, detect if read pairs overlap and only take\n the higher quality base. This is the default.\n\nflag_filter : int\n\n ignore reads where any of the bits in the flag are set. The default is\n BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP.\n\nflag_require : int\n\n only use reads where certain flags are set. The default is 0.\n\nignore_orphans: bool\n\n ignore orphans (paired reads that are not in a proper pair).\n The default is to ignore orphans.\n\nmin_base_quality: int\n\n Minimum base quality. Bases below the minimum quality will\n not be output. The default is 13.\n\nadjust_capq_threshold: int\n\n adjust mapping quality. The default is 0 for no\n adjustment. The recommended value for adjustment is 50.\n\nmin_mapping_quality : int\n\n only use reads above a minimum mapping quality. The default is 0.\n\ncompute_baq: bool\n\n re-alignment computing per-Base Alignment Qualities (BAQ). The\n default is to do re-alignment. Realignment requires a reference\n sequence. If none is present, no realignment will be performed.\n\nredo_baq: bool\n\n recompute per-Base Alignment Quality on the fly ignoring\n existing base qualities. The default is False (use existing\n base qualities).\n\nReturns\n-------\n\nan iterator over genomic positions. : IteratorColumn"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_15pileup = {"pileup", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_15pileup, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_14pileup}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_15pileup(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_contig = 0; + PyObject *__pyx_v_start = 0; + PyObject *__pyx_v_stop = 0; + PyObject *__pyx_v_region = 0; + PyObject *__pyx_v_reference = 0; + PyObject *__pyx_v_end = 0; + PyObject *__pyx_v_kwargs = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[6] = {0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("pileup (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return NULL; + __Pyx_GOTREF(__pyx_v_kwargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_contig,&__pyx_mstate_global->__pyx_n_u_start,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_region,&__pyx_mstate_global->__pyx_n_u_reference,&__pyx_mstate_global->__pyx_n_u_end,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1214, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, __pyx_v_kwargs, values, kwd_pos_args, __pyx_kwds_len, "pileup", 1) < 0) __PYX_ERR(0, 1214, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":1215 + * + * def pileup(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1216 + * def pileup(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1217 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * reference=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1218 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * reference=None, + * end=None, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1219 + * stop=None, + * region=None, + * reference=None, # <<<<<<<<<<<<<< + * end=None, + * **kwargs): +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1220 + * region=None, + * reference=None, + * end=None, # <<<<<<<<<<<<<< + * **kwargs): + * """perform a :term:`pileup` within a :term:`region`. The region is +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_None)); + } else { + switch (__pyx_nargs) { + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1214, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + + /* "pysam/libcalignmentfile.pyx":1215 + * + * def pileup(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1216 + * def pileup(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1217 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * reference=None, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1218 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * reference=None, + * end=None, +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1219 + * stop=None, + * region=None, + * reference=None, # <<<<<<<<<<<<<< + * end=None, + * **kwargs): +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1220 + * region=None, + * reference=None, + * end=None, # <<<<<<<<<<<<<< + * **kwargs): + * """perform a :term:`pileup` within a :term:`region`. The region is +*/ + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_contig = values[0]; + __pyx_v_start = values[1]; + __pyx_v_stop = values[2]; + __pyx_v_region = values[3]; + __pyx_v_reference = values[4]; + __pyx_v_end = values[5]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("pileup", 0, 0, 6, __pyx_nargs); __PYX_ERR(0, 1214, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.pileup", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_14pileup(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region, __pyx_v_reference, __pyx_v_end, __pyx_v_kwargs); + + /* "pysam/libcalignmentfile.pyx":1214 + * return mate + * + * def pileup(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_DECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_14pileup(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_reference, PyObject *__pyx_v_end, PyObject *__pyx_v_kwargs) { + int __pyx_v_rtid; + int __pyx_v_has_coord; + int32_t __pyx_v_rstart; + int32_t __pyx_v_rstop; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *(*__pyx_t_10)(PyObject *); + int __pyx_t_11; + int __pyx_t_12; + int32_t __pyx_t_13; + int32_t __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[42])) + __Pyx_RefNannySetupContext("pileup", 0); + __Pyx_TraceStartFunc("pileup", __pyx_f[0], 1214, 0, 0, 0, __PYX_ERR(0, 1214, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1333 + * cdef int32_t rstart, rstop + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1333, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1333, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1334 + * + * if not self.is_open: + * raise ValueError("I/O operation on closed file") # <<<<<<<<<<<<<< + * + * has_coord, rtid, rstart, rstop = self.parse_region( +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1334, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1334, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1333 + * cdef int32_t rstart, rstop + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1336 + * raise ValueError("I/O operation on closed file") + * + * has_coord, rtid, rstart, rstop = self.parse_region( # <<<<<<<<<<<<<< + * contig, start, stop, region, reference=reference, end=end) + * +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":1337 + * + * has_coord, rtid, rstart, rstop = self.parse_region( + * contig, start, stop, region, reference=reference, end=end) # <<<<<<<<<<<<<< + * + * if has_coord: +*/ + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[5 + ((CYTHON_VECTORCALL) ? 2 : 0)] = {__pyx_t_5, __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference, __pyx_v_reference, __pyx_t_4, __pyx_callargs+5, 0) < 0) __PYX_ERR(0, 1336, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_end, __pyx_v_end, __pyx_t_4, __pyx_callargs+5, 1) < 0) __PYX_ERR(0, 1336, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_parse_region, __pyx_callargs+__pyx_t_6, (5-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { + PyObject* sequence = __pyx_t_1; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 4)) { + if (size > 4) __Pyx_RaiseTooManyValuesError(4); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 1336, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_7 = PyTuple_GET_ITEM(sequence, 2); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_8 = PyTuple_GET_ITEM(sequence, 3); + __Pyx_INCREF(__pyx_t_8); + } else { + __pyx_t_4 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_5); + __pyx_t_7 = __Pyx_PyList_GetItemRef(sequence, 2); + if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyList_GetItemRef(sequence, 3); + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_8); + } + #else + { + Py_ssize_t i; + PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_5,&__pyx_t_7,&__pyx_t_8}; + for (i=0; i < 4; i++) { + PyObject* item = __Pyx_PySequence_ITEM(sequence, i); if (unlikely(!item)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_GOTREF(item); + *(temps[i]) = item; + } + } + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else { + Py_ssize_t index = -1; + PyObject** temps[4] = {&__pyx_t_4,&__pyx_t_5,&__pyx_t_7,&__pyx_t_8}; + __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); + for (index=0; index < 4; index++) { + PyObject* item = __pyx_t_10(__pyx_t_9); if (unlikely(!item)) goto __pyx_L4_unpacking_failed; + __Pyx_GOTREF(item); + *(temps[index]) = item; + } + if (__Pyx_IternextUnpackEndCheck(__pyx_t_10(__pyx_t_9), 4) < 0) __PYX_ERR(0, 1336, __pyx_L1_error) + __pyx_t_10 = NULL; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + goto __pyx_L5_unpacking_done; + __pyx_L4_unpacking_failed:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_10 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 1336, __pyx_L1_error) + __pyx_L5_unpacking_done:; + } + + /* "pysam/libcalignmentfile.pyx":1336 + * raise ValueError("I/O operation on closed file") + * + * has_coord, rtid, rstart, rstop = self.parse_region( # <<<<<<<<<<<<<< + * contig, start, stop, region, reference=reference, end=end) + * +*/ + __pyx_t_11 = __Pyx_PyLong_As_int(__pyx_t_4); if (unlikely((__pyx_t_11 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_12 = __Pyx_PyLong_As_int(__pyx_t_5); if (unlikely((__pyx_t_12 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_13 = __Pyx_PyLong_As_int32_t(__pyx_t_7); if (unlikely((__pyx_t_13 == ((int32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_14 = __Pyx_PyLong_As_int32_t(__pyx_t_8); if (unlikely((__pyx_t_14 == ((int32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_v_has_coord = __pyx_t_11; + __pyx_v_rtid = __pyx_t_12; + __pyx_v_rstart = __pyx_t_13; + __pyx_v_rstop = __pyx_t_14; + + /* "pysam/libcalignmentfile.pyx":1339 + * contig, start, stop, region, reference=reference, end=end) + * + * if has_coord: # <<<<<<<<<<<<<< + * if not self.has_index(): + * raise ValueError("no index available for pileup") +*/ + __pyx_t_3 = (__pyx_v_has_coord != 0); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1340 + * + * if has_coord: + * if not self.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for pileup") + * +*/ + __pyx_t_8 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_8); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1340, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1340, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = (!__pyx_t_3); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":1341 + * if has_coord: + * if not self.has_index(): + * raise ValueError("no index available for pileup") # <<<<<<<<<<<<<< + * + * return IteratorColumnRegion(self, +*/ + __pyx_t_8 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_7 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_mstate_global->__pyx_kp_u_no_index_available_for_pileup}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1341, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1341, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1340 + * + * if has_coord: + * if not self.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for pileup") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1343 + * raise ValueError("no index available for pileup") + * + * return IteratorColumnRegion(self, # <<<<<<<<<<<<<< + * tid=rtid, + * start=rstart, +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_7 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion); + __pyx_t_8 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion); + + /* "pysam/libcalignmentfile.pyx":1344 + * + * return IteratorColumnRegion(self, + * tid=rtid, # <<<<<<<<<<<<<< + * start=rstart, + * stop=rstop, +*/ + __pyx_t_4 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1344, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_rtid); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1344, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (PyDict_SetItem(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_tid, __pyx_t_9) < 0) __PYX_ERR(0, 1344, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":1345 + * return IteratorColumnRegion(self, + * tid=rtid, + * start=rstart, # <<<<<<<<<<<<<< + * stop=rstop, + * **kwargs) +*/ + __pyx_t_9 = __Pyx_PyLong_From_int32_t(__pyx_v_rstart); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1345, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (PyDict_SetItem(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_start, __pyx_t_9) < 0) __PYX_ERR(0, 1344, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":1346 + * tid=rtid, + * start=rstart, + * stop=rstop, # <<<<<<<<<<<<<< + * **kwargs) + * else: +*/ + __pyx_t_9 = __Pyx_PyLong_From_int32_t(__pyx_v_rstop); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1346, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (PyDict_SetItem(__pyx_t_4, __pyx_mstate_global->__pyx_n_u_stop, __pyx_t_9) < 0) __PYX_ERR(0, 1344, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_5 = __pyx_t_4; + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1347 + * start=rstart, + * stop=rstop, + * **kwargs) # <<<<<<<<<<<<<< + * else: + * if self.has_index(): +*/ + if (__Pyx_MergeKeywords(__pyx_t_5, __pyx_v_kwargs) < 0) __PYX_ERR(0, 1347, __pyx_L1_error) + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, ((PyObject *)__pyx_v_self)}; + __pyx_t_1 = __Pyx_PyObject_FastCallDict(__pyx_t_8, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1343, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 41, 0, __PYX_ERR(0, 1343, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1339 + * contig, start, stop, region, reference=reference, end=end) + * + * if has_coord: # <<<<<<<<<<<<<< + * if not self.has_index(): + * raise ValueError("no index available for pileup") +*/ + } + + /* "pysam/libcalignmentfile.pyx":1349 + * **kwargs) + * else: + * if self.has_index(): # <<<<<<<<<<<<<< + * return IteratorColumnAllRefs(self, **kwargs) + * else: +*/ + /*else*/ { + __pyx_t_8 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_8); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1349, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1349, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":1350 + * else: + * if self.has_index(): + * return IteratorColumnAllRefs(self, **kwargs) # <<<<<<<<<<<<<< + * else: + * return IteratorColumnAll(self, **kwargs) +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_8 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + __pyx_t_5 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs); + __pyx_t_7 = PyDict_Copy(__pyx_v_kwargs); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1350, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, ((PyObject *)__pyx_v_self)}; + __pyx_t_1 = __Pyx_PyObject_FastCallDict(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1350, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 56, 0, __PYX_ERR(0, 1350, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1349 + * **kwargs) + * else: + * if self.has_index(): # <<<<<<<<<<<<<< + * return IteratorColumnAllRefs(self, **kwargs) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1352 + * return IteratorColumnAllRefs(self, **kwargs) + * else: + * return IteratorColumnAll(self, **kwargs) # <<<<<<<<<<<<<< + * + * def count(self, +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll); + __pyx_t_7 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll); + __pyx_t_8 = PyDict_Copy(__pyx_v_kwargs); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1352, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, ((PyObject *)__pyx_v_self)}; + __pyx_t_1 = __Pyx_PyObject_FastCallDict(__pyx_t_7, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_8); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1352, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_r = ((PyObject *)__pyx_t_1); + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 61, 0, __PYX_ERR(0, 1352, __pyx_L1_error)); + goto __pyx_L0; + } + } + + /* "pysam/libcalignmentfile.pyx":1214 + * return mate + * + * def pileup(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1214, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.pileup", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1354 + * return IteratorColumnAll(self, **kwargs) + * + * def count(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_17count(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_16count, "AlignmentFile.count(self, contig=None, start=None, stop=None, region=None, until_eof=False, read_callback='nofilter', reference=None, end=None)\n\ncount the number of reads in :term:`region`\n\nThe region is specified by :term:`contig`, `start` and `stop`.\n:term:`reference` and `end` are also accepted for backward\ncompatibility as synonyms for :term:`contig` and `stop`,\nrespectively. Alternatively, a `samtools`_ :term:`region`\nstring can be supplied.\n\nA :term:`SAM` file does not allow random access and if\n`region` or `contig` are given, an exception is raised.\n\nParameters\n----------\n\ncontig : string\n reference_name of the genomic region (chromosome)\n\nstart : int\n start of the genomic region (0-based inclusive)\n\nstop : int\n end of the genomic region (0-based exclusive)\n\nregion : string\n a region string in samtools format.\n\nuntil_eof : bool\n count until the end of the file, possibly including\n unmapped reads as well.\n\nread_callback: string or function\n\n select a call-back to ignore reads when counting. It can\n be either a string with the following values:\n\n ``all``\n skip reads in which any of the following\n flags are set: BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL,\n BAM_FDUP\n\n ``nofilter``\n uses every single read\n\n Alternatively, `read_callback` can be a function\n ``check_read(read)`` that should return True only for\n those reads that shall be included in the counting.\n\nreference : string\n backward compatible synonym for `contig`\n\nend : int\n backward compatible synonym for `stop`\n\nRaises\n------\n\nValueError\n if the genomic coordinates are out of range or invalid."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_17count = {"count", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_17count, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_16count}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_17count(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_contig = 0; + PyObject *__pyx_v_start = 0; + PyObject *__pyx_v_stop = 0; + PyObject *__pyx_v_region = 0; + PyObject *__pyx_v_until_eof = 0; + PyObject *__pyx_v_read_callback = 0; + PyObject *__pyx_v_reference = 0; + PyObject *__pyx_v_end = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[8] = {0,0,0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("count (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_contig,&__pyx_mstate_global->__pyx_n_u_start,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_region,&__pyx_mstate_global->__pyx_n_u_until_eof,&__pyx_mstate_global->__pyx_n_u_read_callback,&__pyx_mstate_global->__pyx_n_u_reference,&__pyx_mstate_global->__pyx_n_u_end,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1354, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "count", 0) < 0) __PYX_ERR(0, 1354, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":1355 + * + * def count(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1356 + * def count(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1357 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * until_eof=False, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1358 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * until_eof=False, + * read_callback="nofilter", +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1359 + * stop=None, + * region=None, + * until_eof=False, # <<<<<<<<<<<<<< + * read_callback="nofilter", + * reference=None, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_False)); + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_n_u_nofilter)); + + /* "pysam/libcalignmentfile.pyx":1361 + * until_eof=False, + * read_callback="nofilter", + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * '''count the number of reads in :term:`region` +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1362 + * read_callback="nofilter", + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * '''count the number of reads in :term:`region` + * +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + } else { + switch (__pyx_nargs) { + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1354, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + + /* "pysam/libcalignmentfile.pyx":1355 + * + * def count(self, + * contig=None, # <<<<<<<<<<<<<< + * start=None, + * stop=None, +*/ + if (!values[0]) values[0] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1356 + * def count(self, + * contig=None, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1357 + * contig=None, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * until_eof=False, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1358 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * until_eof=False, + * read_callback="nofilter", +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1359 + * stop=None, + * region=None, + * until_eof=False, # <<<<<<<<<<<<<< + * read_callback="nofilter", + * reference=None, +*/ + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)Py_False)); + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_n_u_nofilter)); + + /* "pysam/libcalignmentfile.pyx":1361 + * until_eof=False, + * read_callback="nofilter", + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * '''count the number of reads in :term:`region` +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1362 + * read_callback="nofilter", + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * '''count the number of reads in :term:`region` + * +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_contig = values[0]; + __pyx_v_start = values[1]; + __pyx_v_stop = values[2]; + __pyx_v_region = values[3]; + __pyx_v_until_eof = values[4]; + __pyx_v_read_callback = values[5]; + __pyx_v_reference = values[6]; + __pyx_v_end = values[7]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("count", 0, 0, 8, __pyx_nargs); __PYX_ERR(0, 1354, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.count", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_16count(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region, __pyx_v_until_eof, __pyx_v_read_callback, __pyx_v_reference, __pyx_v_end); + + /* "pysam/libcalignmentfile.pyx":1354 + * return IteratorColumnAll(self, **kwargs) + * + * def count(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_16count(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_until_eof, PyObject *__pyx_v_read_callback, PyObject *__pyx_v_reference, PyObject *__pyx_v_end) { + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read = 0; + long __pyx_v_counter; + int __pyx_v_filter_method; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + Py_ssize_t __pyx_t_7; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[43])) + __Pyx_RefNannySetupContext("count", 0); + __Pyx_TraceStartFunc("count", __pyx_f[0], 1354, 0, 0, 0, __PYX_ERR(0, 1354, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1424 + * ''' + * cdef AlignedSegment read + * cdef long counter = 0 # <<<<<<<<<<<<<< + * + * if not self.is_open: +*/ + __pyx_v_counter = 0; + + /* "pysam/libcalignmentfile.pyx":1426 + * cdef long counter = 0 + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1426, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1427 + * + * if not self.is_open: + * raise ValueError("I/O operation on closed file") # <<<<<<<<<<<<<< + * + * cdef int filter_method = 0 +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1427, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1427, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1426 + * cdef long counter = 0 + * + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1429 + * raise ValueError("I/O operation on closed file") + * + * cdef int filter_method = 0 # <<<<<<<<<<<<<< + * if read_callback == "all": + * filter_method = 1 +*/ + __pyx_v_filter_method = 0; + + /* "pysam/libcalignmentfile.pyx":1430 + * + * cdef int filter_method = 0 + * if read_callback == "all": # <<<<<<<<<<<<<< + * filter_method = 1 + * elif read_callback == "nofilter": +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_read_callback, __pyx_mstate_global->__pyx_n_u_all, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1430, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1431 + * cdef int filter_method = 0 + * if read_callback == "all": + * filter_method = 1 # <<<<<<<<<<<<<< + * elif read_callback == "nofilter": + * filter_method = 2 +*/ + __pyx_v_filter_method = 1; + + /* "pysam/libcalignmentfile.pyx":1430 + * + * cdef int filter_method = 0 + * if read_callback == "all": # <<<<<<<<<<<<<< + * filter_method = 1 + * elif read_callback == "nofilter": +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":1432 + * if read_callback == "all": + * filter_method = 1 + * elif read_callback == "nofilter": # <<<<<<<<<<<<<< + * filter_method = 2 + * +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_read_callback, __pyx_mstate_global->__pyx_n_u_nofilter, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1432, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1433 + * filter_method = 1 + * elif read_callback == "nofilter": + * filter_method = 2 # <<<<<<<<<<<<<< + * + * for read in self.fetch(contig=contig, +*/ + __pyx_v_filter_method = 2; + + /* "pysam/libcalignmentfile.pyx":1432 + * if read_callback == "all": + * filter_method = 1 + * elif read_callback == "nofilter": # <<<<<<<<<<<<<< + * filter_method = 2 + * +*/ + } + __pyx_L4:; + + /* "pysam/libcalignmentfile.pyx":1435 + * filter_method = 2 + * + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * start=start, + * stop=stop, +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":1441 + * end=end, + * region=region, + * until_eof=until_eof): # <<<<<<<<<<<<<< + * # apply filter + * if filter_method == 1: +*/ + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 7 : 0)] = {__pyx_t_5, NULL}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_contig, __pyx_v_contig, __pyx_t_4, __pyx_callargs+1, 0) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_start, __pyx_v_start, __pyx_t_4, __pyx_callargs+1, 1) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_stop, __pyx_v_stop, __pyx_t_4, __pyx_callargs+1, 2) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference, __pyx_v_reference, __pyx_t_4, __pyx_callargs+1, 3) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_end, __pyx_v_end, __pyx_t_4, __pyx_callargs+1, 4) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_region, __pyx_v_region, __pyx_t_4, __pyx_callargs+1, 5) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_until_eof, __pyx_v_until_eof, __pyx_t_4, __pyx_callargs+1, 6) < 0) __PYX_ERR(0, 1435, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_fetch, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":1435 + * filter_method = 2 + * + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * start=start, + * stop=stop, +*/ + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_4 = __pyx_t_1; __Pyx_INCREF(__pyx_t_4); + __pyx_t_7 = 0; + __pyx_t_8 = NULL; + } else { + __pyx_t_7 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1435, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_4); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1435, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_8)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1435, __pyx_L1_error) + #endif + if (__pyx_t_7 >= __pyx_temp) break; + } + __pyx_t_1 = __Pyx_PyList_GetItemRef(__pyx_t_4, __pyx_t_7); + ++__pyx_t_7; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1435, __pyx_L1_error) + #endif + if (__pyx_t_7 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_7)); + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_4, __pyx_t_7); + #endif + ++__pyx_t_7; + } + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1435, __pyx_L1_error) + } else { + __pyx_t_1 = __pyx_t_8(__pyx_t_4); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1435, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment))))) __PYX_ERR(0, 1435, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_read, ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1443 + * until_eof=until_eof): + * # apply filter + * if filter_method == 1: # <<<<<<<<<<<<<< + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): +*/ + switch (__pyx_v_filter_method) { + case 1: + + /* "pysam/libcalignmentfile.pyx":1445 + * if filter_method == 1: + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): # <<<<<<<<<<<<<< + * continue + * elif filter_method == 2: +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_flag); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1445, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyLong_AndObjC(__pyx_t_1, __pyx_mstate_global->__pyx_int_1796, 0x704, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1445, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1445, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":1446 + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): + * continue # <<<<<<<<<<<<<< + * elif filter_method == 2: + * # filter = "nofilter" +*/ + goto __pyx_L5_continue; + + /* "pysam/libcalignmentfile.pyx":1445 + * if filter_method == 1: + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): # <<<<<<<<<<<<<< + * continue + * elif filter_method == 2: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1443 + * until_eof=until_eof): + * # apply filter + * if filter_method == 1: # <<<<<<<<<<<<<< + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): +*/ + break; + case 2: + + /* "pysam/libcalignmentfile.pyx":1447 + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): + * continue + * elif filter_method == 2: # <<<<<<<<<<<<<< + * # filter = "nofilter" + * pass +*/ + break; + default: + + /* "pysam/libcalignmentfile.pyx":1451 + * pass + * else: + * if not read_callback(read): # <<<<<<<<<<<<<< + * continue + * counter += 1 +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_v_read_callback); + __pyx_t_9 = __pyx_v_read_callback; + __pyx_t_6 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_9))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_9); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_9); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_9, __pyx__function); + __pyx_t_6 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, ((PyObject *)__pyx_v_read)}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_9, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1451, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 1451, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_2 = (!__pyx_t_3); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":1452 + * else: + * if not read_callback(read): + * continue # <<<<<<<<<<<<<< + * counter += 1 + * +*/ + goto __pyx_L5_continue; + + /* "pysam/libcalignmentfile.pyx":1451 + * pass + * else: + * if not read_callback(read): # <<<<<<<<<<<<<< + * continue + * counter += 1 +*/ + } + break; + } + + /* "pysam/libcalignmentfile.pyx":1453 + * if not read_callback(read): + * continue + * counter += 1 # <<<<<<<<<<<<<< + * + * return counter +*/ + __pyx_v_counter = (__pyx_v_counter + 1); + + /* "pysam/libcalignmentfile.pyx":1435 + * filter_method = 2 + * + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * start=start, + * stop=stop, +*/ + __pyx_L5_continue:; + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1455 + * counter += 1 + * + * return counter # <<<<<<<<<<<<<< + * + * @cython.boundscheck(False) # we do manual bounds checking +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyLong_From_long(__pyx_v_counter); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1455, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 72, 0, __PYX_ERR(0, 1455, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1354 + * return IteratorColumnAll(self, **kwargs) + * + * def count(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1354, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.count", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_read); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1457 + * return counter + * + * @cython.boundscheck(False) # we do manual bounds checking # <<<<<<<<<<<<<< + * def count_coverage(self, + * contig, +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage, "AlignmentFile.count_coverage(self, contig, start=None, stop=None, region=None, quality_threshold=15, read_callback='all', reference=None, end=None)\n\ncount the coverage of genomic positions by reads in :term:`region`.\n\nThe region is specified by :term:`contig`, `start` and `stop`.\n:term:`reference` and `end` are also accepted for backward\ncompatibility as synonyms for :term:`contig` and `stop`,\nrespectively. Alternatively, a `samtools`_ :term:`region`\nstring can be supplied. The coverage is computed per-base [ACGT].\n\nParameters\n----------\n\ncontig : string\n reference_name of the genomic region (chromosome)\n\nstart : int\n start of the genomic region (0-based inclusive). If not\n given, count from the start of the chromosome.\n\nstop : int\n end of the genomic region (0-based exclusive). If not given,\n count to the end of the chromosome.\n\nregion : string\n a region string.\n\nquality_threshold : int\n quality_threshold is the minimum quality score (in phred) a\n base has to reach to be counted.\n\nread_callback: string or function\n\n select a call-back to ignore reads when counting. It can\n be either a string with the following values:\n\n ``all``\n skip reads in which any of the following\n flags are set: BAM_FUNMAP, BAM_FSECONDARY, BAM_FQCFAIL,\n BAM_FDUP\n\n ``nofilter``\n uses every single read\n\n Alternatively, `read_callback` can be a function\n ``check_read(read)`` that should return True only for\n those reads that shall be included in the counting.\n\nreference : string\n backward compatible synonym for `contig`\n\nend : int\n backward compatible synonym for `stop`\n\nRaises\n------\n\nValueError\n if the genomic coordinates are out of range or invalid.\n\nReturns\n-------\n\nfour array.arrays of the same length in order A C G T : tuple"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage = {"count_coverage", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_contig = 0; + PyObject *__pyx_v_start = 0; + PyObject *__pyx_v_stop = 0; + PyObject *__pyx_v_region = 0; + PyObject *__pyx_v_quality_threshold = 0; + PyObject *__pyx_v_read_callback = 0; + PyObject *__pyx_v_reference = 0; + PyObject *__pyx_v_end = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[8] = {0,0,0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("count_coverage (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_contig,&__pyx_mstate_global->__pyx_n_u_start,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_region,&__pyx_mstate_global->__pyx_n_u_quality_threshold,&__pyx_mstate_global->__pyx_n_u_read_callback,&__pyx_mstate_global->__pyx_n_u_reference,&__pyx_mstate_global->__pyx_n_u_end,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1457, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "count_coverage", 0) < 0) __PYX_ERR(0, 1457, __pyx_L3_error) + + /* "pysam/libcalignmentfile.pyx":1460 + * def count_coverage(self, + * contig, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1461 + * contig, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * quality_threshold=15, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1462 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * quality_threshold=15, + * read_callback='all', +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_int_15)); + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_n_u_all)); + + /* "pysam/libcalignmentfile.pyx":1465 + * quality_threshold=15, + * read_callback='all', + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * """count the coverage of genomic positions by reads in :term:`region`. +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1466 + * read_callback='all', + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * """count the coverage of genomic positions by reads in :term:`region`. + * +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("count_coverage", 0, 1, 8, i); __PYX_ERR(0, 1457, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 8: + values[7] = __Pyx_ArgRef_FASTCALL(__pyx_args, 7); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[7])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 7: + values[6] = __Pyx_ArgRef_FASTCALL(__pyx_args, 6); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[6])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 6: + values[5] = __Pyx_ArgRef_FASTCALL(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_FASTCALL(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_FASTCALL(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1457, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1457, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + + /* "pysam/libcalignmentfile.pyx":1460 + * def count_coverage(self, + * contig, + * start=None, # <<<<<<<<<<<<<< + * stop=None, + * region=None, +*/ + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1461 + * contig, + * start=None, + * stop=None, # <<<<<<<<<<<<<< + * region=None, + * quality_threshold=15, +*/ + if (!values[2]) values[2] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1462 + * start=None, + * stop=None, + * region=None, # <<<<<<<<<<<<<< + * quality_threshold=15, + * read_callback='all', +*/ + if (!values[3]) values[3] = __Pyx_NewRef(((PyObject *)Py_None)); + if (!values[4]) values[4] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_int_15)); + if (!values[5]) values[5] = __Pyx_NewRef(((PyObject *)__pyx_mstate_global->__pyx_n_u_all)); + + /* "pysam/libcalignmentfile.pyx":1465 + * quality_threshold=15, + * read_callback='all', + * reference=None, # <<<<<<<<<<<<<< + * end=None): + * """count the coverage of genomic positions by reads in :term:`region`. +*/ + if (!values[6]) values[6] = __Pyx_NewRef(((PyObject *)Py_None)); + + /* "pysam/libcalignmentfile.pyx":1466 + * read_callback='all', + * reference=None, + * end=None): # <<<<<<<<<<<<<< + * """count the coverage of genomic positions by reads in :term:`region`. + * +*/ + if (!values[7]) values[7] = __Pyx_NewRef(((PyObject *)Py_None)); + } + __pyx_v_contig = values[0]; + __pyx_v_start = values[1]; + __pyx_v_stop = values[2]; + __pyx_v_region = values[3]; + __pyx_v_quality_threshold = values[4]; + __pyx_v_read_callback = values[5]; + __pyx_v_reference = values[6]; + __pyx_v_end = values[7]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("count_coverage", 0, 1, 8, __pyx_nargs); __PYX_ERR(0, 1457, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.count_coverage", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_contig, __pyx_v_start, __pyx_v_stop, __pyx_v_region, __pyx_v_quality_threshold, __pyx_v_read_callback, __pyx_v_reference, __pyx_v_end); + + /* "pysam/libcalignmentfile.pyx":1457 + * return counter + * + * @cython.boundscheck(False) # we do manual bounds checking # <<<<<<<<<<<<<< + * def count_coverage(self, + * contig, +*/ + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_contig, PyObject *__pyx_v_start, PyObject *__pyx_v_stop, PyObject *__pyx_v_region, PyObject *__pyx_v_quality_threshold, PyObject *__pyx_v_read_callback, PyObject *__pyx_v_reference, PyObject *__pyx_v_end) { + uint32_t __pyx_v_contig_length; + int __pyx_v__start; + int __pyx_v__stop; + int __pyx_v_length; + arrayobject *__pyx_v_int_array_template = 0; + arrayobject *__pyx_v_count_a = 0; + arrayobject *__pyx_v_count_c = 0; + arrayobject *__pyx_v_count_g = 0; + arrayobject *__pyx_v_count_t = 0; + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read = 0; + PyObject *__pyx_v_seq = 0; + arrayobject *__pyx_v_quality = 0; + int __pyx_v_qpos; + int __pyx_v_refpos; + CYTHON_UNUSED int __pyx_v_c; + int __pyx_v_filter_method; + int __pyx_v__threshold; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + uint32_t __pyx_t_4; + int __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + Py_ssize_t __pyx_t_10; + PyObject *(*__pyx_t_11)(PyObject *); + int __pyx_t_12; + Py_ssize_t __pyx_t_13; + PyObject *(*__pyx_t_14)(PyObject *); + PyObject *__pyx_t_15 = NULL; + PyObject *__pyx_t_16 = NULL; + PyObject *(*__pyx_t_17)(PyObject *); + Py_UCS4 __pyx_t_18; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[44])) + __Pyx_RefNannySetupContext("count_coverage", 0); + __Pyx_TraceStartFunc("count_coverage", __pyx_f[0], 1457, 0, 0, 0, __PYX_ERR(0, 1457, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1532 + * """ + * + * cdef uint32_t contig_length = self.get_reference_length(contig) # <<<<<<<<<<<<<< + * cdef int _start = start if start is not None else 0 + * cdef int _stop = stop if stop is not None else contig_length +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_contig}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_reference_length, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1532, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_4 = __Pyx_PyLong_As_uint32_t(__pyx_t_1); if (unlikely((__pyx_t_4 == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1532, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_contig_length = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":1533 + * + * cdef uint32_t contig_length = self.get_reference_length(contig) + * cdef int _start = start if start is not None else 0 # <<<<<<<<<<<<<< + * cdef int _stop = stop if stop is not None else contig_length + * _stop = _stop if _stop < contig_length else contig_length +*/ + __pyx_t_6 = (__pyx_v_start != Py_None); + if (__pyx_t_6) { + __pyx_t_7 = __Pyx_PyLong_As_int(__pyx_v_start); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1533, __pyx_L1_error) + __pyx_t_5 = __pyx_t_7; + } else { + __pyx_t_5 = 0; + } + __pyx_v__start = __pyx_t_5; + + /* "pysam/libcalignmentfile.pyx":1534 + * cdef uint32_t contig_length = self.get_reference_length(contig) + * cdef int _start = start if start is not None else 0 + * cdef int _stop = stop if stop is not None else contig_length # <<<<<<<<<<<<<< + * _stop = _stop if _stop < contig_length else contig_length + * +*/ + __pyx_t_6 = (__pyx_v_stop != Py_None); + if (__pyx_t_6) { + __pyx_t_7 = __Pyx_PyLong_As_int(__pyx_v_stop); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1534, __pyx_L1_error) + __pyx_t_5 = __pyx_t_7; + } else { + __pyx_t_5 = __pyx_v_contig_length; + } + __pyx_v__stop = __pyx_t_5; + + /* "pysam/libcalignmentfile.pyx":1535 + * cdef int _start = start if start is not None else 0 + * cdef int _stop = stop if stop is not None else contig_length + * _stop = _stop if _stop < contig_length else contig_length # <<<<<<<<<<<<<< + * + * if _stop == _start: +*/ + __pyx_t_6 = (__pyx_v__stop < __pyx_v_contig_length); + if (__pyx_t_6) { + __pyx_t_4 = __pyx_v__stop; + } else { + __pyx_t_4 = __pyx_v_contig_length; + } + __pyx_v__stop = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":1537 + * _stop = _stop if _stop < contig_length else contig_length + * + * if _stop == _start: # <<<<<<<<<<<<<< + * raise ValueError("interval of size 0") + * if _stop < _start: +*/ + __pyx_t_6 = (__pyx_v__stop == __pyx_v__start); + if (unlikely(__pyx_t_6)) { + + /* "pysam/libcalignmentfile.pyx":1538 + * + * if _stop == _start: + * raise ValueError("interval of size 0") # <<<<<<<<<<<<<< + * if _stop < _start: + * raise ValueError("interval of size less than 0") +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_8 = __pyx_builtin_ValueError; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_interval_of_size_0}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1538, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1538, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1537 + * _stop = _stop if _stop < contig_length else contig_length + * + * if _stop == _start: # <<<<<<<<<<<<<< + * raise ValueError("interval of size 0") + * if _stop < _start: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1539 + * if _stop == _start: + * raise ValueError("interval of size 0") + * if _stop < _start: # <<<<<<<<<<<<<< + * raise ValueError("interval of size less than 0") + * +*/ + __pyx_t_6 = (__pyx_v__stop < __pyx_v__start); + if (unlikely(__pyx_t_6)) { + + /* "pysam/libcalignmentfile.pyx":1540 + * raise ValueError("interval of size 0") + * if _stop < _start: + * raise ValueError("interval of size less than 0") # <<<<<<<<<<<<<< + * + * cdef int length = _stop - _start +*/ + __pyx_t_8 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_2 = __pyx_builtin_ValueError; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_8, __pyx_mstate_global->__pyx_kp_u_interval_of_size_less_than_0}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1540, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1540, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1539 + * if _stop == _start: + * raise ValueError("interval of size 0") + * if _stop < _start: # <<<<<<<<<<<<<< + * raise ValueError("interval of size less than 0") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1542 + * raise ValueError("interval of size less than 0") + * + * cdef int length = _stop - _start # <<<<<<<<<<<<<< + * cdef c_array.array int_array_template = array.array('L', []) + * cdef c_array.array count_a +*/ + __pyx_v_length = (__pyx_v__stop - __pyx_v__start); + + /* "pysam/libcalignmentfile.pyx":1543 + * + * cdef int length = _stop - _start + * cdef c_array.array int_array_template = array.array('L', []) # <<<<<<<<<<<<<< + * cdef c_array.array count_a + * cdef c_array.array count_c +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_7cpython_5array_array); + __pyx_t_8 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_7cpython_5array_array); + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1543, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, __pyx_mstate_global->__pyx_n_u_L, __pyx_t_9}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_3, (3-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1543, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __pyx_v_int_array_template = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1548 + * cdef c_array.array count_g + * cdef c_array.array count_t + * count_a = c_array.clone(int_array_template, length, zero=True) # <<<<<<<<<<<<<< + * count_c = c_array.clone(int_array_template, length, zero=True) + * count_g = c_array.clone(int_array_template, length, zero=True) +*/ + __pyx_t_1 = ((PyObject *)__pyx_f_7cpython_5array_clone(__pyx_v_int_array_template, __pyx_v_length, 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1548, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_count_a = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1549 + * cdef c_array.array count_t + * count_a = c_array.clone(int_array_template, length, zero=True) + * count_c = c_array.clone(int_array_template, length, zero=True) # <<<<<<<<<<<<<< + * count_g = c_array.clone(int_array_template, length, zero=True) + * count_t = c_array.clone(int_array_template, length, zero=True) +*/ + __pyx_t_1 = ((PyObject *)__pyx_f_7cpython_5array_clone(__pyx_v_int_array_template, __pyx_v_length, 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1549, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_count_c = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1550 + * count_a = c_array.clone(int_array_template, length, zero=True) + * count_c = c_array.clone(int_array_template, length, zero=True) + * count_g = c_array.clone(int_array_template, length, zero=True) # <<<<<<<<<<<<<< + * count_t = c_array.clone(int_array_template, length, zero=True) + * +*/ + __pyx_t_1 = ((PyObject *)__pyx_f_7cpython_5array_clone(__pyx_v_int_array_template, __pyx_v_length, 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1550, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_count_g = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1551 + * count_c = c_array.clone(int_array_template, length, zero=True) + * count_g = c_array.clone(int_array_template, length, zero=True) + * count_t = c_array.clone(int_array_template, length, zero=True) # <<<<<<<<<<<<<< + * + * cdef AlignedSegment read +*/ + __pyx_t_1 = ((PyObject *)__pyx_f_7cpython_5array_clone(__pyx_v_int_array_template, __pyx_v_length, 1)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1551, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_count_t = ((arrayobject *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1558 + * cdef int qpos + * cdef int refpos + * cdef int c = 0 # <<<<<<<<<<<<<< + * cdef int filter_method = 0 + * +*/ + __pyx_v_c = 0; + + /* "pysam/libcalignmentfile.pyx":1559 + * cdef int refpos + * cdef int c = 0 + * cdef int filter_method = 0 # <<<<<<<<<<<<<< + * + * +*/ + __pyx_v_filter_method = 0; + + /* "pysam/libcalignmentfile.pyx":1562 + * + * + * if read_callback == "all": # <<<<<<<<<<<<<< + * filter_method = 1 + * elif read_callback == "nofilter": +*/ + __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_read_callback, __pyx_mstate_global->__pyx_n_u_all, Py_EQ)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1562, __pyx_L1_error) + if (__pyx_t_6) { + + /* "pysam/libcalignmentfile.pyx":1563 + * + * if read_callback == "all": + * filter_method = 1 # <<<<<<<<<<<<<< + * elif read_callback == "nofilter": + * filter_method = 2 +*/ + __pyx_v_filter_method = 1; + + /* "pysam/libcalignmentfile.pyx":1562 + * + * + * if read_callback == "all": # <<<<<<<<<<<<<< + * filter_method = 1 + * elif read_callback == "nofilter": +*/ + goto __pyx_L5; + } + + /* "pysam/libcalignmentfile.pyx":1564 + * if read_callback == "all": + * filter_method = 1 + * elif read_callback == "nofilter": # <<<<<<<<<<<<<< + * filter_method = 2 + * +*/ + __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_read_callback, __pyx_mstate_global->__pyx_n_u_nofilter, Py_EQ)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1564, __pyx_L1_error) + if (__pyx_t_6) { + + /* "pysam/libcalignmentfile.pyx":1565 + * filter_method = 1 + * elif read_callback == "nofilter": + * filter_method = 2 # <<<<<<<<<<<<<< + * + * cdef int _threshold = quality_threshold or 0 +*/ + __pyx_v_filter_method = 2; + + /* "pysam/libcalignmentfile.pyx":1564 + * if read_callback == "all": + * filter_method = 1 + * elif read_callback == "nofilter": # <<<<<<<<<<<<<< + * filter_method = 2 + * +*/ + } + __pyx_L5:; + + /* "pysam/libcalignmentfile.pyx":1567 + * filter_method = 2 + * + * cdef int _threshold = quality_threshold or 0 # <<<<<<<<<<<<<< + * for read in self.fetch(contig=contig, + * reference=reference, +*/ + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_quality_threshold); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1567, __pyx_L1_error) + if (!__pyx_t_6) { + } else { + __pyx_t_7 = __Pyx_PyLong_As_int(__pyx_v_quality_threshold); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1567, __pyx_L1_error) + __pyx_t_5 = __pyx_t_7; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_5 = 0; + __pyx_L6_bool_binop_done:; + __pyx_v__threshold = __pyx_t_5; + + /* "pysam/libcalignmentfile.pyx":1568 + * + * cdef int _threshold = quality_threshold or 0 + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * reference=reference, + * start=start, +*/ + __pyx_t_8 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_8); + + /* "pysam/libcalignmentfile.pyx":1573 + * stop=stop, + * end=end, + * region=region): # <<<<<<<<<<<<<< + * # apply filter + * if filter_method == 1: +*/ + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 6 : 0)] = {__pyx_t_8, NULL}; + __pyx_t_9 = __Pyx_MakeVectorcallBuilderKwds(6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1568, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_contig, __pyx_v_contig, __pyx_t_9, __pyx_callargs+1, 0) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_reference, __pyx_v_reference, __pyx_t_9, __pyx_callargs+1, 1) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_start, __pyx_v_start, __pyx_t_9, __pyx_callargs+1, 2) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_stop, __pyx_v_stop, __pyx_t_9, __pyx_callargs+1, 3) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_end, __pyx_v_end, __pyx_t_9, __pyx_callargs+1, 4) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_region, __pyx_v_region, __pyx_t_9, __pyx_callargs+1, 5) < 0) __PYX_ERR(0, 1568, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_fetch, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_9); + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1568, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":1568 + * + * cdef int _threshold = quality_threshold or 0 + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * reference=reference, + * start=start, +*/ + if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { + __pyx_t_9 = __pyx_t_1; __Pyx_INCREF(__pyx_t_9); + __pyx_t_10 = 0; + __pyx_t_11 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1568, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_11 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_9); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1568, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (;;) { + if (likely(!__pyx_t_11)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1568, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + __pyx_t_1 = __Pyx_PyList_GetItemRef(__pyx_t_9, __pyx_t_10); + ++__pyx_t_10; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_9); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1568, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_1 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10)); + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(__pyx_t_9, __pyx_t_10); + #endif + ++__pyx_t_10; + } + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1568, __pyx_L1_error) + } else { + __pyx_t_1 = __pyx_t_11(__pyx_t_9); + if (unlikely(!__pyx_t_1)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1568, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment))))) __PYX_ERR(0, 1568, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_read, ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)__pyx_t_1)); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1575 + * region=region): + * # apply filter + * if filter_method == 1: # <<<<<<<<<<<<<< + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): +*/ + switch (__pyx_v_filter_method) { + case 1: + + /* "pysam/libcalignmentfile.pyx":1577 + * if filter_method == 1: + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): # <<<<<<<<<<<<<< + * continue + * elif filter_method == 2: +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_flag); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1577, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_8 = __Pyx_PyLong_AndObjC(__pyx_t_1, __pyx_mstate_global->__pyx_int_1796, 0x704, 0, 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1577, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1577, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + + /* "pysam/libcalignmentfile.pyx":1578 + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): + * continue # <<<<<<<<<<<<<< + * elif filter_method == 2: + * # filter = "nofilter" +*/ + goto __pyx_L8_continue; + + /* "pysam/libcalignmentfile.pyx":1577 + * if filter_method == 1: + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): # <<<<<<<<<<<<<< + * continue + * elif filter_method == 2: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1575 + * region=region): + * # apply filter + * if filter_method == 1: # <<<<<<<<<<<<<< + * # filter = "all" + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): +*/ + break; + case 2: + + /* "pysam/libcalignmentfile.pyx":1579 + * if (read.flag & (0x4 | 0x100 | 0x200 | 0x400)): + * continue + * elif filter_method == 2: # <<<<<<<<<<<<<< + * # filter = "nofilter" + * pass +*/ + break; + default: + + /* "pysam/libcalignmentfile.pyx":1583 + * pass + * else: + * if not read_callback(read): # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_v_read_callback); + __pyx_t_2 = __pyx_v_read_callback; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_1 = PyMethod_GET_SELF(__pyx_t_2); + assert(__pyx_t_1); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_2, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, ((PyObject *)__pyx_v_read)}; + __pyx_t_8 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1583, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1583, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_12 = (!__pyx_t_6); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1584 + * else: + * if not read_callback(read): + * continue # <<<<<<<<<<<<<< + * + * # count +*/ + goto __pyx_L8_continue; + + /* "pysam/libcalignmentfile.pyx":1583 + * pass + * else: + * if not read_callback(read): # <<<<<<<<<<<<<< + * continue + * +*/ + } + break; + } + + /* "pysam/libcalignmentfile.pyx":1587 + * + * # count + * seq = read.seq # <<<<<<<<<<<<<< + * if seq is None: + * continue +*/ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_seq); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1587, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (!(likely(PyUnicode_CheckExact(__pyx_t_8))||((__pyx_t_8) == Py_None) || __Pyx_RaiseUnexpectedTypeError("str", __pyx_t_8))) __PYX_ERR(0, 1587, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_seq, ((PyObject*)__pyx_t_8)); + __pyx_t_8 = 0; + + /* "pysam/libcalignmentfile.pyx":1588 + * # count + * seq = read.seq + * if seq is None: # <<<<<<<<<<<<<< + * continue + * quality = read.query_qualities +*/ + __pyx_t_12 = (__pyx_v_seq == ((PyObject*)Py_None)); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1589 + * seq = read.seq + * if seq is None: + * continue # <<<<<<<<<<<<<< + * quality = read.query_qualities + * +*/ + goto __pyx_L8_continue; + + /* "pysam/libcalignmentfile.pyx":1588 + * # count + * seq = read.seq + * if seq is None: # <<<<<<<<<<<<<< + * continue + * quality = read.query_qualities +*/ + } + + /* "pysam/libcalignmentfile.pyx":1590 + * if seq is None: + * continue + * quality = read.query_qualities # <<<<<<<<<<<<<< + * + * for qpos, refpos in read.get_aligned_pairs(True): +*/ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_n_u_query_qualities); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1590, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (!(likely(((__pyx_t_8) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_8, __pyx_mstate_global->__pyx_ptype_7cpython_5array_array))))) __PYX_ERR(0, 1590, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_quality, ((arrayobject *)__pyx_t_8)); + __pyx_t_8 = 0; + + /* "pysam/libcalignmentfile.pyx":1592 + * quality = read.query_qualities + * + * for qpos, refpos in read.get_aligned_pairs(True): # <<<<<<<<<<<<<< + * if qpos is not None and refpos is not None and \ + * _start <= refpos < _stop: +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_read); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, Py_True}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_aligned_pairs, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + if (likely(PyList_CheckExact(__pyx_t_8)) || PyTuple_CheckExact(__pyx_t_8)) { + __pyx_t_2 = __pyx_t_8; __Pyx_INCREF(__pyx_t_2); + __pyx_t_13 = 0; + __pyx_t_14 = NULL; + } else { + __pyx_t_13 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_14 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_14)) __PYX_ERR(0, 1592, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + for (;;) { + if (likely(!__pyx_t_14)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1592, __pyx_L1_error) + #endif + if (__pyx_t_13 >= __pyx_temp) break; + } + __pyx_t_8 = __Pyx_PyList_GetItemRef(__pyx_t_2, __pyx_t_13); + ++__pyx_t_13; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1592, __pyx_L1_error) + #endif + if (__pyx_t_13 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_8 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_13)); + #else + __pyx_t_8 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_13); + #endif + ++__pyx_t_13; + } + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1592, __pyx_L1_error) + } else { + __pyx_t_8 = __pyx_t_14(__pyx_t_2); + if (unlikely(!__pyx_t_8)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1592, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_8); + if ((likely(PyTuple_CheckExact(__pyx_t_8))) || (PyList_CheckExact(__pyx_t_8))) { + PyObject* sequence = __pyx_t_8; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 1592, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_1); + __pyx_t_15 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_15); + } else { + __pyx_t_1 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_1); + __pyx_t_15 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_15); + } + #else + __pyx_t_1 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_15 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + #endif + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_16 = PyObject_GetIter(__pyx_t_8); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_16); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_17 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_16); + index = 0; __pyx_t_1 = __pyx_t_17(__pyx_t_16); if (unlikely(!__pyx_t_1)) goto __pyx_L15_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_15 = __pyx_t_17(__pyx_t_16); if (unlikely(!__pyx_t_15)) goto __pyx_L15_unpacking_failed; + __Pyx_GOTREF(__pyx_t_15); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_17(__pyx_t_16), 2) < 0) __PYX_ERR(0, 1592, __pyx_L1_error) + __pyx_t_17 = NULL; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + goto __pyx_L16_unpacking_done; + __pyx_L15_unpacking_failed:; + __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; + __pyx_t_17 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 1592, __pyx_L1_error) + __pyx_L16_unpacking_done:; + } + __pyx_t_5 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = __Pyx_PyLong_As_int(__pyx_t_15); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1592, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_v_qpos = __pyx_t_5; + __pyx_v_refpos = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":1593 + * + * for qpos, refpos in read.get_aligned_pairs(True): + * if qpos is not None and refpos is not None and \ # <<<<<<<<<<<<<< + * _start <= refpos < _stop: + * +*/ + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_qpos); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1593, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = (__pyx_t_8 != Py_None); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + } else { + __pyx_t_12 = __pyx_t_6; + goto __pyx_L18_bool_binop_done; + } + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_refpos); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1593, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_6 = (__pyx_t_8 != Py_None); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (__pyx_t_6) { + } else { + __pyx_t_12 = __pyx_t_6; + goto __pyx_L18_bool_binop_done; + } + + /* "pysam/libcalignmentfile.pyx":1594 + * for qpos, refpos in read.get_aligned_pairs(True): + * if qpos is not None and refpos is not None and \ + * _start <= refpos < _stop: # <<<<<<<<<<<<<< + * + * # only check base quality if _threshold > 0 +*/ + __pyx_t_6 = (__pyx_v__start <= __pyx_v_refpos); + if (__pyx_t_6) { + __pyx_t_6 = (__pyx_v_refpos < __pyx_v__stop); + } + __pyx_t_12 = __pyx_t_6; + __pyx_L18_bool_binop_done:; + + /* "pysam/libcalignmentfile.pyx":1593 + * + * for qpos, refpos in read.get_aligned_pairs(True): + * if qpos is not None and refpos is not None and \ # <<<<<<<<<<<<<< + * _start <= refpos < _stop: + * +*/ + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1597 + * + * # only check base quality if _threshold > 0 + * if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold: # <<<<<<<<<<<<<< + * if seq[qpos] == 'A': + * count_a.data.as_ulongs[refpos - _start] += 1 +*/ + __pyx_t_6 = (__pyx_v__threshold != 0); + if (!__pyx_t_6) { + goto __pyx_L23_next_or; + } else { + } + __pyx_t_6 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_quality)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1597, __pyx_L1_error) + if (!__pyx_t_6) { + goto __pyx_L23_next_or; + } else { + } + __pyx_t_8 = __Pyx_GetItemInt(((PyObject *)__pyx_v_quality), __pyx_v_qpos, int, 1, __Pyx_PyLong_From_int, 0, 1, 0, 1); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1597, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_15 = __Pyx_PyLong_From_int(__pyx_v__threshold); if (unlikely(!__pyx_t_15)) __PYX_ERR(0, 1597, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_15); + __pyx_t_1 = PyObject_RichCompare(__pyx_t_8, __pyx_t_15, Py_GE); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1597, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_15); __pyx_t_15 = 0; + __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 1597, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (!__pyx_t_6) { + } else { + __pyx_t_12 = __pyx_t_6; + goto __pyx_L22_bool_binop_done; + } + __pyx_L23_next_or:; + __pyx_t_6 = (!(__pyx_v__threshold != 0)); + __pyx_t_12 = __pyx_t_6; + __pyx_L22_bool_binop_done:; + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1598 + * # only check base quality if _threshold > 0 + * if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold: + * if seq[qpos] == 'A': # <<<<<<<<<<<<<< + * count_a.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'C': +*/ + __pyx_t_18 = __Pyx_GetItemInt_Unicode(__pyx_v_seq, __pyx_v_qpos, int, 1, __Pyx_PyLong_From_int, 0, 1, 0, 1); if (unlikely(__pyx_t_18 == (Py_UCS4)-1)) __PYX_ERR(0, 1598, __pyx_L1_error) + __pyx_t_12 = (__pyx_t_18 == 65); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1599 + * if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold: + * if seq[qpos] == 'A': + * count_a.data.as_ulongs[refpos - _start] += 1 # <<<<<<<<<<<<<< + * if seq[qpos] == 'C': + * count_c.data.as_ulongs[refpos - _start] += 1 +*/ + __pyx_t_7 = (__pyx_v_refpos - __pyx_v__start); + (__pyx_v_count_a->data.as_ulongs[__pyx_t_7]) = ((__pyx_v_count_a->data.as_ulongs[__pyx_t_7]) + 1); + + /* "pysam/libcalignmentfile.pyx":1598 + * # only check base quality if _threshold > 0 + * if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold: + * if seq[qpos] == 'A': # <<<<<<<<<<<<<< + * count_a.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'C': +*/ + } + + /* "pysam/libcalignmentfile.pyx":1600 + * if seq[qpos] == 'A': + * count_a.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'C': # <<<<<<<<<<<<<< + * count_c.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'G': +*/ + __pyx_t_18 = __Pyx_GetItemInt_Unicode(__pyx_v_seq, __pyx_v_qpos, int, 1, __Pyx_PyLong_From_int, 0, 1, 0, 1); if (unlikely(__pyx_t_18 == (Py_UCS4)-1)) __PYX_ERR(0, 1600, __pyx_L1_error) + __pyx_t_12 = (__pyx_t_18 == 67); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1601 + * count_a.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'C': + * count_c.data.as_ulongs[refpos - _start] += 1 # <<<<<<<<<<<<<< + * if seq[qpos] == 'G': + * count_g.data.as_ulongs[refpos - _start] += 1 +*/ + __pyx_t_7 = (__pyx_v_refpos - __pyx_v__start); + (__pyx_v_count_c->data.as_ulongs[__pyx_t_7]) = ((__pyx_v_count_c->data.as_ulongs[__pyx_t_7]) + 1); + + /* "pysam/libcalignmentfile.pyx":1600 + * if seq[qpos] == 'A': + * count_a.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'C': # <<<<<<<<<<<<<< + * count_c.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'G': +*/ + } + + /* "pysam/libcalignmentfile.pyx":1602 + * if seq[qpos] == 'C': + * count_c.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'G': # <<<<<<<<<<<<<< + * count_g.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'T': +*/ + __pyx_t_18 = __Pyx_GetItemInt_Unicode(__pyx_v_seq, __pyx_v_qpos, int, 1, __Pyx_PyLong_From_int, 0, 1, 0, 1); if (unlikely(__pyx_t_18 == (Py_UCS4)-1)) __PYX_ERR(0, 1602, __pyx_L1_error) + __pyx_t_12 = (__pyx_t_18 == 71); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1603 + * count_c.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'G': + * count_g.data.as_ulongs[refpos - _start] += 1 # <<<<<<<<<<<<<< + * if seq[qpos] == 'T': + * count_t.data.as_ulongs[refpos - _start] += 1 +*/ + __pyx_t_7 = (__pyx_v_refpos - __pyx_v__start); + (__pyx_v_count_g->data.as_ulongs[__pyx_t_7]) = ((__pyx_v_count_g->data.as_ulongs[__pyx_t_7]) + 1); + + /* "pysam/libcalignmentfile.pyx":1602 + * if seq[qpos] == 'C': + * count_c.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'G': # <<<<<<<<<<<<<< + * count_g.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'T': +*/ + } + + /* "pysam/libcalignmentfile.pyx":1604 + * if seq[qpos] == 'G': + * count_g.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'T': # <<<<<<<<<<<<<< + * count_t.data.as_ulongs[refpos - _start] += 1 + * +*/ + __pyx_t_18 = __Pyx_GetItemInt_Unicode(__pyx_v_seq, __pyx_v_qpos, int, 1, __Pyx_PyLong_From_int, 0, 1, 0, 1); if (unlikely(__pyx_t_18 == (Py_UCS4)-1)) __PYX_ERR(0, 1604, __pyx_L1_error) + __pyx_t_12 = (__pyx_t_18 == 84); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":1605 + * count_g.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'T': + * count_t.data.as_ulongs[refpos - _start] += 1 # <<<<<<<<<<<<<< + * + * return count_a, count_c, count_g, count_t +*/ + __pyx_t_7 = (__pyx_v_refpos - __pyx_v__start); + (__pyx_v_count_t->data.as_ulongs[__pyx_t_7]) = ((__pyx_v_count_t->data.as_ulongs[__pyx_t_7]) + 1); + + /* "pysam/libcalignmentfile.pyx":1604 + * if seq[qpos] == 'G': + * count_g.data.as_ulongs[refpos - _start] += 1 + * if seq[qpos] == 'T': # <<<<<<<<<<<<<< + * count_t.data.as_ulongs[refpos - _start] += 1 + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1597 + * + * # only check base quality if _threshold > 0 + * if (_threshold and quality and quality[qpos] >= _threshold) or not _threshold: # <<<<<<<<<<<<<< + * if seq[qpos] == 'A': + * count_a.data.as_ulongs[refpos - _start] += 1 +*/ + } + + /* "pysam/libcalignmentfile.pyx":1593 + * + * for qpos, refpos in read.get_aligned_pairs(True): + * if qpos is not None and refpos is not None and \ # <<<<<<<<<<<<<< + * _start <= refpos < _stop: + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1592 + * quality = read.query_qualities + * + * for qpos, refpos in read.get_aligned_pairs(True): # <<<<<<<<<<<<<< + * if qpos is not None and refpos is not None and \ + * _start <= refpos < _stop: +*/ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1568 + * + * cdef int _threshold = quality_threshold or 0 + * for read in self.fetch(contig=contig, # <<<<<<<<<<<<<< + * reference=reference, + * start=start, +*/ + __pyx_L8_continue:; + } + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + + /* "pysam/libcalignmentfile.pyx":1607 + * count_t.data.as_ulongs[refpos - _start] += 1 + * + * return count_a, count_c, count_g, count_t # <<<<<<<<<<<<<< + * + * def find_introns_slow(self, read_iterator): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_9 = PyTuple_New(4); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1607, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF((PyObject *)__pyx_v_count_a); + __Pyx_GIVEREF((PyObject *)__pyx_v_count_a); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_v_count_a)) != (0)) __PYX_ERR(0, 1607, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_count_c); + __Pyx_GIVEREF((PyObject *)__pyx_v_count_c); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 1, ((PyObject *)__pyx_v_count_c)) != (0)) __PYX_ERR(0, 1607, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_count_g); + __Pyx_GIVEREF((PyObject *)__pyx_v_count_g); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 2, ((PyObject *)__pyx_v_count_g)) != (0)) __PYX_ERR(0, 1607, __pyx_L1_error); + __Pyx_INCREF((PyObject *)__pyx_v_count_t); + __Pyx_GIVEREF((PyObject *)__pyx_v_count_t); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 3, ((PyObject *)__pyx_v_count_t)) != (0)) __PYX_ERR(0, 1607, __pyx_L1_error); + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; + __Pyx_TraceReturnValue(__pyx_r, 235, 0, __PYX_ERR(0, 1607, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1457 + * return counter + * + * @cython.boundscheck(False) # we do manual bounds checking # <<<<<<<<<<<<<< + * def count_coverage(self, + * contig, +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_15); + __Pyx_XDECREF(__pyx_t_16); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1457, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.count_coverage", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_int_array_template); + __Pyx_XDECREF((PyObject *)__pyx_v_count_a); + __Pyx_XDECREF((PyObject *)__pyx_v_count_c); + __Pyx_XDECREF((PyObject *)__pyx_v_count_g); + __Pyx_XDECREF((PyObject *)__pyx_v_count_t); + __Pyx_XDECREF((PyObject *)__pyx_v_read); + __Pyx_XDECREF(__pyx_v_seq); + __Pyx_XDECREF((PyObject *)__pyx_v_quality); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1609 + * return count_a, count_c, count_g, count_t + * + * def find_introns_slow(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow, "AlignmentFile.find_introns_slow(self, read_iterator)\n\nReturn a dictionary {(start, stop): count}\nListing the intronic sites in the reads (identified by 'N' in the cigar strings),\nand their support ( = number of reads ).\n\nread_iterator can be the result of a .fetch(...) call.\nOr it can be a generator filtering such reads. Example\nsamfile.find_introns((read for read in samfile.fetch(...) if read.is_reverse)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow = {"find_introns_slow", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_read_iterator = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("find_introns_slow (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_read_iterator,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1609, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1609, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "find_introns_slow", 0) < 0) __PYX_ERR(0, 1609, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("find_introns_slow", 1, 1, 1, i); __PYX_ERR(0, 1609, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1609, __pyx_L3_error) + } + __pyx_v_read_iterator = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("find_introns_slow", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1609, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.find_introns_slow", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_read_iterator); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_read_iterator) { + PyObject *__pyx_v_res = NULL; + PyObject *__pyx_v_r = NULL; + PyObject *__pyx_v_last_read_pos = NULL; + PyObject *__pyx_v_read_loc = NULL; + PyObject *__pyx_v_genome_loc = NULL; + PyObject *__pyx_v_start = NULL; + PyObject *__pyx_v_stop = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *(*__pyx_t_7)(PyObject *); + int __pyx_t_8; + Py_ssize_t __pyx_t_9; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *(*__pyx_t_13)(PyObject *); + int __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[45])) + __Pyx_RefNannySetupContext("find_introns_slow", 0); + __Pyx_TraceStartFunc("find_introns_slow", __pyx_f[0], 1609, 0, 0, 0, __PYX_ERR(0, 1609, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1618 + * samfile.find_introns((read for read in samfile.fetch(...) if read.is_reverse) + * """ + * res = collections.Counter() # <<<<<<<<<<<<<< + * for r in read_iterator: + * if 'N' in r.cigarstring: +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_collections); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_Counter); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1618, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_res = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1619 + * """ + * res = collections.Counter() + * for r in read_iterator: # <<<<<<<<<<<<<< + * if 'N' in r.cigarstring: + * last_read_pos = False +*/ + if (likely(PyList_CheckExact(__pyx_v_read_iterator)) || PyTuple_CheckExact(__pyx_v_read_iterator)) { + __pyx_t_1 = __pyx_v_read_iterator; __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_read_iterator); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1619, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1619, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1619, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1619, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_6)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1619, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_7(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1619, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_r, __pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1620 + * res = collections.Counter() + * for r in read_iterator: + * if 'N' in r.cigarstring: # <<<<<<<<<<<<<< + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_r, __pyx_mstate_global->__pyx_n_u_cigarstring); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1620, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = (__Pyx_PySequence_ContainsTF(__pyx_mstate_global->__pyx_n_u_N, __pyx_t_4, Py_EQ)); if (unlikely((__pyx_t_8 < 0))) __PYX_ERR(0, 1620, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":1621 + * for r in read_iterator: + * if 'N' in r.cigarstring: + * last_read_pos = False # <<<<<<<<<<<<<< + * for read_loc, genome_loc in r.get_aligned_pairs(): + * if read_loc is None and last_read_pos: +*/ + __Pyx_INCREF(Py_False); + __Pyx_XDECREF_SET(__pyx_v_last_read_pos, Py_False); + + /* "pysam/libcalignmentfile.pyx":1622 + * if 'N' in r.cigarstring: + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): # <<<<<<<<<<<<<< + * if read_loc is None and last_read_pos: + * start = genome_loc +*/ + __pyx_t_2 = __pyx_v_r; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_4 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_aligned_pairs, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + if (likely(PyList_CheckExact(__pyx_t_4)) || PyTuple_CheckExact(__pyx_t_4)) { + __pyx_t_2 = __pyx_t_4; __Pyx_INCREF(__pyx_t_2); + __pyx_t_9 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_9 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_2); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1622, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_2))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1622, __pyx_L1_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GetItemRef(__pyx_t_2, __pyx_t_9); + ++__pyx_t_9; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1622, __pyx_L1_error) + #endif + if (__pyx_t_9 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_9)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_2, __pyx_t_9); + #endif + ++__pyx_t_9; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1622, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_10(__pyx_t_2); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1622, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if ((likely(PyTuple_CheckExact(__pyx_t_4))) || (PyList_CheckExact(__pyx_t_4))) { + PyObject* sequence = __pyx_t_4; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 1622, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_11); + } else { + __pyx_t_3 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + __pyx_t_11 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_11); + } + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_11 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_12 = PyObject_GetIter(__pyx_t_4); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1622, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_13 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_12); + index = 0; __pyx_t_3 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_3)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_11 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_11)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_13(__pyx_t_12), 2) < 0) __PYX_ERR(0, 1622, __pyx_L1_error) + __pyx_t_13 = NULL; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + goto __pyx_L9_unpacking_done; + __pyx_L8_unpacking_failed:; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_13 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 1622, __pyx_L1_error) + __pyx_L9_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_read_loc, __pyx_t_3); + __pyx_t_3 = 0; + __Pyx_XDECREF_SET(__pyx_v_genome_loc, __pyx_t_11); + __pyx_t_11 = 0; + + /* "pysam/libcalignmentfile.pyx":1623 + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): + * if read_loc is None and last_read_pos: # <<<<<<<<<<<<<< + * start = genome_loc + * elif read_loc and last_read_pos is None: +*/ + __pyx_t_14 = (__pyx_v_read_loc == Py_None); + if (__pyx_t_14) { + } else { + __pyx_t_8 = __pyx_t_14; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_14 = __Pyx_PyObject_IsTrue(__pyx_v_last_read_pos); if (unlikely((__pyx_t_14 < 0))) __PYX_ERR(0, 1623, __pyx_L1_error) + __pyx_t_8 = __pyx_t_14; + __pyx_L11_bool_binop_done:; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":1624 + * for read_loc, genome_loc in r.get_aligned_pairs(): + * if read_loc is None and last_read_pos: + * start = genome_loc # <<<<<<<<<<<<<< + * elif read_loc and last_read_pos is None: + * stop = genome_loc # we are right exclusive ,so this is correct +*/ + __Pyx_INCREF(__pyx_v_genome_loc); + __Pyx_XDECREF_SET(__pyx_v_start, __pyx_v_genome_loc); + + /* "pysam/libcalignmentfile.pyx":1623 + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): + * if read_loc is None and last_read_pos: # <<<<<<<<<<<<<< + * start = genome_loc + * elif read_loc and last_read_pos is None: +*/ + goto __pyx_L10; + } + + /* "pysam/libcalignmentfile.pyx":1625 + * if read_loc is None and last_read_pos: + * start = genome_loc + * elif read_loc and last_read_pos is None: # <<<<<<<<<<<<<< + * stop = genome_loc # we are right exclusive ,so this is correct + * res[(start, stop)] += 1 +*/ + __pyx_t_14 = __Pyx_PyObject_IsTrue(__pyx_v_read_loc); if (unlikely((__pyx_t_14 < 0))) __PYX_ERR(0, 1625, __pyx_L1_error) + if (__pyx_t_14) { + } else { + __pyx_t_8 = __pyx_t_14; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_14 = (__pyx_v_last_read_pos == Py_None); + __pyx_t_8 = __pyx_t_14; + __pyx_L13_bool_binop_done:; + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":1626 + * start = genome_loc + * elif read_loc and last_read_pos is None: + * stop = genome_loc # we are right exclusive ,so this is correct # <<<<<<<<<<<<<< + * res[(start, stop)] += 1 + * del start +*/ + __Pyx_INCREF(__pyx_v_genome_loc); + __pyx_v_stop = __pyx_v_genome_loc; + + /* "pysam/libcalignmentfile.pyx":1627 + * elif read_loc and last_read_pos is None: + * stop = genome_loc # we are right exclusive ,so this is correct + * res[(start, stop)] += 1 # <<<<<<<<<<<<<< + * del start + * del stop +*/ + if (unlikely(!__pyx_v_start)) { __Pyx_RaiseUnboundLocalError("start"); __PYX_ERR(0, 1627, __pyx_L1_error) } + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1627, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_INCREF(__pyx_v_start); + __Pyx_GIVEREF(__pyx_v_start); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_start) != (0)) __PYX_ERR(0, 1627, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_stop); + __Pyx_GIVEREF(__pyx_v_stop); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_stop) != (0)) __PYX_ERR(0, 1627, __pyx_L1_error); + __pyx_t_11 = __Pyx_PyObject_GetItem(__pyx_v_res, __pyx_t_4); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1627, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_3 = __Pyx_PyLong_AddObjC(__pyx_t_11, __pyx_mstate_global->__pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1627, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely((PyObject_SetItem(__pyx_v_res, __pyx_t_4, __pyx_t_3) < 0))) __PYX_ERR(0, 1627, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1628 + * stop = genome_loc # we are right exclusive ,so this is correct + * res[(start, stop)] += 1 + * del start # <<<<<<<<<<<<<< + * del stop + * last_read_pos = read_loc +*/ + if (unlikely(!__pyx_v_start)) { __Pyx_RaiseUnboundLocalError("start"); __PYX_ERR(0, 1628, __pyx_L1_error) } + __Pyx_DECREF(__pyx_v_start); __pyx_v_start = 0; + + /* "pysam/libcalignmentfile.pyx":1629 + * res[(start, stop)] += 1 + * del start + * del stop # <<<<<<<<<<<<<< + * last_read_pos = read_loc + * return res +*/ + __Pyx_DECREF(__pyx_v_stop); __pyx_v_stop = 0; + + /* "pysam/libcalignmentfile.pyx":1625 + * if read_loc is None and last_read_pos: + * start = genome_loc + * elif read_loc and last_read_pos is None: # <<<<<<<<<<<<<< + * stop = genome_loc # we are right exclusive ,so this is correct + * res[(start, stop)] += 1 +*/ + } + __pyx_L10:; + + /* "pysam/libcalignmentfile.pyx":1630 + * del start + * del stop + * last_read_pos = read_loc # <<<<<<<<<<<<<< + * return res + * +*/ + __Pyx_INCREF(__pyx_v_read_loc); + __Pyx_DECREF_SET(__pyx_v_last_read_pos, __pyx_v_read_loc); + + /* "pysam/libcalignmentfile.pyx":1622 + * if 'N' in r.cigarstring: + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): # <<<<<<<<<<<<<< + * if read_loc is None and last_read_pos: + * start = genome_loc +*/ + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1620 + * res = collections.Counter() + * for r in read_iterator: + * if 'N' in r.cigarstring: # <<<<<<<<<<<<<< + * last_read_pos = False + * for read_loc, genome_loc in r.get_aligned_pairs(): +*/ + } + + /* "pysam/libcalignmentfile.pyx":1619 + * """ + * res = collections.Counter() + * for r in read_iterator: # <<<<<<<<<<<<<< + * if 'N' in r.cigarstring: + * last_read_pos = False +*/ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1631 + * del stop + * last_read_pos = read_loc + * return res # <<<<<<<<<<<<<< + * + * def find_introns(self, read_iterator): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_res); + __pyx_r = __pyx_v_res; + __Pyx_TraceReturnValue(__pyx_r, 47, 0, __PYX_ERR(0, 1631, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1609 + * return count_a, count_c, count_g, count_t + * + * def find_introns_slow(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1609, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.find_introns_slow", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_res); + __Pyx_XDECREF(__pyx_v_r); + __Pyx_XDECREF(__pyx_v_last_read_pos); + __Pyx_XDECREF(__pyx_v_read_loc); + __Pyx_XDECREF(__pyx_v_genome_loc); + __Pyx_XDECREF(__pyx_v_start); + __Pyx_XDECREF(__pyx_v_stop); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1633 + * return res + * + * def find_introns(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns, "AlignmentFile.find_introns(self, read_iterator)\n\nReturn a dictionary {(start, stop): count}\nListing the intronic sites in the reads (identified by 'N' in the cigar strings),\nand their support ( = number of reads ).\n\nread_iterator can be the result of a .fetch(...) call.\nOr it can be a generator filtering such reads. Example\nsamfile.find_introns((read for read in samfile.fetch(...) if read.is_reverse)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns = {"find_introns", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_read_iterator = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("find_introns (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_read_iterator,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1633, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1633, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "find_introns", 0) < 0) __PYX_ERR(0, 1633, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("find_introns", 1, 1, 1, i); __PYX_ERR(0, 1633, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1633, __pyx_L3_error) + } + __pyx_v_read_iterator = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("find_introns", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1633, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.find_introns", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_read_iterator); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_read_iterator) { + uint32_t __pyx_v_base_position; + uint32_t __pyx_v_junc_start; + uint32_t __pyx_v_nt; + int __pyx_v_op; + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_r = 0; + int __pyx_v_BAM_CREF_SKIP; + PyObject *__pyx_v_res = NULL; + PyObject *__pyx_v_match_or_deletion = NULL; + PyObject *__pyx_v_cigar = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + Py_ssize_t __pyx_t_6; + PyObject *(*__pyx_t_7)(PyObject *); + uint32_t __pyx_t_8; + int __pyx_t_9; + Py_ssize_t __pyx_t_10; + PyObject *(*__pyx_t_11)(PyObject *); + PyObject *__pyx_t_12 = NULL; + PyObject *__pyx_t_13 = NULL; + PyObject *(*__pyx_t_14)(PyObject *); + int __pyx_t_15; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[46])) + __Pyx_RefNannySetupContext("find_introns", 0); + __Pyx_TraceStartFunc("find_introns", __pyx_f[0], 1633, 0, 0, 0, __PYX_ERR(0, 1633, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1646 + * int op + * AlignedSegment r + * int BAM_CREF_SKIP = 3 #BAM_CREF_SKIP # <<<<<<<<<<<<<< + * + * res = collections.Counter() +*/ + __pyx_v_BAM_CREF_SKIP = 3; + + /* "pysam/libcalignmentfile.pyx":1648 + * int BAM_CREF_SKIP = 3 #BAM_CREF_SKIP + * + * res = collections.Counter() # <<<<<<<<<<<<<< + * + * match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_collections); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1648, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_Counter); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1648, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1648, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v_res = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1650 + * res = collections.Counter() + * + * match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position # <<<<<<<<<<<<<< + * for r in read_iterator: + * base_position = r.pos +*/ + __pyx_t_1 = PySet_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1650, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PySet_Add(__pyx_t_1, __pyx_mstate_global->__pyx_int_0) < 0) __PYX_ERR(0, 1650, __pyx_L1_error) + if (PySet_Add(__pyx_t_1, __pyx_mstate_global->__pyx_int_2) < 0) __PYX_ERR(0, 1650, __pyx_L1_error) + if (PySet_Add(__pyx_t_1, __pyx_mstate_global->__pyx_int_7) < 0) __PYX_ERR(0, 1650, __pyx_L1_error) + if (PySet_Add(__pyx_t_1, __pyx_mstate_global->__pyx_int_8) < 0) __PYX_ERR(0, 1650, __pyx_L1_error) + __pyx_v_match_or_deletion = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1651 + * + * match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position + * for r in read_iterator: # <<<<<<<<<<<<<< + * base_position = r.pos + * cigar = r.cigartuples +*/ + if (likely(PyList_CheckExact(__pyx_v_read_iterator)) || PyTuple_CheckExact(__pyx_v_read_iterator)) { + __pyx_t_1 = __pyx_v_read_iterator; __Pyx_INCREF(__pyx_t_1); + __pyx_t_6 = 0; + __pyx_t_7 = NULL; + } else { + __pyx_t_6 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_v_read_iterator); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1651, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1651, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_7)) { + if (likely(PyList_CheckExact(__pyx_t_1))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1651, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + __pyx_t_4 = __Pyx_PyList_GetItemRef(__pyx_t_1, __pyx_t_6); + ++__pyx_t_6; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1651, __pyx_L1_error) + #endif + if (__pyx_t_6 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_4 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_6)); + #else + __pyx_t_4 = __Pyx_PySequence_ITEM(__pyx_t_1, __pyx_t_6); + #endif + ++__pyx_t_6; + } + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1651, __pyx_L1_error) + } else { + __pyx_t_4 = __pyx_t_7(__pyx_t_1); + if (unlikely(!__pyx_t_4)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1651, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_mstate_global->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment))))) __PYX_ERR(0, 1651, __pyx_L1_error) + __Pyx_XDECREF_SET(__pyx_v_r, ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1652 + * match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position + * for r in read_iterator: + * base_position = r.pos # <<<<<<<<<<<<<< + * cigar = r.cigartuples + * if cigar is None: +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_r), __pyx_mstate_global->__pyx_n_u_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1652, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_8 = __Pyx_PyLong_As_uint32_t(__pyx_t_4); if (unlikely((__pyx_t_8 == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1652, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_base_position = __pyx_t_8; + + /* "pysam/libcalignmentfile.pyx":1653 + * for r in read_iterator: + * base_position = r.pos + * cigar = r.cigartuples # <<<<<<<<<<<<<< + * if cigar is None: + * continue +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_r), __pyx_mstate_global->__pyx_n_u_cigartuples); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1653, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_XDECREF_SET(__pyx_v_cigar, __pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1654 + * base_position = r.pos + * cigar = r.cigartuples + * if cigar is None: # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_9 = (__pyx_v_cigar == Py_None); + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":1655 + * cigar = r.cigartuples + * if cigar is None: + * continue # <<<<<<<<<<<<<< + * + * for op, nt in cigar: +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":1654 + * base_position = r.pos + * cigar = r.cigartuples + * if cigar is None: # <<<<<<<<<<<<<< + * continue + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1657 + * continue + * + * for op, nt in cigar: # <<<<<<<<<<<<<< + * if op in match_or_deletion: + * base_position += nt +*/ + if (likely(PyList_CheckExact(__pyx_v_cigar)) || PyTuple_CheckExact(__pyx_v_cigar)) { + __pyx_t_4 = __pyx_v_cigar; __Pyx_INCREF(__pyx_t_4); + __pyx_t_10 = 0; + __pyx_t_11 = NULL; + } else { + __pyx_t_10 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_cigar); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_11 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_4); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1657, __pyx_L1_error) + } + for (;;) { + if (likely(!__pyx_t_11)) { + if (likely(PyList_CheckExact(__pyx_t_4))) { + { + Py_ssize_t __pyx_temp = __Pyx_PyList_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1657, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + __pyx_t_2 = __Pyx_PyList_GetItemRef(__pyx_t_4, __pyx_t_10); + ++__pyx_t_10; + } else { + { + Py_ssize_t __pyx_temp = __Pyx_PyTuple_GET_SIZE(__pyx_t_4); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely((__pyx_temp < 0))) __PYX_ERR(0, 1657, __pyx_L1_error) + #endif + if (__pyx_t_10 >= __pyx_temp) break; + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = __Pyx_NewRef(PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_10)); + #else + __pyx_t_2 = __Pyx_PySequence_ITEM(__pyx_t_4, __pyx_t_10); + #endif + ++__pyx_t_10; + } + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1657, __pyx_L1_error) + } else { + __pyx_t_2 = __pyx_t_11(__pyx_t_4); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) __PYX_ERR(0, 1657, __pyx_L1_error) + PyErr_Clear(); + } + break; + } + } + __Pyx_GOTREF(__pyx_t_2); + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 1657, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_12 = PyTuple_GET_ITEM(sequence, 1); + __Pyx_INCREF(__pyx_t_12); + } else { + __pyx_t_3 = __Pyx_PyList_GetItemRef(sequence, 0); + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_3); + __pyx_t_12 = __Pyx_PyList_GetItemRef(sequence, 1); + if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_XGOTREF(__pyx_t_12); + } + #else + __pyx_t_3 = __Pyx_PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_12 = __Pyx_PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_13 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_13); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_14 = (CYTHON_COMPILING_IN_LIMITED_API) ? PyIter_Next : __Pyx_PyObject_GetIterNextFunc(__pyx_t_13); + index = 0; __pyx_t_3 = __pyx_t_14(__pyx_t_13); if (unlikely(!__pyx_t_3)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_3); + index = 1; __pyx_t_12 = __pyx_t_14(__pyx_t_13); if (unlikely(!__pyx_t_12)) goto __pyx_L8_unpacking_failed; + __Pyx_GOTREF(__pyx_t_12); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_14(__pyx_t_13), 2) < 0) __PYX_ERR(0, 1657, __pyx_L1_error) + __pyx_t_14 = NULL; + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + goto __pyx_L9_unpacking_done; + __pyx_L8_unpacking_failed:; + __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; + __pyx_t_14 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 1657, __pyx_L1_error) + __pyx_L9_unpacking_done:; + } + __pyx_t_15 = __Pyx_PyLong_As_int(__pyx_t_3); if (unlikely((__pyx_t_15 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = __Pyx_PyLong_As_uint32_t(__pyx_t_12); if (unlikely((__pyx_t_8 == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 1657, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_v_op = __pyx_t_15; + __pyx_v_nt = __pyx_t_8; + + /* "pysam/libcalignmentfile.pyx":1658 + * + * for op, nt in cigar: + * if op in match_or_deletion: # <<<<<<<<<<<<<< + * base_position += nt + * elif op == BAM_CREF_SKIP: +*/ + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_op); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1658, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_9 = (__Pyx_PySet_ContainsTF(__pyx_t_2, __pyx_v_match_or_deletion, Py_EQ)); if (unlikely((__pyx_t_9 < 0))) __PYX_ERR(0, 1658, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":1659 + * for op, nt in cigar: + * if op in match_or_deletion: + * base_position += nt # <<<<<<<<<<<<<< + * elif op == BAM_CREF_SKIP: + * junc_start = base_position +*/ + __pyx_v_base_position = (__pyx_v_base_position + __pyx_v_nt); + + /* "pysam/libcalignmentfile.pyx":1658 + * + * for op, nt in cigar: + * if op in match_or_deletion: # <<<<<<<<<<<<<< + * base_position += nt + * elif op == BAM_CREF_SKIP: +*/ + goto __pyx_L10; + } + + /* "pysam/libcalignmentfile.pyx":1660 + * if op in match_or_deletion: + * base_position += nt + * elif op == BAM_CREF_SKIP: # <<<<<<<<<<<<<< + * junc_start = base_position + * base_position += nt +*/ + __pyx_t_9 = (__pyx_v_op == __pyx_v_BAM_CREF_SKIP); + if (__pyx_t_9) { + + /* "pysam/libcalignmentfile.pyx":1661 + * base_position += nt + * elif op == BAM_CREF_SKIP: + * junc_start = base_position # <<<<<<<<<<<<<< + * base_position += nt + * res[(junc_start, base_position)] += 1 +*/ + __pyx_v_junc_start = __pyx_v_base_position; + + /* "pysam/libcalignmentfile.pyx":1662 + * elif op == BAM_CREF_SKIP: + * junc_start = base_position + * base_position += nt # <<<<<<<<<<<<<< + * res[(junc_start, base_position)] += 1 + * return res +*/ + __pyx_v_base_position = (__pyx_v_base_position + __pyx_v_nt); + + /* "pysam/libcalignmentfile.pyx":1663 + * junc_start = base_position + * base_position += nt + * res[(junc_start, base_position)] += 1 # <<<<<<<<<<<<<< + * return res + * +*/ + __pyx_t_2 = __Pyx_PyLong_From_uint32_t(__pyx_v_junc_start); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_12 = __Pyx_PyLong_From_uint32_t(__pyx_v_base_position); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2) != (0)) __PYX_ERR(0, 1663, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_12); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_12) != (0)) __PYX_ERR(0, 1663, __pyx_L1_error); + __pyx_t_2 = 0; + __pyx_t_12 = 0; + __pyx_t_12 = __Pyx_PyObject_GetItem(__pyx_v_res, __pyx_t_3); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __pyx_t_2 = __Pyx_PyLong_AddObjC(__pyx_t_12, __pyx_mstate_global->__pyx_int_1, 1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + if (unlikely((PyObject_SetItem(__pyx_v_res, __pyx_t_3, __pyx_t_2) < 0))) __PYX_ERR(0, 1663, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":1660 + * if op in match_or_deletion: + * base_position += nt + * elif op == BAM_CREF_SKIP: # <<<<<<<<<<<<<< + * junc_start = base_position + * base_position += nt +*/ + } + __pyx_L10:; + + /* "pysam/libcalignmentfile.pyx":1657 + * continue + * + * for op, nt in cigar: # <<<<<<<<<<<<<< + * if op in match_or_deletion: + * base_position += nt +*/ + } + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":1651 + * + * match_or_deletion = {0, 2, 7, 8} # only M/=/X (0/7/8) and D (2) are related to genome position + * for r in read_iterator: # <<<<<<<<<<<<<< + * base_position = r.pos + * cigar = r.cigartuples +*/ + __pyx_L3_continue:; + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1664 + * base_position += nt + * res[(junc_start, base_position)] += 1 + * return res # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_res); + __pyx_r = __pyx_v_res; + __Pyx_TraceReturnValue(__pyx_r, 48, 0, __PYX_ERR(0, 1664, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1633 + * return res + * + * def find_introns(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_XDECREF(__pyx_t_13); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1633, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.find_introns", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF((PyObject *)__pyx_v_r); + __Pyx_XDECREF(__pyx_v_res); + __Pyx_XDECREF(__pyx_v_match_or_deletion); + __Pyx_XDECREF(__pyx_v_cigar); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1667 + * + * + * def close(self): # <<<<<<<<<<<<<< + * '''closes the :class:`pysam.AlignmentFile`.''' + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_25close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_24close, "AlignmentFile.close(self)\n\ncloses the :class:`pysam.AlignmentFile`."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_25close = {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_25close, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_24close}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_25close(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("close (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("close", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("close", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_24close(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_24close(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_ret; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[47])) + __Pyx_RefNannySetupContext("close", 0); + __Pyx_TraceStartFunc("close", __pyx_f[0], 1667, 0, 0, 0, __PYX_ERR(0, 1667, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1670 + * '''closes the :class:`pysam.AlignmentFile`.''' + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * return + * +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.htsfile == NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1671 + * + * if self.htsfile == NULL: + * return # <<<<<<<<<<<<<< + * + * if self.index != NULL: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1670 + * '''closes the :class:`pysam.AlignmentFile`.''' + * + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * return + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1673 + * return + * + * if self.index != NULL: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * self.index = NULL +*/ + __pyx_t_1 = (__pyx_v_self->index != NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1674 + * + * if self.index != NULL: + * hts_idx_destroy(self.index) # <<<<<<<<<<<<<< + * self.index = NULL + * +*/ + hts_idx_destroy(__pyx_v_self->index); + + /* "pysam/libcalignmentfile.pyx":1675 + * if self.index != NULL: + * hts_idx_destroy(self.index) + * self.index = NULL # <<<<<<<<<<<<<< + * + * cdef int ret = hts_close(self.htsfile) +*/ + __pyx_v_self->index = NULL; + + /* "pysam/libcalignmentfile.pyx":1673 + * return + * + * if self.index != NULL: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * self.index = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":1677 + * self.index = NULL + * + * cdef int ret = hts_close(self.htsfile) # <<<<<<<<<<<<<< + * self.htsfile = NULL + * +*/ + __pyx_v_ret = hts_close(__pyx_v_self->__pyx_base.htsfile); + + /* "pysam/libcalignmentfile.pyx":1678 + * + * cdef int ret = hts_close(self.htsfile) + * self.htsfile = NULL # <<<<<<<<<<<<<< + * + * self.header = None +*/ + __pyx_v_self->__pyx_base.htsfile = NULL; + + /* "pysam/libcalignmentfile.pyx":1680 + * self.htsfile = NULL + * + * self.header = None # <<<<<<<<<<<<<< + * + * if ret < 0 and errno != EPIPE: +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); + + /* "pysam/libcalignmentfile.pyx":1682 + * self.header = None + * + * if ret < 0 and errno != EPIPE: # <<<<<<<<<<<<<< + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) +*/ + __pyx_t_2 = (__pyx_v_ret < 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L6_bool_binop_done; + } + __pyx_t_2 = (errno != EPIPE); + __pyx_t_1 = __pyx_t_2; + __pyx_L6_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1683 + * + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): # <<<<<<<<<<<<<< + * raise OSError_from_errno("Closing failed", self.filename) + * else: +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_2 = PyUnicode_Check(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L9_bool_binop_done; + } + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_2 = PyBytes_Check(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = __pyx_t_2; + __pyx_L9_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1684 + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) # <<<<<<<<<<<<<< + * else: + * raise OSError_from_errno("Closing failed") +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5.__pyx_n = 1; + __pyx_t_5.filename = __pyx_t_3; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Closing_failed, &__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1684, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1684, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1683 + * + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): # <<<<<<<<<<<<<< + * raise OSError_from_errno("Closing failed", self.filename) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1686 + * raise OSError_from_errno("Closing failed", self.filename) + * else: + * raise OSError_from_errno("Closing failed") # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + /*else*/ { + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Closing_failed, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1686, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1686, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1682 + * self.header = None + * + * if ret < 0 and errno != EPIPE: # <<<<<<<<<<<<<< + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1667 + * + * + * def close(self): # <<<<<<<<<<<<<< + * '''closes the :class:`pysam.AlignmentFile`.''' + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 1667, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1667, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.close", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1688 + * raise OSError_from_errno("Closing failed") + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * cdef int ret = 0 + * +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_27__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_27__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_26__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_26__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_ret; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[48])) + __Pyx_RefNannySetupContext("__dealloc__", 0); + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 1688, 0, 0, 0, __PYX_ERR(0, 1688, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1689 + * + * def __dealloc__(self): + * cdef int ret = 0 # <<<<<<<<<<<<<< + * + * if self.index != NULL: +*/ + __pyx_v_ret = 0; + + /* "pysam/libcalignmentfile.pyx":1691 + * cdef int ret = 0 + * + * if self.index != NULL: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * self.index = NULL +*/ + __pyx_t_1 = (__pyx_v_self->index != NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1692 + * + * if self.index != NULL: + * hts_idx_destroy(self.index) # <<<<<<<<<<<<<< + * self.index = NULL + * +*/ + hts_idx_destroy(__pyx_v_self->index); + + /* "pysam/libcalignmentfile.pyx":1693 + * if self.index != NULL: + * hts_idx_destroy(self.index) + * self.index = NULL # <<<<<<<<<<<<<< + * + * if self.htsfile != NULL: +*/ + __pyx_v_self->index = NULL; + + /* "pysam/libcalignmentfile.pyx":1691 + * cdef int ret = 0 + * + * if self.index != NULL: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * self.index = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":1695 + * self.index = NULL + * + * if self.htsfile != NULL: # <<<<<<<<<<<<<< + * ret = hts_close(self.htsfile) + * self.htsfile = NULL +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.htsfile != NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1696 + * + * if self.htsfile != NULL: + * ret = hts_close(self.htsfile) # <<<<<<<<<<<<<< + * self.htsfile = NULL + * +*/ + __pyx_v_ret = hts_close(__pyx_v_self->__pyx_base.htsfile); + + /* "pysam/libcalignmentfile.pyx":1697 + * if self.htsfile != NULL: + * ret = hts_close(self.htsfile) + * self.htsfile = NULL # <<<<<<<<<<<<<< + * + * self.header = None +*/ + __pyx_v_self->__pyx_base.htsfile = NULL; + + /* "pysam/libcalignmentfile.pyx":1695 + * self.index = NULL + * + * if self.htsfile != NULL: # <<<<<<<<<<<<<< + * ret = hts_close(self.htsfile) + * self.htsfile = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":1699 + * self.htsfile = NULL + * + * self.header = None # <<<<<<<<<<<<<< + * + * if self.b: +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); + + /* "pysam/libcalignmentfile.pyx":1701 + * self.header = None + * + * if self.b: # <<<<<<<<<<<<<< + * bam_destroy1(self.b) + * self.b = NULL +*/ + __pyx_t_1 = (__pyx_v_self->b != 0); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1702 + * + * if self.b: + * bam_destroy1(self.b) # <<<<<<<<<<<<<< + * self.b = NULL + * +*/ + bam_destroy1(__pyx_v_self->b); + + /* "pysam/libcalignmentfile.pyx":1703 + * if self.b: + * bam_destroy1(self.b) + * self.b = NULL # <<<<<<<<<<<<<< + * + * if ret < 0 and errno != EPIPE: +*/ + __pyx_v_self->b = NULL; + + /* "pysam/libcalignmentfile.pyx":1701 + * self.header = None + * + * if self.b: # <<<<<<<<<<<<<< + * bam_destroy1(self.b) + * self.b = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":1705 + * self.b = NULL + * + * if ret < 0 and errno != EPIPE: # <<<<<<<<<<<<<< + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) +*/ + __pyx_t_2 = (__pyx_v_ret < 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L7_bool_binop_done; + } + __pyx_t_2 = (errno != EPIPE); + __pyx_t_1 = __pyx_t_2; + __pyx_L7_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":1706 + * + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): # <<<<<<<<<<<<<< + * raise OSError_from_errno("Closing failed", self.filename) + * else: +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_2 = PyUnicode_Check(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (!__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L10_bool_binop_done; + } + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_2 = PyBytes_Check(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = __pyx_t_2; + __pyx_L10_bool_binop_done:; + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1707 + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) # <<<<<<<<<<<<<< + * else: + * raise OSError_from_errno("Closing failed") +*/ + __pyx_t_3 = __pyx_v_self->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_5.__pyx_n = 1; + __pyx_t_5.filename = __pyx_t_3; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Closing_failed, &__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1707, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1707, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1706 + * + * if ret < 0 and errno != EPIPE: + * if isinstance(self.filename, (str, bytes)): # <<<<<<<<<<<<<< + * raise OSError_from_errno("Closing failed", self.filename) + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1709 + * raise OSError_from_errno("Closing failed", self.filename) + * else: + * raise OSError_from_errno("Closing failed") # <<<<<<<<<<<<<< + * + * cpdef int write(self, AlignedSegment read) except -1: +*/ + /*else*/ { + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Closing_failed, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1709, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1709, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1705 + * self.b = NULL + * + * if ret < 0 and errno != EPIPE: # <<<<<<<<<<<<<< + * if isinstance(self.filename, (str, bytes)): + * raise OSError_from_errno("Closing failed", self.filename) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1688 + * raise OSError_from_errno("Closing failed") + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * cdef int ret = 0 + * +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 1688, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1688, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.AlignmentFile.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); +} + +/* "pysam/libcalignmentfile.pyx":1711 + * raise OSError_from_errno("Closing failed") + * + * cpdef int write(self, AlignedSegment read) except -1: # <<<<<<<<<<<<<< + * ''' + * write a single :class:`pysam.AlignedSegment` to disk. +*/ + +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_29write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +static int __pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_write(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read, int __pyx_skip_dispatch) { + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[49])) + __Pyx_RefNannySetupContext("write", 0); + __Pyx_TraceStartFunc("write", __pyx_f[0], 1711, 0, 0, __pyx_skip_dispatch, __PYX_ERR(0, 1711, __pyx_L1_error)); + /* Check if called by wrapper */ + if (unlikely(__pyx_skip_dispatch)) ; + /* Check if overridden in Python */ + else if ( + #if !CYTHON_USE_TYPE_SLOTS + unlikely(Py_TYPE(((PyObject *)__pyx_v_self)) != __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile && + __Pyx_PyType_HasFeature(Py_TYPE(((PyObject *)__pyx_v_self)), Py_TPFLAGS_HAVE_GC)) + #else + unlikely(Py_TYPE(((PyObject *)__pyx_v_self))->tp_dictoffset != 0 || __Pyx_PyType_HasFeature(Py_TYPE(((PyObject *)__pyx_v_self)), (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE))) + #endif + ) { + #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS + static PY_UINT64_T __pyx_tp_dict_version = __PYX_DICT_VERSION_INIT, __pyx_obj_dict_version = __PYX_DICT_VERSION_INIT; + if (unlikely(!__Pyx_object_dict_version_matches(((PyObject *)__pyx_v_self), __pyx_tp_dict_version, __pyx_obj_dict_version))) { + PY_UINT64_T __pyx_typedict_guard = __Pyx_get_tp_dict_version(((PyObject *)__pyx_v_self)); + #endif + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_write); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!__Pyx_IsSameCFunction(__pyx_t_1, (void(*)(void)) __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_29write)) { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_4 = __pyx_t_1; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_3); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_3); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, ((PyObject *)__pyx_v_read)}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_6 = __Pyx_PyLong_As_int(__pyx_t_2); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_6; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 0, 0, __PYX_ERR(0, 1711, __pyx_L1_error)); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L0; + } + #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS + __pyx_tp_dict_version = __Pyx_get_tp_dict_version(((PyObject *)__pyx_v_self)); + __pyx_obj_dict_version = __Pyx_get_object_dict_version(((PyObject *)__pyx_v_self)); + if (unlikely(__pyx_typedict_guard != __pyx_tp_dict_version)) { + __pyx_tp_dict_version = __pyx_obj_dict_version = __PYX_DICT_VERSION_INIT; + } + #endif + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_PYTYPE_LOOKUP && CYTHON_USE_TYPE_SLOTS + } + #endif + } + + /* "pysam/libcalignmentfile.pyx":1724 + * this will be 0. + * ''' + * if not self.is_open: # <<<<<<<<<<<<<< + * return 0 + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1724, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 1724, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = (!__pyx_t_7); + if (__pyx_t_8) { + + /* "pysam/libcalignmentfile.pyx":1725 + * ''' + * if not self.is_open: + * return 0 # <<<<<<<<<<<<<< + * + * if self.header.ptr.n_targets <= read._delegate.core.tid: +*/ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 6, 0, __PYX_ERR(0, 1725, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1724 + * this will be 0. + * ''' + * if not self.is_open: # <<<<<<<<<<<<<< + * return 0 + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1727 + * return 0 + * + * if self.header.ptr.n_targets <= read._delegate.core.tid: # <<<<<<<<<<<<<< + * raise ValueError( + * "AlignedSegment refers to reference number {} that " +*/ + __pyx_t_8 = (__pyx_v_self->header->ptr->n_targets <= __pyx_v_read->_delegate->core.tid); + if (unlikely(__pyx_t_8)) { + + /* "pysam/libcalignmentfile.pyx":1728 + * + * if self.header.ptr.n_targets <= read._delegate.core.tid: + * raise ValueError( # <<<<<<<<<<<<<< + * "AlignedSegment refers to reference number {} that " + * "is larger than the number of references ({}) in the header".format( +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":1730 + * raise ValueError( + * "AlignedSegment refers to reference number {} that " + * "is larger than the number of references ({}) in the header".format( # <<<<<<<<<<<<<< + * read._delegate.core.tid, self.header.ptr.n_targets)) + * +*/ + __pyx_t_9 = __pyx_mstate_global->__pyx_kp_u_AlignedSegment_refers_to_referen; + __Pyx_INCREF(__pyx_t_9); + + /* "pysam/libcalignmentfile.pyx":1731 + * "AlignedSegment refers to reference number {} that " + * "is larger than the number of references ({}) in the header".format( + * read._delegate.core.tid, self.header.ptr.n_targets)) # <<<<<<<<<<<<<< + * + * cdef int ret +*/ + __pyx_t_10 = __Pyx_PyLong_From_int32_t(__pyx_v_read->_delegate->core.tid); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1731, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyLong_From_int32_t(__pyx_v_self->header->ptr->n_targets); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 1731, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_9, __pyx_t_10, __pyx_t_11}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1730, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1728, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1728, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1727 + * return 0 + * + * if self.header.ptr.n_targets <= read._delegate.core.tid: # <<<<<<<<<<<<<< + * raise ValueError( + * "AlignedSegment refers to reference number {} that " +*/ + } + + /* "pysam/libcalignmentfile.pyx":1734 + * + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_write1(self.htsfile, + * self.header.ptr, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1735 + * cdef int ret + * with nogil: + * ret = sam_write1(self.htsfile, # <<<<<<<<<<<<<< + * self.header.ptr, + * read._delegate) +*/ + __pyx_v_ret = sam_write1(__pyx_v_self->__pyx_base.htsfile, __pyx_v_self->header->ptr, __pyx_v_read->_delegate); + } + + /* "pysam/libcalignmentfile.pyx":1734 + * + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_write1(self.htsfile, + * self.header.ptr, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L7; + } + __pyx_L7:; + } + } + + /* "pysam/libcalignmentfile.pyx":1742 + * # when ret == -1 we get a "SystemError: error return without + * # exception set". + * if ret < 0: # <<<<<<<<<<<<<< + * raise IOError("sam_write1 failed with error code {}".format(ret)) + * +*/ + __pyx_t_8 = (__pyx_v_ret < 0); + if (unlikely(__pyx_t_8)) { + + /* "pysam/libcalignmentfile.pyx":1743 + * # exception set". + * if ret < 0: + * raise IOError("sam_write1 failed with error code {}".format(ret)) # <<<<<<<<<<<<<< + * + * return ret +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_3 = __pyx_builtin_IOError; + __pyx_t_11 = __pyx_mstate_global->__pyx_kp_u_sam_write1_failed_with_error_cod; + __Pyx_INCREF(__pyx_t_11); + __pyx_t_10 = __Pyx_PyLong_From_int(__pyx_v_ret); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1743, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_11, __pyx_t_10}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1743, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_2}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1743, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1743, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1742 + * # when ret == -1 we get a "SystemError: error return without + * # exception set". + * if ret < 0: # <<<<<<<<<<<<<< + * raise IOError("sam_write1 failed with error code {}".format(ret)) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1745 + * raise IOError("sam_write1 failed with error code {}".format(ret)) + * + * return ret # <<<<<<<<<<<<<< + * + * # context manager interface +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 54, 0, __PYX_ERR(0, 1745, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1711 + * raise OSError_from_errno("Closing failed") + * + * cpdef int write(self, AlignedSegment read) except -1: # <<<<<<<<<<<<<< + * ''' + * write a single :class:`pysam.AlignedSegment` to disk. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1711, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_29write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_28write, "AlignmentFile.write(self, AlignedSegment read) -> int\n\nwrite a single :class:`pysam.AlignedSegment` to disk.\n\nRaises:\n ValueError\n if the writing failed\n\nReturns:\n int :\n the number of bytes written. If the file is closed,\n this will be 0."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_29write = {"write", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_29write, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_28write}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_29write(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("write (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_read,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1711, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1711, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "write", 0) < 0) __PYX_ERR(0, 1711, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, i); __PYX_ERR(0, 1711, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1711, __pyx_L3_error) + } + __pyx_v_read = ((struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("write", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1711, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_read), __pyx_mstate_global->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment, 1, "read", 0))) __PYX_ERR(0, 1711, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_28write(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_read); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_28write(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *__pyx_v_read) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[49])) + __Pyx_RefNannySetupContext("write", 0); + __Pyx_TraceStartFunc("write (wrapper)", __pyx_f[0], 1711, 0, 0, 0, __PYX_ERR(0, 1711, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_write(__pyx_v_self, __pyx_v_read, 1); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 1711, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1711, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.write", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1748 + * + * # context manager interface + * def __enter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__, "AlignmentFile.__enter__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__ = {"__enter__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__enter__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__enter__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__enter__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[50])) + __Pyx_RefNannySetupContext("__enter__", 0); + __Pyx_TraceStartFunc("__enter__", __pyx_f[0], 1748, 0, 0, 0, __PYX_ERR(0, 1748, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1749 + * # context manager interface + * def __enter__(self): + * return self # <<<<<<<<<<<<<< + * + * def __exit__(self, exc_type, exc_value, traceback): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 1749, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1748 + * + * # context manager interface + * def __enter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1748, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__enter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1751 + * return self + * + * def __exit__(self, exc_type, exc_value, traceback): # <<<<<<<<<<<<<< + * self.close() + * return False +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__, "AlignmentFile.__exit__(self, exc_type, exc_value, traceback)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__ = {"__exit__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v_exc_type = 0; + CYTHON_UNUSED PyObject *__pyx_v_exc_value = 0; + CYTHON_UNUSED PyObject *__pyx_v_traceback = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__exit__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_exc_type,&__pyx_mstate_global->__pyx_n_u_exc_value,&__pyx_mstate_global->__pyx_n_u_traceback,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1751, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1751, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1751, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1751, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__exit__", 0) < 0) __PYX_ERR(0, 1751, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__exit__", 1, 3, 3, i); __PYX_ERR(0, 1751, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1751, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1751, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 1751, __pyx_L3_error) + } + __pyx_v_exc_type = values[0]; + __pyx_v_exc_value = values[1]; + __pyx_v_traceback = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__exit__", 1, 3, 3, __pyx_nargs); __PYX_ERR(0, 1751, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__exit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_exc_type, __pyx_v_exc_value, __pyx_v_traceback); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_exc_type, CYTHON_UNUSED PyObject *__pyx_v_exc_value, CYTHON_UNUSED PyObject *__pyx_v_traceback) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[51])) + __Pyx_RefNannySetupContext("__exit__", 0); + __Pyx_TraceStartFunc("__exit__", __pyx_f[0], 1751, 0, 0, 0, __PYX_ERR(0, 1751, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1752 + * + * def __exit__(self, exc_type, exc_value, traceback): + * self.close() # <<<<<<<<<<<<<< + * return False + * +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_close, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1752, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1753 + * def __exit__(self, exc_type, exc_value, traceback): + * self.close() + * return False # <<<<<<<<<<<<<< + * + * ############################################################### +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(Py_False); + __pyx_r = Py_False; + __Pyx_TraceReturnValue(__pyx_r, 4, 0, __PYX_ERR(0, 1753, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1751 + * return self + * + * def __exit__(self, exc_type, exc_value, traceback): # <<<<<<<<<<<<<< + * self.close() + * return False +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1751, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__exit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1767 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef int tid +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6mapped_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6mapped_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6mapped___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6mapped___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_tid; + uint64_t __pyx_v_total; + uint64_t __pyx_v_mapped; + uint64_t __pyx_v_unmapped; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[52])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1767, 0, 0, 0, __PYX_ERR(0, 1767, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1768 + * """ + * def __get__(self): + * self.check_index() # <<<<<<<<<<<<<< + * cdef int tid + * cdef uint64_t total = 0 +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_check_index, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1768, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1770 + * self.check_index() + * cdef int tid + * cdef uint64_t total = 0 # <<<<<<<<<<<<<< + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: +*/ + __pyx_v_total = 0; + + /* "pysam/libcalignmentfile.pyx":1772 + * cdef uint64_t total = 0 + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: # <<<<<<<<<<<<<< + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1772, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1772, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (__pyx_v_tid = 0; __pyx_v_tid < __pyx_t_4; __pyx_v_tid++) { + + /* "pysam/libcalignmentfile.pyx":1773 + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += mapped +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1774 + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) # <<<<<<<<<<<<<< + * total += mapped + * return total +*/ + (void)(hts_idx_get_stat(__pyx_v_self->index, __pyx_v_tid, (&__pyx_v_mapped), (&__pyx_v_unmapped))); + } + + /* "pysam/libcalignmentfile.pyx":1773 + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += mapped +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":1775 + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += mapped # <<<<<<<<<<<<<< + * return total + * +*/ + __pyx_v_total = (__pyx_v_total + __pyx_v_mapped); + } + + /* "pysam/libcalignmentfile.pyx":1776 + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += mapped + * return total # <<<<<<<<<<<<<< + * + * property unmapped: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_uint64_t(__pyx_v_total); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1776, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 24, 0, __PYX_ERR(0, 1776, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1767 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef int tid +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1767, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.mapped.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1785 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef int tid +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_tid; + uint64_t __pyx_v_total; + uint64_t __pyx_v_mapped; + uint64_t __pyx_v_unmapped; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[53])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1785, 0, 0, 0, __PYX_ERR(0, 1785, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1786 + * """ + * def __get__(self): + * self.check_index() # <<<<<<<<<<<<<< + * cdef int tid + * cdef uint64_t total = hts_idx_get_n_no_coor(self.index) +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_check_index, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1786, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1788 + * self.check_index() + * cdef int tid + * cdef uint64_t total = hts_idx_get_n_no_coor(self.index) # <<<<<<<<<<<<<< + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: +*/ + __pyx_v_total = hts_idx_get_n_no_coor(__pyx_v_self->index); + + /* "pysam/libcalignmentfile.pyx":1790 + * cdef uint64_t total = hts_idx_get_n_no_coor(self.index) + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: # <<<<<<<<<<<<<< + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1790, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1790, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (__pyx_v_tid = 0; __pyx_v_tid < __pyx_t_4; __pyx_v_tid++) { + + /* "pysam/libcalignmentfile.pyx":1791 + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += unmapped +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1792 + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) # <<<<<<<<<<<<<< + * total += unmapped + * return total +*/ + (void)(hts_idx_get_stat(__pyx_v_self->index, __pyx_v_tid, (&__pyx_v_mapped), (&__pyx_v_unmapped))); + } + + /* "pysam/libcalignmentfile.pyx":1791 + * cdef uint64_t mapped, unmapped + * for tid from 0 <= tid < self.header.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += unmapped +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":1793 + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += unmapped # <<<<<<<<<<<<<< + * return total + * +*/ + __pyx_v_total = (__pyx_v_total + __pyx_v_unmapped); + } + + /* "pysam/libcalignmentfile.pyx":1794 + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * total += unmapped + * return total # <<<<<<<<<<<<<< + * + * property nocoordinate: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_uint64_t(__pyx_v_total); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1794, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 27, 0, __PYX_ERR(0, 1794, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1785 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef int tid +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1785, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.unmapped.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1803 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef uint64_t n +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + uint64_t __pyx_v_n; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[54])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1803, 0, 0, 0, __PYX_ERR(0, 1803, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1804 + * """ + * def __get__(self): + * self.check_index() # <<<<<<<<<<<<<< + * cdef uint64_t n + * with nogil: +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_check_index, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1804, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1806 + * self.check_index() + * cdef uint64_t n + * with nogil: # <<<<<<<<<<<<<< + * n = hts_idx_get_n_no_coor(self.index) + * return n +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1807 + * cdef uint64_t n + * with nogil: + * n = hts_idx_get_n_no_coor(self.index) # <<<<<<<<<<<<<< + * return n + * +*/ + __pyx_v_n = hts_idx_get_n_no_coor(__pyx_v_self->index); + } + + /* "pysam/libcalignmentfile.pyx":1806 + * self.check_index() + * cdef uint64_t n + * with nogil: # <<<<<<<<<<<<<< + * n = hts_idx_get_n_no_coor(self.index) + * return n +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":1808 + * with nogil: + * n = hts_idx_get_n_no_coor(self.index) + * return n # <<<<<<<<<<<<<< + * + * def get_index_statistics(self): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_uint64_t(__pyx_v_n); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1808, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 10, 0, __PYX_ERR(0, 1808, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1803 + * index format does not record these statistics.) + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * self.check_index() + * cdef uint64_t n +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1803, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.nocoordinate.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1810 + * return n + * + * def get_index_statistics(self): # <<<<<<<<<<<<<< + * """return statistics about mapped/unmapped reads per chromosome as + * they are stored in the index, similarly to the statistics printed +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics, "AlignmentFile.get_index_statistics(self)\n\nreturn statistics about mapped/unmapped reads per chromosome as\nthey are stored in the index, similarly to the statistics printed\nby the ``samtools idxstats`` command.\n\nCRAI indexes do not record these statistics, so for a CRAM file\nwith a .crai index the returned statistics will all be 0.\n\nReturns:\n list :\n a list of records for each chromosome. Each record has the\n attributes 'contig', 'mapped', 'unmapped' and 'total'."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics = {"get_index_statistics", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_index_statistics (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("get_index_statistics", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("get_index_statistics", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_tid; + uint64_t __pyx_v_mapped; + uint64_t __pyx_v_unmapped; + PyObject *__pyx_v_results = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + int __pyx_t_11; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[55])) + __Pyx_RefNannySetupContext("get_index_statistics", 0); + __Pyx_TraceStartFunc("get_index_statistics", __pyx_f[0], 1810, 0, 0, 0, __PYX_ERR(0, 1810, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1824 + * """ + * + * self.check_index() # <<<<<<<<<<<<<< + * cdef int tid + * cdef uint64_t mapped, unmapped +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_check_index, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1824, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1827 + * cdef int tid + * cdef uint64_t mapped, unmapped + * results = [] # <<<<<<<<<<<<<< + * # TODO: use header + * for tid from 0 <= tid < self.nreferences: +*/ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1827, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_results = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":1829 + * results = [] + * # TODO: use header + * for tid from 0 <= tid < self.nreferences: # <<<<<<<<<<<<<< + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1829, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1829, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + for (__pyx_v_tid = 0; __pyx_v_tid < __pyx_t_4; __pyx_v_tid++) { + + /* "pysam/libcalignmentfile.pyx":1830 + * # TODO: use header + * for tid from 0 <= tid < self.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * results.append( +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1831 + * for tid from 0 <= tid < self.nreferences: + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) # <<<<<<<<<<<<<< + * results.append( + * IndexStats._make(( +*/ + (void)(hts_idx_get_stat(__pyx_v_self->index, __pyx_v_tid, (&__pyx_v_mapped), (&__pyx_v_unmapped))); + } + + /* "pysam/libcalignmentfile.pyx":1830 + * # TODO: use header + * for tid from 0 <= tid < self.nreferences: + * with nogil: # <<<<<<<<<<<<<< + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * results.append( +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":1833 + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * results.append( + * IndexStats._make(( # <<<<<<<<<<<<<< + * self.get_reference_name(tid), + * mapped, +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_IndexStats); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1833, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_make); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1833, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":1834 + * results.append( + * IndexStats._make(( + * self.get_reference_name(tid), # <<<<<<<<<<<<<< + * mapped, + * unmapped, +*/ + __pyx_t_7 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_tid); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1834, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_8}; + __pyx_t_5 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_reference_name, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1834, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + + /* "pysam/libcalignmentfile.pyx":1835 + * IndexStats._make(( + * self.get_reference_name(tid), + * mapped, # <<<<<<<<<<<<<< + * unmapped, + * mapped + unmapped))) +*/ + __pyx_t_8 = __Pyx_PyLong_From_uint64_t(__pyx_v_mapped); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1835, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + /* "pysam/libcalignmentfile.pyx":1836 + * self.get_reference_name(tid), + * mapped, + * unmapped, # <<<<<<<<<<<<<< + * mapped + unmapped))) + * +*/ + __pyx_t_7 = __Pyx_PyLong_From_uint64_t(__pyx_v_unmapped); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 1836, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "pysam/libcalignmentfile.pyx":1837 + * mapped, + * unmapped, + * mapped + unmapped))) # <<<<<<<<<<<<<< + * + * return results +*/ + __pyx_t_9 = __Pyx_PyLong_From_uint64_t((__pyx_v_mapped + __pyx_v_unmapped)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1837, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + + /* "pysam/libcalignmentfile.pyx":1834 + * results.append( + * IndexStats._make(( + * self.get_reference_name(tid), # <<<<<<<<<<<<<< + * mapped, + * unmapped, +*/ + __pyx_t_10 = PyTuple_New(4); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 1834, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5) != (0)) __PYX_ERR(0, 1834, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_8); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_8) != (0)) __PYX_ERR(0, 1834, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_10, 2, __pyx_t_7) != (0)) __PYX_ERR(0, 1834, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_9); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_10, 3, __pyx_t_9) != (0)) __PYX_ERR(0, 1834, __pyx_L1_error); + __pyx_t_5 = 0; + __pyx_t_8 = 0; + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_t_3 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_3 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_t_10}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1833, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":1832 + * with nogil: + * hts_idx_get_stat(self.index, tid, &mapped, &unmapped) + * results.append( # <<<<<<<<<<<<<< + * IndexStats._make(( + * self.get_reference_name(tid), +*/ + __pyx_t_11 = __Pyx_PyList_Append(__pyx_v_results, __pyx_t_1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(0, 1832, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "pysam/libcalignmentfile.pyx":1839 + * mapped + unmapped))) + * + * return results # <<<<<<<<<<<<<< + * + * ############################################################### +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_results); + __pyx_r = __pyx_v_results; + __Pyx_TraceReturnValue(__pyx_r, 36, 0, __PYX_ERR(0, 1839, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1810 + * return n + * + * def get_index_statistics(self): # <<<<<<<<<<<<<< + * """return statistics about mapped/unmapped reads per chromosome as + * they are stored in the index, similarly to the statistics printed +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1810, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_index_statistics", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_results); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1846 + * ## and multiple_iterators) + * ## Possible solutions: deprecate or open new file handle + * def __iter__(self): # <<<<<<<<<<<<<< + * if not self.is_open: + * raise ValueError("I/O operation on closed file") +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_37__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_37__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_36__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_36__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[56])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 1846, 0, 0, 0, __PYX_ERR(0, 1846, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1847 + * ## Possible solutions: deprecate or open new file handle + * def __iter__(self): + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1847, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1847, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1848 + * def __iter__(self): + * if not self.is_open: + * raise ValueError("I/O operation on closed file") # <<<<<<<<<<<<<< + * + * if not self.is_bam and self.header.nreferences == 0: +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1848, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1848, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1847 + * ## Possible solutions: deprecate or open new file handle + * def __iter__(self): + * if not self.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":1850 + * raise ValueError("I/O operation on closed file") + * + * if not self.is_bam and self.header.nreferences == 0: # <<<<<<<<<<<<<< + * raise NotImplementedError( + * "can not iterate over samfile without header") +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1850, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1850, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_7 = (!__pyx_t_2); + if (__pyx_t_7) { + } else { + __pyx_t_3 = __pyx_t_7; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1850, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = (__Pyx_PyLong_BoolEqObjC(__pyx_t_1, __pyx_mstate_global->__pyx_int_0, 0, 0)); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 1850, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = __pyx_t_7; + __pyx_L5_bool_binop_done:; + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1851 + * + * if not self.is_bam and self.header.nreferences == 0: + * raise NotImplementedError( # <<<<<<<<<<<<<< + * "can not iterate over samfile without header") + * return self +*/ + __pyx_t_5 = NULL; + __Pyx_INCREF(__pyx_builtin_NotImplementedError); + __pyx_t_4 = __pyx_builtin_NotImplementedError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, __pyx_mstate_global->__pyx_kp_u_can_not_iterate_over_samfile_wit}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1851, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1851, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1850 + * raise ValueError("I/O operation on closed file") + * + * if not self.is_bam and self.header.nreferences == 0: # <<<<<<<<<<<<<< + * raise NotImplementedError( + * "can not iterate over samfile without header") +*/ + } + + /* "pysam/libcalignmentfile.pyx":1853 + * raise NotImplementedError( + * "can not iterate over samfile without header") + * return self # <<<<<<<<<<<<<< + * + * cdef bam1_t * getCurrent(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 23, 0, __PYX_ERR(0, 1853, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1846 + * ## and multiple_iterators) + * ## Possible solutions: deprecate or open new file handle + * def __iter__(self): # <<<<<<<<<<<<<< + * if not self.is_open: + * raise ValueError("I/O operation on closed file") +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1846, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1855 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + bam1_t *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[57])) + __Pyx_TraceStartFunc("getCurrent", __pyx_f[0], 1855, 0, 0, 0, __PYX_ERR(0, 1855, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1856 + * + * cdef bam1_t * getCurrent(self): + * return self.b # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __pyx_r = __pyx_v_self->b; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 1856, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1855 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1855, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.getCurrent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1858 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * ''' + * cversion of iterator. Used by :class:`pysam.AlignmentFile.IteratorColumn`. +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_ret; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + bam_hdr_t *__pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[58])) + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 1858, 0, 0, 0, __PYX_ERR(0, 1858, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1863 + * ''' + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_read1(self.htsfile, +*/ + __pyx_t_1 = __pyx_v_self->header->ptr; + __pyx_v_hdr = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":1864 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":1865 + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: + * ret = sam_read1(self.htsfile, # <<<<<<<<<<<<<< + * hdr, + * self.b) +*/ + __pyx_v_ret = sam_read1(__pyx_v_self->__pyx_base.htsfile, __pyx_v_hdr, __pyx_v_self->b); + } + + /* "pysam/libcalignmentfile.pyx":1864 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":1868 + * hdr, + * self.b) + * return ret # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 14, 0, __PYX_ERR(0, 1868, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1858 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * ''' + * cversion of iterator. Used by :class:`pysam.AlignmentFile.IteratorColumn`. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1858, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1870 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_38__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_38__next__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + int __pyx_v_ret; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[59])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 1870, 0, 0, 0, __PYX_ERR(0, 1870, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1871 + * + * def __next__(self): + * cdef int ret = self.cnext() # <<<<<<<<<<<<<< + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self->__pyx_base.__pyx_vtab)->cnext(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1871, __pyx_L1_error) + __pyx_v_ret = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":1872 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + __pyx_t_2 = (__pyx_v_ret >= 0); + if (likely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":1873 + * cdef int ret = self.cnext() + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) # <<<<<<<<<<<<<< + * elif ret == -1: + * raise StopIteration +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1873, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 9, 0, __PYX_ERR(0, 1873, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1872 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1874 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + __pyx_t_2 = (__pyx_v_ret == -1L); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":1875 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: + * raise StopIteration # <<<<<<<<<<<<<< + * else: + * raise IOError(read_failure_reason(ret)) +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":1874 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1877 + * raise StopIteration + * else: + * raise IOError(read_failure_reason(ret)) # <<<<<<<<<<<<<< + * + * ########################################### +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_5 = __pyx_builtin_IOError; + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_read_failure_reason); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 1877, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_ret); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 1877, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_10 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 1877, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_10 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 1877, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 1877, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1870 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1870, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1881 + * ########################################### + * # methods/properties referencing the header + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid, "AlignmentFile.is_valid_tid(self, int tid)\n\nreturn True if the numerical :term:`tid` is valid; False otherwise.\n\nNote that the unmapped tid code (-1) counts as an invalid."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid = {"is_valid_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + int __pyx_v_tid; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("is_valid_tid (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_tid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1881, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1881, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "is_valid_tid", 0) < 0) __PYX_ERR(0, 1881, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("is_valid_tid", 1, 1, 1, i); __PYX_ERR(0, 1881, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1881, __pyx_L3_error) + } + __pyx_v_tid = __Pyx_PyLong_As_int(values[0]); if (unlikely((__pyx_v_tid == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1881, __pyx_L3_error) + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("is_valid_tid", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1881, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.is_valid_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_tid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, int __pyx_v_tid) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[60])) + __Pyx_RefNannySetupContext("is_valid_tid", 0); + __Pyx_TraceStartFunc("is_valid_tid", __pyx_f[0], 1881, 0, 0, 0, __PYX_ERR(0, 1881, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1887 + * Note that the unmapped tid code (-1) counts as an invalid. + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.is_valid_tid(tid) +*/ + __pyx_t_1 = (((PyObject *)__pyx_v_self->header) == Py_None); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1888 + * """ + * if self.header is None: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * return self.header.is_valid_tid(tid) + * +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1888, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1888, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1887 + * Note that the unmapped tid code (-1) counts as an invalid. + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.is_valid_tid(tid) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1889 + * if self.header is None: + * raise ValueError("header not available in closed files") + * return self.header.is_valid_tid(tid) # <<<<<<<<<<<<<< + * + * def get_tid(self, reference): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_tid); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 1889, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_is_valid_tid, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1889, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 10, 0, __PYX_ERR(0, 1889, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1881 + * ########################################### + * # methods/properties referencing the header + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1881, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.is_valid_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1891 + * return self.header.is_valid_tid(tid) + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid, "AlignmentFile.get_tid(self, reference)\n\nreturn the numerical :term:`tid` corresponding to\n:term:`reference`\n\nreturns -1 if reference is not known."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid = {"get_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_tid (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1891, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1891, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_tid", 0) < 0) __PYX_ERR(0, 1891, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_tid", 1, 1, 1, i); __PYX_ERR(0, 1891, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1891, __pyx_L3_error) + } + __pyx_v_reference = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_tid", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1891, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_reference); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[61])) + __Pyx_RefNannySetupContext("get_tid", 0); + __Pyx_TraceStartFunc("get_tid", __pyx_f[0], 1891, 0, 0, 0, __PYX_ERR(0, 1891, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1898 + * returns -1 if reference is not known. + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_tid(reference) +*/ + __pyx_t_1 = (((PyObject *)__pyx_v_self->header) == Py_None); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1899 + * """ + * if self.header is None: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * return self.header.get_tid(reference) + * +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1899, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1899, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1898 + * returns -1 if reference is not known. + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_tid(reference) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1900 + * if self.header is None: + * raise ValueError("header not available in closed files") + * return self.header.get_tid(reference) # <<<<<<<<<<<<<< + * + * def get_reference_name(self, tid): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_v_reference}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_tid, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1900, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 10, 0, __PYX_ERR(0, 1900, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1891 + * return self.header.is_valid_tid(tid) + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1891, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_tid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1902 + * return self.header.get_tid(reference) + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` name corresponding to numerical :term:`tid` +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name, "AlignmentFile.get_reference_name(self, tid)\n\nreturn :term:`reference` name corresponding to numerical :term:`tid`"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name = {"get_reference_name", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_tid = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_reference_name (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_tid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1902, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1902, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_reference_name", 0) < 0) __PYX_ERR(0, 1902, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_reference_name", 1, 1, 1, i); __PYX_ERR(0, 1902, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1902, __pyx_L3_error) + } + __pyx_v_tid = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_reference_name", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1902, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_reference_name", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_tid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_tid) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[62])) + __Pyx_RefNannySetupContext("get_reference_name", 0); + __Pyx_TraceStartFunc("get_reference_name", __pyx_f[0], 1902, 0, 0, 0, __PYX_ERR(0, 1902, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1906 + * return :term:`reference` name corresponding to numerical :term:`tid` + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_reference_name(tid) +*/ + __pyx_t_1 = (((PyObject *)__pyx_v_self->header) == Py_None); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1907 + * """ + * if self.header is None: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * return self.header.get_reference_name(tid) + * +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1907, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1907, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1906 + * return :term:`reference` name corresponding to numerical :term:`tid` + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_reference_name(tid) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1908 + * if self.header is None: + * raise ValueError("header not available in closed files") + * return self.header.get_reference_name(tid) # <<<<<<<<<<<<<< + * + * def get_reference_length(self, reference): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_v_tid}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_reference_name, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1908, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 10, 0, __PYX_ERR(0, 1908, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1902 + * return self.header.get_tid(reference) + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` name corresponding to numerical :term:`tid` +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1902, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_reference_name", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1910 + * return self.header.get_reference_name(tid) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` length corresponding to numerical :term:`tid` +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length, "AlignmentFile.get_reference_length(self, reference)\n\nreturn :term:`reference` length corresponding to numerical :term:`tid`"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length = {"get_reference_length", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("get_reference_length (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1910, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1910, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "get_reference_length", 0) < 0) __PYX_ERR(0, 1910, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("get_reference_length", 1, 1, 1, i); __PYX_ERR(0, 1910, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1910, __pyx_L3_error) + } + __pyx_v_reference = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("get_reference_length", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1910, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_reference_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_reference); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[63])) + __Pyx_RefNannySetupContext("get_reference_length", 0); + __Pyx_TraceStartFunc("get_reference_length", __pyx_f[0], 1910, 0, 0, 0, __PYX_ERR(0, 1910, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1914 + * return :term:`reference` length corresponding to numerical :term:`tid` + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_reference_length(reference) +*/ + __pyx_t_1 = (((PyObject *)__pyx_v_self->header) == Py_None); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1915 + * """ + * if self.header is None: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * return self.header.get_reference_length(reference) + * +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1915, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1915, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1914 + * return :term:`reference` length corresponding to numerical :term:`tid` + * """ + * if self.header is None: # <<<<<<<<<<<<<< + * raise ValueError("header not available in closed files") + * return self.header.get_reference_length(reference) +*/ + } + + /* "pysam/libcalignmentfile.pyx":1916 + * if self.header is None: + * raise ValueError("header not available in closed files") + * return self.header.get_reference_length(reference) # <<<<<<<<<<<<<< + * + * property nreferences: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_v_reference}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_reference_length, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1916, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 10, 0, __PYX_ERR(0, 1916, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1910 + * return self.header.get_reference_name(tid) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` length corresponding to numerical :term:`tid` +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1910, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.get_reference_length", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1921 + * """int with the number of :term:`reference` sequences in the file. + * This is a read-only attribute.""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.nreferences +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[64])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1921, 0, 0, 0, __PYX_ERR(0, 1921, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1922 + * This is a read-only attribute.""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.nreferences + * else: +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->header)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1922, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1923 + * def __get__(self): + * if self.header: + * return self.header.nreferences # <<<<<<<<<<<<<< + * else: + * raise ValueError("header not available in closed files") +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1923, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 4, 0, __PYX_ERR(0, 1923, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1922 + * This is a read-only attribute.""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.nreferences + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1925 + * return self.header.nreferences + * else: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * + * property references: +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1925, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1925, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1921 + * """int with the number of :term:`reference` sequences in the file. + * This is a read-only attribute.""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.nreferences +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1921, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.nreferences.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1930 + * """tuple with the names of :term:`reference` sequences. This is a + * read-only attribute""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.references +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_10references_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_10references_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10references___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_10references___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[65])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1930, 0, 0, 0, __PYX_ERR(0, 1930, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1931 + * read-only attribute""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.references + * else: +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->header)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1931, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1932 + * def __get__(self): + * if self.header: + * return self.header.references # <<<<<<<<<<<<<< + * else: + * raise ValueError("header not available in closed files") +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_references); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1932, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 4, 0, __PYX_ERR(0, 1932, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1931 + * read-only attribute""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.references + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1934 + * return self.header.references + * else: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * + * property lengths: +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1934, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1934, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1930 + * """tuple with the names of :term:`reference` sequences. This is a + * read-only attribute""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.references +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1930, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.references.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1942 + * + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.lengths +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7lengths_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7lengths_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_7lengths___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_7lengths___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[66])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1942, 0, 0, 0, __PYX_ERR(0, 1942, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1943 + * """ + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.lengths + * else: +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->header)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1943, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1944 + * def __get__(self): + * if self.header: + * return self.header.lengths # <<<<<<<<<<<<<< + * else: + * raise ValueError("header not available in closed files") +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->header), __pyx_mstate_global->__pyx_n_u_lengths); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1944, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 4, 0, __PYX_ERR(0, 1944, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1943 + * """ + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.lengths + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1946 + * return self.header.lengths + * else: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * + * # Compatibility functions for pysam < 0.14 +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_4 = __pyx_builtin_ValueError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1946, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1946, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1942 + * + * """ + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.lengths +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1942, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.lengths.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1951 + * property text: + * """deprecated, use :attr:`references` and :attr:`lengths` instead""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.__str__() +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_4text_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_4text_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4text___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_4text___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[67])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 1951, 0, 0, 0, __PYX_ERR(0, 1951, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1952 + * """deprecated, use :attr:`references` and :attr:`lengths` instead""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.__str__() + * else: +*/ + __pyx_t_1 = __Pyx_PyObject_IsTrue(((PyObject *)__pyx_v_self->header)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 1952, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":1953 + * def __get__(self): + * if self.header: + * return self.header.__str__() # <<<<<<<<<<<<<< + * else: + * raise ValueError("header not available in closed files") +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_self->header); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_str, __pyx_callargs+__pyx_t_4, (1-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1953, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 4, 0, __PYX_ERR(0, 1953, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1952 + * """deprecated, use :attr:`references` and :attr:`lengths` instead""" + * def __get__(self): + * if self.header: # <<<<<<<<<<<<<< + * return self.header.__str__() + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":1955 + * return self.header.__str__() + * else: + * raise ValueError("header not available in closed files") # <<<<<<<<<<<<<< + * + * # Compatibility functions for pysam < 0.8.3 +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_4 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_header_not_available_in_closed_f}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (__pyx_t_4*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1955, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 1955, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":1951 + * property text: + * """deprecated, use :attr:`references` and :attr:`lengths` instead""" + * def __get__(self): # <<<<<<<<<<<<<< + * if self.header: + * return self.header.__str__() +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1951, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.text.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1958 + * + * # Compatibility functions for pysam < 0.8.3 + * def gettid(self, reference): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_tid` instead""" + * return self.get_tid(reference) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_49gettid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_48gettid, "AlignmentFile.gettid(self, reference)\n\ndeprecated, use :meth:`get_tid` instead"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_49gettid = {"gettid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_49gettid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_48gettid}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_49gettid(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_reference = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("gettid (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_reference,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1958, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1958, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "gettid", 0) < 0) __PYX_ERR(0, 1958, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("gettid", 1, 1, 1, i); __PYX_ERR(0, 1958, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1958, __pyx_L3_error) + } + __pyx_v_reference = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("gettid", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1958, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.gettid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_48gettid(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_reference); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_48gettid(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_reference) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[68])) + __Pyx_RefNannySetupContext("gettid", 0); + __Pyx_TraceStartFunc("gettid", __pyx_f[0], 1958, 0, 0, 0, __PYX_ERR(0, 1958, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1960 + * def gettid(self, reference): + * """deprecated, use :meth:`get_tid` instead""" + * return self.get_tid(reference) # <<<<<<<<<<<<<< + * + * def getrname(self, tid): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_reference}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_tid, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1960, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 1960, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1958 + * + * # Compatibility functions for pysam < 0.8.3 + * def gettid(self, reference): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_tid` instead""" + * return self.get_tid(reference) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1958, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.gettid", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1962 + * return self.get_tid(reference) + * + * def getrname(self, tid): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_reference_name` instead""" + * return self.get_reference_name(tid) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_51getrname(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_50getrname, "AlignmentFile.getrname(self, tid)\n\ndeprecated, use :meth:`get_reference_name` instead"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_51getrname = {"getrname", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_51getrname, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_50getrname}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_51getrname(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_tid = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("getrname (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_tid,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1962, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1962, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "getrname", 0) < 0) __PYX_ERR(0, 1962, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("getrname", 1, 1, 1, i); __PYX_ERR(0, 1962, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1962, __pyx_L3_error) + } + __pyx_v_tid = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("getrname", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 1962, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.getrname", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_50getrname(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v_tid); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_50getrname(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, PyObject *__pyx_v_tid) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[69])) + __Pyx_RefNannySetupContext("getrname", 0); + __Pyx_TraceStartFunc("getrname", __pyx_f[0], 1962, 0, 0, 0, __PYX_ERR(0, 1962, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1964 + * def getrname(self, tid): + * """deprecated, use :meth:`get_reference_name` instead""" + * return self.get_reference_name(tid) # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_v_tid}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_get_reference_name, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1964, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 1964, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":1962 + * return self.get_tid(reference) + * + * def getrname(self, tid): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_reference_name` instead""" + * return self.get_reference_name(tid) +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1962, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.getrname", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pxd":46 + * + * cdef class AlignmentFile(HTSFile): + * cdef readonly object reference_filename # <<<<<<<<<<<<<< + * cdef readonly AlignmentHeader header + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[70])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[4], 46, 0, 0, 0, __PYX_ERR(4, 46, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->reference_filename); + __pyx_r = __pyx_v_self->reference_filename; + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(4, 46, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(4, 46, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.reference_filename.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pxd":47 + * cdef class AlignmentFile(HTSFile): + * cdef readonly object reference_filename + * cdef readonly AlignmentHeader header # <<<<<<<<<<<<<< + * + * # pointer to index +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6header_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6header_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6header___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_6header___get__(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[71])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[4], 47, 0, 0, 0, __PYX_ERR(4, 47, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->header); + __pyx_r = ((PyObject *)__pyx_v_self->header); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(4, 47, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(4, 47, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.header.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__, "AlignmentFile.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[72])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__, "AlignmentFile.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[73])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.AlignmentFile.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":1992 + * ''' + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=False): # <<<<<<<<<<<<<< + * cdef char *cfilename + * cdef char *creference_filename +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 1992, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1992, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1992, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 1992, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 1992, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 1992, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 1992, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + if (values[1]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 1992, __pyx_L3_error) + } else { + __pyx_v_multiple_iterators = ((int)0); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 1992, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRow.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 1992, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)__pyx_v_self), __pyx_v_samfile, __pyx_v_multiple_iterators); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators) { + char *__pyx_v_cfilename; + char *__pyx_v_creference_filename; + char *__pyx_v_cindexname; + CYTHON_UNUSED PyObject *__pyx_v_bindex_filename = NULL; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + char *__pyx_t_7; + htsFile *__pyx_t_8; + hts_idx_t *__pyx_t_9; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[74])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 1992, 0, 0, 0, __PYX_ERR(0, 1992, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":1995 + * cdef char *cfilename + * cdef char *creference_filename + * cdef char *cindexname = NULL # <<<<<<<<<<<<<< + * + * if not samfile.is_open: +*/ + __pyx_v_cindexname = NULL; + + /* "pysam/libcalignmentfile.pyx":1997 + * cdef char *cindexname = NULL + * + * if not samfile.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_n_u_is_open); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1997, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 1997, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":1998 + * + * if not samfile.is_open: + * raise ValueError("I/O operation on closed file") # <<<<<<<<<<<<<< + * + * # makes sure that samfile stays alive as long as the +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_I_O_operation_on_closed_file}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1998, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 1998, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":1997 + * cdef char *cindexname = NULL + * + * if not samfile.is_open: # <<<<<<<<<<<<<< + * raise ValueError("I/O operation on closed file") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2002 + * # makes sure that samfile stays alive as long as the + * # iterator is alive + * self.samfile = samfile # <<<<<<<<<<<<<< + * + * # reopen the file - note that this makes the iterator +*/ + __Pyx_INCREF((PyObject *)__pyx_v_samfile); + __Pyx_GIVEREF((PyObject *)__pyx_v_samfile); + __Pyx_GOTREF((PyObject *)__pyx_v_self->samfile); + __Pyx_DECREF((PyObject *)__pyx_v_self->samfile); + __pyx_v_self->samfile = __pyx_v_samfile; + + /* "pysam/libcalignmentfile.pyx":2006 + * # reopen the file - note that this makes the iterator + * # slow and causes pileup to slow down significantly. + * if multiple_iterators: # <<<<<<<<<<<<<< + * + * cfilename = samfile.filename +*/ + __pyx_t_3 = (__pyx_v_multiple_iterators != 0); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2008 + * if multiple_iterators: + * + * cfilename = samfile.filename # <<<<<<<<<<<<<< + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') +*/ + __pyx_t_7 = __Pyx_PyObject_AsWritableString(__pyx_v_samfile->__pyx_base.filename); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(0, 2008, __pyx_L1_error) + __pyx_v_cfilename = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":2009 + * + * cfilename = samfile.filename + * with nogil: # <<<<<<<<<<<<<< + * self.htsfile = hts_open(cfilename, 'r') + * assert self.htsfile != NULL +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2010 + * cfilename = samfile.filename + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') # <<<<<<<<<<<<<< + * assert self.htsfile != NULL + * +*/ + __pyx_v_self->htsfile = hts_open(__pyx_v_cfilename, ((char const *)"r")); + } + + /* "pysam/libcalignmentfile.pyx":2009 + * + * cfilename = samfile.filename + * with nogil: # <<<<<<<<<<<<<< + * self.htsfile = hts_open(cfilename, 'r') + * assert self.htsfile != NULL +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L7; + } + __pyx_L7:; + } + } + + /* "pysam/libcalignmentfile.pyx":2011 + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') + * assert self.htsfile != NULL # <<<<<<<<<<<<<< + * + * if samfile.has_index(): +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_3 = (__pyx_v_self->htsfile != NULL); + if (unlikely(!__pyx_t_3)) { + __Pyx_Raise(__pyx_builtin_AssertionError, 0, 0, 0); + __PYX_ERR(0, 2011, __pyx_L1_error) + } + } + #else + if ((1)); else __PYX_ERR(0, 2011, __pyx_L1_error) + #endif + + /* "pysam/libcalignmentfile.pyx":2013 + * assert self.htsfile != NULL + * + * if samfile.has_index(): # <<<<<<<<<<<<<< + * if samfile.index_filename: + * cindexname = bindex_filename = encode_filename(samfile.index_filename) +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_samfile); + __Pyx_INCREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_5, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2013, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 2013, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2014 + * + * if samfile.has_index(): + * if samfile.index_filename: # <<<<<<<<<<<<<< + * cindexname = bindex_filename = encode_filename(samfile.index_filename) + * with nogil: +*/ + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_v_samfile->__pyx_base.index_filename); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 2014, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2015 + * if samfile.has_index(): + * if samfile.index_filename: + * cindexname = bindex_filename = encode_filename(samfile.index_filename) # <<<<<<<<<<<<<< + * with nogil: + * self.index = sam_index_load2(self.htsfile, cfilename, cindexname) +*/ + __pyx_t_1 = __pyx_v_samfile->__pyx_base.index_filename; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_5 = __pyx_f_5pysam_9libcutils_encode_filename(__pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2015, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(__pyx_t_5 == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(0, 2015, __pyx_L1_error) + } + __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_t_5); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(0, 2015, __pyx_L1_error) + __pyx_v_cindexname = __pyx_t_7; + __Pyx_INCREF(__pyx_t_5); + __pyx_v_bindex_filename = ((PyObject*)__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":2014 + * + * if samfile.has_index(): + * if samfile.index_filename: # <<<<<<<<<<<<<< + * cindexname = bindex_filename = encode_filename(samfile.index_filename) + * with nogil: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2016 + * if samfile.index_filename: + * cindexname = bindex_filename = encode_filename(samfile.index_filename) + * with nogil: # <<<<<<<<<<<<<< + * self.index = sam_index_load2(self.htsfile, cfilename, cindexname) + * else: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2017 + * cindexname = bindex_filename = encode_filename(samfile.index_filename) + * with nogil: + * self.index = sam_index_load2(self.htsfile, cfilename, cindexname) # <<<<<<<<<<<<<< + * else: + * self.index = NULL +*/ + __pyx_v_self->index = sam_index_load2(__pyx_v_self->htsfile, __pyx_v_cfilename, __pyx_v_cindexname); + } + + /* "pysam/libcalignmentfile.pyx":2016 + * if samfile.index_filename: + * cindexname = bindex_filename = encode_filename(samfile.index_filename) + * with nogil: # <<<<<<<<<<<<<< + * self.index = sam_index_load2(self.htsfile, cfilename, cindexname) + * else: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L12; + } + __pyx_L12:; + } + } + + /* "pysam/libcalignmentfile.pyx":2013 + * assert self.htsfile != NULL + * + * if samfile.has_index(): # <<<<<<<<<<<<<< + * if samfile.index_filename: + * cindexname = bindex_filename = encode_filename(samfile.index_filename) +*/ + goto __pyx_L8; + } + + /* "pysam/libcalignmentfile.pyx":2019 + * self.index = sam_index_load2(self.htsfile, cfilename, cindexname) + * else: + * self.index = NULL # <<<<<<<<<<<<<< + * + * # need to advance in newly opened file to position after header +*/ + /*else*/ { + __pyx_v_self->index = NULL; + } + __pyx_L8:; + + /* "pysam/libcalignmentfile.pyx":2023 + * # need to advance in newly opened file to position after header + * # better: use seek/tell? + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr is NULL: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2024 + * # better: use seek/tell? + * with nogil: + * hdr = sam_hdr_read(self.htsfile) # <<<<<<<<<<<<<< + * if hdr is NULL: + * raise IOError("unable to read header information") +*/ + __pyx_v_hdr = sam_hdr_read(__pyx_v_self->htsfile); + } + + /* "pysam/libcalignmentfile.pyx":2023 + * # need to advance in newly opened file to position after header + * # better: use seek/tell? + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr is NULL: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L15; + } + __pyx_L15:; + } + } + + /* "pysam/libcalignmentfile.pyx":2025 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr is NULL: # <<<<<<<<<<<<<< + * raise IOError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) +*/ + __pyx_t_3 = (__pyx_v_hdr == NULL); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2026 + * hdr = sam_hdr_read(self.htsfile) + * if hdr is NULL: + * raise IOError("unable to read header information") # <<<<<<<<<<<<<< + * self.header = makeAlignmentHeader(hdr) + * +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_4 = __pyx_builtin_IOError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_mstate_global->__pyx_kp_u_unable_to_read_header_informatio}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2026, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 2026, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2025 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr is NULL: # <<<<<<<<<<<<<< + * raise IOError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2027 + * if hdr is NULL: + * raise IOError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) # <<<<<<<<<<<<<< + * + * self.owns_samfile = True +*/ + __pyx_t_5 = ((PyObject *)__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(__pyx_v_hdr)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2027, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_5); + __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":2029 + * self.header = makeAlignmentHeader(hdr) + * + * self.owns_samfile = True # <<<<<<<<<<<<<< + * + * # options specific to CRAM files +*/ + __pyx_v_self->owns_samfile = 1; + + /* "pysam/libcalignmentfile.pyx":2032 + * + * # options specific to CRAM files + * if samfile.is_cram and samfile.reference_filename: # <<<<<<<<<<<<<< + * creference_filename = samfile.reference_filename + * hts_set_opt(self.htsfile, +*/ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2032, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2032, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L18_bool_binop_done; + } + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_samfile->reference_filename); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2032, __pyx_L1_error) + __pyx_t_3 = __pyx_t_2; + __pyx_L18_bool_binop_done:; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2033 + * # options specific to CRAM files + * if samfile.is_cram and samfile.reference_filename: + * creference_filename = samfile.reference_filename # <<<<<<<<<<<<<< + * hts_set_opt(self.htsfile, + * CRAM_OPT_REFERENCE, +*/ + __pyx_t_7 = __Pyx_PyObject_AsWritableString(__pyx_v_samfile->reference_filename); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(0, 2033, __pyx_L1_error) + __pyx_v_creference_filename = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":2034 + * if samfile.is_cram and samfile.reference_filename: + * creference_filename = samfile.reference_filename + * hts_set_opt(self.htsfile, # <<<<<<<<<<<<<< + * CRAM_OPT_REFERENCE, + * creference_filename) +*/ + (void)(hts_set_opt(__pyx_v_self->htsfile, CRAM_OPT_REFERENCE, __pyx_v_creference_filename)); + + /* "pysam/libcalignmentfile.pyx":2032 + * + * # options specific to CRAM files + * if samfile.is_cram and samfile.reference_filename: # <<<<<<<<<<<<<< + * creference_filename = samfile.reference_filename + * hts_set_opt(self.htsfile, +*/ + } + + /* "pysam/libcalignmentfile.pyx":2006 + * # reopen the file - note that this makes the iterator + * # slow and causes pileup to slow down significantly. + * if multiple_iterators: # <<<<<<<<<<<<<< + * + * cfilename = samfile.filename +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2039 + * + * else: + * self.htsfile = samfile.htsfile # <<<<<<<<<<<<<< + * self.index = samfile.index + * self.owns_samfile = False +*/ + /*else*/ { + __pyx_t_8 = __pyx_v_samfile->__pyx_base.htsfile; + __pyx_v_self->htsfile = __pyx_t_8; + + /* "pysam/libcalignmentfile.pyx":2040 + * else: + * self.htsfile = samfile.htsfile + * self.index = samfile.index # <<<<<<<<<<<<<< + * self.owns_samfile = False + * self.header = samfile.header +*/ + __pyx_t_9 = __pyx_v_samfile->index; + __pyx_v_self->index = __pyx_t_9; + + /* "pysam/libcalignmentfile.pyx":2041 + * self.htsfile = samfile.htsfile + * self.index = samfile.index + * self.owns_samfile = False # <<<<<<<<<<<<<< + * self.header = samfile.header + * +*/ + __pyx_v_self->owns_samfile = 0; + + /* "pysam/libcalignmentfile.pyx":2042 + * self.index = samfile.index + * self.owns_samfile = False + * self.header = samfile.header # <<<<<<<<<<<<<< + * + * self.retval = 0 +*/ + __pyx_t_5 = ((PyObject *)__pyx_v_samfile->header); + __Pyx_INCREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_5); + __pyx_t_5 = 0; + } + __pyx_L4:; + + /* "pysam/libcalignmentfile.pyx":2044 + * self.header = samfile.header + * + * self.retval = 0 # <<<<<<<<<<<<<< + * + * self.b = bam_init1() +*/ + __pyx_v_self->retval = 0; + + /* "pysam/libcalignmentfile.pyx":2046 + * self.retval = 0 + * + * self.b = bam_init1() # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + __pyx_v_self->b = bam_init1(); + + /* "pysam/libcalignmentfile.pyx":1992 + * ''' + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=False): # <<<<<<<<<<<<<< + * cdef char *cfilename + * cdef char *creference_filename +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 1992, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 1992, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRow.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_bindex_filename); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2048 + * self.b = bam_init1() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * bam_destroy1(self.b) + * if self.owns_samfile: +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_3__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_2__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_2__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self) { + __Pyx_TraceDeclarationsFunc + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[75])) + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 2048, 0, 0, 0, __PYX_ERR(0, 2048, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2049 + * + * def __dealloc__(self): + * bam_destroy1(self.b) # <<<<<<<<<<<<<< + * if self.owns_samfile: + * hts_idx_destroy(self.index) +*/ + bam_destroy1(__pyx_v_self->b); + + /* "pysam/libcalignmentfile.pyx":2050 + * def __dealloc__(self): + * bam_destroy1(self.b) + * if self.owns_samfile: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * hts_close(self.htsfile) +*/ + __pyx_t_1 = (__pyx_v_self->owns_samfile != 0); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2051 + * bam_destroy1(self.b) + * if self.owns_samfile: + * hts_idx_destroy(self.index) # <<<<<<<<<<<<<< + * hts_close(self.htsfile) + * +*/ + hts_idx_destroy(__pyx_v_self->index); + + /* "pysam/libcalignmentfile.pyx":2052 + * if self.owns_samfile: + * hts_idx_destroy(self.index) + * hts_close(self.htsfile) # <<<<<<<<<<<<<< + * + * +*/ + (void)(hts_close(__pyx_v_self->htsfile)); + + /* "pysam/libcalignmentfile.pyx":2050 + * def __dealloc__(self): + * bam_destroy1(self.b) + * if self.owns_samfile: # <<<<<<<<<<<<<< + * hts_idx_destroy(self.index) + * hts_close(self.htsfile) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2048 + * self.b = bam_init1() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * bam_destroy1(self.b) + * if self.owns_samfile: +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 2048, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2048, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.IteratorRow.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__, "IteratorRow.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[76])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRow.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__, "IteratorRow.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRow.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[77])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRow.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2069 + * """ + * + * def __init__(self, AlignmentFile samfile, # <<<<<<<<<<<<<< + * int tid, int beg, int stop, + * int multiple_iterators=False): +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_tid; + int __pyx_v_beg; + int __pyx_v_stop; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[5] = {0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_tid,&__pyx_mstate_global->__pyx_n_u_beg,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2069, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2069, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 4; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 4, 5, i); __PYX_ERR(0, 2069, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 2069, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 2069, __pyx_L3_error) + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2069, __pyx_L3_error) + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2069, __pyx_L3_error) + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2069, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + __pyx_v_tid = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_tid == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2070, __pyx_L3_error) + __pyx_v_beg = __Pyx_PyLong_As_int(values[2]); if (unlikely((__pyx_v_beg == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2070, __pyx_L3_error) + __pyx_v_stop = __Pyx_PyLong_As_int(values[3]); if (unlikely((__pyx_v_stop == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2070, __pyx_L3_error) + if (values[4]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[4]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2071, __pyx_L3_error) + } else { + + /* "pysam/libcalignmentfile.pyx":2071 + * def __init__(self, AlignmentFile samfile, + * int tid, int beg, int stop, + * int multiple_iterators=False): # <<<<<<<<<<<<<< + * + * if not samfile.has_index(): +*/ + __pyx_v_multiple_iterators = ((int)0); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 4, 5, __pyx_nargs); __PYX_ERR(0, 2069, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2069, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self), __pyx_v_samfile, __pyx_v_tid, __pyx_v_beg, __pyx_v_stop, __pyx_v_multiple_iterators); + + /* "pysam/libcalignmentfile.pyx":2069 + * """ + * + * def __init__(self, AlignmentFile samfile, # <<<<<<<<<<<<<< + * int tid, int beg, int stop, + * int multiple_iterators=False): +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_tid, int __pyx_v_beg, int __pyx_v_stop, int __pyx_v_multiple_iterators) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[78])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2069, 0, 0, 0, __PYX_ERR(0, 2069, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2073 + * int multiple_iterators=False): + * + * if not samfile.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for iteration") + * +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_samfile); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2073, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_4 < 0))) __PYX_ERR(0, 2073, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_5 = (!__pyx_t_4); + if (unlikely(__pyx_t_5)) { + + /* "pysam/libcalignmentfile.pyx":2074 + * + * if not samfile.has_index(): + * raise ValueError("no index available for iteration") # <<<<<<<<<<<<<< + * + * super().__init__(samfile, multiple_iterators=multiple_iterators) +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_6 = __pyx_builtin_ValueError; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_no_index_available_for_iteration}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2074, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 2074, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2073 + * int multiple_iterators=False): + * + * if not samfile.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for iteration") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2076 + * raise ValueError("no index available for iteration") + * + * super().__init__(samfile, multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * with nogil: + * self.iter = sam_itr_queryi( +*/ + __pyx_t_7 = NULL; + __Pyx_INCREF(__pyx_builtin_super); + __pyx_t_8 = __pyx_builtin_super; + __pyx_t_3 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_7, ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion), ((PyObject *)__pyx_v_self)}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_3, (3-__pyx_t_3) | (__pyx_t_3*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2076, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __pyx_t_6 = __pyx_t_2; + __Pyx_INCREF(__pyx_t_6); + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_multiple_iterators); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2076, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_6, ((PyObject *)__pyx_v_samfile)}; + __pyx_t_7 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 2076, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_t_8, __pyx_t_7, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 2076, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_init, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_7); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2076, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2077 + * + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * with nogil: # <<<<<<<<<<<<<< + * self.iter = sam_itr_queryi( + * self.index, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2078 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * with nogil: + * self.iter = sam_itr_queryi( # <<<<<<<<<<<<<< + * self.index, + * tid, +*/ + __pyx_v_self->iter = sam_itr_queryi(__pyx_v_self->__pyx_base.index, __pyx_v_tid, __pyx_v_beg, __pyx_v_stop); + } + + /* "pysam/libcalignmentfile.pyx":2077 + * + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * with nogil: # <<<<<<<<<<<<<< + * self.iter = sam_itr_queryi( + * self.index, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L6; + } + __pyx_L6:; + } + } + + /* "pysam/libcalignmentfile.pyx":2069 + * """ + * + * def __init__(self, AlignmentFile samfile, # <<<<<<<<<<<<<< + * int tid, int beg, int stop, + * int multiple_iterators=False): +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2069, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2069, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2084 + * stop) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_3__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_3__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_2__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[79])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2084, 0, 0, 0, __PYX_ERR(0, 2084, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2085 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * cdef bam1_t * getCurrent(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2085, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2084 + * stop) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2084, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2087 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + bam1_t *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[80])) + __Pyx_TraceStartFunc("getCurrent", __pyx_f[0], 2087, 0, 0, 0, __PYX_ERR(0, 2087, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2088 + * + * cdef bam1_t * getCurrent(self): + * return self.b # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __pyx_r = __pyx_v_self->__pyx_base.b; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2088, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2087 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2087, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.getCurrent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2090 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * with nogil: +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[81])) + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 2090, 0, 0, 0, __PYX_ERR(0, 2090, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2092 + * cdef int cnext(self): + * '''cversion of iterator. Used by IteratorColumn''' + * with nogil: # <<<<<<<<<<<<<< + * self.retval = hts_itr_next(hts_get_bgzfp(self.htsfile), + * self.iter, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2093 + * '''cversion of iterator. Used by IteratorColumn''' + * with nogil: + * self.retval = hts_itr_next(hts_get_bgzfp(self.htsfile), # <<<<<<<<<<<<<< + * self.iter, + * self.b, +*/ + __pyx_v_self->__pyx_base.retval = hts_itr_next(hts_get_bgzfp(__pyx_v_self->__pyx_base.htsfile), __pyx_v_self->iter, __pyx_v_self->__pyx_base.b, __pyx_v_self->__pyx_base.htsfile); + } + + /* "pysam/libcalignmentfile.pyx":2092 + * cdef int cnext(self): + * '''cversion of iterator. Used by IteratorColumn''' + * with nogil: # <<<<<<<<<<<<<< + * self.retval = hts_itr_next(hts_get_bgzfp(self.htsfile), + * self.iter, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":2090 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * with nogil: +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 0, 0, __PYX_ERR(0, 2090, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2090, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2098 + * self.htsfile) + * + * def __next__(self): # <<<<<<<<<<<<<< + * self.cnext() + * if self.retval >= 0: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_4__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[82])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2098, 0, 0, 0, __PYX_ERR(0, 2098, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2099 + * + * def __next__(self): + * self.cnext() # <<<<<<<<<<<<<< + * if self.retval >= 0: + * return makeAlignedSegment(self.b, self.header) +*/ + ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self->__pyx_vtab)->cnext(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2099, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2100 + * def __next__(self): + * self.cnext() + * if self.retval >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif self.retval == -1: +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.retval >= 0); + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2101 + * self.cnext() + * if self.retval >= 0: + * return makeAlignedSegment(self.b, self.header) # <<<<<<<<<<<<<< + * elif self.retval == -1: + * raise StopIteration +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->__pyx_base.b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_2))); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + __Pyx_TraceReturnValue(__pyx_r, 9, 0, __PYX_ERR(0, 2101, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2100 + * def __next__(self): + * self.cnext() + * if self.retval >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif self.retval == -1: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2102 + * if self.retval >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif self.retval == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * elif self.retval == -2: +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.retval == -1L); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2103 + * return makeAlignedSegment(self.b, self.header) + * elif self.retval == -1: + * raise StopIteration # <<<<<<<<<<<<<< + * elif self.retval == -2: + * # Note: it is currently not the case that hts_iter_next +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2102 + * if self.retval >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif self.retval == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * elif self.retval == -2: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2104 + * elif self.retval == -1: + * raise StopIteration + * elif self.retval == -2: # <<<<<<<<<<<<<< + * # Note: it is currently not the case that hts_iter_next + * # returns -2 for a truncated file. +*/ + __pyx_t_1 = (__pyx_v_self->__pyx_base.retval == -2L); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2108 + * # returns -2 for a truncated file. + * # See https://github.com/pysam-developers/pysam/pull/50#issuecomment-64928625 + * raise IOError('truncated file') # <<<<<<<<<<<<<< + * else: + * raise IOError("error while reading file {}: {}".format(self.samfile.filename, self.retval)) +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_4 = __pyx_builtin_IOError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, __pyx_mstate_global->__pyx_kp_u_truncated_file}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 2108, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2104 + * elif self.retval == -1: + * raise StopIteration + * elif self.retval == -2: # <<<<<<<<<<<<<< + * # Note: it is currently not the case that hts_iter_next + * # returns -2 for a truncated file. +*/ + } + + /* "pysam/libcalignmentfile.pyx":2110 + * raise IOError('truncated file') + * else: + * raise IOError("error while reading file {}: {}".format(self.samfile.filename, self.retval)) # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + /*else*/ { + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_2 = __pyx_builtin_IOError; + __pyx_t_7 = __pyx_mstate_global->__pyx_kp_u_error_while_reading_file_2; + __Pyx_INCREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_self->__pyx_base.retval); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_7, __pyx_v_self->__pyx_base.samfile->__pyx_base.filename, __pyx_t_8}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_5, (3-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_6}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2110, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 2110, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":2098 + * self.htsfile) + * + * def __next__(self): # <<<<<<<<<<<<<< + * self.cnext() + * if self.retval >= 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2098, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2112 + * raise IOError("error while reading file {}: {}".format(self.samfile.filename, self.retval)) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * hts_itr_destroy(self.iter) + * +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_7__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_7__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_6__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_6__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[83])) + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 2112, 0, 0, 0, __PYX_ERR(0, 2112, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2113 + * + * def __dealloc__(self): + * hts_itr_destroy(self.iter) # <<<<<<<<<<<<<< + * + * +*/ + hts_itr_destroy(__pyx_v_self->iter); + + /* "pysam/libcalignmentfile.pyx":2112 + * raise IOError("error while reading file {}: {}".format(self.samfile.filename, self.retval)) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * hts_itr_destroy(self.iter) + * +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 2112, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2112, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.IteratorRowRegion.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__, "IteratorRowRegion.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[84])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_s, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__, "IteratorRowRegion.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[85])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_s, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowRegion.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2128 + * """ + * + * def __init__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int n, +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_n; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_n,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2128, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2128, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2128, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2128, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2128, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 3, i); __PYX_ERR(0, 2128, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2128, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2128, __pyx_L3_error) + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2128, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + __pyx_v_n = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_n == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2130, __pyx_L3_error) + if (values[2]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[2]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2131, __pyx_L3_error) + } else { + + /* "pysam/libcalignmentfile.pyx":2131 + * AlignmentFile samfile, + * int n, + * int multiple_iterators=False): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + __pyx_v_multiple_iterators = ((int)0); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 3, __pyx_nargs); __PYX_ERR(0, 2128, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2129, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self), __pyx_v_samfile, __pyx_v_n, __pyx_v_multiple_iterators); + + /* "pysam/libcalignmentfile.pyx":2128 + * """ + * + * def __init__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int n, +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_n, int __pyx_v_multiple_iterators) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[86])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2128, 0, 0, 0, __PYX_ERR(0, 2128, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2132 + * int n, + * int multiple_iterators=False): + * super().__init__(samfile, multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * self.max_rows = n +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_super); + __pyx_t_5 = __pyx_builtin_super; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead), ((PyObject *)__pyx_v_self)}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_multiple_iterators); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_2, ((PyObject *)__pyx_v_samfile)}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_t_5, __pyx_t_4, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 2132, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_init, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2132, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2134 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * self.max_rows = n # <<<<<<<<<<<<<< + * self.current_row = 0 + * +*/ + __pyx_v_self->max_rows = __pyx_v_n; + + /* "pysam/libcalignmentfile.pyx":2135 + * + * self.max_rows = n + * self.current_row = 0 # <<<<<<<<<<<<<< + * + * def __iter__(self): +*/ + __pyx_v_self->current_row = 0; + + /* "pysam/libcalignmentfile.pyx":2128 + * """ + * + * def __init__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int n, +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2128, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2128, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2137 + * self.current_row = 0 + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_3__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_3__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_2__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[87])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2137, 0, 0, 0, __PYX_ERR(0, 2137, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2138 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * cdef bam1_t * getCurrent(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2138, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2137 + * self.current_row = 0 + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2137, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2140 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self) { + bam1_t *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[88])) + __Pyx_TraceStartFunc("getCurrent", __pyx_f[0], 2140, 0, 0, 0, __PYX_ERR(0, 2140, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2141 + * + * cdef bam1_t * getCurrent(self): + * return self.b # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __pyx_r = __pyx_v_self->__pyx_base.b; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2141, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2140 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2140, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.getCurrent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2143 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self) { + int __pyx_v_ret; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + bam_hdr_t *__pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[89])) + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 2143, 0, 0, 0, __PYX_ERR(0, 2143, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2146 + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_read1(self.htsfile, +*/ + __pyx_t_1 = __pyx_v_self->__pyx_base.header->ptr; + __pyx_v_hdr = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2147 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2148 + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: + * ret = sam_read1(self.htsfile, # <<<<<<<<<<<<<< + * hdr, + * self.b) +*/ + __pyx_v_ret = sam_read1(__pyx_v_self->__pyx_base.htsfile, __pyx_v_hdr, __pyx_v_self->__pyx_base.b); + } + + /* "pysam/libcalignmentfile.pyx":2147 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":2151 + * hdr, + * self.b) + * return ret # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 14, 0, __PYX_ERR(0, 2151, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2143 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2143, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2153 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * if self.current_row >= self.max_rows: + * raise StopIteration +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_4__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self) { + int __pyx_v_ret; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[90])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2153, 0, 0, 0, __PYX_ERR(0, 2153, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2154 + * + * def __next__(self): + * if self.current_row >= self.max_rows: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + __pyx_t_1 = (__pyx_v_self->current_row >= __pyx_v_self->max_rows); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2155 + * def __next__(self): + * if self.current_row >= self.max_rows: + * raise StopIteration # <<<<<<<<<<<<<< + * + * cdef int ret = self.cnext() +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2154 + * + * def __next__(self): + * if self.current_row >= self.max_rows: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2157 + * raise StopIteration + * + * cdef int ret = self.cnext() # <<<<<<<<<<<<<< + * if ret >= 0: + * self.current_row += 1 +*/ + __pyx_t_2 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self->__pyx_vtab)->cnext(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2157, __pyx_L1_error) + __pyx_v_ret = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2158 + * + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * self.current_row += 1 + * return makeAlignedSegment(self.b, self.header) +*/ + __pyx_t_1 = (__pyx_v_ret >= 0); + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2159 + * cdef int ret = self.cnext() + * if ret >= 0: + * self.current_row += 1 # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + __pyx_v_self->current_row = (__pyx_v_self->current_row + 1); + + /* "pysam/libcalignmentfile.pyx":2160 + * if ret >= 0: + * self.current_row += 1 + * return makeAlignedSegment(self.b, self.header) # <<<<<<<<<<<<<< + * elif ret == -1: + * raise StopIteration +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->__pyx_base.b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2160, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 19, 0, __PYX_ERR(0, 2160, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2158 + * + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * self.current_row += 1 + * return makeAlignedSegment(self.b, self.header) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2161 + * self.current_row += 1 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + __pyx_t_1 = (__pyx_v_ret == -1L); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2162 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: + * raise StopIteration # <<<<<<<<<<<<<< + * else: + * raise IOError(read_failure_reason(ret)) +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2161 + * self.current_row += 1 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2164 + * raise StopIteration + * else: + * raise IOError(read_failure_reason(ret)) # <<<<<<<<<<<<<< + * + * +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_5 = __pyx_builtin_IOError; + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_read_failure_reason); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_ret); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 2164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_10 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_10 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2164, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 2164, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":2153 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * if self.current_row >= self.max_rows: + * raise StopIteration +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2153, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__, "IteratorRowHead.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[91])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__, "IteratorRowHead.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[92])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowHead.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2180 + * """ + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=False): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2180, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2180, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2180, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2180, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 2180, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2180, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2180, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + if (values[1]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2180, __pyx_L3_error) + } else { + __pyx_v_multiple_iterators = ((int)0); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 2180, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2180, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self), __pyx_v_samfile, __pyx_v_multiple_iterators); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[93])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2180, 0, 0, 0, __PYX_ERR(0, 2180, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2181 + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=False): + * super().__init__(samfile, multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * def __iter__(self): +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_super); + __pyx_t_5 = __pyx_builtin_super; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll), ((PyObject *)__pyx_v_self)}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_multiple_iterators); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_2, ((PyObject *)__pyx_v_samfile)}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_t_5, __pyx_t_4, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 2181, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_init, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2181, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2180 + * """ + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=False): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2180, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2180, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2183 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_3__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_3__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_2__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[94])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2183, 0, 0, 0, __PYX_ERR(0, 2183, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2184 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * cdef bam1_t * getCurrent(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2184, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2183 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2183, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2186 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self) { + bam1_t *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[95])) + __Pyx_TraceStartFunc("getCurrent", __pyx_f[0], 2186, 0, 0, 0, __PYX_ERR(0, 2186, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2187 + * + * cdef bam1_t * getCurrent(self): + * return self.b # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __pyx_r = __pyx_v_self->__pyx_base.b; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2187, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2186 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2186, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.getCurrent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2189 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self) { + int __pyx_v_ret; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + bam_hdr_t *__pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[96])) + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 2189, 0, 0, 0, __PYX_ERR(0, 2189, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2192 + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_read1(self.htsfile, +*/ + __pyx_t_1 = __pyx_v_self->__pyx_base.header->ptr; + __pyx_v_hdr = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2193 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2194 + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: + * ret = sam_read1(self.htsfile, # <<<<<<<<<<<<<< + * hdr, + * self.b) +*/ + __pyx_v_ret = sam_read1(__pyx_v_self->__pyx_base.htsfile, __pyx_v_hdr, __pyx_v_self->__pyx_base.b); + } + + /* "pysam/libcalignmentfile.pyx":2193 + * cdef int ret + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":2197 + * hdr, + * self.b) + * return ret # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 14, 0, __PYX_ERR(0, 2197, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2189 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator. Used by IteratorColumn''' + * cdef int ret +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2189, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2199 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_4__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self) { + int __pyx_v_ret; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[97])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2199, 0, 0, 0, __PYX_ERR(0, 2199, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2200 + * + * def __next__(self): + * cdef int ret = self.cnext() # <<<<<<<<<<<<<< + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self->__pyx_vtab)->cnext(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2200, __pyx_L1_error) + __pyx_v_ret = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2201 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + __pyx_t_2 = (__pyx_v_ret >= 0); + if (likely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2202 + * cdef int ret = self.cnext() + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) # <<<<<<<<<<<<<< + * elif ret == -1: + * raise StopIteration +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->__pyx_base.b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2202, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 9, 0, __PYX_ERR(0, 2202, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2201 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2203 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + __pyx_t_2 = (__pyx_v_ret == -1L); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2204 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: + * raise StopIteration # <<<<<<<<<<<<<< + * else: + * raise IOError(read_failure_reason(ret)) +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2203 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2206 + * raise StopIteration + * else: + * raise IOError(read_failure_reason(ret)) # <<<<<<<<<<<<<< + * + * +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_5 = __pyx_builtin_IOError; + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_read_failure_reason); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_ret); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 2206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_10 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_10 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2206, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 2206, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":2199 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2199, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__, "IteratorRowAll.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[98])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__, "IteratorRowAll.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[99])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAll.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2220 + * """ + * + * def __init__(self, AlignmentFile samfile, multiple_iterators=False): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + PyObject *__pyx_v_multiple_iterators = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2220, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2220, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2220, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2220, __pyx_L3_error) + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_False)); + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 2220, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2220, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2220, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + if (!values[1]) values[1] = __Pyx_NewRef(((PyObject *)Py_False)); + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + __pyx_v_multiple_iterators = values[1]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 2220, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2220, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self), __pyx_v_samfile, __pyx_v_multiple_iterators); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_multiple_iterators) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_t_7; + int __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[100])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2220, 0, 0, 0, __PYX_ERR(0, 2220, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2221 + * + * def __init__(self, AlignmentFile samfile, multiple_iterators=False): + * super().__init__(samfile, multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * if not samfile.has_index(): +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_super); + __pyx_t_5 = __pyx_builtin_super; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs), ((PyObject *)__pyx_v_self)}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2221, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_2, ((PyObject *)__pyx_v_samfile)}; + __pyx_t_5 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2221, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_v_multiple_iterators, __pyx_t_5, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 2221, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_init, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_5); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2221, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2223 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * if not samfile.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for fetch") + * +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_samfile); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_index, __pyx_callargs+__pyx_t_6, (1-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2223, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_t_7 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_7 < 0))) __PYX_ERR(0, 2223, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_8 = (!__pyx_t_7); + if (unlikely(__pyx_t_8)) { + + /* "pysam/libcalignmentfile.pyx":2224 + * + * if not samfile.has_index(): + * raise ValueError("no index available for fetch") # <<<<<<<<<<<<<< + * + * self.tid = -1 +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_no_index_available_for_fetch}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2224, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 2224, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2223 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * if not samfile.has_index(): # <<<<<<<<<<<<<< + * raise ValueError("no index available for fetch") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2226 + * raise ValueError("no index available for fetch") + * + * self.tid = -1 # <<<<<<<<<<<<<< + * + * def nextiter(self): +*/ + __pyx_v_self->tid = -1; + + /* "pysam/libcalignmentfile.pyx":2220 + * """ + * + * def __init__(self, AlignmentFile samfile, multiple_iterators=False): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2220, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2220, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2228 + * self.tid = -1 + * + * def nextiter(self): # <<<<<<<<<<<<<< + * # get a new iterator for a chromosome. The file + * # will not be re-opened. +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter, "IteratorRowAllRefs.nextiter(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter = {"nextiter", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("nextiter (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("nextiter", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("nextiter", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + htsFile *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[101])) + __Pyx_RefNannySetupContext("nextiter", 0); + __Pyx_TraceStartFunc("nextiter", __pyx_f[0], 2228, 0, 0, 0, __PYX_ERR(0, 2228, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2231 + * # get a new iterator for a chromosome. The file + * # will not be re-opened. + * self.rowiter = IteratorRowRegion(self.samfile, # <<<<<<<<<<<<<< + * self.tid, + * 0, +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + + /* "pysam/libcalignmentfile.pyx":2232 + * # will not be re-opened. + * self.rowiter = IteratorRowRegion(self.samfile, + * self.tid, # <<<<<<<<<<<<<< + * 0, + * MAX_POS) +*/ + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_self->tid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2232, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "pysam/libcalignmentfile.pyx":2234 + * self.tid, + * 0, + * MAX_POS) # <<<<<<<<<<<<<< + * # set htsfile and header of the rowiter + * # to the values in this iterator to reflect multiple_iterators +*/ + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_5pysam_17libcalignmentfile_MAX_POS); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2234, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[5] = {__pyx_t_2, ((PyObject *)__pyx_v_self->__pyx_base.samfile), __pyx_t_4, __pyx_mstate_global->__pyx_int_0, __pyx_t_5}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_6, (5-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2231, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":2231 + * # get a new iterator for a chromosome. The file + * # will not be re-opened. + * self.rowiter = IteratorRowRegion(self.samfile, # <<<<<<<<<<<<<< + * self.tid, + * 0, +*/ + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->rowiter); + __Pyx_DECREF((PyObject *)__pyx_v_self->rowiter); + __pyx_v_self->rowiter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2237 + * # set htsfile and header of the rowiter + * # to the values in this iterator to reflect multiple_iterators + * self.rowiter.htsfile = self.htsfile # <<<<<<<<<<<<<< + * self.rowiter.header = self.header + * +*/ + __pyx_t_7 = __pyx_v_self->__pyx_base.htsfile; + __pyx_v_self->rowiter->__pyx_base.htsfile = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":2238 + * # to the values in this iterator to reflect multiple_iterators + * self.rowiter.htsfile = self.htsfile + * self.rowiter.header = self.header # <<<<<<<<<<<<<< + * + * # make sure the iterator understand that IteratorRowAllRefs +*/ + __pyx_t_1 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->rowiter->__pyx_base.header); + __Pyx_DECREF((PyObject *)__pyx_v_self->rowiter->__pyx_base.header); + __pyx_v_self->rowiter->__pyx_base.header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2242 + * # make sure the iterator understand that IteratorRowAllRefs + * # has ownership + * self.rowiter.owns_samfile = False # <<<<<<<<<<<<<< + * + * def __iter__(self): +*/ + __pyx_v_self->rowiter->__pyx_base.owns_samfile = 0; + + /* "pysam/libcalignmentfile.pyx":2228 + * self.tid = -1 + * + * def nextiter(self): # <<<<<<<<<<<<<< + * # get a new iterator for a chromosome. The file + * # will not be re-opened. +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2228, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2228, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.nextiter", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2244 + * self.rowiter.owns_samfile = False + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_5__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_5__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_4__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_4__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[102])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2244, 0, 0, 0, __PYX_ERR(0, 2244, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2245 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2245, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2244 + * self.rowiter.owns_samfile = False + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2244, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2247 + * return self + * + * def __next__(self): # <<<<<<<<<<<<<< + * # Create an initial iterator + * if self.tid == -1: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_6__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_6__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[103])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2247, 0, 0, 0, __PYX_ERR(0, 2247, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2249 + * def __next__(self): + * # Create an initial iterator + * if self.tid == -1: # <<<<<<<<<<<<<< + * if not self.samfile.nreferences: + * raise StopIteration +*/ + __pyx_t_1 = (__pyx_v_self->tid == -1L); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2250 + * # Create an initial iterator + * if self.tid == -1: + * if not self.samfile.nreferences: # <<<<<<<<<<<<<< + * raise StopIteration + * self.tid = 0 +*/ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->__pyx_base.samfile), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 2250, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = (!__pyx_t_1); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2251 + * if self.tid == -1: + * if not self.samfile.nreferences: + * raise StopIteration # <<<<<<<<<<<<<< + * self.tid = 0 + * self.nextiter() +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2250 + * # Create an initial iterator + * if self.tid == -1: + * if not self.samfile.nreferences: # <<<<<<<<<<<<<< + * raise StopIteration + * self.tid = 0 +*/ + } + + /* "pysam/libcalignmentfile.pyx":2252 + * if not self.samfile.nreferences: + * raise StopIteration + * self.tid = 0 # <<<<<<<<<<<<<< + * self.nextiter() + * +*/ + __pyx_v_self->tid = 0; + + /* "pysam/libcalignmentfile.pyx":2253 + * raise StopIteration + * self.tid = 0 + * self.nextiter() # <<<<<<<<<<<<<< + * + * while 1: +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_4); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, NULL}; + __pyx_t_2 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_nextiter, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2253, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2249 + * def __next__(self): + * # Create an initial iterator + * if self.tid == -1: # <<<<<<<<<<<<<< + * if not self.samfile.nreferences: + * raise StopIteration +*/ + } + + /* "pysam/libcalignmentfile.pyx":2255 + * self.nextiter() + * + * while 1: # <<<<<<<<<<<<<< + * self.rowiter.cnext() + * +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2256 + * + * while 1: + * self.rowiter.cnext() # <<<<<<<<<<<<<< + * + * # If current iterator is not exhausted, return aligned read +*/ + ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_v_self->rowiter->__pyx_vtab)->cnext(__pyx_v_self->rowiter); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2256, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2259 + * + * # If current iterator is not exhausted, return aligned read + * if self.rowiter.retval > 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.rowiter.b, self.header) + * +*/ + __pyx_t_3 = (__pyx_v_self->rowiter->__pyx_base.retval > 0); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2260 + * # If current iterator is not exhausted, return aligned read + * if self.rowiter.retval > 0: + * return makeAlignedSegment(self.rowiter.b, self.header) # <<<<<<<<<<<<<< + * + * self.tid += 1 +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->rowiter->__pyx_base.b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_2))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2260, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 29, 0, __PYX_ERR(0, 2260, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2259 + * + * # If current iterator is not exhausted, return aligned read + * if self.rowiter.retval > 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.rowiter.b, self.header) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2262 + * return makeAlignedSegment(self.rowiter.b, self.header) + * + * self.tid += 1 # <<<<<<<<<<<<<< + * + * # Otherwise, proceed to next reference or stop +*/ + __pyx_v_self->tid = (__pyx_v_self->tid + 1); + + /* "pysam/libcalignmentfile.pyx":2265 + * + * # Otherwise, proceed to next reference or stop + * if self.tid < self.samfile.nreferences: # <<<<<<<<<<<<<< + * self.nextiter() + * else: +*/ + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_self->tid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2265, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->__pyx_base.samfile), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2265, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_4, __pyx_t_2, Py_LT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2265, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 2265, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (likely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2266 + * # Otherwise, proceed to next reference or stop + * if self.tid < self.samfile.nreferences: + * self.nextiter() # <<<<<<<<<<<<<< + * else: + * raise StopIteration +*/ + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_6 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_nextiter, __pyx_callargs+__pyx_t_5, (1-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2266, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "pysam/libcalignmentfile.pyx":2265 + * + * # Otherwise, proceed to next reference or stop + * if self.tid < self.samfile.nreferences: # <<<<<<<<<<<<<< + * self.nextiter() + * else: +*/ + goto __pyx_L8; + } + + /* "pysam/libcalignmentfile.pyx":2268 + * self.nextiter() + * else: + * raise StopIteration # <<<<<<<<<<<<<< + * + * +*/ + /*else*/ { + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + } + __pyx_L8:; + } + + /* "pysam/libcalignmentfile.pyx":2247 + * return self + * + * def __next__(self): # <<<<<<<<<<<<<< + * # Create an initial iterator + * if self.tid == -1: +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2247, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2247, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__, "IteratorRowAllRefs.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[104])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__, "IteratorRowAllRefs.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[105])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowAllRefs.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2281 + * """ + * + * def __init__(self, AlignmentFile samfile, positions, int multiple_iterators=True): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + PyObject *__pyx_v_positions = 0; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_positions,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2281, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2281, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2281, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2281, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2281, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 2; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 3, i); __PYX_ERR(0, 2281, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2281, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2281, __pyx_L3_error) + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2281, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + __pyx_v_positions = values[1]; + if (values[2]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[2]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2281, __pyx_L3_error) + } else { + __pyx_v_multiple_iterators = ((int)1); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 3, __pyx_nargs); __PYX_ERR(0, 2281, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2281, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self), __pyx_v_samfile, __pyx_v_positions, __pyx_v_multiple_iterators); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_positions, int __pyx_v_multiple_iterators) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[106])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2281, 0, 0, 0, __PYX_ERR(0, 2281, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2282 + * + * def __init__(self, AlignmentFile samfile, positions, int multiple_iterators=True): + * super().__init__(samfile, multiple_iterators=multiple_iterators) # <<<<<<<<<<<<<< + * + * self.positions = positions +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_super); + __pyx_t_5 = __pyx_builtin_super; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_4, ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection), ((PyObject *)__pyx_v_self)}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_2 = __pyx_t_3; + __Pyx_INCREF(__pyx_t_2); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_multiple_iterators); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 0; + { + PyObject *__pyx_callargs[2 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_2, ((PyObject *)__pyx_v_samfile)}; + __pyx_t_4 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_t_5, __pyx_t_4, __pyx_callargs+2, 0) < 0) __PYX_ERR(0, 2282, __pyx_L1_error) + __pyx_t_1 = __Pyx_Object_VectorcallMethod_CallFromBuilder(__pyx_mstate_global->__pyx_n_u_init, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_4); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2282, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2284 + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * + * self.positions = positions # <<<<<<<<<<<<<< + * self.current_pos = 0 + * +*/ + __Pyx_INCREF(__pyx_v_positions); + __Pyx_GIVEREF(__pyx_v_positions); + __Pyx_GOTREF(__pyx_v_self->positions); + __Pyx_DECREF(__pyx_v_self->positions); + __pyx_v_self->positions = __pyx_v_positions; + + /* "pysam/libcalignmentfile.pyx":2285 + * + * self.positions = positions + * self.current_pos = 0 # <<<<<<<<<<<<<< + * + * def __iter__(self): +*/ + __pyx_v_self->current_pos = 0; + + /* "pysam/libcalignmentfile.pyx":2281 + * """ + * + * def __init__(self, AlignmentFile samfile, positions, int multiple_iterators=True): # <<<<<<<<<<<<<< + * super().__init__(samfile, multiple_iterators=multiple_iterators) + * +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2281, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2281, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2287 + * self.current_pos = 0 + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_3__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_3__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_2__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[107])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2287, 0, 0, 0, __PYX_ERR(0, 2287, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2288 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * cdef bam1_t * getCurrent(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2288, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2287 + * self.current_pos = 0 + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2287, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2290 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + +static bam1_t *__pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_getCurrent(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self) { + bam1_t *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[108])) + __Pyx_TraceStartFunc("getCurrent", __pyx_f[0], 2290, 0, 0, 0, __PYX_ERR(0, 2290, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2291 + * + * cdef bam1_t * getCurrent(self): + * return self.b # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __pyx_r = __pyx_v_self->__pyx_base.b; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2291, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2290 + * return self + * + * cdef bam1_t * getCurrent(self): # <<<<<<<<<<<<<< + * return self.b + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2290, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.getCurrent", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2293 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator''' + * # end iteration if out of positions +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self) { + int __pyx_v_ret; + uint64_t __pyx_v_pos; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + uint64_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno __pyx_t_6; + bam_hdr_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[109])) + __Pyx_RefNannySetupContext("cnext", 0); + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 2293, 0, 0, 0, __PYX_ERR(0, 2293, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2296 + * '''cversion of iterator''' + * # end iteration if out of positions + * if self.current_pos >= len(self.positions): return -1 # <<<<<<<<<<<<<< + * + * cdef int ret +*/ + __pyx_t_1 = __pyx_v_self->positions; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_2 = PyObject_Length(__pyx_t_1); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1))) __PYX_ERR(0, 2296, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (__pyx_v_self->current_pos >= __pyx_t_2); + if (__pyx_t_3) { + __pyx_r = -1; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 9, 0, __PYX_ERR(0, 2296, __pyx_L1_error)); + goto __pyx_L0; + } + + /* "pysam/libcalignmentfile.pyx":2299 + * + * cdef int ret + * cdef uint64_t pos = self.positions[self.current_pos] # <<<<<<<<<<<<<< + * with nogil: + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) +*/ + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_self->positions, __pyx_v_self->current_pos, int, 1, __Pyx_PyLong_From_int, 0, 1, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2299, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyLong_As_uint64_t(__pyx_t_1); if (unlikely((__pyx_t_4 == ((uint64_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 2299, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_pos = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":2300 + * cdef int ret + * cdef uint64_t pos = self.positions[self.current_pos] + * with nogil: # <<<<<<<<<<<<<< + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) + * if ret < 0: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2301 + * cdef uint64_t pos = self.positions[self.current_pos] + * with nogil: + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) # <<<<<<<<<<<<<< + * if ret < 0: + * raise OSError_from_errno("Can't seek", self.samfile.filename) +*/ + __pyx_v_ret = bgzf_seek(hts_get_bgzfp(__pyx_v_self->__pyx_base.htsfile), __pyx_v_pos, 0); + } + + /* "pysam/libcalignmentfile.pyx":2300 + * cdef int ret + * cdef uint64_t pos = self.positions[self.current_pos] + * with nogil: # <<<<<<<<<<<<<< + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) + * if ret < 0: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L6; + } + __pyx_L6:; + } + } + + /* "pysam/libcalignmentfile.pyx":2302 + * with nogil: + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) + * if ret < 0: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Can't seek", self.samfile.filename) + * self.current_pos += 1 +*/ + __pyx_t_3 = (__pyx_v_ret < 0); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2303 + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) + * if ret < 0: + * raise OSError_from_errno("Can't seek", self.samfile.filename) # <<<<<<<<<<<<<< + * self.current_pos += 1 + * +*/ + __pyx_t_1 = __pyx_v_self->__pyx_base.samfile->__pyx_base.filename; + __Pyx_INCREF(__pyx_t_1); + __pyx_t_6.__pyx_n = 1; + __pyx_t_6.filename = __pyx_t_1; + __pyx_t_5 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Can_t_seek, &__pyx_t_6); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2303, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 2303, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2302 + * with nogil: + * ret = bgzf_seek(hts_get_bgzfp(self.htsfile), pos, 0) + * if ret < 0: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Can't seek", self.samfile.filename) + * self.current_pos += 1 +*/ + } + + /* "pysam/libcalignmentfile.pyx":2304 + * if ret < 0: + * raise OSError_from_errno("Can't seek", self.samfile.filename) + * self.current_pos += 1 # <<<<<<<<<<<<<< + * + * cdef bam_hdr_t * hdr = self.header.ptr +*/ + __pyx_v_self->current_pos = (__pyx_v_self->current_pos + 1); + + /* "pysam/libcalignmentfile.pyx":2306 + * self.current_pos += 1 + * + * cdef bam_hdr_t * hdr = self.header.ptr # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_read1(self.htsfile, +*/ + __pyx_t_7 = __pyx_v_self->__pyx_base.header->ptr; + __pyx_v_hdr = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":2307 + * + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2308 + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: + * ret = sam_read1(self.htsfile, # <<<<<<<<<<<<<< + * hdr, + * self.b) +*/ + __pyx_v_ret = sam_read1(__pyx_v_self->__pyx_base.htsfile, __pyx_v_hdr, __pyx_v_self->__pyx_base.b); + } + + /* "pysam/libcalignmentfile.pyx":2307 + * + * cdef bam_hdr_t * hdr = self.header.ptr + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L10; + } + __pyx_L10:; + } + } + + /* "pysam/libcalignmentfile.pyx":2311 + * hdr, + * self.b) + * return ret # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 54, 0, __PYX_ERR(0, 2311, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2293 + * return self.b + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''cversion of iterator''' + * # end iteration if out of positions +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2293, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2313 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_4__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_4__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self) { + int __pyx_v_ret; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[110])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2313, 0, 0, 0, __PYX_ERR(0, 2313, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2314 + * + * def __next__(self): + * cdef int ret = self.cnext() # <<<<<<<<<<<<<< + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self->__pyx_vtab)->cnext(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2314, __pyx_L1_error) + __pyx_v_ret = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2315 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + __pyx_t_2 = (__pyx_v_ret >= 0); + if (likely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2316 + * cdef int ret = self.cnext() + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) # <<<<<<<<<<<<<< + * elif ret == -1: + * raise StopIteration +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.header); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment(__pyx_v_self->__pyx_base.b, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2316, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + __Pyx_TraceReturnValue(__pyx_r, 9, 0, __PYX_ERR(0, 2316, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2315 + * def __next__(self): + * cdef int ret = self.cnext() + * if ret >= 0: # <<<<<<<<<<<<<< + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2317 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + __pyx_t_2 = (__pyx_v_ret == -1L); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2318 + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: + * raise StopIteration # <<<<<<<<<<<<<< + * else: + * raise IOError(read_failure_reason(ret)) +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2317 + * if ret >= 0: + * return makeAlignedSegment(self.b, self.header) + * elif ret == -1: # <<<<<<<<<<<<<< + * raise StopIteration + * else: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2320 + * raise StopIteration + * else: + * raise IOError(read_failure_reason(ret)) # <<<<<<<<<<<<<< + * + * +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_IOError); + __pyx_t_5 = __pyx_builtin_IOError; + __pyx_t_7 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_read_failure_reason); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_PyLong_From_int(__pyx_v_ret); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 2320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_8))) { + __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_8); + assert(__pyx_t_7); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_8); + __Pyx_INCREF(__pyx_t_7); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_8, __pyx__function); + __pyx_t_10 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_6 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + } + __pyx_t_10 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2320, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 2320, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":2313 + * return ret + * + * def __next__(self): # <<<<<<<<<<<<<< + * cdef int ret = self.cnext() + * if ret >= 0: +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2313, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__, "IteratorRowSelection.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[111])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__, "IteratorRowSelection.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[112])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_b_self_htsfile_self_index_c, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorRowSelection.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2323 + * + * + * cdef int __advance_nofilter(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''advance without any read filtering. + * ''' +*/ + +static int __pyx_f_5pysam_17libcalignmentfile___advance_nofilter(void *__pyx_v_data, bam1_t *__pyx_v_b) { + __pyx_t_5pysam_17libcalignmentfile___iterdata *__pyx_v_d; + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[113])) + __Pyx_TraceStartFunc("__advance_nofilter", __pyx_f[0], 2323, 0, 0, 0, __PYX_ERR(0, 2323, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2326 + * '''advance without any read filtering. + * ''' + * cdef __iterdata * d = <__iterdata*>data # <<<<<<<<<<<<<< + * cdef int ret + * with nogil: +*/ + __pyx_v_d = ((__pyx_t_5pysam_17libcalignmentfile___iterdata *)__pyx_v_data); + + /* "pysam/libcalignmentfile.pyx":2328 + * cdef __iterdata * d = <__iterdata*>data + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) + * return ret +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2329 + * cdef int ret + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) # <<<<<<<<<<<<<< + * return ret + * +*/ + __pyx_v_ret = sam_itr_next(__pyx_v_d->htsfile, __pyx_v_d->iter, __pyx_v_b); + } + + /* "pysam/libcalignmentfile.pyx":2328 + * cdef __iterdata * d = <__iterdata*>data + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) + * return ret +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":2330 + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) + * return ret # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 14, 0, __PYX_ERR(0, 2330, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2323 + * + * + * cdef int __advance_nofilter(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''advance without any read filtering. + * ''' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2323, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__advance_nofilter", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2333 + * + * + * cdef int __advance_raw_nofilter(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''advance (without iterator) without any read filtering. + * ''' +*/ + +static int __pyx_f_5pysam_17libcalignmentfile___advance_raw_nofilter(void *__pyx_v_data, bam1_t *__pyx_v_b) { + __pyx_t_5pysam_17libcalignmentfile___iterdata *__pyx_v_d; + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[114])) + __Pyx_TraceStartFunc("__advance_raw_nofilter", __pyx_f[0], 2333, 0, 0, 0, __PYX_ERR(0, 2333, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2336 + * '''advance (without iterator) without any read filtering. + * ''' + * cdef __iterdata * d = <__iterdata*>data # <<<<<<<<<<<<<< + * cdef int ret + * with nogil: +*/ + __pyx_v_d = ((__pyx_t_5pysam_17libcalignmentfile___iterdata *)__pyx_v_data); + + /* "pysam/libcalignmentfile.pyx":2338 + * cdef __iterdata * d = <__iterdata*>data + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(d.htsfile, d.header, b) + * return ret +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2339 + * cdef int ret + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) # <<<<<<<<<<<<<< + * return ret + * +*/ + __pyx_v_ret = sam_read1(__pyx_v_d->htsfile, __pyx_v_d->header, __pyx_v_b); + } + + /* "pysam/libcalignmentfile.pyx":2338 + * cdef __iterdata * d = <__iterdata*>data + * cdef int ret + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(d.htsfile, d.header, b) + * return ret +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L5; + } + __pyx_L5:; + } + } + + /* "pysam/libcalignmentfile.pyx":2340 + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) + * return ret # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 14, 0, __PYX_ERR(0, 2340, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2333 + * + * + * cdef int __advance_raw_nofilter(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''advance (without iterator) without any read filtering. + * ''' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2333, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__advance_raw_nofilter", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2343 + * + * + * cdef int __advance_all(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''only use reads for pileup passing basic filters such as + * +*/ + +static int __pyx_f_5pysam_17libcalignmentfile___advance_all(void *__pyx_v_data, bam1_t *__pyx_v_b) { + __pyx_t_5pysam_17libcalignmentfile___iterdata *__pyx_v_d; + CYTHON_UNUSED PyObject *__pyx_v_mask = 0; + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[115])) + __Pyx_RefNannySetupContext("__advance_all", 0); + __Pyx_TraceStartFunc("__advance_all", __pyx_f[0], 2343, 0, 0, 0, __PYX_ERR(0, 2343, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2349 + * ''' + * + * cdef __iterdata * d = <__iterdata*>data # <<<<<<<<<<<<<< + * cdef mask = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP + * cdef int ret +*/ + __pyx_v_d = ((__pyx_t_5pysam_17libcalignmentfile___iterdata *)__pyx_v_data); + + /* "pysam/libcalignmentfile.pyx":2350 + * + * cdef __iterdata * d = <__iterdata*>data + * cdef mask = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP # <<<<<<<<<<<<<< + * cdef int ret + * while 1: +*/ + __pyx_t_1 = __Pyx_PyLong_From_int((((BAM_FUNMAP | BAM_FSECONDARY) | BAM_FQCFAIL) | BAM_FDUP)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2350, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_mask = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2352 + * cdef mask = BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP + * cdef int ret + * while 1: # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2353 + * cdef int ret + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) + * if ret < 0: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2354 + * while 1: + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) # <<<<<<<<<<<<<< + * if ret < 0: + * break +*/ + __pyx_v_ret = sam_itr_next(__pyx_v_d->htsfile, __pyx_v_d->iter, __pyx_v_b); + } + + /* "pysam/libcalignmentfile.pyx":2353 + * cdef int ret + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) + * if ret < 0: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":2355 + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + __pyx_t_2 = (__pyx_v_ret < 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2356 + * ret = sam_itr_next(d.htsfile, d.iter, b) + * if ret < 0: + * break # <<<<<<<<<<<<<< + * if b.core.flag & d.flag_filter: + * continue +*/ + goto __pyx_L4_break; + + /* "pysam/libcalignmentfile.pyx":2355 + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2357 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * break +*/ + __pyx_t_2 = ((__pyx_v_b->core.flag & __pyx_v_d->flag_filter) != 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2358 + * break + * if b.core.flag & d.flag_filter: + * continue # <<<<<<<<<<<<<< + * break + * return ret +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2357 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * break +*/ + } + + /* "pysam/libcalignmentfile.pyx":2359 + * if b.core.flag & d.flag_filter: + * continue + * break # <<<<<<<<<<<<<< + * return ret + * +*/ + goto __pyx_L4_break; + __pyx_L3_continue:; + } + __pyx_L4_break:; + + /* "pysam/libcalignmentfile.pyx":2360 + * continue + * break + * return ret # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 37, 0, __PYX_ERR(0, 2360, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2343 + * + * + * cdef int __advance_all(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''only use reads for pileup passing basic filters such as + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2343, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__advance_all", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_mask); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2363 + * + * + * cdef int __advance_raw_all(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''only use reads for pileup passing basic filters such as + * +*/ + +static int __pyx_f_5pysam_17libcalignmentfile___advance_raw_all(void *__pyx_v_data, bam1_t *__pyx_v_b) { + __pyx_t_5pysam_17libcalignmentfile___iterdata *__pyx_v_d; + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[116])) + __Pyx_TraceStartFunc("__advance_raw_all", __pyx_f[0], 2363, 0, 0, 0, __PYX_ERR(0, 2363, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2369 + * ''' + * + * cdef __iterdata * d = <__iterdata*>data # <<<<<<<<<<<<<< + * cdef int ret + * while 1: +*/ + __pyx_v_d = ((__pyx_t_5pysam_17libcalignmentfile___iterdata *)__pyx_v_data); + + /* "pysam/libcalignmentfile.pyx":2371 + * cdef __iterdata * d = <__iterdata*>data + * cdef int ret + * while 1: # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2372 + * cdef int ret + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(d.htsfile, d.header, b) + * if ret < 0: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2373 + * while 1: + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) # <<<<<<<<<<<<<< + * if ret < 0: + * break +*/ + __pyx_v_ret = sam_read1(__pyx_v_d->htsfile, __pyx_v_d->header, __pyx_v_b); + } + + /* "pysam/libcalignmentfile.pyx":2372 + * cdef int ret + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_read1(d.htsfile, d.header, b) + * if ret < 0: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":2374 + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + __pyx_t_1 = (__pyx_v_ret < 0); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2375 + * ret = sam_read1(d.htsfile, d.header, b) + * if ret < 0: + * break # <<<<<<<<<<<<<< + * if b.core.flag & d.flag_filter: + * continue +*/ + goto __pyx_L4_break; + + /* "pysam/libcalignmentfile.pyx":2374 + * with nogil: + * ret = sam_read1(d.htsfile, d.header, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2376 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * break +*/ + __pyx_t_1 = ((__pyx_v_b->core.flag & __pyx_v_d->flag_filter) != 0); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2377 + * break + * if b.core.flag & d.flag_filter: + * continue # <<<<<<<<<<<<<< + * break + * return ret +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2376 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * break +*/ + } + + /* "pysam/libcalignmentfile.pyx":2378 + * if b.core.flag & d.flag_filter: + * continue + * break # <<<<<<<<<<<<<< + * return ret + * +*/ + goto __pyx_L4_break; + __pyx_L3_continue:; + } + __pyx_L4_break:; + + /* "pysam/libcalignmentfile.pyx":2379 + * continue + * break + * return ret # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 29, 0, __PYX_ERR(0, 2379, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2363 + * + * + * cdef int __advance_raw_all(void *data, bam1_t *b): # <<<<<<<<<<<<<< + * '''only use reads for pileup passing basic filters such as + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2363, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__advance_raw_all", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2382 + * + * + * cdef int __advance_samtools(void * data, bam1_t * b): # <<<<<<<<<<<<<< + * '''advance using same filter and read processing as in + * the samtools pileup. +*/ + +static int __pyx_f_5pysam_17libcalignmentfile___advance_samtools(void *__pyx_v_data, bam1_t *__pyx_v_b) { + __pyx_t_5pysam_17libcalignmentfile___iterdata *__pyx_v_d; + int __pyx_v_ret; + int __pyx_v_q; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + int __pyx_t_3; + int32_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + size_t __pyx_t_12; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[117])) + __Pyx_RefNannySetupContext("__advance_samtools", 0); + __Pyx_TraceStartFunc("__advance_samtools", __pyx_f[0], 2382, 0, 0, 0, __PYX_ERR(0, 2382, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2386 + * the samtools pileup. + * ''' + * cdef __iterdata * d = <__iterdata*>data # <<<<<<<<<<<<<< + * cdef int ret + * cdef int q +*/ + __pyx_v_d = ((__pyx_t_5pysam_17libcalignmentfile___iterdata *)__pyx_v_data); + + /* "pysam/libcalignmentfile.pyx":2390 + * cdef int q + * + * while 1: # <<<<<<<<<<<<<< + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2391 + * + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) + * if ret < 0: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2392 + * while 1: + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) # <<<<<<<<<<<<<< + * if ret < 0: + * break +*/ + __pyx_t_2 = (__pyx_v_d->iter != 0); + if (__pyx_t_2) { + __pyx_t_1 = sam_itr_next(__pyx_v_d->htsfile, __pyx_v_d->iter, __pyx_v_b); + } else { + __pyx_t_1 = sam_read1(__pyx_v_d->htsfile, __pyx_v_d->header, __pyx_v_b); + } + __pyx_v_ret = __pyx_t_1; + } + + /* "pysam/libcalignmentfile.pyx":2391 + * + * while 1: + * with nogil: # <<<<<<<<<<<<<< + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) + * if ret < 0: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":2393 + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + __pyx_t_2 = (__pyx_v_ret < 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2394 + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) + * if ret < 0: + * break # <<<<<<<<<<<<<< + * if b.core.flag & d.flag_filter: + * continue +*/ + goto __pyx_L4_break; + + /* "pysam/libcalignmentfile.pyx":2393 + * with nogil: + * ret = sam_itr_next(d.htsfile, d.iter, b) if d.iter else sam_read1(d.htsfile, d.header, b) + * if ret < 0: # <<<<<<<<<<<<<< + * break + * if b.core.flag & d.flag_filter: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2395 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * if d.flag_require and not (b.core.flag & d.flag_require): +*/ + __pyx_t_2 = ((__pyx_v_b->core.flag & __pyx_v_d->flag_filter) != 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2396 + * break + * if b.core.flag & d.flag_filter: + * continue # <<<<<<<<<<<<<< + * if d.flag_require and not (b.core.flag & d.flag_require): + * continue +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2395 + * if ret < 0: + * break + * if b.core.flag & d.flag_filter: # <<<<<<<<<<<<<< + * continue + * if d.flag_require and not (b.core.flag & d.flag_require): +*/ + } + + /* "pysam/libcalignmentfile.pyx":2397 + * if b.core.flag & d.flag_filter: + * continue + * if d.flag_require and not (b.core.flag & d.flag_require): # <<<<<<<<<<<<<< + * continue + * +*/ + __pyx_t_3 = (__pyx_v_d->flag_require != 0); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L13_bool_binop_done; + } + __pyx_t_3 = (!((__pyx_v_b->core.flag & __pyx_v_d->flag_require) != 0)); + __pyx_t_2 = __pyx_t_3; + __pyx_L13_bool_binop_done:; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2398 + * continue + * if d.flag_require and not (b.core.flag & d.flag_require): + * continue # <<<<<<<<<<<<<< + * + * # reload sequence +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2397 + * if b.core.flag & d.flag_filter: + * continue + * if d.flag_require and not (b.core.flag & d.flag_require): # <<<<<<<<<<<<<< + * continue + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2401 + * + * # reload sequence + * if d.fastafile != NULL and b.core.tid != d.tid: # <<<<<<<<<<<<<< + * if d.seq != NULL: + * free(d.seq) +*/ + __pyx_t_3 = (__pyx_v_d->fastafile != NULL); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L16_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_b->core.tid != __pyx_v_d->tid); + __pyx_t_2 = __pyx_t_3; + __pyx_L16_bool_binop_done:; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2402 + * # reload sequence + * if d.fastafile != NULL and b.core.tid != d.tid: + * if d.seq != NULL: # <<<<<<<<<<<<<< + * free(d.seq) + * d.tid = b.core.tid +*/ + __pyx_t_2 = (__pyx_v_d->seq != NULL); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2403 + * if d.fastafile != NULL and b.core.tid != d.tid: + * if d.seq != NULL: + * free(d.seq) # <<<<<<<<<<<<<< + * d.tid = b.core.tid + * with nogil: +*/ + free(__pyx_v_d->seq); + + /* "pysam/libcalignmentfile.pyx":2402 + * # reload sequence + * if d.fastafile != NULL and b.core.tid != d.tid: + * if d.seq != NULL: # <<<<<<<<<<<<<< + * free(d.seq) + * d.tid = b.core.tid +*/ + } + + /* "pysam/libcalignmentfile.pyx":2404 + * if d.seq != NULL: + * free(d.seq) + * d.tid = b.core.tid # <<<<<<<<<<<<<< + * with nogil: + * d.seq = faidx_fetch_seq( +*/ + __pyx_t_4 = __pyx_v_b->core.tid; + __pyx_v_d->tid = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":2405 + * free(d.seq) + * d.tid = b.core.tid + * with nogil: # <<<<<<<<<<<<<< + * d.seq = faidx_fetch_seq( + * d.fastafile, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2406 + * d.tid = b.core.tid + * with nogil: + * d.seq = faidx_fetch_seq( # <<<<<<<<<<<<<< + * d.fastafile, + * d.header.target_name[d.tid], +*/ + __pyx_v_d->seq = faidx_fetch_seq(__pyx_v_d->fastafile, (__pyx_v_d->header->target_name[__pyx_v_d->tid]), 0, __pyx_v_5pysam_17libcalignmentfile_MAX_POS, (&__pyx_v_d->seq_len)); + } + + /* "pysam/libcalignmentfile.pyx":2405 + * free(d.seq) + * d.tid = b.core.tid + * with nogil: # <<<<<<<<<<<<<< + * d.seq = faidx_fetch_seq( + * d.fastafile, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L23; + } + __pyx_L23:; + } + } + + /* "pysam/libcalignmentfile.pyx":2412 + * &d.seq_len) + * + * if d.seq == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "reference sequence for '{}' (tid={}) not found".format( +*/ + __pyx_t_2 = (__pyx_v_d->seq == NULL); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2413 + * + * if d.seq == NULL: + * raise ValueError( # <<<<<<<<<<<<<< + * "reference sequence for '{}' (tid={}) not found".format( + * d.header.target_name[d.tid], d.tid)) +*/ + __pyx_t_6 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_7 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":2414 + * if d.seq == NULL: + * raise ValueError( + * "reference sequence for '{}' (tid={}) not found".format( # <<<<<<<<<<<<<< + * d.header.target_name[d.tid], d.tid)) + * +*/ + __pyx_t_9 = __pyx_mstate_global->__pyx_kp_u_reference_sequence_for_tid_not_f; + __Pyx_INCREF(__pyx_t_9); + + /* "pysam/libcalignmentfile.pyx":2415 + * raise ValueError( + * "reference sequence for '{}' (tid={}) not found".format( + * d.header.target_name[d.tid], d.tid)) # <<<<<<<<<<<<<< + * + * # realign read - changes base qualities +*/ + __pyx_t_10 = __Pyx_PyBytes_FromString((__pyx_v_d->header->target_name[__pyx_v_d->tid])); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 2415, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + __pyx_t_11 = __Pyx_PyLong_From_int(__pyx_v_d->tid); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 2415, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_12 = 0; + { + PyObject *__pyx_callargs[3] = {__pyx_t_9, __pyx_t_10, __pyx_t_11}; + __pyx_t_8 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_12, (3-__pyx_t_12) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2414, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + } + __pyx_t_12 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_6, __pyx_t_8}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_12, (2-__pyx_t_12) | (__pyx_t_12*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2413, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 2413, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2412 + * &d.seq_len) + * + * if d.seq == NULL: # <<<<<<<<<<<<<< + * raise ValueError( + * "reference sequence for '{}' (tid={}) not found".format( +*/ + } + + /* "pysam/libcalignmentfile.pyx":2401 + * + * # reload sequence + * if d.fastafile != NULL and b.core.tid != d.tid: # <<<<<<<<<<<<<< + * if d.seq != NULL: + * free(d.seq) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2418 + * + * # realign read - changes base qualities + * if d.seq != NULL and d.compute_baq: # <<<<<<<<<<<<<< + * # 4th option to realign is flag: + * # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4 +*/ + __pyx_t_3 = (__pyx_v_d->seq != NULL); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L26_bool_binop_done; + } + __pyx_t_2 = __pyx_v_d->compute_baq; + __pyx_L26_bool_binop_done:; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2421 + * # 4th option to realign is flag: + * # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4 + * if d.redo_baq: # <<<<<<<<<<<<<< + * sam_prob_realn(b, d.seq, d.seq_len, 7) + * else: +*/ + if (__pyx_v_d->redo_baq) { + + /* "pysam/libcalignmentfile.pyx":2422 + * # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4 + * if d.redo_baq: + * sam_prob_realn(b, d.seq, d.seq_len, 7) # <<<<<<<<<<<<<< + * else: + * sam_prob_realn(b, d.seq, d.seq_len, 3) +*/ + (void)(sam_prob_realn(__pyx_v_b, __pyx_v_d->seq, __pyx_v_d->seq_len, 7)); + + /* "pysam/libcalignmentfile.pyx":2421 + * # 4th option to realign is flag: + * # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4 + * if d.redo_baq: # <<<<<<<<<<<<<< + * sam_prob_realn(b, d.seq, d.seq_len, 7) + * else: +*/ + goto __pyx_L28; + } + + /* "pysam/libcalignmentfile.pyx":2424 + * sam_prob_realn(b, d.seq, d.seq_len, 7) + * else: + * sam_prob_realn(b, d.seq, d.seq_len, 3) # <<<<<<<<<<<<<< + * + * if d.seq != NULL and d.adjust_capq_threshold > 10: +*/ + /*else*/ { + (void)(sam_prob_realn(__pyx_v_b, __pyx_v_d->seq, __pyx_v_d->seq_len, 3)); + } + __pyx_L28:; + + /* "pysam/libcalignmentfile.pyx":2418 + * + * # realign read - changes base qualities + * if d.seq != NULL and d.compute_baq: # <<<<<<<<<<<<<< + * # 4th option to realign is flag: + * # apply_baq = flag&1, extend_baq = flag&2, redo_baq = flag&4 +*/ + } + + /* "pysam/libcalignmentfile.pyx":2426 + * sam_prob_realn(b, d.seq, d.seq_len, 3) + * + * if d.seq != NULL and d.adjust_capq_threshold > 10: # <<<<<<<<<<<<<< + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) + * if q < 0: +*/ + __pyx_t_3 = (__pyx_v_d->seq != NULL); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L30_bool_binop_done; + } + __pyx_t_3 = (__pyx_v_d->adjust_capq_threshold > 10); + __pyx_t_2 = __pyx_t_3; + __pyx_L30_bool_binop_done:; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2427 + * + * if d.seq != NULL and d.adjust_capq_threshold > 10: + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) # <<<<<<<<<<<<<< + * if q < 0: + * continue +*/ + __pyx_v_q = sam_cap_mapq(__pyx_v_b, __pyx_v_d->seq, __pyx_v_d->seq_len, __pyx_v_d->adjust_capq_threshold); + + /* "pysam/libcalignmentfile.pyx":2428 + * if d.seq != NULL and d.adjust_capq_threshold > 10: + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) + * if q < 0: # <<<<<<<<<<<<<< + * continue + * elif b.core.qual > q: +*/ + __pyx_t_2 = (__pyx_v_q < 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2429 + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) + * if q < 0: + * continue # <<<<<<<<<<<<<< + * elif b.core.qual > q: + * b.core.qual = q +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2428 + * if d.seq != NULL and d.adjust_capq_threshold > 10: + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) + * if q < 0: # <<<<<<<<<<<<<< + * continue + * elif b.core.qual > q: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2430 + * if q < 0: + * continue + * elif b.core.qual > q: # <<<<<<<<<<<<<< + * b.core.qual = q + * +*/ + __pyx_t_2 = (__pyx_v_b->core.qual > __pyx_v_q); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2431 + * continue + * elif b.core.qual > q: + * b.core.qual = q # <<<<<<<<<<<<<< + * + * if b.core.qual < d.min_mapping_quality: +*/ + __pyx_v_b->core.qual = __pyx_v_q; + + /* "pysam/libcalignmentfile.pyx":2430 + * if q < 0: + * continue + * elif b.core.qual > q: # <<<<<<<<<<<<<< + * b.core.qual = q + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2426 + * sam_prob_realn(b, d.seq, d.seq_len, 3) + * + * if d.seq != NULL and d.adjust_capq_threshold > 10: # <<<<<<<<<<<<<< + * q = sam_cap_mapq(b, d.seq, d.seq_len, d.adjust_capq_threshold) + * if q < 0: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2433 + * b.core.qual = q + * + * if b.core.qual < d.min_mapping_quality: # <<<<<<<<<<<<<< + * continue + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): +*/ + __pyx_t_2 = (__pyx_v_b->core.qual < __pyx_v_d->min_mapping_quality); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2434 + * + * if b.core.qual < d.min_mapping_quality: + * continue # <<<<<<<<<<<<<< + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): + * continue +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2433 + * b.core.qual = q + * + * if b.core.qual < d.min_mapping_quality: # <<<<<<<<<<<<<< + * continue + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): +*/ + } + + /* "pysam/libcalignmentfile.pyx":2435 + * if b.core.qual < d.min_mapping_quality: + * continue + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): # <<<<<<<<<<<<<< + * continue + * +*/ + if (__pyx_v_d->ignore_orphans) { + } else { + __pyx_t_2 = __pyx_v_d->ignore_orphans; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_3 = ((__pyx_v_b->core.flag & BAM_FPAIRED) != 0); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_3 = (!((__pyx_v_b->core.flag & BAM_FPROPER_PAIR) != 0)); + __pyx_t_2 = __pyx_t_3; + __pyx_L35_bool_binop_done:; + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2436 + * continue + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): + * continue # <<<<<<<<<<<<<< + * + * break +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2435 + * if b.core.qual < d.min_mapping_quality: + * continue + * if d.ignore_orphans and b.core.flag & BAM_FPAIRED and not (b.core.flag & BAM_FPROPER_PAIR): # <<<<<<<<<<<<<< + * continue + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2438 + * continue + * + * break # <<<<<<<<<<<<<< + * + * return ret +*/ + goto __pyx_L4_break; + __pyx_L3_continue:; + } + __pyx_L4_break:; + + /* "pysam/libcalignmentfile.pyx":2440 + * break + * + * return ret # <<<<<<<<<<<<<< + * + * +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 199, 0, __PYX_ERR(0, 2440, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2382 + * + * + * cdef int __advance_samtools(void * data, bam1_t * b): # <<<<<<<<<<<<<< + * '''advance using same filter and read processing as in + * the samtools pileup. +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2382, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__advance_samtools", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2475 + * ''' + * + * def __cinit__( self, AlignmentFile samfile, **kwargs): # <<<<<<<<<<<<<< + * self.samfile = samfile + * self.fastafile = kwargs.get("fastafile", None) +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_v_kwargs = PyDict_New(); if (unlikely(!__pyx_v_kwargs)) return -1; + __Pyx_GOTREF(__pyx_v_kwargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2475, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2475, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, __pyx_v_kwargs, values, kwd_pos_args, __pyx_kwds_len, "__cinit__", 1) < 0) __PYX_ERR(0, 2475, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, i); __PYX_ERR(0, 2475, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2475, __pyx_L3_error) + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2475, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_DECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2475, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_samfile, __pyx_v_kwargs); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_DECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, PyObject *__pyx_v_kwargs) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + uint32_t __pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[118])) + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 2475, 0, 0, 0, __PYX_ERR(0, 2475, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2476 + * + * def __cinit__( self, AlignmentFile samfile, **kwargs): + * self.samfile = samfile # <<<<<<<<<<<<<< + * self.fastafile = kwargs.get("fastafile", None) + * self.stepper = kwargs.get("stepper", "samtools") +*/ + __Pyx_INCREF((PyObject *)__pyx_v_samfile); + __Pyx_GIVEREF((PyObject *)__pyx_v_samfile); + __Pyx_GOTREF((PyObject *)__pyx_v_self->samfile); + __Pyx_DECREF((PyObject *)__pyx_v_self->samfile); + __pyx_v_self->samfile = __pyx_v_samfile; + + /* "pysam/libcalignmentfile.pyx":2477 + * def __cinit__( self, AlignmentFile samfile, **kwargs): + * self.samfile = samfile + * self.fastafile = kwargs.get("fastafile", None) # <<<<<<<<<<<<<< + * self.stepper = kwargs.get("stepper", "samtools") + * self.max_depth = kwargs.get("max_depth", 8000) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_fastafile, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2477, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_mstate_global->__pyx_ptype_5pysam_9libcfaidx_FastaFile))))) __PYX_ERR(0, 2477, __pyx_L1_error) + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->fastafile); + __Pyx_DECREF((PyObject *)__pyx_v_self->fastafile); + __pyx_v_self->fastafile = ((struct __pyx_obj_5pysam_9libcfaidx_FastaFile *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2478 + * self.samfile = samfile + * self.fastafile = kwargs.get("fastafile", None) + * self.stepper = kwargs.get("stepper", "samtools") # <<<<<<<<<<<<<< + * self.max_depth = kwargs.get("max_depth", 8000) + * self.ignore_overlaps = kwargs.get("ignore_overlaps", True) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_stepper, __pyx_mstate_global->__pyx_n_u_samtools); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2478, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->stepper); + __Pyx_DECREF(__pyx_v_self->stepper); + __pyx_v_self->stepper = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2479 + * self.fastafile = kwargs.get("fastafile", None) + * self.stepper = kwargs.get("stepper", "samtools") + * self.max_depth = kwargs.get("max_depth", 8000) # <<<<<<<<<<<<<< + * self.ignore_overlaps = kwargs.get("ignore_overlaps", True) + * self.min_base_quality = kwargs.get("min_base_quality", 13) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_max_depth, __pyx_mstate_global->__pyx_int_8000); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2479, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2479, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->max_depth = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2480 + * self.stepper = kwargs.get("stepper", "samtools") + * self.max_depth = kwargs.get("max_depth", 8000) + * self.ignore_overlaps = kwargs.get("ignore_overlaps", True) # <<<<<<<<<<<<<< + * self.min_base_quality = kwargs.get("min_base_quality", 13) + * self.iterdata.seq = NULL +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_ignore_overlaps, Py_True); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2480, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2480, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->ignore_overlaps = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":2481 + * self.max_depth = kwargs.get("max_depth", 8000) + * self.ignore_overlaps = kwargs.get("ignore_overlaps", True) + * self.min_base_quality = kwargs.get("min_base_quality", 13) # <<<<<<<<<<<<<< + * self.iterdata.seq = NULL + * self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_min_base_quality, __pyx_mstate_global->__pyx_int_13); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2481, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_4 = __Pyx_PyLong_As_uint32_t(__pyx_t_1); if (unlikely((__pyx_t_4 == ((uint32_t)-1)) && PyErr_Occurred())) __PYX_ERR(0, 2481, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->min_base_quality = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":2482 + * self.ignore_overlaps = kwargs.get("ignore_overlaps", True) + * self.min_base_quality = kwargs.get("min_base_quality", 13) + * self.iterdata.seq = NULL # <<<<<<<<<<<<<< + * self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0) + * self.iterdata.flag_require = kwargs.get("flag_require", 0) +*/ + __pyx_v_self->iterdata.seq = NULL; + + /* "pysam/libcalignmentfile.pyx":2483 + * self.min_base_quality = kwargs.get("min_base_quality", 13) + * self.iterdata.seq = NULL + * self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0) # <<<<<<<<<<<<<< + * self.iterdata.flag_require = kwargs.get("flag_require", 0) + * self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_min_mapping_quality, __pyx_mstate_global->__pyx_int_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2483, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->iterdata.min_mapping_quality = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2484 + * self.iterdata.seq = NULL + * self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0) + * self.iterdata.flag_require = kwargs.get("flag_require", 0) # <<<<<<<<<<<<<< + * self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) + * self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0) +*/ + __pyx_t_1 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_flag_require, __pyx_mstate_global->__pyx_int_0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2484, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2484, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_self->iterdata.flag_require = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2485 + * self.iterdata.min_mapping_quality = kwargs.get("min_mapping_quality", 0) + * self.iterdata.flag_require = kwargs.get("flag_require", 0) + * self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) # <<<<<<<<<<<<<< + * self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0) + * self.iterdata.compute_baq = kwargs.get("compute_baq", True) +*/ + __pyx_t_1 = __Pyx_PyLong_From_int((((BAM_FUNMAP | BAM_FSECONDARY) | BAM_FQCFAIL) | BAM_FDUP)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_flag_filter, __pyx_t_1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2485, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_5); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2485, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->iterdata.flag_filter = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2486 + * self.iterdata.flag_require = kwargs.get("flag_require", 0) + * self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) + * self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0) # <<<<<<<<<<<<<< + * self.iterdata.compute_baq = kwargs.get("compute_baq", True) + * self.iterdata.redo_baq = kwargs.get("redo_baq", False) +*/ + __pyx_t_5 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_adjust_capq_threshold, __pyx_mstate_global->__pyx_int_0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2486, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_5); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2486, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->iterdata.adjust_capq_threshold = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2487 + * self.iterdata.flag_filter = kwargs.get("flag_filter", BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) + * self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0) + * self.iterdata.compute_baq = kwargs.get("compute_baq", True) # <<<<<<<<<<<<<< + * self.iterdata.redo_baq = kwargs.get("redo_baq", False) + * self.iterdata.ignore_orphans = kwargs.get("ignore_orphans", True) +*/ + __pyx_t_5 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_compute_baq, Py_True); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2487, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2487, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->iterdata.compute_baq = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":2488 + * self.iterdata.adjust_capq_threshold = kwargs.get("adjust_capq_threshold", 0) + * self.iterdata.compute_baq = kwargs.get("compute_baq", True) + * self.iterdata.redo_baq = kwargs.get("redo_baq", False) # <<<<<<<<<<<<<< + * self.iterdata.ignore_orphans = kwargs.get("ignore_orphans", True) + * +*/ + __pyx_t_5 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_redo_baq, Py_False); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2488, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2488, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->iterdata.redo_baq = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":2489 + * self.iterdata.compute_baq = kwargs.get("compute_baq", True) + * self.iterdata.redo_baq = kwargs.get("redo_baq", False) + * self.iterdata.ignore_orphans = kwargs.get("ignore_orphans", True) # <<<<<<<<<<<<<< + * + * self.tid = 0 +*/ + __pyx_t_5 = __Pyx_PyDict_GetItemDefault(__pyx_v_kwargs, __pyx_mstate_global->__pyx_n_u_ignore_orphans, Py_True); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2489, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2489, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_v_self->iterdata.ignore_orphans = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":2491 + * self.iterdata.ignore_orphans = kwargs.get("ignore_orphans", True) + * + * self.tid = 0 # <<<<<<<<<<<<<< + * self.pos = 0 + * self.n_plp = 0 +*/ + __pyx_v_self->tid = 0; + + /* "pysam/libcalignmentfile.pyx":2492 + * + * self.tid = 0 + * self.pos = 0 # <<<<<<<<<<<<<< + * self.n_plp = 0 + * self.plp = NULL +*/ + __pyx_v_self->pos = 0; + + /* "pysam/libcalignmentfile.pyx":2493 + * self.tid = 0 + * self.pos = 0 + * self.n_plp = 0 # <<<<<<<<<<<<<< + * self.plp = NULL + * self.pileup_iter = NULL +*/ + __pyx_v_self->n_plp = 0; + + /* "pysam/libcalignmentfile.pyx":2494 + * self.pos = 0 + * self.n_plp = 0 + * self.plp = NULL # <<<<<<<<<<<<<< + * self.pileup_iter = NULL + * +*/ + __pyx_v_self->plp = NULL; + + /* "pysam/libcalignmentfile.pyx":2495 + * self.n_plp = 0 + * self.plp = NULL + * self.pileup_iter = NULL # <<<<<<<<<<<<<< + * + * def __iter__(self): +*/ + __pyx_v_self->pileup_iter = ((bam_mplp_t)NULL); + + /* "pysam/libcalignmentfile.pyx":2475 + * ''' + * + * def __cinit__( self, AlignmentFile samfile, **kwargs): # <<<<<<<<<<<<<< + * self.samfile = samfile + * self.fastafile = kwargs.get("fastafile", None) +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2475, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2475, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2497 + * self.pileup_iter = NULL + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__iter__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_2__iter__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_2__iter__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[119])) + __Pyx_RefNannySetupContext("__iter__", 0); + __Pyx_TraceStartFunc("__iter__", __pyx_f[0], 2497, 0, 0, 0, __PYX_ERR(0, 2497, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2498 + * + * def __iter__(self): + * return self # <<<<<<<<<<<<<< + * + * cdef int cnext(self): +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self); + __pyx_r = ((PyObject *)__pyx_v_self); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2498, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2497 + * self.pileup_iter = NULL + * + * def __iter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2497, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__iter__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2500 + * return self + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''perform next iteration. + * ''' +*/ + +static int __pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_cnext(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + int __pyx_v_ret; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[120])) + __Pyx_TraceStartFunc("cnext", __pyx_f[0], 2500, 0, 0, 0, __PYX_ERR(0, 2500, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2504 + * ''' + * # do not release gil here because of call-backs + * cdef int ret = bam_mplp_auto(self.pileup_iter, # <<<<<<<<<<<<<< + * &self.tid, + * &self.pos, +*/ + __pyx_v_ret = bam_mplp_auto(__pyx_v_self->pileup_iter, (&__pyx_v_self->tid), (&__pyx_v_self->pos), (&__pyx_v_self->n_plp), (&__pyx_v_self->plp)); + + /* "pysam/libcalignmentfile.pyx":2509 + * &self.n_plp, + * &self.plp) + * return ret # <<<<<<<<<<<<<< + * + * cdef char * get_sequence(self): +*/ + __pyx_r = __pyx_v_ret; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_PyLong_From_int, 18, 0, __PYX_ERR(0, 2509, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2500 + * return self + * + * cdef int cnext(self): # <<<<<<<<<<<<<< + * '''perform next iteration. + * ''' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2500, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.cnext", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2511 + * return ret + * + * cdef char * get_sequence(self): # <<<<<<<<<<<<<< + * '''return current reference sequence underlying the iterator. + * ''' +*/ + +static char *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_get_sequence(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + char *__pyx_r; + __Pyx_TraceDeclarationsFunc + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[121])) + __Pyx_TraceStartFunc("get_sequence", __pyx_f[0], 2511, 0, 0, 0, __PYX_ERR(0, 2511, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2514 + * '''return current reference sequence underlying the iterator. + * ''' + * return self.iterdata.seq # <<<<<<<<<<<<<< + * + * property seq_len: +*/ + __pyx_r = __pyx_v_self->iterdata.seq; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2514, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2511 + * return ret + * + * cdef char * get_sequence(self): # <<<<<<<<<<<<<< + * '''return current reference sequence underlying the iterator. + * ''' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2511, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.get_sequence", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2518 + * property seq_len: + * '''current sequence length.''' + * def __get__(self): # <<<<<<<<<<<<<< + * return self.iterdata.seq_len + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len___get__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[122])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2518, 0, 0, 0, __PYX_ERR(0, 2518, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2519 + * '''current sequence length.''' + * def __get__(self): + * return self.iterdata.seq_len # <<<<<<<<<<<<<< + * + * def add_reference(self, FastaFile fastafile): +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->iterdata.seq_len); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2519, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2519, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2518 + * property seq_len: + * '''current sequence length.''' + * def __get__(self): # <<<<<<<<<<<<<< + * return self.iterdata.seq_len + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2518, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.seq_len.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2521 + * return self.iterdata.seq_len + * + * def add_reference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * ''' + * add reference sequences in `fastafile` to iterator.''' +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference, "IteratorColumn.add_reference(self, FastaFile fastafile)\n\nadd reference sequences in `fastafile` to iterator."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference = {"add_reference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("add_reference (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_fastafile,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2521, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2521, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "add_reference", 0) < 0) __PYX_ERR(0, 2521, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("add_reference", 1, 1, 1, i); __PYX_ERR(0, 2521, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2521, __pyx_L3_error) + } + __pyx_v_fastafile = ((struct __pyx_obj_5pysam_9libcfaidx_FastaFile *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("add_reference", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2521, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.add_reference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fastafile), __pyx_mstate_global->__pyx_ptype_5pysam_9libcfaidx_FastaFile, 1, "fastafile", 0))) __PYX_ERR(0, 2521, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_fastafile); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + faidx_t *__pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[123])) + __Pyx_RefNannySetupContext("add_reference", 0); + __Pyx_TraceStartFunc("add_reference", __pyx_f[0], 2521, 0, 0, 0, __PYX_ERR(0, 2521, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2524 + * ''' + * add reference sequences in `fastafile` to iterator.''' + * self.fastafile = fastafile # <<<<<<<<<<<<<< + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) +*/ + __Pyx_INCREF((PyObject *)__pyx_v_fastafile); + __Pyx_GIVEREF((PyObject *)__pyx_v_fastafile); + __Pyx_GOTREF((PyObject *)__pyx_v_self->fastafile); + __Pyx_DECREF((PyObject *)__pyx_v_self->fastafile); + __pyx_v_self->fastafile = __pyx_v_fastafile; + + /* "pysam/libcalignmentfile.pyx":2525 + * add reference sequences in `fastafile` to iterator.''' + * self.fastafile = fastafile + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.tid = -1 +*/ + __pyx_t_1 = (__pyx_v_self->iterdata.seq != NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2526 + * self.fastafile = fastafile + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) # <<<<<<<<<<<<<< + * self.iterdata.tid = -1 + * self.iterdata.fastafile = self.fastafile.fastafile +*/ + free(__pyx_v_self->iterdata.seq); + + /* "pysam/libcalignmentfile.pyx":2525 + * add reference sequences in `fastafile` to iterator.''' + * self.fastafile = fastafile + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.tid = -1 +*/ + } + + /* "pysam/libcalignmentfile.pyx":2527 + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) + * self.iterdata.tid = -1 # <<<<<<<<<<<<<< + * self.iterdata.fastafile = self.fastafile.fastafile + * +*/ + __pyx_v_self->iterdata.tid = -1; + + /* "pysam/libcalignmentfile.pyx":2528 + * free(self.iterdata.seq) + * self.iterdata.tid = -1 + * self.iterdata.fastafile = self.fastafile.fastafile # <<<<<<<<<<<<<< + * + * def has_reference(self): +*/ + __pyx_t_2 = __pyx_v_self->fastafile->fastafile; + __pyx_v_self->iterdata.fastafile = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2521 + * return self.iterdata.seq_len + * + * def add_reference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * ''' + * add reference sequences in `fastafile` to iterator.''' +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2521, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2521, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.add_reference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2530 + * self.iterdata.fastafile = self.fastafile.fastafile + * + * def has_reference(self): # <<<<<<<<<<<<<< + * ''' + * return true if iterator is associated with a reference''' +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference, "IteratorColumn.has_reference(self)\n\nreturn true if iterator is associated with a reference"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference = {"has_reference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("has_reference (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("has_reference", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("has_reference", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[124])) + __Pyx_RefNannySetupContext("has_reference", 0); + __Pyx_TraceStartFunc("has_reference", __pyx_f[0], 2530, 0, 0, 0, __PYX_ERR(0, 2530, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2533 + * ''' + * return true if iterator is associated with a reference''' + * return self.fastafile # <<<<<<<<<<<<<< + * + * cdef _setup_iterator(self, +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF((PyObject *)__pyx_v_self->fastafile); + __pyx_r = ((PyObject *)__pyx_v_self->fastafile); + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2533, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2530 + * self.iterdata.fastafile = self.fastafile.fastafile + * + * def has_reference(self): # <<<<<<<<<<<<<< + * ''' + * return true if iterator is associated with a reference''' +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2530, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.has_reference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2535 + * return self.fastafile + * + * cdef _setup_iterator(self, # <<<<<<<<<<<<<< + * int tid, + * int start, +*/ + +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, int __pyx_v_tid, int __pyx_v_start, int __pyx_v_stop, struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator *__pyx_optional_args) { + int __pyx_v_multiple_iterators = ((int)0); + void *__pyx_v_data[1]; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + size_t __pyx_t_8; + htsFile *__pyx_t_9; + hts_itr_t *__pyx_t_10; + bam_hdr_t *__pyx_t_11; + int __pyx_t_12; + faidx_t *__pyx_t_13; + int __pyx_t_14; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[125])) + __Pyx_RefNannySetupContext("_setup_iterator", 0); + __Pyx_TraceStartFunc("_setup_iterator", __pyx_f[0], 2535, 0, 0, 0, __PYX_ERR(0, 2535, __pyx_L1_error)); + if (__pyx_optional_args) { + if (__pyx_optional_args->__pyx_n > 0) { + __pyx_v_multiple_iterators = __pyx_optional_args->multiple_iterators; + } + } + + /* "pysam/libcalignmentfile.pyx":2542 + * '''setup the iterator structure''' + * + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators) # <<<<<<<<<<<<<< + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.iter = self.iter.iter +*/ + __pyx_t_2 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_tid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2542, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyLong_From_int(__pyx_v_start); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2542, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyLong_From_int(__pyx_v_stop); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2542, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_From_int(__pyx_v_multiple_iterators); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 2542, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[6] = {__pyx_t_2, ((PyObject *)__pyx_v_self->samfile), __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_8, (6-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2542, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_1); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_1); + __Pyx_GOTREF((PyObject *)__pyx_v_self->iter); + __Pyx_DECREF((PyObject *)__pyx_v_self->iter); + __pyx_v_self->iter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2543 + * + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators) + * self.iterdata.htsfile = self.samfile.htsfile # <<<<<<<<<<<<<< + * self.iterdata.iter = self.iter.iter + * self.iterdata.seq = NULL +*/ + __pyx_t_9 = __pyx_v_self->samfile->__pyx_base.htsfile; + __pyx_v_self->iterdata.htsfile = __pyx_t_9; + + /* "pysam/libcalignmentfile.pyx":2544 + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators) + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.iter = self.iter.iter # <<<<<<<<<<<<<< + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 +*/ + __pyx_t_10 = __pyx_v_self->iter->iter; + __pyx_v_self->iterdata.iter = __pyx_t_10; + + /* "pysam/libcalignmentfile.pyx":2545 + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.iter = self.iter.iter + * self.iterdata.seq = NULL # <<<<<<<<<<<<<< + * self.iterdata.tid = -1 + * self.iterdata.header = self.samfile.header.ptr +*/ + __pyx_v_self->iterdata.seq = NULL; + + /* "pysam/libcalignmentfile.pyx":2546 + * self.iterdata.iter = self.iter.iter + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 # <<<<<<<<<<<<<< + * self.iterdata.header = self.samfile.header.ptr + * +*/ + __pyx_v_self->iterdata.tid = -1; + + /* "pysam/libcalignmentfile.pyx":2547 + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 + * self.iterdata.header = self.samfile.header.ptr # <<<<<<<<<<<<<< + * + * if self.fastafile is not None: +*/ + __pyx_t_11 = __pyx_v_self->samfile->header->ptr; + __pyx_v_self->iterdata.header = __pyx_t_11; + + /* "pysam/libcalignmentfile.pyx":2549 + * self.iterdata.header = self.samfile.header.ptr + * + * if self.fastafile is not None: # <<<<<<<<<<<<<< + * self.iterdata.fastafile = self.fastafile.fastafile + * else: +*/ + __pyx_t_12 = (((PyObject *)__pyx_v_self->fastafile) != Py_None); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":2550 + * + * if self.fastafile is not None: + * self.iterdata.fastafile = self.fastafile.fastafile # <<<<<<<<<<<<<< + * else: + * self.iterdata.fastafile = NULL +*/ + __pyx_t_13 = __pyx_v_self->fastafile->fastafile; + __pyx_v_self->iterdata.fastafile = __pyx_t_13; + + /* "pysam/libcalignmentfile.pyx":2549 + * self.iterdata.header = self.samfile.header.ptr + * + * if self.fastafile is not None: # <<<<<<<<<<<<<< + * self.iterdata.fastafile = self.fastafile.fastafile + * else: +*/ + goto __pyx_L3; + } + + /* "pysam/libcalignmentfile.pyx":2552 + * self.iterdata.fastafile = self.fastafile.fastafile + * else: + * self.iterdata.fastafile = NULL # <<<<<<<<<<<<<< + * + * # Free any previously allocated memory before reassigning +*/ + /*else*/ { + __pyx_v_self->iterdata.fastafile = NULL; + } + __pyx_L3:; + + /* "pysam/libcalignmentfile.pyx":2556 + * # Free any previously allocated memory before reassigning + * # pileup_iter + * self._free_pileup_iter() # <<<<<<<<<<<<<< + * + * cdef void * data[1] +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self->__pyx_vtab)->_free_pileup_iter(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2556, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2559 + * + * cdef void * data[1] + * data[0] = &self.iterdata # <<<<<<<<<<<<<< + * + * if self.stepper is None or self.stepper == "all": +*/ + (__pyx_v_data[0]) = ((void *)(&__pyx_v_self->iterdata)); + + /* "pysam/libcalignmentfile.pyx":2561 + * data[0] = &self.iterdata + * + * if self.stepper is None or self.stepper == "all": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_14 = (__pyx_v_self->stepper == Py_None); + if (!__pyx_t_14) { + } else { + __pyx_t_12 = __pyx_t_14; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_14 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_all, Py_EQ)); if (unlikely((__pyx_t_14 < 0))) __PYX_ERR(0, 2561, __pyx_L1_error) + __pyx_t_12 = __pyx_t_14; + __pyx_L5_bool_binop_done:; + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":2562 + * + * if self.stepper is None or self.stepper == "all": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_all, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2563 + * if self.stepper is None or self.stepper == "all": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_all, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_all)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2562 + * + * if self.stepper is None or self.stepper == "all": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_all, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":2561 + * data[0] = &self.iterdata + * + * if self.stepper is None or self.stepper == "all": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2566 + * &__advance_all, + * data) + * elif self.stepper == "nofilter": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_12 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_nofilter, Py_EQ)); if (unlikely((__pyx_t_12 < 0))) __PYX_ERR(0, 2566, __pyx_L1_error) + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":2567 + * data) + * elif self.stepper == "nofilter": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_nofilter, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2568 + * elif self.stepper == "nofilter": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_nofilter, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_nofilter)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2567 + * data) + * elif self.stepper == "nofilter": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_nofilter, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L12; + } + __pyx_L12:; + } + } + + /* "pysam/libcalignmentfile.pyx":2566 + * &__advance_all, + * data) + * elif self.stepper == "nofilter": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2571 + * &__advance_nofilter, + * data) + * elif self.stepper == "samtools": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_12 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_samtools, Py_EQ)); if (unlikely((__pyx_t_12 < 0))) __PYX_ERR(0, 2571, __pyx_L1_error) + if (likely(__pyx_t_12)) { + + /* "pysam/libcalignmentfile.pyx":2572 + * data) + * elif self.stepper == "samtools": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_samtools, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2573 + * elif self.stepper == "samtools": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_samtools, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_samtools)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2572 + * data) + * elif self.stepper == "samtools": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_samtools, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L15; + } + __pyx_L15:; + } + } + + /* "pysam/libcalignmentfile.pyx":2571 + * &__advance_nofilter, + * data) + * elif self.stepper == "samtools": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2577 + * data) + * else: + * raise ValueError( # <<<<<<<<<<<<<< + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * +*/ + /*else*/ { + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_7 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":2578 + * else: + * raise ValueError( + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) # <<<<<<<<<<<<<< + * + * if self.max_depth: +*/ + __pyx_t_6 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_unknown_stepper_option_s_in_Iter, __pyx_v_self->stepper); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2578, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_8, (2-__pyx_t_8) | (__pyx_t_8*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2577, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 2577, __pyx_L1_error) + } + __pyx_L4:; + + /* "pysam/libcalignmentfile.pyx":2580 + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * + * if self.max_depth: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) +*/ + __pyx_t_12 = (__pyx_v_self->max_depth != 0); + if (__pyx_t_12) { + + /* "pysam/libcalignmentfile.pyx":2581 + * + * if self.max_depth: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2582 + * if self.max_depth: + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) # <<<<<<<<<<<<<< + * + * if self.ignore_overlaps: +*/ + bam_mplp_set_maxcnt(__pyx_v_self->pileup_iter, __pyx_v_self->max_depth); + } + + /* "pysam/libcalignmentfile.pyx":2581 + * + * if self.max_depth: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L19; + } + __pyx_L19:; + } + } + + /* "pysam/libcalignmentfile.pyx":2580 + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * + * if self.max_depth: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2584 + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * + * if self.ignore_overlaps: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) +*/ + if (__pyx_v_self->ignore_overlaps) { + + /* "pysam/libcalignmentfile.pyx":2585 + * + * if self.ignore_overlaps: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_init_overlaps(self.pileup_iter) + * +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2586 + * if self.ignore_overlaps: + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) # <<<<<<<<<<<<<< + * + * cdef _setup_raw_rest_iterator(self): +*/ + bam_mplp_init_overlaps(__pyx_v_self->pileup_iter); + } + + /* "pysam/libcalignmentfile.pyx":2585 + * + * if self.ignore_overlaps: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_init_overlaps(self.pileup_iter) + * +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L23; + } + __pyx_L23:; + } + } + + /* "pysam/libcalignmentfile.pyx":2584 + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * + * if self.ignore_overlaps: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2535 + * return self.fastafile + * + * cdef _setup_iterator(self, # <<<<<<<<<<<<<< + * int tid, + * int start, +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2535, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2535, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn._setup_iterator", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2588 + * bam_mplp_init_overlaps(self.pileup_iter) + * + * cdef _setup_raw_rest_iterator(self): # <<<<<<<<<<<<<< + * '''set up an "iterator" that just uses sam_read1(), similar to HTS_IDX_REST''' + * +*/ + +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_raw_rest_iterator(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + void *__pyx_v_data[1]; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + htsFile *__pyx_t_1; + bam_hdr_t *__pyx_t_2; + int __pyx_t_3; + faidx_t *__pyx_t_4; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[126])) + __Pyx_RefNannySetupContext("_setup_raw_rest_iterator", 0); + __Pyx_TraceStartFunc("_setup_raw_rest_iterator", __pyx_f[0], 2588, 0, 0, 0, __PYX_ERR(0, 2588, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2591 + * '''set up an "iterator" that just uses sam_read1(), similar to HTS_IDX_REST''' + * + * self.iter = None # <<<<<<<<<<<<<< + * self.iterdata.iter = NULL + * self.iterdata.htsfile = self.samfile.htsfile +*/ + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + __Pyx_GOTREF((PyObject *)__pyx_v_self->iter); + __Pyx_DECREF((PyObject *)__pyx_v_self->iter); + __pyx_v_self->iter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)Py_None); + + /* "pysam/libcalignmentfile.pyx":2592 + * + * self.iter = None + * self.iterdata.iter = NULL # <<<<<<<<<<<<<< + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.seq = NULL +*/ + __pyx_v_self->iterdata.iter = NULL; + + /* "pysam/libcalignmentfile.pyx":2593 + * self.iter = None + * self.iterdata.iter = NULL + * self.iterdata.htsfile = self.samfile.htsfile # <<<<<<<<<<<<<< + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 +*/ + __pyx_t_1 = __pyx_v_self->samfile->__pyx_base.htsfile; + __pyx_v_self->iterdata.htsfile = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2594 + * self.iterdata.iter = NULL + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.seq = NULL # <<<<<<<<<<<<<< + * self.iterdata.tid = -1 + * self.iterdata.header = self.samfile.header.ptr +*/ + __pyx_v_self->iterdata.seq = NULL; + + /* "pysam/libcalignmentfile.pyx":2595 + * self.iterdata.htsfile = self.samfile.htsfile + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 # <<<<<<<<<<<<<< + * self.iterdata.header = self.samfile.header.ptr + * +*/ + __pyx_v_self->iterdata.tid = -1; + + /* "pysam/libcalignmentfile.pyx":2596 + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 + * self.iterdata.header = self.samfile.header.ptr # <<<<<<<<<<<<<< + * + * if self.fastafile is not None: +*/ + __pyx_t_2 = __pyx_v_self->samfile->header->ptr; + __pyx_v_self->iterdata.header = __pyx_t_2; + + /* "pysam/libcalignmentfile.pyx":2598 + * self.iterdata.header = self.samfile.header.ptr + * + * if self.fastafile is not None: # <<<<<<<<<<<<<< + * self.iterdata.fastafile = self.fastafile.fastafile + * else: +*/ + __pyx_t_3 = (((PyObject *)__pyx_v_self->fastafile) != Py_None); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2599 + * + * if self.fastafile is not None: + * self.iterdata.fastafile = self.fastafile.fastafile # <<<<<<<<<<<<<< + * else: + * self.iterdata.fastafile = NULL +*/ + __pyx_t_4 = __pyx_v_self->fastafile->fastafile; + __pyx_v_self->iterdata.fastafile = __pyx_t_4; + + /* "pysam/libcalignmentfile.pyx":2598 + * self.iterdata.header = self.samfile.header.ptr + * + * if self.fastafile is not None: # <<<<<<<<<<<<<< + * self.iterdata.fastafile = self.fastafile.fastafile + * else: +*/ + goto __pyx_L3; + } + + /* "pysam/libcalignmentfile.pyx":2601 + * self.iterdata.fastafile = self.fastafile.fastafile + * else: + * self.iterdata.fastafile = NULL # <<<<<<<<<<<<<< + * + * # Free any previously allocated memory before reassigning +*/ + /*else*/ { + __pyx_v_self->iterdata.fastafile = NULL; + } + __pyx_L3:; + + /* "pysam/libcalignmentfile.pyx":2605 + * # Free any previously allocated memory before reassigning + * # pileup_iter + * self._free_pileup_iter() # <<<<<<<<<<<<<< + * + * cdef void * data[1] +*/ + __pyx_t_5 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self->__pyx_vtab)->_free_pileup_iter(__pyx_v_self); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2605, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":2608 + * + * cdef void * data[1] + * data[0] = &self.iterdata # <<<<<<<<<<<<<< + * + * if self.stepper is None or self.stepper == "all": +*/ + (__pyx_v_data[0]) = ((void *)(&__pyx_v_self->iterdata)); + + /* "pysam/libcalignmentfile.pyx":2610 + * data[0] = &self.iterdata + * + * if self.stepper is None or self.stepper == "all": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_6 = (__pyx_v_self->stepper == Py_None); + if (!__pyx_t_6) { + } else { + __pyx_t_3 = __pyx_t_6; + goto __pyx_L5_bool_binop_done; + } + __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_all, Py_EQ)); if (unlikely((__pyx_t_6 < 0))) __PYX_ERR(0, 2610, __pyx_L1_error) + __pyx_t_3 = __pyx_t_6; + __pyx_L5_bool_binop_done:; + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2611 + * + * if self.stepper is None or self.stepper == "all": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_raw_all, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2612 + * if self.stepper is None or self.stepper == "all": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_raw_all, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_raw_all)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2611 + * + * if self.stepper is None or self.stepper == "all": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_raw_all, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L9; + } + __pyx_L9:; + } + } + + /* "pysam/libcalignmentfile.pyx":2610 + * data[0] = &self.iterdata + * + * if self.stepper is None or self.stepper == "all": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2615 + * &__advance_raw_all, + * data) + * elif self.stepper == "nofilter": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_nofilter, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 2615, __pyx_L1_error) + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2616 + * data) + * elif self.stepper == "nofilter": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_raw_nofilter, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2617 + * elif self.stepper == "nofilter": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_raw_nofilter, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_raw_nofilter)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2616 + * data) + * elif self.stepper == "nofilter": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_raw_nofilter, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L12; + } + __pyx_L12:; + } + } + + /* "pysam/libcalignmentfile.pyx":2615 + * &__advance_raw_all, + * data) + * elif self.stepper == "nofilter": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2620 + * &__advance_raw_nofilter, + * data) + * elif self.stepper == "samtools": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + __pyx_t_3 = (__Pyx_PyUnicode_Equals(__pyx_v_self->stepper, __pyx_mstate_global->__pyx_n_u_samtools, Py_EQ)); if (unlikely((__pyx_t_3 < 0))) __PYX_ERR(0, 2620, __pyx_L1_error) + if (likely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2621 + * data) + * elif self.stepper == "samtools": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_samtools, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2622 + * elif self.stepper == "samtools": + * with nogil: + * self.pileup_iter = bam_mplp_init(1, # <<<<<<<<<<<<<< + * &__advance_samtools, + * data) +*/ + __pyx_v_self->pileup_iter = bam_mplp_init(1, ((bam_plp_auto_f)(&__pyx_f_5pysam_17libcalignmentfile___advance_samtools)), __pyx_v_data); + } + + /* "pysam/libcalignmentfile.pyx":2621 + * data) + * elif self.stepper == "samtools": + * with nogil: # <<<<<<<<<<<<<< + * self.pileup_iter = bam_mplp_init(1, + * &__advance_samtools, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L15; + } + __pyx_L15:; + } + } + + /* "pysam/libcalignmentfile.pyx":2620 + * &__advance_raw_nofilter, + * data) + * elif self.stepper == "samtools": # <<<<<<<<<<<<<< + * with nogil: + * self.pileup_iter = bam_mplp_init(1, +*/ + goto __pyx_L4; + } + + /* "pysam/libcalignmentfile.pyx":2626 + * data) + * else: + * raise ValueError( # <<<<<<<<<<<<<< + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * +*/ + /*else*/ { + __pyx_t_7 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_8 = __pyx_builtin_ValueError; + + /* "pysam/libcalignmentfile.pyx":2627 + * else: + * raise ValueError( + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) # <<<<<<<<<<<<<< + * + * if self.max_depth: +*/ + __pyx_t_9 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_unknown_stepper_option_s_in_Iter, __pyx_v_self->stepper); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 2627, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_5 = __Pyx_PyObject_FastCall(__pyx_t_8, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (__pyx_t_10*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2626, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + } + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(0, 2626, __pyx_L1_error) + } + __pyx_L4:; + + /* "pysam/libcalignmentfile.pyx":2629 + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * + * if self.max_depth: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) +*/ + __pyx_t_3 = (__pyx_v_self->max_depth != 0); + if (__pyx_t_3) { + + /* "pysam/libcalignmentfile.pyx":2630 + * + * if self.max_depth: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2631 + * if self.max_depth: + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) # <<<<<<<<<<<<<< + * + * if self.ignore_overlaps: +*/ + bam_mplp_set_maxcnt(__pyx_v_self->pileup_iter, __pyx_v_self->max_depth); + } + + /* "pysam/libcalignmentfile.pyx":2630 + * + * if self.max_depth: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L19; + } + __pyx_L19:; + } + } + + /* "pysam/libcalignmentfile.pyx":2629 + * "unknown stepper option `%s` in IteratorColumn" % self.stepper) + * + * if self.max_depth: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2633 + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * + * if self.ignore_overlaps: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) +*/ + if (__pyx_v_self->ignore_overlaps) { + + /* "pysam/libcalignmentfile.pyx":2634 + * + * if self.ignore_overlaps: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_init_overlaps(self.pileup_iter) + * +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2635 + * if self.ignore_overlaps: + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) # <<<<<<<<<<<<<< + * + * cdef reset(self, tid, start, stop): +*/ + bam_mplp_init_overlaps(__pyx_v_self->pileup_iter); + } + + /* "pysam/libcalignmentfile.pyx":2634 + * + * if self.ignore_overlaps: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_init_overlaps(self.pileup_iter) + * +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L23; + } + __pyx_L23:; + } + } + + /* "pysam/libcalignmentfile.pyx":2633 + * bam_mplp_set_maxcnt(self.pileup_iter, self.max_depth) + * + * if self.ignore_overlaps: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_init_overlaps(self.pileup_iter) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2588 + * bam_mplp_init_overlaps(self.pileup_iter) + * + * cdef _setup_raw_rest_iterator(self): # <<<<<<<<<<<<<< + * '''set up an "iterator" that just uses sam_read1(), similar to HTS_IDX_REST''' + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2588, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2588, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn._setup_raw_rest_iterator", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2637 + * bam_mplp_init_overlaps(self.pileup_iter) + * + * cdef reset(self, tid, start, stop): # <<<<<<<<<<<<<< + * '''reset iterator position. + * +*/ + +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_reset(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, PyObject *__pyx_v_tid, PyObject *__pyx_v_start, PyObject *__pyx_v_stop) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + hts_itr_t *__pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[127])) + __Pyx_RefNannySetupContext("reset", 0); + __Pyx_TraceStartFunc("reset", __pyx_f[0], 2637, 0, 0, 0, __PYX_ERR(0, 2637, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2643 + * having to incur the full set-up costs. + * ''' + * if self.iter is None: # <<<<<<<<<<<<<< + * raise TypeError("Raw iterator set up without region cannot be reset") + * +*/ + __pyx_t_1 = (((PyObject *)__pyx_v_self->iter) == Py_None); + if (unlikely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2644 + * ''' + * if self.iter is None: + * raise TypeError("Raw iterator set up without region cannot be reset") # <<<<<<<<<<<<<< + * + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators=0) +*/ + __pyx_t_3 = NULL; + __Pyx_INCREF(__pyx_builtin_TypeError); + __pyx_t_4 = __pyx_builtin_TypeError; + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_mstate_global->__pyx_kp_u_Raw_iterator_set_up_without_regi}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2644, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 2644, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2643 + * having to incur the full set-up costs. + * ''' + * if self.iter is None: # <<<<<<<<<<<<<< + * raise TypeError("Raw iterator set up without region cannot be reset") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2646 + * raise TypeError("Raw iterator set up without region cannot be reset") + * + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators=0) # <<<<<<<<<<<<<< + * self.iterdata.iter = self.iter.iter + * +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion); + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[5 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_4, ((PyObject *)__pyx_v_self->samfile), __pyx_v_tid, __pyx_v_start, __pyx_v_stop}; + __pyx_t_6 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2646, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, __pyx_mstate_global->__pyx_int_0, __pyx_t_6, __pyx_callargs+5, 0) < 0) __PYX_ERR(0, 2646, __pyx_L1_error) + __pyx_t_2 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_3, __pyx_callargs+__pyx_t_5, (5-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_6); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2646, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_2); + } + __Pyx_GIVEREF((PyObject *)__pyx_t_2); + __Pyx_GOTREF((PyObject *)__pyx_v_self->iter); + __Pyx_DECREF((PyObject *)__pyx_v_self->iter); + __pyx_v_self->iter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)__pyx_t_2); + __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2647 + * + * self.iter = IteratorRowRegion(self.samfile, tid, start, stop, multiple_iterators=0) + * self.iterdata.iter = self.iter.iter # <<<<<<<<<<<<<< + * + * # invalidate sequence if different tid +*/ + __pyx_t_7 = __pyx_v_self->iter->iter; + __pyx_v_self->iterdata.iter = __pyx_t_7; + + /* "pysam/libcalignmentfile.pyx":2650 + * + * # invalidate sequence if different tid + * if self.tid != tid: # <<<<<<<<<<<<<< + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) +*/ + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_self->tid); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2650, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyObject_RichCompare(__pyx_t_2, __pyx_v_tid, Py_NE); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2650, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 2650, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2651 + * # invalidate sequence if different tid + * if self.tid != tid: + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.seq = NULL +*/ + __pyx_t_1 = (__pyx_v_self->iterdata.seq != NULL); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2652 + * if self.tid != tid: + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) # <<<<<<<<<<<<<< + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 +*/ + free(__pyx_v_self->iterdata.seq); + + /* "pysam/libcalignmentfile.pyx":2651 + * # invalidate sequence if different tid + * if self.tid != tid: + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.seq = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":2653 + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) + * self.iterdata.seq = NULL # <<<<<<<<<<<<<< + * self.iterdata.tid = -1 + * +*/ + __pyx_v_self->iterdata.seq = NULL; + + /* "pysam/libcalignmentfile.pyx":2654 + * free(self.iterdata.seq) + * self.iterdata.seq = NULL + * self.iterdata.tid = -1 # <<<<<<<<<<<<<< + * + * # self.pileup_iter = bam_mplp_init(1 +*/ + __pyx_v_self->iterdata.tid = -1; + + /* "pysam/libcalignmentfile.pyx":2650 + * + * # invalidate sequence if different tid + * if self.tid != tid: # <<<<<<<<<<<<<< + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2659 + * # &__advancepileup, + * # &self.iterdata) + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_reset(self.pileup_iter) + * +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2660 + * # &self.iterdata) + * with nogil: + * bam_mplp_reset(self.pileup_iter) # <<<<<<<<<<<<<< + * + * cdef _free_pileup_iter(self): +*/ + bam_mplp_reset(__pyx_v_self->pileup_iter); + } + + /* "pysam/libcalignmentfile.pyx":2659 + * # &__advancepileup, + * # &self.iterdata) + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_reset(self.pileup_iter) + * +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L8; + } + __pyx_L8:; + } + } + + /* "pysam/libcalignmentfile.pyx":2637 + * bam_mplp_init_overlaps(self.pileup_iter) + * + * cdef reset(self, tid, start, stop): # <<<<<<<<<<<<<< + * '''reset iterator position. + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2637, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2637, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.reset", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2662 + * bam_mplp_reset(self.pileup_iter) + * + * cdef _free_pileup_iter(self): # <<<<<<<<<<<<<< + * '''free the memory alloc'd by bam_plp_init. + * +*/ + +static PyObject *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__free_pileup_iter(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[128])) + __Pyx_RefNannySetupContext("_free_pileup_iter", 0); + __Pyx_TraceStartFunc("_free_pileup_iter", __pyx_f[0], 2662, 0, 0, 0, __PYX_ERR(0, 2662, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2667 + * This is needed before setup_iterator allocates another + * pileup_iter, or else memory will be lost. ''' + * if self.pileup_iter != NULL: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_reset(self.pileup_iter) +*/ + __pyx_t_1 = (__pyx_v_self->pileup_iter != ((bam_mplp_t)NULL)); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2668 + * pileup_iter, or else memory will be lost. ''' + * if self.pileup_iter != NULL: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_reset(self.pileup_iter) + * bam_mplp_destroy(self.pileup_iter) +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2669 + * if self.pileup_iter != NULL: + * with nogil: + * bam_mplp_reset(self.pileup_iter) # <<<<<<<<<<<<<< + * bam_mplp_destroy(self.pileup_iter) + * self.pileup_iter = NULL +*/ + bam_mplp_reset(__pyx_v_self->pileup_iter); + + /* "pysam/libcalignmentfile.pyx":2670 + * with nogil: + * bam_mplp_reset(self.pileup_iter) + * bam_mplp_destroy(self.pileup_iter) # <<<<<<<<<<<<<< + * self.pileup_iter = NULL + * +*/ + bam_mplp_destroy(__pyx_v_self->pileup_iter); + + /* "pysam/libcalignmentfile.pyx":2671 + * bam_mplp_reset(self.pileup_iter) + * bam_mplp_destroy(self.pileup_iter) + * self.pileup_iter = NULL # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + __pyx_v_self->pileup_iter = ((bam_mplp_t)NULL); + } + + /* "pysam/libcalignmentfile.pyx":2668 + * pileup_iter, or else memory will be lost. ''' + * if self.pileup_iter != NULL: + * with nogil: # <<<<<<<<<<<<<< + * bam_mplp_reset(self.pileup_iter) + * bam_mplp_destroy(self.pileup_iter) +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L6; + } + __pyx_L6:; + } + } + + /* "pysam/libcalignmentfile.pyx":2667 + * This is needed before setup_iterator allocates another + * pileup_iter, or else memory will be lost. ''' + * if self.pileup_iter != NULL: # <<<<<<<<<<<<<< + * with nogil: + * bam_mplp_reset(self.pileup_iter) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2662 + * bam_mplp_reset(self.pileup_iter) + * + * cdef _free_pileup_iter(self): # <<<<<<<<<<<<<< + * '''free the memory alloc'd by bam_plp_init. + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2662, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2662, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn._free_pileup_iter", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2673 + * self.pileup_iter = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * # reset in order to avoid memory leak messages for iterators + * # that have not been fully consumed +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_9__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_9__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_8__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_8__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[129])) + __Pyx_RefNannySetupContext("__dealloc__", 0); + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 2673, 0, 0, 0, __PYX_ERR(0, 2673, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2676 + * # reset in order to avoid memory leak messages for iterators + * # that have not been fully consumed + * self._free_pileup_iter() # <<<<<<<<<<<<<< + * self.plp = NULL + * +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self->__pyx_vtab)->_free_pileup_iter(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2676, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2677 + * # that have not been fully consumed + * self._free_pileup_iter() + * self.plp = NULL # <<<<<<<<<<<<<< + * + * if self.iterdata.seq != NULL: +*/ + __pyx_v_self->plp = ((bam_pileup1_t const *)NULL); + + /* "pysam/libcalignmentfile.pyx":2679 + * self.plp = NULL + * + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.seq = NULL +*/ + __pyx_t_2 = (__pyx_v_self->iterdata.seq != NULL); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2680 + * + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) # <<<<<<<<<<<<<< + * self.iterdata.seq = NULL + * +*/ + free(__pyx_v_self->iterdata.seq); + + /* "pysam/libcalignmentfile.pyx":2681 + * if self.iterdata.seq != NULL: + * free(self.iterdata.seq) + * self.iterdata.seq = NULL # <<<<<<<<<<<<<< + * + * # backwards compatibility +*/ + __pyx_v_self->iterdata.seq = NULL; + + /* "pysam/libcalignmentfile.pyx":2679 + * self.plp = NULL + * + * if self.iterdata.seq != NULL: # <<<<<<<<<<<<<< + * free(self.iterdata.seq) + * self.iterdata.seq = NULL +*/ + } + + /* "pysam/libcalignmentfile.pyx":2673 + * self.pileup_iter = NULL + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * # reset in order to avoid memory leak messages for iterators + * # that have not been fully consumed +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 2673, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2673, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.IteratorColumn.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); +} + +/* "pysam/libcalignmentfile.pyx":2685 + * # backwards compatibility + * + * def hasReference(self): # <<<<<<<<<<<<<< + * return self.has_reference() + * cdef char * getSequence(self): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference, "IteratorColumn.hasReference(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference = {"hasReference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("hasReference (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("hasReference", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("hasReference", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[130])) + __Pyx_RefNannySetupContext("hasReference", 0); + __Pyx_TraceStartFunc("hasReference", __pyx_f[0], 2685, 0, 0, 0, __PYX_ERR(0, 2685, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2686 + * + * def hasReference(self): + * return self.has_reference() # <<<<<<<<<<<<<< + * cdef char * getSequence(self): + * return self.get_sequence() +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, NULL}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_has_reference, __pyx_callargs+__pyx_t_3, (1-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2686, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2686, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2685 + * # backwards compatibility + * + * def hasReference(self): # <<<<<<<<<<<<<< + * return self.has_reference() + * cdef char * getSequence(self): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2685, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.hasReference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2687 + * def hasReference(self): + * return self.has_reference() + * cdef char * getSequence(self): # <<<<<<<<<<<<<< + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): +*/ + +static char *__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_getSequence(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + char *__pyx_r; + __Pyx_TraceDeclarationsFunc + char *__pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[131])) + __Pyx_TraceStartFunc("getSequence", __pyx_f[0], 2687, 0, 0, 0, __PYX_ERR(0, 2687, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2688 + * return self.has_reference() + * cdef char * getSequence(self): + * return self.get_sequence() # <<<<<<<<<<<<<< + * def addReference(self, FastaFile fastafile): + * return self.add_reference(fastafile) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self->__pyx_vtab)->get_sequence(__pyx_v_self); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2688, __pyx_L1_error) + __pyx_r = __pyx_t_1; + __Pyx_TraceReturnValue(Py_None, 1, 0, __PYX_ERR(0, 2688, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2687 + * def hasReference(self): + * return self.has_reference() + * cdef char * getSequence(self): # <<<<<<<<<<<<<< + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2687, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.getSequence", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2689 + * cdef char * getSequence(self): + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * return self.add_reference(fastafile) + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_13addReference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_12addReference, "IteratorColumn.addReference(self, FastaFile fastafile)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_13addReference = {"addReference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_13addReference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_12addReference}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_13addReference(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("addReference (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_fastafile,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2689, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2689, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "addReference", 0) < 0) __PYX_ERR(0, 2689, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("addReference", 1, 1, 1, i); __PYX_ERR(0, 2689, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2689, __pyx_L3_error) + } + __pyx_v_fastafile = ((struct __pyx_obj_5pysam_9libcfaidx_FastaFile *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("addReference", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2689, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.addReference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_fastafile), __pyx_mstate_global->__pyx_ptype_5pysam_9libcfaidx_FastaFile, 1, "fastafile", 0))) __PYX_ERR(0, 2689, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_12addReference(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_fastafile); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = NULL; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_12addReference(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, struct __pyx_obj_5pysam_9libcfaidx_FastaFile *__pyx_v_fastafile) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + size_t __pyx_t_3; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[132])) + __Pyx_RefNannySetupContext("addReference", 0); + __Pyx_TraceStartFunc("addReference", __pyx_f[0], 2689, 0, 0, 0, __PYX_ERR(0, 2689, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2690 + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): + * return self.add_reference(fastafile) # <<<<<<<<<<<<<< + * + * +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = ((PyObject *)__pyx_v_self); + __Pyx_INCREF(__pyx_t_2); + __pyx_t_3 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, ((PyObject *)__pyx_v_fastafile)}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_add_reference, __pyx_callargs+__pyx_t_3, (2-__pyx_t_3) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2690, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2690, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2689 + * cdef char * getSequence(self): + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * return self.add_reference(fastafile) + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2689, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.addReference", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__, "IteratorColumn.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[133])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__, "IteratorColumn.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[134])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumn.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2696 + * '''iterates over a region only. + * ''' + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int tid = 0, +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_tid; + int __pyx_v_start; + int __pyx_v_stop; + int __pyx_v_truncate; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[6] = {0,0,0,0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_tid,&__pyx_mstate_global->__pyx_n_u_start,&__pyx_mstate_global->__pyx_n_u_stop,&__pyx_mstate_global->__pyx_n_u_truncate,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2696, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 6: + values[5] = __Pyx_ArgRef_VARARGS(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, __pyx_v_kwargs, values, kwd_pos_args, __pyx_kwds_len, "__cinit__", 1) < 0) __PYX_ERR(0, 2696, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 1, 6, i); __PYX_ERR(0, 2696, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 6: + values[5] = __Pyx_ArgRef_VARARGS(__pyx_args, 5); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[5])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 5: + values[4] = __Pyx_ArgRef_VARARGS(__pyx_args, 4); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[4])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 4: + values[3] = __Pyx_ArgRef_VARARGS(__pyx_args, 3); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[3])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 3: + values[2] = __Pyx_ArgRef_VARARGS(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2696, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2696, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + if (values[1]) { + __pyx_v_tid = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_tid == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2698, __pyx_L3_error) + } else { + __pyx_v_tid = ((int)0); + } + if (values[2]) { + __pyx_v_start = __Pyx_PyLong_As_int(values[2]); if (unlikely((__pyx_v_start == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2699, __pyx_L3_error) + } else { + __pyx_v_start = ((int)0); + } + if (values[3]) { + __pyx_v_stop = __Pyx_PyLong_As_int(values[3]); if (unlikely((__pyx_v_stop == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2700, __pyx_L3_error) + } else { + __pyx_v_stop = __pyx_mstate_global->__pyx_k__10; + } + if (values[4]) { + __pyx_v_truncate = __Pyx_PyLong_As_int(values[4]); if (unlikely((__pyx_v_truncate == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2701, __pyx_L3_error) + } else { + + /* "pysam/libcalignmentfile.pyx":2701 + * int start = 0, + * int stop = MAX_POS, + * int truncate = False, # <<<<<<<<<<<<<< + * int multiple_iterators = True, + * **kwargs ): +*/ + __pyx_v_truncate = ((int)0); + } + if (values[5]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[5]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2702, __pyx_L3_error) + } else { + + /* "pysam/libcalignmentfile.pyx":2702 + * int stop = MAX_POS, + * int truncate = False, + * int multiple_iterators = True, # <<<<<<<<<<<<<< + * **kwargs ): + * +*/ + __pyx_v_multiple_iterators = ((int)1); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 1, 6, __pyx_nargs); __PYX_ERR(0, 2696, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_XDECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2697, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self), __pyx_v_samfile, __pyx_v_tid, __pyx_v_start, __pyx_v_stop, __pyx_v_truncate, __pyx_v_multiple_iterators, __pyx_v_kwargs); + + /* "pysam/libcalignmentfile.pyx":2696 + * '''iterates over a region only. + * ''' + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int tid = 0, +*/ + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_tid, int __pyx_v_start, int __pyx_v_stop, int __pyx_v_truncate, int __pyx_v_multiple_iterators, CYTHON_UNUSED PyObject *__pyx_v_kwargs) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator __pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[135])) + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 2696, 0, 0, 0, __PYX_ERR(0, 2696, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2707 + * # initialize iterator. Multiple iterators not available + * # for CRAM. + * if multiple_iterators and samfile.is_cram: # <<<<<<<<<<<<<< + * warnings.warn("multiple_iterators not implemented for CRAM") + * multiple_iterators = False +*/ + __pyx_t_2 = (__pyx_v_multiple_iterators != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_n_u_is_cram); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2707, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2707, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = __pyx_t_2; + __pyx_L4_bool_binop_done:; + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2708 + * # for CRAM. + * if multiple_iterators and samfile.is_cram: + * warnings.warn("multiple_iterators not implemented for CRAM") # <<<<<<<<<<<<<< + * multiple_iterators = False + * +*/ + __pyx_t_4 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_warnings); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2708, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_warn); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2708, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_7 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_6))) { + __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_6); + assert(__pyx_t_4); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_6); + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_6, __pyx__function); + __pyx_t_7 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_multiple_iterators_not_implement_2}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2708, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":2709 + * if multiple_iterators and samfile.is_cram: + * warnings.warn("multiple_iterators not implemented for CRAM") + * multiple_iterators = False # <<<<<<<<<<<<<< + * + * self._setup_iterator(tid, start, stop, multiple_iterators) +*/ + __pyx_v_multiple_iterators = 0; + + /* "pysam/libcalignmentfile.pyx":2707 + * # initialize iterator. Multiple iterators not available + * # for CRAM. + * if multiple_iterators and samfile.is_cram: # <<<<<<<<<<<<<< + * warnings.warn("multiple_iterators not implemented for CRAM") + * multiple_iterators = False +*/ + } + + /* "pysam/libcalignmentfile.pyx":2711 + * multiple_iterators = False + * + * self._setup_iterator(tid, start, stop, multiple_iterators) # <<<<<<<<<<<<<< + * self.start = start + * self.stop = stop +*/ + __pyx_t_8.__pyx_n = 1; + __pyx_t_8.multiple_iterators = __pyx_v_multiple_iterators; + __pyx_t_3 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._setup_iterator(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_tid, __pyx_v_start, __pyx_v_stop, &__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2711, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "pysam/libcalignmentfile.pyx":2712 + * + * self._setup_iterator(tid, start, stop, multiple_iterators) + * self.start = start # <<<<<<<<<<<<<< + * self.stop = stop + * self.truncate = truncate +*/ + __pyx_v_self->start = __pyx_v_start; + + /* "pysam/libcalignmentfile.pyx":2713 + * self._setup_iterator(tid, start, stop, multiple_iterators) + * self.start = start + * self.stop = stop # <<<<<<<<<<<<<< + * self.truncate = truncate + * +*/ + __pyx_v_self->stop = __pyx_v_stop; + + /* "pysam/libcalignmentfile.pyx":2714 + * self.start = start + * self.stop = stop + * self.truncate = truncate # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_v_self->truncate = __pyx_v_truncate; + + /* "pysam/libcalignmentfile.pyx":2696 + * '''iterates over a region only. + * ''' + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * int tid = 0, +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2696, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2696, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2716 + * self.truncate = truncate + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_2__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self) { + int __pyx_v_n; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[136])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2716, 0, 0, 0, __PYX_ERR(0, 2716, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2720 + * cdef int n + * + * while 1: # <<<<<<<<<<<<<< + * n = self.cnext() + * if n < 0: +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2721 + * + * while 1: + * n = self.cnext() # <<<<<<<<<<<<<< + * if n < 0: + * raise ValueError("error during iteration" ) +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.cnext(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2721, __pyx_L1_error) + __pyx_v_n = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2722 + * while 1: + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration" ) + * +*/ + __pyx_t_2 = (__pyx_v_n < 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2723 + * n = self.cnext() + * if n < 0: + * raise ValueError("error during iteration" ) # <<<<<<<<<<<<<< + * + * if n == 0: +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_error_during_iteration}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2723, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 2723, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2722 + * while 1: + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration" ) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2725 + * raise ValueError("error during iteration" ) + * + * if n == 0: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + __pyx_t_2 = (__pyx_v_n == 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2726 + * + * if n == 0: + * raise StopIteration # <<<<<<<<<<<<<< + * + * if self.truncate: +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2725 + * raise ValueError("error during iteration" ) + * + * if n == 0: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2728 + * raise StopIteration + * + * if self.truncate: # <<<<<<<<<<<<<< + * if self.start > self.pos: + * continue +*/ + __pyx_t_2 = (__pyx_v_self->truncate != 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2729 + * + * if self.truncate: + * if self.start > self.pos: # <<<<<<<<<<<<<< + * continue + * if self.pos >= self.stop: +*/ + __pyx_t_2 = (__pyx_v_self->start > __pyx_v_self->__pyx_base.pos); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2730 + * if self.truncate: + * if self.start > self.pos: + * continue # <<<<<<<<<<<<<< + * if self.pos >= self.stop: + * raise StopIteration +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2729 + * + * if self.truncate: + * if self.start > self.pos: # <<<<<<<<<<<<<< + * continue + * if self.pos >= self.stop: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2731 + * if self.start > self.pos: + * continue + * if self.pos >= self.stop: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + __pyx_t_2 = (__pyx_v_self->__pyx_base.pos >= __pyx_v_self->stop); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2732 + * continue + * if self.pos >= self.stop: + * raise StopIteration # <<<<<<<<<<<<<< + * + * return makePileupColumn(&self.plp, +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2731 + * if self.start > self.pos: + * continue + * if self.pos >= self.stop: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2728 + * raise StopIteration + * + * if self.truncate: # <<<<<<<<<<<<<< + * if self.start > self.pos: + * continue +*/ + } + + /* "pysam/libcalignmentfile.pyx":2734 + * raise StopIteration + * + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __Pyx_XDECREF(__pyx_r); + + /* "pysam/libcalignmentfile.pyx":2740 + * self.min_base_quality, + * self.iterdata.seq, + * self.samfile.header) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.samfile->header); + __Pyx_INCREF(__pyx_t_3); + + /* "pysam/libcalignmentfile.pyx":2734 + * raise StopIteration + * + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __pyx_t_5 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makePileupColumn((&__pyx_v_self->__pyx_base.plp), __pyx_v_self->__pyx_base.tid, __pyx_v_self->__pyx_base.pos, __pyx_v_self->__pyx_base.n_plp, __pyx_v_self->__pyx_base.min_base_quality, __pyx_v_self->__pyx_base.iterdata.seq, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2734, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + __Pyx_TraceReturnValue(__pyx_r, 36, 0, __PYX_ERR(0, 2734, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L3_continue:; + } + + /* "pysam/libcalignmentfile.pyx":2716 + * self.truncate = truncate + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2716, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2716, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__, "IteratorColumnRegion.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[137])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__, "IteratorColumnRegion.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[138])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnRegion.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2747 + * """ + * + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * **kwargs): +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + CYTHON_UNUSED PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2747, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2747, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, __pyx_v_kwargs, values, kwd_pos_args, __pyx_kwds_len, "__cinit__", 1) < 0) __PYX_ERR(0, 2747, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, i); __PYX_ERR(0, 2747, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2747, __pyx_L3_error) + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2747, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_XDECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2748, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self), __pyx_v_samfile, __pyx_v_kwargs); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, CYTHON_UNUSED PyObject *__pyx_v_kwargs) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[139])) + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 2747, 0, 0, 0, __PYX_ERR(0, 2747, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2752 + * + * # no iteration over empty files + * if not samfile.nreferences: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2752, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2752, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = (!__pyx_t_2); + if (unlikely(__pyx_t_3)) { + + /* "pysam/libcalignmentfile.pyx":2753 + * # no iteration over empty files + * if not samfile.nreferences: + * raise StopIteration # <<<<<<<<<<<<<< + * + * # initialize iterator +*/ + __Pyx_Raise(__pyx_builtin_StopIteration, 0, 0, 0); + __PYX_ERR(0, 2753, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2752 + * + * # no iteration over empty files + * if not samfile.nreferences: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2756 + * + * # initialize iterator + * self._setup_iterator(self.tid, 0, MAX_POS, 1) # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_t_4.__pyx_n = 1; + __pyx_t_4.multiple_iterators = 1; + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._setup_iterator(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_self->__pyx_base.tid, 0, __pyx_v_5pysam_17libcalignmentfile_MAX_POS, &__pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2756, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2747 + * """ + * + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * **kwargs): +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2747, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2747, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2758 + * self._setup_iterator(self.tid, 0, MAX_POS, 1) + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_2__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self) { + int __pyx_v_n; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator __pyx_t_7; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[140])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2758, 0, 0, 0, __PYX_ERR(0, 2758, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2761 + * + * cdef int n + * while 1: # <<<<<<<<<<<<<< + * n = self.cnext() + * if n < 0: +*/ + while (1) { + + /* "pysam/libcalignmentfile.pyx":2762 + * cdef int n + * while 1: + * n = self.cnext() # <<<<<<<<<<<<<< + * if n < 0: + * raise ValueError("error during iteration") +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.cnext(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2762, __pyx_L1_error) + __pyx_v_n = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2763 + * while 1: + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration") + * +*/ + __pyx_t_2 = (__pyx_v_n < 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2764 + * n = self.cnext() + * if n < 0: + * raise ValueError("error during iteration") # <<<<<<<<<<<<<< + * + * # proceed to next reference or stop +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_error_during_iteration}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2764, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 2764, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2763 + * while 1: + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2767 + * + * # proceed to next reference or stop + * if n == 0: # <<<<<<<<<<<<<< + * self.tid += 1 + * if self.tid < self.samfile.nreferences: +*/ + __pyx_t_2 = (__pyx_v_n == 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2768 + * # proceed to next reference or stop + * if n == 0: + * self.tid += 1 # <<<<<<<<<<<<<< + * if self.tid < self.samfile.nreferences: + * self._setup_iterator(self.tid, 0, MAX_POS, 0) +*/ + __pyx_v_self->__pyx_base.tid = (__pyx_v_self->__pyx_base.tid + 1); + + /* "pysam/libcalignmentfile.pyx":2769 + * if n == 0: + * self.tid += 1 + * if self.tid < self.samfile.nreferences: # <<<<<<<<<<<<<< + * self._setup_iterator(self.tid, 0, MAX_POS, 0) + * else: +*/ + __pyx_t_3 = __Pyx_PyLong_From_int(__pyx_v_self->__pyx_base.tid); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2769, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self->__pyx_base.samfile), __pyx_mstate_global->__pyx_n_u_nreferences); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2769, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_t_5, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2769, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2769, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (likely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2770 + * self.tid += 1 + * if self.tid < self.samfile.nreferences: + * self._setup_iterator(self.tid, 0, MAX_POS, 0) # <<<<<<<<<<<<<< + * else: + * raise StopIteration +*/ + __pyx_t_7.__pyx_n = 1; + __pyx_t_7.multiple_iterators = 0; + __pyx_t_4 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._setup_iterator(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self), __pyx_v_self->__pyx_base.tid, 0, __pyx_v_5pysam_17libcalignmentfile_MAX_POS, &__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2770, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":2769 + * if n == 0: + * self.tid += 1 + * if self.tid < self.samfile.nreferences: # <<<<<<<<<<<<<< + * self._setup_iterator(self.tid, 0, MAX_POS, 0) + * else: +*/ + goto __pyx_L7; + } + + /* "pysam/libcalignmentfile.pyx":2772 + * self._setup_iterator(self.tid, 0, MAX_POS, 0) + * else: + * raise StopIteration # <<<<<<<<<<<<<< + * continue + * +*/ + /*else*/ { + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + } + __pyx_L7:; + + /* "pysam/libcalignmentfile.pyx":2773 + * else: + * raise StopIteration + * continue # <<<<<<<<<<<<<< + * + * # return result, if within same reference +*/ + goto __pyx_L3_continue; + + /* "pysam/libcalignmentfile.pyx":2767 + * + * # proceed to next reference or stop + * if n == 0: # <<<<<<<<<<<<<< + * self.tid += 1 + * if self.tid < self.samfile.nreferences: +*/ + } + + /* "pysam/libcalignmentfile.pyx":2776 + * + * # return result, if within same reference + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __Pyx_XDECREF(__pyx_r); + + /* "pysam/libcalignmentfile.pyx":2782 + * self.min_base_quality, + * self.iterdata.seq, + * self.samfile.header) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_self->__pyx_base.samfile->header); + __Pyx_INCREF(__pyx_t_4); + + /* "pysam/libcalignmentfile.pyx":2776 + * + * # return result, if within same reference + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __pyx_t_5 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makePileupColumn((&__pyx_v_self->__pyx_base.plp), __pyx_v_self->__pyx_base.tid, __pyx_v_self->__pyx_base.pos, __pyx_v_self->__pyx_base.n_plp, __pyx_v_self->__pyx_base.min_base_quality, __pyx_v_self->__pyx_base.iterdata.seq, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4))); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2776, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + __Pyx_TraceReturnValue(__pyx_r, 38, 0, __PYX_ERR(0, 2776, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L3_continue:; + } + + /* "pysam/libcalignmentfile.pyx":2758 + * self._setup_iterator(self.tid, 0, MAX_POS, 1) + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2758, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2758, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__, "IteratorColumnAllRefs.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[141])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__, "IteratorColumnAllRefs.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[142])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAllRefs.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2789 + * """ + * + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * **kwargs): +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + CYTHON_UNUSED PyObject *__pyx_v_kwargs = 0; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2789, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2789, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, __pyx_v_kwargs, values, kwd_pos_args, __pyx_kwds_len, "__cinit__", 1) < 0) __PYX_ERR(0, 2789, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, i); __PYX_ERR(0, 2789, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2789, __pyx_L3_error) + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2789, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_XDECREF(__pyx_v_kwargs); __pyx_v_kwargs = 0; + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2790, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll___cinit__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self), __pyx_v_samfile, __pyx_v_kwargs); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_XDECREF(__pyx_v_kwargs); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll___cinit__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self, CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, CYTHON_UNUSED PyObject *__pyx_v_kwargs) { + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[143])) + __Pyx_RefNannySetupContext("__cinit__", 0); + __Pyx_TraceStartFunc("__cinit__", __pyx_f[0], 2789, 0, 0, 0, __PYX_ERR(0, 2789, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2793 + * **kwargs): + * + * self._setup_raw_rest_iterator() # <<<<<<<<<<<<<< + * + * def __next__(self): +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._setup_raw_rest_iterator(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2793, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2789 + * """ + * + * def __cinit__(self, # <<<<<<<<<<<<<< + * AlignmentFile samfile, + * **kwargs): +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2789, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2789, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2795 + * self._setup_raw_rest_iterator() + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__next__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_2__next__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_2__next__(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self) { + int __pyx_v_n; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_error_without_exception = 0; /* StopIteration */ + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[144])) + __Pyx_RefNannySetupContext("__next__", 0); + __Pyx_TraceStartFunc("__next__", __pyx_f[0], 2795, 0, 0, 0, __PYX_ERR(0, 2795, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2798 + * + * cdef int n + * n = self.cnext() # <<<<<<<<<<<<<< + * if n < 0: + * raise ValueError("error during iteration") +*/ + __pyx_t_1 = ((struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base.cnext(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)__pyx_v_self)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 2798, __pyx_L1_error) + __pyx_v_n = __pyx_t_1; + + /* "pysam/libcalignmentfile.pyx":2799 + * cdef int n + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration") + * +*/ + __pyx_t_2 = (__pyx_v_n < 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2800 + * n = self.cnext() + * if n < 0: + * raise ValueError("error during iteration") # <<<<<<<<<<<<<< + * + * if n == 0: +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_ValueError); + __pyx_t_5 = __pyx_builtin_ValueError; + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_mstate_global->__pyx_kp_u_error_during_iteration}; + __pyx_t_3 = __Pyx_PyObject_FastCall(__pyx_t_5, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2800, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(0, 2800, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2799 + * cdef int n + * n = self.cnext() + * if n < 0: # <<<<<<<<<<<<<< + * raise ValueError("error during iteration") + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2802 + * raise ValueError("error during iteration") + * + * if n == 0: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + __pyx_t_2 = (__pyx_v_n == 0); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2803 + * + * if n == 0: + * raise StopIteration # <<<<<<<<<<<<<< + * + * return makePileupColumn(&self.plp, +*/ + __pyx_error_without_exception = 1; + goto __pyx_L1_error;; + + /* "pysam/libcalignmentfile.pyx":2802 + * raise ValueError("error during iteration") + * + * if n == 0: # <<<<<<<<<<<<<< + * raise StopIteration + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2805 + * raise StopIteration + * + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __Pyx_XDECREF(__pyx_r); + + /* "pysam/libcalignmentfile.pyx":2811 + * self.min_base_quality, + * self.iterdata.seq, + * self.samfile.header) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_3 = ((PyObject *)__pyx_v_self->__pyx_base.samfile->header); + __Pyx_INCREF(__pyx_t_3); + + /* "pysam/libcalignmentfile.pyx":2805 + * raise StopIteration + * + * return makePileupColumn(&self.plp, # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __pyx_t_5 = ((PyObject *)__pyx_f_5pysam_18libcalignedsegment_makePileupColumn((&__pyx_v_self->__pyx_base.plp), __pyx_v_self->__pyx_base.tid, __pyx_v_self->__pyx_base.pos, __pyx_v_self->__pyx_base.n_plp, __pyx_v_self->__pyx_base.min_base_quality, __pyx_v_self->__pyx_base.iterdata.seq, ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_3))); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2805, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + __Pyx_TraceReturnValue(__pyx_r, 18, 0, __PYX_ERR(0, 2805, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2795 + * self._setup_raw_rest_iterator() + * + * def __next__(self): # <<<<<<<<<<<<<< + * + * cdef int n +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2795, __pyx_L1_error)); + #endif + if (!__pyx_error_without_exception) { + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__next__", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__, "IteratorColumnAll.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[145])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__, "IteratorColumnAll.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[146])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_no_default___reduce___due_to_non, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IteratorColumnAll.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2827 + * property tid: + * '''the chromosome ID as is defined in the header''' + * def __get__(self): # <<<<<<<<<<<<<< + * return self._tid + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3tid_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3tid_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3tid___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3tid___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[147])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2827, 0, 0, 0, __PYX_ERR(0, 2827, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2828 + * '''the chromosome ID as is defined in the header''' + * def __get__(self): + * return self._tid # <<<<<<<<<<<<<< + * + * property pos: +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_tid); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2828, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2828, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2827 + * property tid: + * '''the chromosome ID as is defined in the header''' + * def __get__(self): # <<<<<<<<<<<<<< + * return self._tid + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2827, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.tid.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2832 + * property pos: + * '''nucleotide position of SNP.''' + * def __get__(self): return self._pos # <<<<<<<<<<<<<< + * + * property reference_base: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3pos_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3pos_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3pos___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_3pos___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[148])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2832, 0, 0, 0, __PYX_ERR(0, 2832, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2832, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2832, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2832, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.pos.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2836 + * property reference_base: + * '''reference base at pos. ``N`` if no reference sequence supplied.''' + * def __get__(self): return from_string_and_size( &self._reference_base, 1 ) # <<<<<<<<<<<<<< + * + * property genotype: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_14reference_base_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_14reference_base_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_14reference_base___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_14reference_base___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[149])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2836, 0, 0, 0, __PYX_ERR(0, 2836, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_5pysam_9libcutils_from_string_and_size((&__pyx_v_self->_reference_base), 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2836, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2836, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2836, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.reference_base.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2840 + * property genotype: + * '''the genotype called.''' + * def __get__(self): return from_string_and_size( &self._genotype, 1 ) # <<<<<<<<<<<<<< + * + * property consensus_quality: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8genotype_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8genotype_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8genotype___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8genotype___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[150])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2840, 0, 0, 0, __PYX_ERR(0, 2840, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __pyx_f_5pysam_9libcutils_from_string_and_size((&__pyx_v_self->_genotype), 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2840, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2840, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2840, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.genotype.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2844 + * property consensus_quality: + * '''the genotype quality (Phred-scaled).''' + * def __get__(self): return self._consensus_quality # <<<<<<<<<<<<<< + * + * property snp_quality: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[151])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2844, 0, 0, 0, __PYX_ERR(0, 2844, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_consensus_quality); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2844, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2844, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2844, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.consensus_quality.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2849 + * '''the snp quality (Phred scaled) - probability of consensus being + * identical to reference sequence.''' + * def __get__(self): return self._snp_quality # <<<<<<<<<<<<<< + * + * property mapping_quality: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_11snp_quality_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_11snp_quality_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_11snp_quality___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_11snp_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[152])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2849, 0, 0, 0, __PYX_ERR(0, 2849, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_snp_quality); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2849, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2849, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2849, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.snp_quality.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2854 + * '''the root mean square (rms) of the mapping quality of all reads + * involved in the call.''' + * def __get__(self): return self._rms_mapping_quality # <<<<<<<<<<<<<< + * + * property coverage: +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[153])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2854, 0, 0, 0, __PYX_ERR(0, 2854, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_rms_mapping_quality); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2854, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2854, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2854, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.mapping_quality.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2858 + * property coverage: + * '''coverage or read depth - the number of reads involved in the call.''' + * def __get__(self): return self._coverage # <<<<<<<<<<<<<< + * + * def __str__(self): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8coverage_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8coverage_1__get__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8coverage___get__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_8coverage___get__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[154])) + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_TraceStartFunc("__get__", __pyx_f[0], 2858, 0, 0, 0, __PYX_ERR(0, 2858, __pyx_L1_error)); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_coverage); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2858, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2858, __pyx_L1_error)); + goto __pyx_L0; + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2858, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.coverage.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2860 + * def __get__(self): return self._coverage + * + * def __str__(self): # <<<<<<<<<<<<<< + * + * return "\t".join( map(str, ( +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_1__str__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_1__str__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall___str__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall___str__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + PyObject *__pyx_t_10 = NULL; + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + size_t __pyx_t_13; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[155])) + __Pyx_RefNannySetupContext("__str__", 0); + __Pyx_TraceStartFunc("__str__", __pyx_f[0], 2860, 0, 0, 0, __PYX_ERR(0, 2860, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2862 + * def __str__(self): + * + * return "\t".join( map(str, ( # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = NULL; + __Pyx_INCREF(__pyx_builtin_map); + __pyx_t_3 = __pyx_builtin_map; + + /* "pysam/libcalignmentfile.pyx":2863 + * + * return "\t".join( map(str, ( + * self.tid, # <<<<<<<<<<<<<< + * self.pos, + * self.reference_base, +*/ + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_tid); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2863, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + + /* "pysam/libcalignmentfile.pyx":2864 + * return "\t".join( map(str, ( + * self.tid, + * self.pos, # <<<<<<<<<<<<<< + * self.reference_base, + * self.genotype, +*/ + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_pos); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2864, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":2865 + * self.tid, + * self.pos, + * self.reference_base, # <<<<<<<<<<<<<< + * self.genotype, + * self.consensus_quality, +*/ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_reference_base); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 2865, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "pysam/libcalignmentfile.pyx":2866 + * self.pos, + * self.reference_base, + * self.genotype, # <<<<<<<<<<<<<< + * self.consensus_quality, + * self.snp_quality, +*/ + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_genotype); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 2866, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "pysam/libcalignmentfile.pyx":2867 + * self.reference_base, + * self.genotype, + * self.consensus_quality, # <<<<<<<<<<<<<< + * self.snp_quality, + * self.mapping_quality, +*/ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_consensus_quality); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2867, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + + /* "pysam/libcalignmentfile.pyx":2868 + * self.genotype, + * self.consensus_quality, + * self.snp_quality, # <<<<<<<<<<<<<< + * self.mapping_quality, + * self.coverage ) ) ) +*/ + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_snp_quality); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 2868, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + + /* "pysam/libcalignmentfile.pyx":2869 + * self.consensus_quality, + * self.snp_quality, + * self.mapping_quality, # <<<<<<<<<<<<<< + * self.coverage ) ) ) + * +*/ + __pyx_t_10 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_mapping_quality); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 2869, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_10); + + /* "pysam/libcalignmentfile.pyx":2870 + * self.snp_quality, + * self.mapping_quality, + * self.coverage ) ) ) # <<<<<<<<<<<<<< + * + * +*/ + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_coverage); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 2870, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + + /* "pysam/libcalignmentfile.pyx":2863 + * + * return "\t".join( map(str, ( + * self.tid, # <<<<<<<<<<<<<< + * self.pos, + * self.reference_base, +*/ + __pyx_t_12 = PyTuple_New(8); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 2863, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_4) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 1, __pyx_t_5) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 2, __pyx_t_6) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 3, __pyx_t_7) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_8); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 4, __pyx_t_8) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_9); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 5, __pyx_t_9) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_10); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 6, __pyx_t_10) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_11); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_12, 7, __pyx_t_11) != (0)) __PYX_ERR(0, 2863, __pyx_L1_error); + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_t_10 = 0; + __pyx_t_11 = 0; + __pyx_t_13 = 1; + { + PyObject *__pyx_callargs[3] = {__pyx_t_2, ((PyObject *)(&PyUnicode_Type)), __pyx_t_12}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_3, __pyx_callargs+__pyx_t_13, (3-__pyx_t_13) | (__pyx_t_13*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2862, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + + /* "pysam/libcalignmentfile.pyx":2862 + * def __str__(self): + * + * return "\t".join( map(str, ( # <<<<<<<<<<<<<< + * self.tid, + * self.pos, +*/ + __pyx_t_3 = PyUnicode_Join(__pyx_mstate_global->__pyx_kp_u__2, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2862, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + __Pyx_TraceReturnValue(__pyx_r, 1, 0, __PYX_ERR(0, 2862, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2860 + * def __get__(self): return self._coverage + * + * def __str__(self): # <<<<<<<<<<<<<< + * + * return "\t".join( map(str, ( +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2860, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__, "SNPCall.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; + int __pyx_v_use_setstate; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[156])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":5 + * cdef object _dict + * cdef bint use_setstate + * state = (self._consensus_quality, self._coverage, self._genotype, self._pos, self._reference_base, self._rms_mapping_quality, self._snp_quality, self._tid) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: +*/ + __pyx_t_1 = __Pyx_PyLong_From_int(__pyx_v_self->_consensus_quality); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_From_int(__pyx_v_self->_coverage); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = __Pyx_PyLong_From_char(__pyx_v_self->_genotype); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyLong_From_int(__pyx_v_self->_pos); if (unlikely(!__pyx_t_4)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyLong_From_char(__pyx_v_self->_reference_base); if (unlikely(!__pyx_t_5)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = __Pyx_PyLong_From_int(__pyx_v_self->_rms_mapping_quality); if (unlikely(!__pyx_t_6)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyLong_From_int(__pyx_v_self->_snp_quality); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyLong_From_int(__pyx_v_self->_tid); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(8); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GIVEREF(__pyx_t_1); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_2); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_t_2) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_3); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 2, __pyx_t_3) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_4); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 3, __pyx_t_4) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_5); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 4, __pyx_t_5) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_6); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 5, __pyx_t_6) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 6, __pyx_t_7) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_8); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 7, __pyx_t_8) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __pyx_t_1 = 0; + __pyx_t_2 = 0; + __pyx_t_3 = 0; + __pyx_t_4 = 0; + __pyx_t_5 = 0; + __pyx_t_6 = 0; + __pyx_t_7 = 0; + __pyx_t_8 = 0; + __pyx_v_state = ((PyObject*)__pyx_t_9); + __pyx_t_9 = 0; + + /* "(tree fragment)":6 + * cdef bint use_setstate + * state = (self._consensus_quality, self._coverage, self._genotype, self._pos, self._reference_base, self._rms_mapping_quality, self._snp_quality, self._tid) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None: + * state += (_dict,) +*/ + __pyx_t_9 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_mstate_global->__pyx_n_u_dict, Py_None); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_v__dict = __pyx_t_9; + __pyx_t_9 = 0; + + /* "(tree fragment)":7 + * state = (self._consensus_quality, self._coverage, self._genotype, self._pos, self._reference_base, self._rms_mapping_quality, self._snp_quality, self._tid) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + __pyx_t_10 = (__pyx_v__dict != Py_None); + if (__pyx_t_10) { + + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: +*/ + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_v__dict) != (0)) __PYX_ERR(3, 8, __pyx_L1_error); + __pyx_t_8 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_9); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_8)); + __pyx_t_8 = 0; + + /* "(tree fragment)":9 + * if _dict is not None: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = False +*/ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":7 + * state = (self._consensus_quality, self._coverage, self._genotype, self._pos, self._reference_base, self._rms_mapping_quality, self._snp_quality, self._tid) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True +*/ + goto __pyx_L3; + } + + /* "(tree fragment)":11 + * use_setstate = True + * else: + * use_setstate = False # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, None), state +*/ + /*else*/ { + __pyx_v_use_setstate = 0; + } + __pyx_L3:; + + /* "(tree fragment)":12 + * else: + * use_setstate = False + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, None), state + * else: +*/ + if (__pyx_v_use_setstate) { + + /* "(tree fragment)":13 + * use_setstate = False + * if use_setstate: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_8, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_SNPCall); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = PyTuple_New(3); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_239452417); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_239452417); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_mstate_global->__pyx_int_239452417) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 2, Py_None) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __pyx_t_7 = PyTuple_New(3); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_GIVEREF(__pyx_t_8); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_9); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_9) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_v_state) != (0)) __PYX_ERR(3, 13, __pyx_L1_error); + __pyx_t_8 = 0; + __pyx_t_9 = 0; + __pyx_r = __pyx_t_7; + __pyx_t_7 = 0; + __Pyx_TraceReturnValue(__pyx_r, 36, 0, __PYX_ERR(3, 13, __pyx_L1_error)); + goto __pyx_L0; + + /* "(tree fragment)":12 + * else: + * use_setstate = False + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, None), state + * else: +*/ + } + + /* "(tree fragment)":15 + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, None), state + * else: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_SNPCall__set_state(self, __pyx_state) +*/ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_SNPCall); if (unlikely(!__pyx_t_7)) __PYX_ERR(3, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = PyTuple_New(3); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))) != (0)) __PYX_ERR(3, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_mstate_global->__pyx_int_239452417); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_int_239452417); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_mstate_global->__pyx_int_239452417) != (0)) __PYX_ERR(3, 15, __pyx_L1_error); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_9, 2, __pyx_v_state) != (0)) __PYX_ERR(3, 15, __pyx_L1_error); + __pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_7); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_7) != (0)) __PYX_ERR(3, 15, __pyx_L1_error); + __Pyx_GIVEREF(__pyx_t_9); + if (__Pyx_PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_9) != (0)) __PYX_ERR(3, 15, __pyx_L1_error); + __pyx_t_7 = 0; + __pyx_t_9 = 0; + __pyx_r = __pyx_t_8; + __pyx_t_8 = 0; + __Pyx_TraceReturnValue(__pyx_r, 44, 0, __PYX_ERR(3, 15, __pyx_L1_error)); + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":16 + * else: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_SNPCall__set_state(self, __pyx_state) +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__, "SNPCall.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 16, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 16, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 16, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 16, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 16, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 16, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[157])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 16, 0, 0, 0, __PYX_ERR(3, 16, __pyx_L1_error)); + + /* "(tree fragment)":17 + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_SNPCall__set_state(self, __pyx_state) # <<<<<<<<<<<<<< +*/ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_v___pyx_state))) __PYX_ERR(3, 17, __pyx_L1_error) + __pyx_t_1 = __pyx_f_5pysam_17libcalignmentfile___pyx_unpickle_SNPCall__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 17, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_SNPCall__set_state(self, __pyx_state) +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(3, 16, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 16, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.SNPCall.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2895 + * """ + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=True): # <<<<<<<<<<<<<< + * cdef char *cfilename + * +*/ + +/* Python wrapper */ +static int __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static int __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile = 0; + int __pyx_v_multiple_iterators; + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[2] = {0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + int __pyx_r; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return -1; + #endif + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_samfile,&__pyx_mstate_global->__pyx_n_u_multiple_iterators,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_VARARGS(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2895, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2895, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2895, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__init__", 0) < 0) __PYX_ERR(0, 2895, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, i); __PYX_ERR(0, 2895, __pyx_L3_error) } + } + } else { + switch (__pyx_nargs) { + case 2: + values[1] = __Pyx_ArgRef_VARARGS(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(0, 2895, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_VARARGS(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2895, __pyx_L3_error) + break; + default: goto __pyx_L5_argtuple_error; + } + } + __pyx_v_samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)values[0]); + if (values[1]) { + __pyx_v_multiple_iterators = __Pyx_PyLong_As_int(values[1]); if (unlikely((__pyx_v_multiple_iterators == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 2895, __pyx_L3_error) + } else { + __pyx_v_multiple_iterators = ((int)1); + } + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, __pyx_nargs); __PYX_ERR(0, 2895, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return -1; + __pyx_L4_argument_unpacking_done:; + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, 1, "samfile", 0))) __PYX_ERR(0, 2895, __pyx_L1_error) + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads___init__(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self), __pyx_v_samfile, __pyx_v_multiple_iterators); + + /* function exit code */ + goto __pyx_L0; + __pyx_L1_error:; + __pyx_r = -1; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + goto __pyx_L7_cleaned_up; + __pyx_L0:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __pyx_L7_cleaned_up:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static int __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads___init__(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *__pyx_v_samfile, int __pyx_v_multiple_iterators) { + char *__pyx_v_cfilename; + bam_hdr_t *__pyx_v_hdr; + int __pyx_r; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + char *__pyx_t_3; + PyObject *__pyx_t_4 = NULL; + struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + size_t __pyx_t_7; + htsFile *__pyx_t_8; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[158])) + __Pyx_RefNannySetupContext("__init__", 0); + __Pyx_TraceStartFunc("__init__", __pyx_f[0], 2895, 0, 0, 0, __PYX_ERR(0, 2895, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2900 + * # makes sure that samfile stays alive as long as this + * # object is alive. + * self.samfile = samfile # <<<<<<<<<<<<<< + * cdef bam_hdr_t * hdr = NULL + * assert samfile.is_bam, "can only apply IndexReads on bam files" +*/ + __Pyx_INCREF((PyObject *)__pyx_v_samfile); + __Pyx_GIVEREF((PyObject *)__pyx_v_samfile); + __Pyx_GOTREF((PyObject *)__pyx_v_self->samfile); + __Pyx_DECREF((PyObject *)__pyx_v_self->samfile); + __pyx_v_self->samfile = __pyx_v_samfile; + + /* "pysam/libcalignmentfile.pyx":2901 + * # object is alive. + * self.samfile = samfile + * cdef bam_hdr_t * hdr = NULL # <<<<<<<<<<<<<< + * assert samfile.is_bam, "can only apply IndexReads on bam files" + * +*/ + __pyx_v_hdr = NULL; + + /* "pysam/libcalignmentfile.pyx":2902 + * self.samfile = samfile + * cdef bam_hdr_t * hdr = NULL + * assert samfile.is_bam, "can only apply IndexReads on bam files" # <<<<<<<<<<<<<< + * + * # multiple_iterators the file - note that this makes the iterator +*/ + #ifndef CYTHON_WITHOUT_ASSERTIONS + if (unlikely(__pyx_assertions_enabled())) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_samfile), __pyx_mstate_global->__pyx_n_u_is_bam); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2902, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(0, 2902, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (unlikely(!__pyx_t_2)) { + __Pyx_Raise(__pyx_builtin_AssertionError, __pyx_mstate_global->__pyx_kp_u_can_only_apply_IndexReads_on_bam, 0, 0); + __PYX_ERR(0, 2902, __pyx_L1_error) + } + } + #else + if ((1)); else __PYX_ERR(0, 2902, __pyx_L1_error) + #endif + + /* "pysam/libcalignmentfile.pyx":2906 + * # multiple_iterators the file - note that this makes the iterator + * # slow and causes pileup to slow down significantly. + * if multiple_iterators: # <<<<<<<<<<<<<< + * cfilename = samfile.filename + * with nogil: +*/ + __pyx_t_2 = (__pyx_v_multiple_iterators != 0); + if (__pyx_t_2) { + + /* "pysam/libcalignmentfile.pyx":2907 + * # slow and causes pileup to slow down significantly. + * if multiple_iterators: + * cfilename = samfile.filename # <<<<<<<<<<<<<< + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') +*/ + __pyx_t_3 = __Pyx_PyObject_AsWritableString(__pyx_v_samfile->__pyx_base.filename); if (unlikely((!__pyx_t_3) && PyErr_Occurred())) __PYX_ERR(0, 2907, __pyx_L1_error) + __pyx_v_cfilename = __pyx_t_3; + + /* "pysam/libcalignmentfile.pyx":2908 + * if multiple_iterators: + * cfilename = samfile.filename + * with nogil: # <<<<<<<<<<<<<< + * self.htsfile = hts_open(cfilename, 'r') + * if self.htsfile == NULL: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2909 + * cfilename = samfile.filename + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') # <<<<<<<<<<<<<< + * if self.htsfile == NULL: + * raise OSError_from_errno("Unable to reopen file", cfilename) +*/ + __pyx_v_self->htsfile = hts_open(__pyx_v_cfilename, ((char const *)"r")); + } + + /* "pysam/libcalignmentfile.pyx":2908 + * if multiple_iterators: + * cfilename = samfile.filename + * with nogil: # <<<<<<<<<<<<<< + * self.htsfile = hts_open(cfilename, 'r') + * if self.htsfile == NULL: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L6; + } + __pyx_L6:; + } + } + + /* "pysam/libcalignmentfile.pyx":2910 + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Unable to reopen file", cfilename) + * +*/ + __pyx_t_2 = (__pyx_v_self->htsfile == NULL); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2911 + * self.htsfile = hts_open(cfilename, 'r') + * if self.htsfile == NULL: + * raise OSError_from_errno("Unable to reopen file", cfilename) # <<<<<<<<<<<<<< + * + * # need to advance in newly opened file to position after header +*/ + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_cfilename); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2911, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5.__pyx_n = 1; + __pyx_t_5.filename = __pyx_t_1; + __pyx_t_4 = __pyx_f_5pysam_9libcutils_OSError_from_errno(__pyx_mstate_global->__pyx_kp_u_Unable_to_reopen_file, &__pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2911, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 2911, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2910 + * with nogil: + * self.htsfile = hts_open(cfilename, 'r') + * if self.htsfile == NULL: # <<<<<<<<<<<<<< + * raise OSError_from_errno("Unable to reopen file", cfilename) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2915 + * # need to advance in newly opened file to position after header + * # better: use seek/tell? + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2916 + * # better: use seek/tell? + * with nogil: + * hdr = sam_hdr_read(self.htsfile) # <<<<<<<<<<<<<< + * if hdr == NULL: + * raise OSError("unable to read header information") +*/ + __pyx_v_hdr = sam_hdr_read(__pyx_v_self->htsfile); + } + + /* "pysam/libcalignmentfile.pyx":2915 + * # need to advance in newly opened file to position after header + * # better: use seek/tell? + * with nogil: # <<<<<<<<<<<<<< + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L10; + } + __pyx_L10:; + } + } + + /* "pysam/libcalignmentfile.pyx":2917 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise OSError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) +*/ + __pyx_t_2 = (__pyx_v_hdr == NULL); + if (unlikely(__pyx_t_2)) { + + /* "pysam/libcalignmentfile.pyx":2918 + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: + * raise OSError("unable to read header information") # <<<<<<<<<<<<<< + * self.header = makeAlignmentHeader(hdr) + * self.owns_samfile = True +*/ + __pyx_t_1 = NULL; + __Pyx_INCREF(__pyx_builtin_OSError); + __pyx_t_6 = __pyx_builtin_OSError; + __pyx_t_7 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_1, __pyx_mstate_global->__pyx_kp_u_unable_to_read_header_informatio}; + __pyx_t_4 = __Pyx_PyObject_FastCall(__pyx_t_6, __pyx_callargs+__pyx_t_7, (2-__pyx_t_7) | (__pyx_t_7*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2918, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + } + __Pyx_Raise(__pyx_t_4, 0, 0, 0); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __PYX_ERR(0, 2918, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2917 + * with nogil: + * hdr = sam_hdr_read(self.htsfile) + * if hdr == NULL: # <<<<<<<<<<<<<< + * raise OSError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2919 + * if hdr == NULL: + * raise OSError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) # <<<<<<<<<<<<<< + * self.owns_samfile = True + * else: +*/ + __pyx_t_4 = ((PyObject *)__pyx_f_5pysam_17libcalignmentfile_makeAlignmentHeader(__pyx_v_hdr)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2919, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":2920 + * raise OSError("unable to read header information") + * self.header = makeAlignmentHeader(hdr) + * self.owns_samfile = True # <<<<<<<<<<<<<< + * else: + * self.htsfile = self.samfile.htsfile +*/ + __pyx_v_self->owns_samfile = 1; + + /* "pysam/libcalignmentfile.pyx":2906 + * # multiple_iterators the file - note that this makes the iterator + * # slow and causes pileup to slow down significantly. + * if multiple_iterators: # <<<<<<<<<<<<<< + * cfilename = samfile.filename + * with nogil: +*/ + goto __pyx_L3; + } + + /* "pysam/libcalignmentfile.pyx":2922 + * self.owns_samfile = True + * else: + * self.htsfile = self.samfile.htsfile # <<<<<<<<<<<<<< + * self.header = samfile.header + * self.owns_samfile = False +*/ + /*else*/ { + __pyx_t_8 = __pyx_v_self->samfile->__pyx_base.htsfile; + __pyx_v_self->htsfile = __pyx_t_8; + + /* "pysam/libcalignmentfile.pyx":2923 + * else: + * self.htsfile = self.samfile.htsfile + * self.header = samfile.header # <<<<<<<<<<<<<< + * self.owns_samfile = False + * +*/ + __pyx_t_4 = ((PyObject *)__pyx_v_samfile->header); + __Pyx_INCREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_4); + __Pyx_GOTREF((PyObject *)__pyx_v_self->header); + __Pyx_DECREF((PyObject *)__pyx_v_self->header); + __pyx_v_self->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)__pyx_t_4); + __pyx_t_4 = 0; + + /* "pysam/libcalignmentfile.pyx":2924 + * self.htsfile = self.samfile.htsfile + * self.header = samfile.header + * self.owns_samfile = False # <<<<<<<<<<<<<< + * + * def build(self): +*/ + __pyx_v_self->owns_samfile = 0; + } + __pyx_L3:; + + /* "pysam/libcalignmentfile.pyx":2895 + * """ + * + * def __init__(self, AlignmentFile samfile, int multiple_iterators=True): # <<<<<<<<<<<<<< + * cdef char *cfilename + * +*/ + + /* function exit code */ + __pyx_r = 0; + __Pyx_TraceReturnCValue(__pyx_r, __Pyx_Owned_Py_None, 0, 0, __PYX_ERR(0, 2895, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2895, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2926 + * self.owns_samfile = False + * + * def build(self): # <<<<<<<<<<<<<< + * '''build the index.''' + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_3build(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_2build, "IndexedReads.build(self)\n\nbuild the index."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_3build = {"build", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_3build, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_2build}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_3build(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("build (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("build", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("build", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_2build(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_2build(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self) { + int __pyx_v_ret; + bam1_t *__pyx_v_b; + uint64_t __pyx_v_pos; + bam_hdr_t *__pyx_v_hdr; + PyObject *__pyx_v_qname = NULL; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + size_t __pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + bam_hdr_t *__pyx_t_9; + int __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[159])) + __Pyx_RefNannySetupContext("build", 0); + __Pyx_TraceStartFunc("build", __pyx_f[0], 2926, 0, 0, 0, __PYX_ERR(0, 2926, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2929 + * '''build the index.''' + * + * self.index = collections.defaultdict(list) # <<<<<<<<<<<<<< + * + * # this method will start indexing from the current file position +*/ + __pyx_t_2 = NULL; + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_collections); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2929, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_defaultdict); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 2929, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = 1; + #if CYTHON_UNPACK_METHODS + if (unlikely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_4); + assert(__pyx_t_2); + PyObject* __pyx__function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_2); + __Pyx_INCREF(__pyx__function); + __Pyx_DECREF_SET(__pyx_t_4, __pyx__function); + __pyx_t_5 = 0; + } + #endif + { + PyObject *__pyx_callargs[2] = {__pyx_t_2, ((PyObject *)(&PyList_Type))}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_4, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2929, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v_self->index); + __Pyx_DECREF(__pyx_v_self->index); + __pyx_v_self->index = __pyx_t_1; + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2932 + * + * # this method will start indexing from the current file position + * cdef int ret = 1 # <<<<<<<<<<<<<< + * cdef bam1_t * b = calloc(1, sizeof( bam1_t)) + * if b == NULL: +*/ + __pyx_v_ret = 1; + + /* "pysam/libcalignmentfile.pyx":2933 + * # this method will start indexing from the current file position + * cdef int ret = 1 + * cdef bam1_t * b = calloc(1, sizeof( bam1_t)) # <<<<<<<<<<<<<< + * if b == NULL: + * raise MemoryError("could not allocate {} bytes".format(sizeof(bam1_t))) +*/ + __pyx_v_b = ((bam1_t *)calloc(1, (sizeof(bam1_t)))); + + /* "pysam/libcalignmentfile.pyx":2934 + * cdef int ret = 1 + * cdef bam1_t * b = calloc(1, sizeof( bam1_t)) + * if b == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(sizeof(bam1_t))) + * +*/ + __pyx_t_6 = (__pyx_v_b == NULL); + if (unlikely(__pyx_t_6)) { + + /* "pysam/libcalignmentfile.pyx":2935 + * cdef bam1_t * b = calloc(1, sizeof( bam1_t)) + * if b == NULL: + * raise MemoryError("could not allocate {} bytes".format(sizeof(bam1_t))) # <<<<<<<<<<<<<< + * + * cdef uint64_t pos +*/ + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_MemoryError); + __pyx_t_2 = __pyx_builtin_MemoryError; + __pyx_t_7 = __pyx_mstate_global->__pyx_kp_u_could_not_allocate_bytes; + __Pyx_INCREF(__pyx_t_7); + __pyx_t_8 = __Pyx_PyLong_FromSize_t((sizeof(bam1_t))); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 2935, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_5 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_8}; + __pyx_t_3 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_format, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 2935, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_5 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_3}; + __pyx_t_1 = __Pyx_PyObject_FastCall(__pyx_t_2, __pyx_callargs+__pyx_t_5, (2-__pyx_t_5) | (__pyx_t_5*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2935, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 2935, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":2934 + * cdef int ret = 1 + * cdef bam1_t * b = calloc(1, sizeof( bam1_t)) + * if b == NULL: # <<<<<<<<<<<<<< + * raise MemoryError("could not allocate {} bytes".format(sizeof(bam1_t))) + * +*/ + } + + /* "pysam/libcalignmentfile.pyx":2938 + * + * cdef uint64_t pos + * cdef bam_hdr_t * hdr = self.header.ptr # <<<<<<<<<<<<<< + * + * while ret > 0: +*/ + __pyx_t_9 = __pyx_v_self->header->ptr; + __pyx_v_hdr = __pyx_t_9; + + /* "pysam/libcalignmentfile.pyx":2940 + * cdef bam_hdr_t * hdr = self.header.ptr + * + * while ret > 0: # <<<<<<<<<<<<<< + * with nogil: + * pos = bgzf_tell(hts_get_bgzfp(self.htsfile)) +*/ + while (1) { + __pyx_t_6 = (__pyx_v_ret > 0); + if (!__pyx_t_6) break; + + /* "pysam/libcalignmentfile.pyx":2941 + * + * while ret > 0: + * with nogil: # <<<<<<<<<<<<<< + * pos = bgzf_tell(hts_get_bgzfp(self.htsfile)) + * ret = sam_read1(self.htsfile, +*/ + { + PyThreadState *_save; + _save = NULL; + Py_UNBLOCK_THREADS + __Pyx_FastGIL_Remember(); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":2942 + * while ret > 0: + * with nogil: + * pos = bgzf_tell(hts_get_bgzfp(self.htsfile)) # <<<<<<<<<<<<<< + * ret = sam_read1(self.htsfile, + * hdr, +*/ + __pyx_v_pos = bgzf_tell(hts_get_bgzfp(__pyx_v_self->htsfile)); + + /* "pysam/libcalignmentfile.pyx":2943 + * with nogil: + * pos = bgzf_tell(hts_get_bgzfp(self.htsfile)) + * ret = sam_read1(self.htsfile, # <<<<<<<<<<<<<< + * hdr, + * b) +*/ + __pyx_v_ret = sam_read1(__pyx_v_self->htsfile, __pyx_v_hdr, __pyx_v_b); + } + + /* "pysam/libcalignmentfile.pyx":2941 + * + * while ret > 0: + * with nogil: # <<<<<<<<<<<<<< + * pos = bgzf_tell(hts_get_bgzfp(self.htsfile)) + * ret = sam_read1(self.htsfile, +*/ + /*finally:*/ { + /*normal exit:*/{ + __Pyx_FastGIL_Forget(); + Py_BLOCK_THREADS + goto __pyx_L10; + } + __pyx_L10:; + } + } + + /* "pysam/libcalignmentfile.pyx":2947 + * b) + * + * if ret > 0: # <<<<<<<<<<<<<< + * qname = charptr_to_str(pysam_bam_get_qname(b)) + * self.index[qname].append(pos) +*/ + __pyx_t_6 = (__pyx_v_ret > 0); + if (__pyx_t_6) { + + /* "pysam/libcalignmentfile.pyx":2948 + * + * if ret > 0: + * qname = charptr_to_str(pysam_bam_get_qname(b)) # <<<<<<<<<<<<<< + * self.index[qname].append(pos) + * +*/ + __pyx_t_1 = __pyx_f_5pysam_9libcutils_charptr_to_str(pysam_bam_get_qname(__pyx_v_b), NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2948, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_XDECREF_SET(__pyx_v_qname, __pyx_t_1); + __pyx_t_1 = 0; + + /* "pysam/libcalignmentfile.pyx":2949 + * if ret > 0: + * qname = charptr_to_str(pysam_bam_get_qname(b)) + * self.index[qname].append(pos) # <<<<<<<<<<<<<< + * + * bam_destroy1(b) +*/ + __pyx_t_1 = __Pyx_PyObject_GetItem(__pyx_v_self->index, __pyx_v_qname); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2949, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_From_uint64_t(__pyx_v_pos); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2949, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_10 = __Pyx_PyObject_Append(__pyx_t_1, __pyx_t_2); if (unlikely(__pyx_t_10 == ((int)-1))) __PYX_ERR(0, 2949, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2947 + * b) + * + * if ret > 0: # <<<<<<<<<<<<<< + * qname = charptr_to_str(pysam_bam_get_qname(b)) + * self.index[qname].append(pos) +*/ + } + } + + /* "pysam/libcalignmentfile.pyx":2951 + * self.index[qname].append(pos) + * + * bam_destroy1(b) # <<<<<<<<<<<<<< + * + * def find(self, query_name): +*/ + bam_destroy1(__pyx_v_b); + + /* "pysam/libcalignmentfile.pyx":2926 + * self.owns_samfile = False + * + * def build(self): # <<<<<<<<<<<<<< + * '''build the index.''' + * +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(0, 2926, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2926, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.build", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_qname); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2953 + * bam_destroy1(b) + * + * def find(self, query_name): # <<<<<<<<<<<<<< + * '''find `query_name` in index. + * +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_5find(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_4find, "IndexedReads.find(self, query_name)\n\nfind `query_name` in index.\n\nReturns\n-------\n\nIteratorRowSelection\n Returns an iterator over all reads with query_name.\n\nRaises\n------\n\nKeyError\n if the `query_name` is not in the index."); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_5find = {"find", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_5find, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_4find}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_5find(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v_query_name = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("find (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_query_name,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(0, 2953, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2953, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "find", 0) < 0) __PYX_ERR(0, 2953, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("find", 1, 1, 1, i); __PYX_ERR(0, 2953, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(0, 2953, __pyx_L3_error) + } + __pyx_v_query_name = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("find", 1, 1, 1, __pyx_nargs); __PYX_ERR(0, 2953, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.find", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_4find(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self), __pyx_v_query_name); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_4find(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, PyObject *__pyx_v_query_name) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + size_t __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[160])) + __Pyx_RefNannySetupContext("find", 0); + __Pyx_TraceStartFunc("find", __pyx_f[0], 2953, 0, 0, 0, __PYX_ERR(0, 2953, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2969 + * + * ''' + * if query_name in self.index: # <<<<<<<<<<<<<< + * return IteratorRowSelection( + * self.samfile, +*/ + __pyx_t_1 = (__Pyx_PySequence_ContainsTF(__pyx_v_query_name, __pyx_v_self->index, Py_EQ)); if (unlikely((__pyx_t_1 < 0))) __PYX_ERR(0, 2969, __pyx_L1_error) + if (likely(__pyx_t_1)) { + + /* "pysam/libcalignmentfile.pyx":2970 + * ''' + * if query_name in self.index: + * return IteratorRowSelection( # <<<<<<<<<<<<<< + * self.samfile, + * self.index[query_name], +*/ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = NULL; + __Pyx_INCREF((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection); + __pyx_t_4 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection); + + /* "pysam/libcalignmentfile.pyx":2972 + * return IteratorRowSelection( + * self.samfile, + * self.index[query_name], # <<<<<<<<<<<<<< + * multiple_iterators = False) + * else: +*/ + __pyx_t_5 = __Pyx_PyObject_GetItem(__pyx_v_self->index, __pyx_v_query_name); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2972, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + + /* "pysam/libcalignmentfile.pyx":2973 + * self.samfile, + * self.index[query_name], + * multiple_iterators = False) # <<<<<<<<<<<<<< + * else: + * raise KeyError("read %s not found" % query_name) +*/ + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[3 + ((CYTHON_VECTORCALL) ? 1 : 0)] = {__pyx_t_3, ((PyObject *)__pyx_v_self->samfile), __pyx_t_5}; + __pyx_t_7 = __Pyx_MakeVectorcallBuilderKwds(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 2970, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_VectorcallBuilder_AddArg(__pyx_mstate_global->__pyx_n_u_multiple_iterators, Py_False, __pyx_t_7, __pyx_callargs+3, 0) < 0) __PYX_ERR(0, 2970, __pyx_L1_error) + __pyx_t_2 = __Pyx_Object_Vectorcall_CallFromBuilder(__pyx_t_4, __pyx_callargs+__pyx_t_6, (3-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET), __pyx_t_7); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2970, __pyx_L1_error) + __Pyx_GOTREF((PyObject *)__pyx_t_2); + } + __pyx_r = ((PyObject *)__pyx_t_2); + __pyx_t_2 = 0; + __Pyx_TraceReturnValue(__pyx_r, 6, 0, __PYX_ERR(0, 2970, __pyx_L1_error)); + goto __pyx_L0; + + /* "pysam/libcalignmentfile.pyx":2969 + * + * ''' + * if query_name in self.index: # <<<<<<<<<<<<<< + * return IteratorRowSelection( + * self.samfile, +*/ + } + + /* "pysam/libcalignmentfile.pyx":2975 + * multiple_iterators = False) + * else: + * raise KeyError("read %s not found" % query_name) # <<<<<<<<<<<<<< + * + * def __dealloc__(self): +*/ + /*else*/ { + __pyx_t_4 = NULL; + __Pyx_INCREF(__pyx_builtin_KeyError); + __pyx_t_7 = __pyx_builtin_KeyError; + __pyx_t_5 = __Pyx_PyUnicode_FormatSafe(__pyx_mstate_global->__pyx_kp_u_read_s_not_found, __pyx_v_query_name); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 2975, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = 1; + { + PyObject *__pyx_callargs[2] = {__pyx_t_4, __pyx_t_5}; + __pyx_t_2 = __Pyx_PyObject_FastCall(__pyx_t_7, __pyx_callargs+__pyx_t_6, (2-__pyx_t_6) | (__pyx_t_6*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2975, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + } + __Pyx_Raise(__pyx_t_2, 0, 0, 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __PYX_ERR(0, 2975, __pyx_L1_error) + } + + /* "pysam/libcalignmentfile.pyx":2953 + * bam_destroy1(b) + * + * def find(self, query_name): # <<<<<<<<<<<<<< + * '''find `query_name` in index. + * +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2953, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.find", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "pysam/libcalignmentfile.pyx":2977 + * raise KeyError("read %s not found" % query_name) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * if self.owns_samfile: + * hts_close(self.htsfile) +*/ + +/* Python wrapper */ +static void __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_7__dealloc__(PyObject *__pyx_v_self); /*proto*/ +static void __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_7__dealloc__(PyObject *__pyx_v_self) { + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); + __pyx_kwvalues = __Pyx_KwValues_VARARGS(__pyx_args, __pyx_nargs); + __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_6__dealloc__(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +static void __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_6__dealloc__(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self) { + __Pyx_TraceDeclarationsFunc + int __pyx_t_1; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[161])) + __Pyx_TraceStartFunc("__dealloc__", __pyx_f[0], 2977, 0, 0, 0, __PYX_ERR(0, 2977, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":2978 + * + * def __dealloc__(self): + * if self.owns_samfile: # <<<<<<<<<<<<<< + * hts_close(self.htsfile) +*/ + __pyx_t_1 = (__pyx_v_self->owns_samfile != 0); + if (__pyx_t_1) { + + /* "pysam/libcalignmentfile.pyx":2979 + * def __dealloc__(self): + * if self.owns_samfile: + * hts_close(self.htsfile) # <<<<<<<<<<<<<< +*/ + (void)(hts_close(__pyx_v_self->htsfile)); + + /* "pysam/libcalignmentfile.pyx":2978 + * + * def __dealloc__(self): + * if self.owns_samfile: # <<<<<<<<<<<<<< + * hts_close(self.htsfile) +*/ + } + + /* "pysam/libcalignmentfile.pyx":2977 + * raise KeyError("read %s not found" % query_name) + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * if self.owns_samfile: + * hts_close(self.htsfile) +*/ + + /* function exit code */ + __Pyx_TraceReturnValue(Py_None, 0, 0, __PYX_ERR(0, 2977, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(0, 2977, __pyx_L1_error)); + #endif + __Pyx_WriteUnraisable("pysam.libcalignmentfile.IndexedReads.__dealloc__", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); + __pyx_L0:; + __Pyx_PyMonitoring_ExitScope(0); +} + +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__, "IndexedReads.__reduce_cython__(self)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__ = {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + if (unlikely(__pyx_nargs > 0)) { __Pyx_RaiseArgtupleInvalid("__reduce_cython__", 1, 0, 0, __pyx_nargs); return NULL; } + const Py_ssize_t __pyx_kwds_len = unlikely(__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len < 0)) return NULL; + if (unlikely(__pyx_kwds_len > 0)) {__Pyx_RejectKeywords("__reduce_cython__", __pyx_kwds); return NULL;} + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[162])) + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_TraceStartFunc("__reduce_cython__", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_htsfile_cannot_be_converted, 0, 0); + __PYX_ERR(3, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__, "IndexedReads.__setstate_cython__(self, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__ = {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__(PyObject *__pyx_v_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + CYTHON_UNUSED PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[1] = {0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__setstate_cython__", 0) < 0) __PYX_ERR(3, 3, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 1; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, i); __PYX_ERR(3, 3, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 1)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 3, __pyx_L3_error) + } + __pyx_v___pyx_state = values[0]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__setstate_cython__", 1, 1, 1, __pyx_nargs); __PYX_ERR(3, 3, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__(((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)__pyx_v_self), __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[163])) + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + __Pyx_TraceStartFunc("__setstate_cython__", __pyx_f[3], 3, 0, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + + /* "(tree fragment)":4 + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" # <<<<<<<<<<<<<< +*/ + __Pyx_Raise(__pyx_builtin_TypeError, __pyx_mstate_global->__pyx_kp_u_self_htsfile_cannot_be_converted, 0, 0); + __PYX_ERR(3, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 3, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.IndexedReads.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":1 + * def __pyx_unpickle_SNPCall(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result +*/ + +/* Python wrapper */ +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_5__pyx_unpickle_SNPCall(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +); /*proto*/ +PyDoc_STRVAR(__pyx_doc_5pysam_17libcalignmentfile_4__pyx_unpickle_SNPCall, "__pyx_unpickle_SNPCall(__pyx_type, long __pyx_checksum, __pyx_state)"); +static PyMethodDef __pyx_mdef_5pysam_17libcalignmentfile_5__pyx_unpickle_SNPCall = {"__pyx_unpickle_SNPCall", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_5__pyx_unpickle_SNPCall, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_4__pyx_unpickle_SNPCall}; +static PyObject *__pyx_pw_5pysam_17libcalignmentfile_5__pyx_unpickle_SNPCall(PyObject *__pyx_self, +#if CYTHON_METH_FASTCALL +PyObject *const *__pyx_args, Py_ssize_t __pyx_nargs, PyObject *__pyx_kwds +#else +PyObject *__pyx_args, PyObject *__pyx_kwds +#endif +) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + #if !CYTHON_METH_FASTCALL + CYTHON_UNUSED Py_ssize_t __pyx_nargs; + #endif + CYTHON_UNUSED PyObject *const *__pyx_kwvalues; + PyObject* values[3] = {0,0,0}; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_SNPCall (wrapper)", 0); + #if !CYTHON_METH_FASTCALL + #if CYTHON_ASSUME_SAFE_SIZE + __pyx_nargs = PyTuple_GET_SIZE(__pyx_args); + #else + __pyx_nargs = PyTuple_Size(__pyx_args); if (unlikely(__pyx_nargs < 0)) return NULL; + #endif + #endif + __pyx_kwvalues = __Pyx_KwValues_FASTCALL(__pyx_args, __pyx_nargs); + { + PyObject ** const __pyx_pyargnames[] = {&__pyx_mstate_global->__pyx_n_u_pyx_type,&__pyx_mstate_global->__pyx_n_u_pyx_checksum,&__pyx_mstate_global->__pyx_n_u_pyx_state,0}; + const Py_ssize_t __pyx_kwds_len = (__pyx_kwds) ? __Pyx_NumKwargs_FASTCALL(__pyx_kwds) : 0; + if (unlikely(__pyx_kwds_len) < 0) __PYX_ERR(3, 1, __pyx_L3_error) + if (__pyx_kwds_len > 0) { + switch (__pyx_nargs) { + case 3: + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(3, 1, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 2: + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(3, 1, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 1: + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 1, __pyx_L3_error) + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + const Py_ssize_t kwd_pos_args = __pyx_nargs; + if (__Pyx_ParseKeywords(__pyx_kwds, __pyx_kwvalues, __pyx_pyargnames, 0, values, kwd_pos_args, __pyx_kwds_len, "__pyx_unpickle_SNPCall", 0) < 0) __PYX_ERR(3, 1, __pyx_L3_error) + for (Py_ssize_t i = __pyx_nargs; i < 3; i++) { + if (unlikely(!values[i])) { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_SNPCall", 1, 3, 3, i); __PYX_ERR(3, 1, __pyx_L3_error) } + } + } else if (unlikely(__pyx_nargs != 3)) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = __Pyx_ArgRef_FASTCALL(__pyx_args, 0); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[0])) __PYX_ERR(3, 1, __pyx_L3_error) + values[1] = __Pyx_ArgRef_FASTCALL(__pyx_args, 1); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[1])) __PYX_ERR(3, 1, __pyx_L3_error) + values[2] = __Pyx_ArgRef_FASTCALL(__pyx_args, 2); + if (!CYTHON_ASSUME_SAFE_MACROS && unlikely(!values[2])) __PYX_ERR(3, 1, __pyx_L3_error) + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyLong_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(3, 1, __pyx_L3_error) + __pyx_v___pyx_state = values[2]; + } + goto __pyx_L6_skip; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_SNPCall", 1, 3, 3, __pyx_nargs); __PYX_ERR(3, 1, __pyx_L3_error) + __pyx_L6_skip:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L3_error:; + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_AddTraceback("pysam.libcalignmentfile.__pyx_unpickle_SNPCall", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_5pysam_17libcalignmentfile_4__pyx_unpickle_SNPCall(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); + + /* function exit code */ + for (Py_ssize_t __pyx_temp=0; __pyx_temp < (Py_ssize_t)(sizeof(values)/sizeof(values[0])); ++__pyx_temp) { + Py_XDECREF(values[__pyx_temp]); + } + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_5pysam_17libcalignmentfile_4__pyx_unpickle_SNPCall(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_PickleError = 0; + PyObject *__pyx_v___pyx_result = 0; + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + size_t __pyx_t_4; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[164])) + __Pyx_RefNannySetupContext("__pyx_unpickle_SNPCall", 0); + __Pyx_TraceStartFunc("__pyx_unpickle_SNPCall", __pyx_f[3], 1, 0, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum not in (0xe45c101, 0x1134a9c, 0x50b2281): # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum +*/ + __pyx_t_1 = __Pyx_PyLong_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_t_1, __pyx_mstate_global->__pyx_tuple[1], Py_NE)); if (unlikely((__pyx_t_2 < 0))) __PYX_ERR(3, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + if (__pyx_t_2) { + + /* "(tree fragment)":5 + * cdef object __pyx_result + * if __pyx_checksum not in (0xe45c101, 0x1134a9c, 0x50b2281): + * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum + * __pyx_result = SNPCall.__new__(__pyx_type) +*/ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_mstate_global->__pyx_n_u_PickleError); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_n_u_PickleError); + if (__Pyx_PyList_SET_ITEM(__pyx_t_1, 0, __pyx_mstate_global->__pyx_n_u_PickleError) != (0)) __PYX_ERR(3, 5, __pyx_L1_error); + __pyx_t_3 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_pickle, __pyx_t_1, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_3, __pyx_mstate_global->__pyx_n_u_PickleError); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v___pyx_PickleError = __pyx_t_1; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "(tree fragment)":6 + * if __pyx_checksum not in (0xe45c101, 0x1134a9c, 0x50b2281): + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum # <<<<<<<<<<<<<< + * __pyx_result = SNPCall.__new__(__pyx_type) + * if __pyx_state is not None: +*/ + __pyx_t_3 = __Pyx_PyLong_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_3)) __PYX_ERR(3, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = PyUnicode_Format(__pyx_mstate_global->__pyx_kp_u_Incompatible_checksums_0x_x_vs_0, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_v___pyx_PickleError, __pyx_t_1, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(3, 6, __pyx_L1_error) + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum not in (0xe45c101, 0x1134a9c, 0x50b2281): # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum +*/ + } + + /* "(tree fragment)":7 + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum + * __pyx_result = SNPCall.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) +*/ + __pyx_t_3 = ((PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall); + __Pyx_INCREF(__pyx_t_3); + __pyx_t_4 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_3, __pyx_v___pyx_type}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_new, __pyx_callargs+__pyx_t_4, (2-__pyx_t_4) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __pyx_v___pyx_result = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum + * __pyx_result = SNPCall.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + __pyx_t_2 = (__pyx_v___pyx_state != Py_None); + if (__pyx_t_2) { + + /* "(tree fragment)":9 + * __pyx_result = SNPCall.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): +*/ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None) || __Pyx_RaiseUnexpectedTypeError("tuple", __pyx_v___pyx_state))) __PYX_ERR(3, 9, __pyx_L1_error) + __pyx_t_1 = __pyx_f_5pysam_17libcalignmentfile___pyx_unpickle_SNPCall__set_state(((struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":8 + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum + * __pyx_result = SNPCall.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) + * return __pyx_result +*/ + } + + /* "(tree fragment)":10 + * if __pyx_state is not None: + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] +*/ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + __Pyx_TraceReturnValue(__pyx_r, 29, 0, __PYX_ERR(3, 10, __pyx_L1_error)); + goto __pyx_L0; + + /* "(tree fragment)":1 + * def __pyx_unpickle_SNPCall(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result +*/ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 1, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__pyx_unpickle_SNPCall", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_PickleError); + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":11 + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): +*/ + +static PyObject *__pyx_f_5pysam_17libcalignmentfile___pyx_unpickle_SNPCall__set_state(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_TraceDeclarationsFunc + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + char __pyx_t_3; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + size_t __pyx_t_10; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_TraceFrameInit(((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[165])) + __Pyx_RefNannySetupContext("__pyx_unpickle_SNPCall__set_state", 0); + __Pyx_TraceStartFunc("__pyx_unpickle_SNPCall__set_state", __pyx_f[3], 11, 0, 0, 0, __PYX_ERR(3, 11, __pyx_L1_error)); + + /* "(tree fragment)":12 + * return __pyx_result + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] # <<<<<<<<<<<<<< + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[8]) +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_consensus_quality = __pyx_t_2; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_coverage = __pyx_t_2; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyLong_As_char(__pyx_t_1); if (unlikely((__pyx_t_3 == (char)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_genotype = __pyx_t_3; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_pos = __pyx_t_2; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 4, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = __Pyx_PyLong_As_char(__pyx_t_1); if (unlikely((__pyx_t_3 == (char)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_reference_base = __pyx_t_3; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 5, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_rms_mapping_quality = __pyx_t_2; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 6, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_snp_quality = __pyx_t_2; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 12, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 7, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_PyLong_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(3, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v___pyx_result->_tid = __pyx_t_2; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[8]) +*/ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(3, 13, __pyx_L1_error) + } + __pyx_t_5 = __Pyx_PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(3, 13, __pyx_L1_error) + __pyx_t_6 = (__pyx_t_5 > 8); + if (__pyx_t_6) { + } else { + __pyx_t_4 = __pyx_t_6; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_6 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_mstate_global->__pyx_n_u_dict); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(3, 13, __pyx_L1_error) + __pyx_t_4 = __pyx_t_6; + __pyx_L4_bool_binop_done:; + if (__pyx_t_4) { + + /* "(tree fragment)":14 + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[8]) # <<<<<<<<<<<<<< +*/ + __pyx_t_8 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_mstate_global->__pyx_n_u_dict); if (unlikely(!__pyx_t_8)) __PYX_ERR(3, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_7 = __pyx_t_8; + __Pyx_INCREF(__pyx_t_7); + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(3, 14, __pyx_L1_error) + } + __pyx_t_9 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 8, long, 1, __Pyx_PyLong_From_long, 0, 0, 1, 1); if (unlikely(!__pyx_t_9)) __PYX_ERR(3, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = 0; + { + PyObject *__pyx_callargs[2] = {__pyx_t_7, __pyx_t_9}; + __pyx_t_1 = __Pyx_PyObject_FastCallMethod(__pyx_mstate_global->__pyx_n_u_update, __pyx_callargs+__pyx_t_10, (2-__pyx_t_10) | (1*__Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET)); + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":13 + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[8]) +*/ + } + + /* "(tree fragment)":11 + * __pyx_unpickle_SNPCall__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_SNPCall__set_state(SNPCall __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result._consensus_quality = __pyx_state[0]; __pyx_result._coverage = __pyx_state[1]; __pyx_result._genotype = __pyx_state[2]; __pyx_result._pos = __pyx_state[3]; __pyx_result._reference_base = __pyx_state[4]; __pyx_result._rms_mapping_quality = __pyx_state[5]; __pyx_result._snp_quality = __pyx_state[6]; __pyx_result._tid = __pyx_state[7] + * if len(__pyx_state) > 8 and hasattr(__pyx_result, '__dict__'): +*/ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_TraceReturnValue(__pyx_r, 0, 0, __PYX_ERR(3, 11, __pyx_L1_error)); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + #if CYTHON_USE_SYS_MONITORING + __Pyx_TraceExceptionUnwind(0, 0); + #else + __Pyx_TraceReturnValue(NULL, 0, 0, __PYX_ERR(3, 11, __pyx_L1_error)); + #endif + __Pyx_AddTraceback("pysam.libcalignmentfile.__pyx_unpickle_SNPCall__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_PyMonitoring_ExitScope(0); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +/* #### Code section: module_exttypes ### */ + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentHeader(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_1__cinit__(o, __pyx_mstate_global->__pyx_empty_tuple, NULL) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentHeader(PyObject *o) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentHeader) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_13__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + #if CYTHON_USE_TYPE_SLOTS + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static PyObject *__pyx_sq_item_5pysam_17libcalignmentfile_AlignmentHeader(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyLong_FromSsize_t(i); if(!x) return 0; + #if CYTHON_USE_TYPE_SLOTS || (!CYTHON_USE_TYPE_SPECS && __PYX_LIMITED_VERSION_HEX < 0x030A0000) + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + #else + r = ((binaryfunc)PyType_GetSlot(Py_TYPE(o), Py_mp_subscript))(o, x); + #endif + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_5pysam_17libcalignmentfile_AlignmentHeader(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_35__setitem__(o, i, v); + } + else { + __Pyx_TypeName o_type_name; + o_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(o)); + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by " __Pyx_FMT_TYPENAME, o_type_name); + __Pyx_DECREF_TypeName(o_type_name); + return -1; + } +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_nreferences(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11nreferences_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_references(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_10references_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_lengths(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7lengths_1__get__(o); +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_AlignmentHeader[] = { + {"_from_text_and_lengths", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_4_from_text_and_lengths}, + {"from_text", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_6from_text}, + {"from_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_8from_dict}, + {"from_references", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_10from_references}, + {"copy", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_17copy, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_16copy}, + {"_build_sequence_section", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_18_build_sequence_section}, + {"to_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_20to_dict}, + {"as_dict", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_22as_dict}, + {"get_reference_name", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_24get_reference_name}, + {"get_reference_length", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_26get_reference_length}, + {"is_valid_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_28is_valid_tid}, + {"get_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_30get_tid}, + {"items", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_39items, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_38items}, + {"iteritems", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_40iteritems}, + {"keys", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_43keys, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_42keys}, + {"values", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_45values, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_44values}, + {"get", (PyCFunction)(void(*)(void))(PyCFunctionWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_47get, METH_VARARGS|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_46get}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_52__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_54__setstate_cython__}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_5pysam_17libcalignmentfile_AlignmentHeader[] = { + {"nreferences", __pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_nreferences, 0, PyDoc_STR("int with the number of :term:`reference` sequences in the file.\n\n This is a read-only attribute."), 0}, + {"references", __pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_references, 0, PyDoc_STR("tuple with the names of :term:`reference` sequences. This is a\n read-only attribute"), 0}, + {"lengths", __pyx_getprop_5pysam_17libcalignmentfile_15AlignmentHeader_lengths, 0, PyDoc_STR("tuple of the lengths of the :term:`reference` sequences. This is a\n read-only attribute. The lengths are in the same order as\n :attr:`pysam.AlignmentFile.references`\n "), 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_AlignmentHeader_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentHeader}, + {Py_nb_bool, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_15__bool__}, + {Py_sq_length, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__}, + {Py_sq_item, (void *)__pyx_sq_item_5pysam_17libcalignmentfile_AlignmentHeader}, + {Py_sq_contains, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_51__contains__}, + {Py_mp_length, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__}, + {Py_mp_subscript, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_37__getitem__}, + {Py_mp_ass_subscript, (void *)__pyx_mp_ass_subscript_5pysam_17libcalignmentfile_AlignmentHeader}, + {Py_tp_str, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_33__str__}, + {Py_tp_doc, (void *)PyDoc_STR("AlignmentHeader()\n\nheader information for a :class:`AlignmentFile` object\n\nParameters\n----------\nheader_dict : dict\n build header from a multi-level dictionary. The\n first level are the four types ('HD', 'SQ', ...). The second\n level are a list of lines, with each line being a list of\n tag-value pairs. The header is constructed first from all the\n defined fields, followed by user tags in alphabetical\n order. Alternatively, an :class:`~pysam.AlignmentHeader`\n object can be passed directly.\n\ntext : string\n use the string provided as the header\n\nreference_names : list\n see reference_lengths\n\nreference_lengths : list\n build header from list of chromosome names and lengths. By\n default, 'SQ' and 'LN' tags will be added to the header\n text. This option can be changed by unsetting the flag\n `add_sq_text`.\n\nadd_sq_text : bool\n do not add 'SQ' and 'LN' tags to header. This option permits\n construction :term:`SAM` formatted files without a header.")}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_AlignmentHeader}, + {Py_tp_getset, (void *)__pyx_getsets_5pysam_17libcalignmentfile_AlignmentHeader}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_3__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentHeader}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_AlignmentHeader_spec = { + "pysam.libcalignmentfile.AlignmentHeader", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, + __pyx_type_5pysam_17libcalignmentfile_AlignmentHeader_slots, +}; +#else + +static PyNumberMethods __pyx_tp_as_number_AlignmentHeader = { + 0, /*nb_add*/ + 0, /*nb_subtract*/ + 0, /*nb_multiply*/ + 0, /*nb_remainder*/ + 0, /*nb_divmod*/ + 0, /*nb_power*/ + 0, /*nb_negative*/ + 0, /*nb_positive*/ + 0, /*nb_absolute*/ + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_15__bool__, /*nb_bool*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ + 0, /*nb_int*/ + 0, /*nb_long (reserved)*/ + 0, /*nb_float*/ + 0, /*nb_inplace_add*/ + 0, /*nb_inplace_subtract*/ + 0, /*nb_inplace_multiply*/ + 0, /*nb_inplace_remainder*/ + 0, /*nb_inplace_power*/ + 0, /*nb_inplace_lshift*/ + 0, /*nb_inplace_rshift*/ + 0, /*nb_inplace_and*/ + 0, /*nb_inplace_xor*/ + 0, /*nb_inplace_or*/ + 0, /*nb_floor_divide*/ + 0, /*nb_true_divide*/ + 0, /*nb_inplace_floor_divide*/ + 0, /*nb_inplace_true_divide*/ + 0, /*nb_index*/ + 0, /*nb_matrix_multiply*/ + 0, /*nb_inplace_matrix_multiply*/ +}; + +static PySequenceMethods __pyx_tp_as_sequence_AlignmentHeader = { + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_5pysam_17libcalignmentfile_AlignmentHeader, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_51__contains__, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_AlignmentHeader = { + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_49__len__, /*mp_length*/ + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_37__getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_5pysam_17libcalignmentfile_AlignmentHeader, /*mp_ass_subscript*/ +}; + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_AlignmentHeader = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""AlignmentHeader", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentHeader, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + &__pyx_tp_as_number_AlignmentHeader, /*tp_as_number*/ + &__pyx_tp_as_sequence_AlignmentHeader, /*tp_as_sequence*/ + &__pyx_tp_as_mapping_AlignmentHeader, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_33__str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + PyDoc_STR("AlignmentHeader()\n\nheader information for a :class:`AlignmentFile` object\n\nParameters\n----------\nheader_dict : dict\n build header from a multi-level dictionary. The\n first level are the four types ('HD', 'SQ', ...). The second\n level are a list of lines, with each line being a list of\n tag-value pairs. The header is constructed first from all the\n defined fields, followed by user tags in alphabetical\n order. Alternatively, an :class:`~pysam.AlignmentHeader`\n object can be passed directly.\n\ntext : string\n use the string provided as the header\n\nreference_names : list\n see reference_lengths\n\nreference_lengths : list\n build header from list of chromosome names and lengths. By\n default, 'SQ' and 'LN' tags will be added to the header\n text. This option can be changed by unsetting the flag\n `add_sq_text`.\n\nadd_sq_text : bool\n do not add 'SQ' and 'LN' tags to header. This option permits\n construction :term:`SAM` formatted files without a header."), /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_AlignmentHeader, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_5pysam_17libcalignmentfile_AlignmentHeader, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_15AlignmentHeader_3__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_AlignmentHeader, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_AlignmentFile __pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentFile(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *p; + PyObject *o = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile, tp_new, newfunc)(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile*)__pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile; + p->reference_filename = Py_None; Py_INCREF(Py_None); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentFile(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *p = (struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentFile) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_27__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->reference_filename); + Py_CLEAR(p->header); + if (PyType_IS_GC(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile)) PyObject_GC_Track(o); + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile)) __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile, tp_dealloc, destructor)(o); else + #endif + __Pyx_call_next_tp_dealloc(o, __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentFile); +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_AlignmentFile(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *p = (struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)o; + #if !CYTHON_USE_MODULE_STATE + e = 0; + if (likely(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile)) { + traverseproc traverse = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile, tp_traverse, traverseproc); + if (traverse) { e = traverse(o, v, a); } + } else + #endif + { e = __Pyx_call_next_tp_traverse(o, v, a, __pyx_tp_traverse_5pysam_17libcalignmentfile_AlignmentFile); } + if (e) return e; + { + e = __Pyx_call_type_traverse(o, 0, v, a); + if (e) return e; + } + if (p->reference_filename) { + e = (*v)(p->reference_filename, a); if (e) return e; + } + if (p->header) { + e = (*v)(((PyObject *)p->header), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_AlignmentFile(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *p = (struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)o; + #if !CYTHON_USE_MODULE_STATE + if (likely(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile)) { + inquiry clear = __Pyx_PyType_GetSlot(__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile, tp_clear, inquiry); + if (clear) clear(o); + } else + #endif + { __Pyx_call_next_tp_clear(o, __pyx_tp_clear_5pysam_17libcalignmentfile_AlignmentFile); } + tmp = ((PyObject*)p->reference_filename); + p->reference_filename = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->header); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_mapped(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6mapped_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_unmapped(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_8unmapped_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_nocoordinate(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_12nocoordinate_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_nreferences(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11nreferences_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_references(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_10references_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_lengths(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7lengths_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_text(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_4text_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_reference_filename(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_18reference_filename_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_header(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_6header_1__get__(o); +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_AlignmentFile[] = { + {"has_index", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_3has_index, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_2has_index}, + {"check_index", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_5check_index, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_4check_index}, + {"_open", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_7_open, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_6_open}, + {"fetch", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_9fetch, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_8fetch}, + {"head", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_11head, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_10head}, + {"mate", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_13mate, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_12mate}, + {"pileup", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_15pileup, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_14pileup}, + {"count", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_17count, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_16count}, + {"count_coverage", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_18count_coverage}, + {"find_introns_slow", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_20find_introns_slow}, + {"find_introns", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_22find_introns}, + {"close", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_25close, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_24close}, + {"__enter__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_30__enter__}, + {"__exit__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_32__exit__}, + {"get_index_statistics", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_34get_index_statistics}, + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__, METH_NOARGS|METH_COEXIST, 0}, + {"is_valid_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_40is_valid_tid}, + {"get_tid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_42get_tid}, + {"get_reference_name", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_44get_reference_name}, + {"get_reference_length", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_46get_reference_length}, + {"gettid", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_49gettid, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_48gettid}, + {"getrname", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_51getrname, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_50getrname}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_52__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_13AlignmentFile_54__setstate_cython__}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_5pysam_17libcalignmentfile_AlignmentFile[] = { + {"mapped", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_mapped, 0, PyDoc_STR("int with total number of mapped alignments according to the\n statistics recorded in the index. This is a read-only\n attribute.\n (This will be 0 for a CRAM file indexed by a .crai index, as that\n index format does not record these statistics.)\n "), 0}, + {"unmapped", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_unmapped, 0, PyDoc_STR("int with total number of unmapped reads according to the statistics\n recorded in the index. This number of reads includes the number of reads\n without coordinates. This is a read-only attribute.\n (This will be 0 for a CRAM file indexed by a .crai index, as that\n index format does not record these statistics.)\n "), 0}, + {"nocoordinate", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_nocoordinate, 0, PyDoc_STR("int with total number of reads without coordinates according to the\n statistics recorded in the index, i.e., the statistic printed for \"*\"\n by the ``samtools idxstats`` command. This is a read-only attribute.\n (This will be 0 for a CRAM file indexed by a .crai index, as that\n index format does not record these statistics.)\n "), 0}, + {"nreferences", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_nreferences, 0, PyDoc_STR("int with the number of :term:`reference` sequences in the file.\n This is a read-only attribute."), 0}, + {"references", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_references, 0, PyDoc_STR("tuple with the names of :term:`reference` sequences. This is a\n read-only attribute"), 0}, + {"lengths", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_lengths, 0, PyDoc_STR("tuple of the lengths of the :term:`reference` sequences. This is a\n read-only attribute. The lengths are in the same order as\n :attr:`pysam.AlignmentFile.references`\n\n "), 0}, + {"text", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_text, 0, PyDoc_STR("deprecated, use :attr:`references` and :attr:`lengths` instead"), 0}, + {"reference_filename", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_reference_filename, 0, 0, 0}, + {"header", __pyx_getprop_5pysam_17libcalignmentfile_13AlignmentFile_header, 0, 0, 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_AlignmentFile_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentFile}, + {Py_tp_doc, (void *)PyDoc_STR("AlignmentFile(filepath_or_object, mode=None, template=None,\n reference_names=None, reference_lengths=None, text=NULL,\n header=None, add_sq_text=False, check_header=True, check_sq=True,\n reference_filename=None, filename=None, index_filename=None,\n filepath_index=None, require_index=False, duplicate_filehandle=True,\n ignore_truncation=False, threads=1)\n\n A :term:`SAM`/:term:`BAM`/:term:`CRAM` formatted file.\n\n If `filepath_or_object` is a string, the file is automatically\n opened. If `filepath_or_object` is a python File object, the\n already opened file will be used.\n\n If the file is opened for reading and an index exists (if file is BAM, a\n .bai file or if CRAM a .crai file), it will be opened automatically.\n `index_filename` may be specified explicitly. If the index is not named\n in the standard manner, not located in the same directory as the\n BAM/CRAM file, or is remote. Without an index, random access via\n :meth:`~pysam.AlignmentFile.fetch` and :meth:`~pysam.AlignmentFile.pileup`\n is disabled.\n\n For writing, the header of a :term:`SAM` file/:term:`BAM` file can\n be constituted from several sources (see also the samtools format\n specification):\n\n 1. If `template` is given, the header is copied from another\n `AlignmentFile` (`template` must be a\n :class:`~pysam.AlignmentFile`).\n\n 2. If `header` is given, the header is built from a\n multi-level dictionary.\n\n 3. If `text` is given, new header text is copied from raw\n text.\n\n 4. The names (`reference_names`) and lengths\n (`reference_lengths`) are supplied directly as lists.\n\n When reading or writing a CRAM file, the filename of a FASTA-formatted\n reference can be specified with `reference_filename`.\n\n By default, if a file is opened in mode 'r', it is checked\n for a valid header (`check_header` = True) and a definition of\n chr""omosome names (`check_sq` = True).\n\n Parameters\n ----------\n mode : string\n `mode` should be ``r`` for reading or ``w`` for writing. The\n default is text mode (:term:`SAM`). For binary (:term:`BAM`)\n I/O you should append ``b`` for compressed or ``u`` for\n uncompressed :term:`BAM` output. Use ``h`` to output header\n information in text (:term:`TAM`) mode. Use ``c`` for\n :term:`CRAM` formatted files.\n\n If ``b`` is present, it must immediately follow ``r`` or\n ``w``. Valid modes are ``r``, ``w``, ``wh``, ``rb``, ``wb``,\n ``wbu``, ``wb0``, ``rc`` and ``wc``. For instance, to open a\n :term:`BAM` formatted file for reading, type::\n\n f = pysam.AlignmentFile('ex1.bam','rb')\n\n If mode is not specified, the method will try to auto-detect\n in the order 'rb', 'r', thus both the following should work::\n\n f1 = pysam.AlignmentFile('ex1.bam')\n f2 = pysam.AlignmentFile('ex1.sam')\n\n template : AlignmentFile\n when writing, copy header from file `template`.\n\n header : dict or AlignmentHeader\n when writing, build header from a multi-level dictionary. The\n first level are the four types ('HD', 'SQ', ...). The second\n level are a list of lines, with each line being a list of\n tag-value pairs. The header is constructed first from all the\n defined fields, followed by user tags in alphabetical\n order. Alternatively, an :class:`~pysam.AlignmentHeader`\n object can be passed directly.\n\n text : string\n when writing, use the string provided as the header\n\n reference_names : list\n see reference_lengths\n\n reference_lengths : list\n when writing or opening a SAM file without header build header\n from list of chromosome names and lengths. By default, 'SQ'\n and 'LN' tags will be added to the header text. This option\n ""can be changed by unsetting the flag `add_sq_text`.\n\n add_sq_text : bool\n do not add 'SQ' and 'LN' tags to header. This option permits\n construction :term:`SAM` formatted files without a header.\n\n add_sam_header : bool\n when outputting SAM the default is to output a header. This is\n equivalent to opening the file in 'wh' mode. If this option is\n set to False, no header will be output. To read such a file,\n set `check_header=False`.\n\n check_header : bool\n obsolete: when reading a SAM file, check if header is present\n (default=True)\n\n check_sq : bool\n when reading, check if SQ entries are present in header\n (default=True)\n\n reference_filename : string\n Path to a FASTA-formatted reference file. Valid only for CRAM files.\n When reading a CRAM file, this overrides both ``$REF_PATH`` and the URL\n specified in the header (``UR`` tag), which are normally used to find\n the reference.\n\n index_filename : string\n Explicit path to the index file. Only needed if the index is not\n named in the standard manner, not located in the same directory as\n the BAM/CRAM file, or is remote. An IOError is raised if the index\n cannot be found or is invalid.\n\n filepath_index : string\n Alias for `index_filename`.\n\n require_index : bool\n When reading, require that an index file is present and is valid or\n raise an IOError. (default=False)\n\n filename : string\n Alternative to filepath_or_object. Filename of the file\n to be opened.\n\n duplicate_filehandle: bool\n By default, file handles passed either directly or through\n File-like objects will be duplicated before passing them to\n htslib. The duplication prevents issues where the same stream\n will be closed by htslib and through destruction of the\n high-level python object. Set ""to False to turn off\n duplication.\n\n ignore_truncation: bool\n Issue a warning, instead of raising an error if the current file\n appears to be truncated due to a missing EOF marker. Only applies\n to bgzipped formats. (Default=False)\n\n format_options: list\n A list of key=value strings, as accepted by --input-fmt-option and\n --output-fmt-option in samtools.\n threads: integer\n Number of threads to use for compressing/decompressing BAM/CRAM files.\n Setting threads to > 1 cannot be combined with `ignore_truncation`.\n (Default=1)\n ")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_AlignmentFile}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_AlignmentFile}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_37__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_AlignmentFile}, + {Py_tp_getset, (void *)__pyx_getsets_5pysam_17libcalignmentfile_AlignmentFile}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_AlignmentFile}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_AlignmentFile_spec = { + "pysam.libcalignmentfile.AlignmentFile", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC|Py_TPFLAGS_HAVE_FINALIZE, + __pyx_type_5pysam_17libcalignmentfile_AlignmentFile_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_AlignmentFile = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""AlignmentFile", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_AlignmentFile, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC|Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/ + PyDoc_STR("AlignmentFile(filepath_or_object, mode=None, template=None,\n reference_names=None, reference_lengths=None, text=NULL,\n header=None, add_sq_text=False, check_header=True, check_sq=True,\n reference_filename=None, filename=None, index_filename=None,\n filepath_index=None, require_index=False, duplicate_filehandle=True,\n ignore_truncation=False, threads=1)\n\n A :term:`SAM`/:term:`BAM`/:term:`CRAM` formatted file.\n\n If `filepath_or_object` is a string, the file is automatically\n opened. If `filepath_or_object` is a python File object, the\n already opened file will be used.\n\n If the file is opened for reading and an index exists (if file is BAM, a\n .bai file or if CRAM a .crai file), it will be opened automatically.\n `index_filename` may be specified explicitly. If the index is not named\n in the standard manner, not located in the same directory as the\n BAM/CRAM file, or is remote. Without an index, random access via\n :meth:`~pysam.AlignmentFile.fetch` and :meth:`~pysam.AlignmentFile.pileup`\n is disabled.\n\n For writing, the header of a :term:`SAM` file/:term:`BAM` file can\n be constituted from several sources (see also the samtools format\n specification):\n\n 1. If `template` is given, the header is copied from another\n `AlignmentFile` (`template` must be a\n :class:`~pysam.AlignmentFile`).\n\n 2. If `header` is given, the header is built from a\n multi-level dictionary.\n\n 3. If `text` is given, new header text is copied from raw\n text.\n\n 4. The names (`reference_names`) and lengths\n (`reference_lengths`) are supplied directly as lists.\n\n When reading or writing a CRAM file, the filename of a FASTA-formatted\n reference can be specified with `reference_filename`.\n\n By default, if a file is opened in mode 'r', it is checked\n for a valid header (`check_header` = True) and a definition of\n chr""omosome names (`check_sq` = True).\n\n Parameters\n ----------\n mode : string\n `mode` should be ``r`` for reading or ``w`` for writing. The\n default is text mode (:term:`SAM`). For binary (:term:`BAM`)\n I/O you should append ``b`` for compressed or ``u`` for\n uncompressed :term:`BAM` output. Use ``h`` to output header\n information in text (:term:`TAM`) mode. Use ``c`` for\n :term:`CRAM` formatted files.\n\n If ``b`` is present, it must immediately follow ``r`` or\n ``w``. Valid modes are ``r``, ``w``, ``wh``, ``rb``, ``wb``,\n ``wbu``, ``wb0``, ``rc`` and ``wc``. For instance, to open a\n :term:`BAM` formatted file for reading, type::\n\n f = pysam.AlignmentFile('ex1.bam','rb')\n\n If mode is not specified, the method will try to auto-detect\n in the order 'rb', 'r', thus both the following should work::\n\n f1 = pysam.AlignmentFile('ex1.bam')\n f2 = pysam.AlignmentFile('ex1.sam')\n\n template : AlignmentFile\n when writing, copy header from file `template`.\n\n header : dict or AlignmentHeader\n when writing, build header from a multi-level dictionary. The\n first level are the four types ('HD', 'SQ', ...). The second\n level are a list of lines, with each line being a list of\n tag-value pairs. The header is constructed first from all the\n defined fields, followed by user tags in alphabetical\n order. Alternatively, an :class:`~pysam.AlignmentHeader`\n object can be passed directly.\n\n text : string\n when writing, use the string provided as the header\n\n reference_names : list\n see reference_lengths\n\n reference_lengths : list\n when writing or opening a SAM file without header build header\n from list of chromosome names and lengths. By default, 'SQ'\n and 'LN' tags will be added to the header text. This option\n ""can be changed by unsetting the flag `add_sq_text`.\n\n add_sq_text : bool\n do not add 'SQ' and 'LN' tags to header. This option permits\n construction :term:`SAM` formatted files without a header.\n\n add_sam_header : bool\n when outputting SAM the default is to output a header. This is\n equivalent to opening the file in 'wh' mode. If this option is\n set to False, no header will be output. To read such a file,\n set `check_header=False`.\n\n check_header : bool\n obsolete: when reading a SAM file, check if header is present\n (default=True)\n\n check_sq : bool\n when reading, check if SQ entries are present in header\n (default=True)\n\n reference_filename : string\n Path to a FASTA-formatted reference file. Valid only for CRAM files.\n When reading a CRAM file, this overrides both ``$REF_PATH`` and the URL\n specified in the header (``UR`` tag), which are normally used to find\n the reference.\n\n index_filename : string\n Explicit path to the index file. Only needed if the index is not\n named in the standard manner, not located in the same directory as\n the BAM/CRAM file, or is remote. An IOError is raised if the index\n cannot be found or is invalid.\n\n filepath_index : string\n Alias for `index_filename`.\n\n require_index : bool\n When reading, require that an index file is present and is valid or\n raise an IOError. (default=False)\n\n filename : string\n Alternative to filepath_or_object. Filename of the file\n to be opened.\n\n duplicate_filehandle: bool\n By default, file handles passed either directly or through\n File-like objects will be duplicated before passing them to\n htslib. The duplication prevents issues where the same stream\n will be closed by htslib and through destruction of the\n high-level python object. Set ""to False to turn off\n duplication.\n\n ignore_truncation: bool\n Issue a warning, instead of raising an error if the current file\n appears to be truncated due to a missing EOF marker. Only applies\n to bgzipped formats. (Default=False)\n\n format_options: list\n A list of key=value strings, as accepted by --input-fmt-option and\n --output-fmt-option in samtools.\n threads: integer\n Number of threads to use for compressing/decompressing BAM/CRAM files.\n Setting threads to > 1 cannot be combined with `ignore_truncation`.\n (Default=1)\n "), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_AlignmentFile, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_AlignmentFile, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_37__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_13AlignmentFile_39__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_AlignmentFile, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_5pysam_17libcalignmentfile_AlignmentFile, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_AlignmentFile, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)o); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_3__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->samfile); + Py_CLEAR(p->header); + #if CYTHON_USE_TYPE_SLOTS + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->samfile) { + e = (*v)(((PyObject *)p->samfile), a); if (e) return e; + } + if (p->header) { + e = (*v)(((PyObject *)p->header), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow *)o; + tmp = ((PyObject*)p->samfile); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->header); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRow[] = { + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_4__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_11IteratorRow_6__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRow_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_doc, (void *)PyDoc_STR("IteratorRow(AlignmentFile samfile, int multiple_iterators=False)\n\nabstract base class for iterators over mapped reads.\n\nVarious iterators implement different behaviours for wrapping around\ncontig boundaries. Examples include:\n\n:class:`pysam.IteratorRowRegion`\n iterate within a single contig and a defined region.\n\n:class:`pysam.IteratorRowAll`\n iterate until EOF. This iterator will also include unmapped reads.\n\n:class:`pysam.IteratorRowAllRefs`\n iterate over all reads in all reference sequences.\n\nThe method :meth:`AlignmentFile.fetch` returns an IteratorRow.\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRow_spec = { + "pysam.libcalignmentfile.IteratorRow", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRow_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRow = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRow", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRow), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRow(AlignmentFile samfile, int multiple_iterators=False)\n\nabstract base class for iterators over mapped reads.\n\nVarious iterators implement different behaviours for wrapping around\ncontig boundaries. Examples include:\n\n:class:`pysam.IteratorRowRegion`\n iterate within a single contig and a defined region.\n\n:class:`pysam.IteratorRowAll`\n iterate until EOF. This iterator will also include unmapped reads.\n\n:class:`pysam.IteratorRowAllRefs`\n iterate over all reads in all reference sequences.\n\nThe method :meth:`AlignmentFile.fetch` returns an IteratorRow.\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRow, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_11IteratorRow_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowRegion __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowRegion; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowRegion(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)o); + p->__pyx_vtab = __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion; + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowRegion(PyObject *o) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowRegion) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_7__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + PyObject_GC_Track(o); + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow(o); +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRowRegion[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_8__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorRowRegion_10__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowRegion}, + {Py_tp_doc, (void *)PyDoc_STR("IteratorRowRegion(AlignmentFile samfile, int tid, int beg, int stop, int multiple_iterators=False)\n\n*(AlignmentFile samfile, int tid, int beg, int stop,\nint multiple_iterators=False)*\n\niterate over mapped reads in a region.\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_3__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRowRegion}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowRegion}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion_spec = { + "pysam.libcalignmentfile.IteratorRowRegion", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRowRegion", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowRegion, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRowRegion(AlignmentFile samfile, int tid, int beg, int stop, int multiple_iterators=False)\n\n*(AlignmentFile samfile, int tid, int beg, int stop,\nint multiple_iterators=False)*\n\niterate over mapped reads in a region.\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_3__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_5__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRowRegion, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_17IteratorRowRegion_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowRegion, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowHead __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowHead; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowHead(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *)o); + p->__pyx_vtab = __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead; + return o; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRowHead[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_6__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_15IteratorRowHead_8__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRowHead_slots[] = { + {Py_tp_doc, (void *)PyDoc_STR("IteratorRowHead(AlignmentFile samfile, int n, int multiple_iterators=False)\n\n*(AlignmentFile samfile, n, int multiple_iterators=False)*\n\niterate over first n reads in `samfile`\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.head`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_3__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRowHead}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowHead}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRowHead_spec = { + "pysam.libcalignmentfile.IteratorRowHead", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRowHead_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRowHead = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRowHead", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRowHead(AlignmentFile samfile, int n, int multiple_iterators=False)\n\n*(AlignmentFile samfile, n, int multiple_iterators=False)*\n\niterate over first n reads in `samfile`\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.head`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_3__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_5__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRowHead, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_15IteratorRowHead_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowHead, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowAll __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowAll; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAll(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *)o); + p->__pyx_vtab = __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll; + return o; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRowAll[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_6__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorRowAll_8__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRowAll_slots[] = { + {Py_tp_doc, (void *)PyDoc_STR("IteratorRowAll(AlignmentFile samfile, int multiple_iterators=False)\n\n*(AlignmentFile samfile, int multiple_iterators=False)*\n\niterate over all reads in `samfile`\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_3__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRowAll}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAll}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRowAll_spec = { + "pysam.libcalignmentfile.IteratorRowAll", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRowAll_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRowAll = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRowAll", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRowAll(AlignmentFile samfile, int multiple_iterators=False)\n\n*(AlignmentFile samfile, int multiple_iterators=False)*\n\niterate over all reads in `samfile`\n\n.. note::\n\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_3__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_5__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRowAll, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_14IteratorRowAll_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAll, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAllRefs(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)o); + p->rowiter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowAllRefs(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowAllRefs) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->rowiter); + PyObject_GC_Track(o); + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow(o); +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowAllRefs(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)o; + e = __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow(o, v, a); if (e) return e; + if (p->rowiter) { + e = (*v)(((PyObject *)p->rowiter), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowAllRefs(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs *)o; + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow(o); + tmp = ((PyObject*)p->rowiter); + p->rowiter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRowAllRefs[] = { + {"nextiter", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_2nextiter}, + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_8__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_18IteratorRowAllRefs_10__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowAllRefs}, + {Py_tp_doc, (void *)PyDoc_STR("IteratorRowAllRefs(AlignmentFile samfile, multiple_iterators=False)\n\niterates over all mapped reads by chaining iterators over each\nreference\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowAllRefs}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowAllRefs}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_5__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRowAllRefs}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAllRefs}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs_spec = { + "pysam.libcalignmentfile.IteratorRowAllRefs", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRowAllRefs", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAllRefs), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowAllRefs, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRowAllRefs(AlignmentFile samfile, multiple_iterators=False)\n\niterates over all mapped reads by chaining iterators over each\nreference\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a\n :meth:`AlignmentFile.fetch`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowAllRefs, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowAllRefs, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_5__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_7__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRowAllRefs, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_18IteratorRowAllRefs_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowAllRefs, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorRowSelection __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowSelection; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowSelection(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRow(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)o); + p->__pyx_vtab = __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection; + p->positions = Py_None; Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowSelection(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowSelection) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + Py_CLEAR(p->positions); + PyObject_GC_Track(o); + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRow(o); +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowSelection(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)o; + e = __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRow(o, v, a); if (e) return e; + if (p->positions) { + e = (*v)(p->positions, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowSelection(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *)o; + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRow(o); + tmp = ((PyObject*)p->positions); + p->positions = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorRowSelection[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_6__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorRowSelection_8__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowSelection}, + {Py_tp_doc, (void *)PyDoc_STR("IteratorRowSelection(AlignmentFile samfile, positions, int multiple_iterators=True)\n\n*(AlignmentFile samfile)*\n\niterate over reads in `samfile` at a given list of file positions.\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a :meth:`AlignmentFile.fetch`.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowSelection}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowSelection}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_3__iter__}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorRowSelection}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowSelection}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection_spec = { + "pysam.libcalignmentfile.IteratorRowSelection", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorRowSelection", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorRowSelection, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IteratorRowSelection(AlignmentFile samfile, positions, int multiple_iterators=True)\n\n*(AlignmentFile samfile)*\n\niterate over reads in `samfile` at a given list of file positions.\n\n.. note::\n It is usually not necessary to create an object of this class\n explicitly. It is returned as a result of call to a :meth:`AlignmentFile.fetch`."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorRowSelection, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorRowSelection, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_3__iter__, /*tp_iter*/ + __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_5__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorRowSelection, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_20IteratorRowSelection_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorRowSelection, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)o); + p->__pyx_vtab = __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; + p->iter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)Py_None); Py_INCREF(Py_None); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + p->fastafile = ((struct __pyx_obj_5pysam_9libcfaidx_FastaFile *)Py_None); Py_INCREF(Py_None); + p->stepper = Py_None; Py_INCREF(Py_None); + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_9__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->iter); + Py_CLEAR(p->samfile); + Py_CLEAR(p->fastafile); + Py_CLEAR(p->stepper); + #if CYTHON_USE_TYPE_SLOTS + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->iter) { + e = (*v)(((PyObject *)p->iter), a); if (e) return e; + } + if (p->samfile) { + e = (*v)(((PyObject *)p->samfile), a); if (e) return e; + } + if (p->fastafile) { + e = (*v)(((PyObject *)p->fastafile), a); if (e) return e; + } + if (p->stepper) { + e = (*v)(p->stepper, a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *)o; + tmp = ((PyObject*)p->iter); + p->iter = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->samfile); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->fastafile); + p->fastafile = ((struct __pyx_obj_5pysam_9libcfaidx_FastaFile *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->stepper); + p->stepper = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_14IteratorColumn_seq_len(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7seq_len_1__get__(o); +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorColumn[] = { + {"add_reference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_4add_reference}, + {"has_reference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_6has_reference}, + {"hasReference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_10hasReference}, + {"addReference", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_13addReference, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_12addReference}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_14__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_14IteratorColumn_16__setstate_cython__}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_5pysam_17libcalignmentfile_IteratorColumn[] = { + {"seq_len", __pyx_getprop_5pysam_17libcalignmentfile_14IteratorColumn_seq_len, 0, PyDoc_STR("current sequence length."), 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorColumn_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_doc, (void *)PyDoc_STR("abstract base class for iterators over columns.\n\n IteratorColumn objects wrap the pileup functionality of samtools.\n\n For reasons of efficiency, the iterator points to the current\n pileup buffer. The pileup buffer is updated at every iteration.\n This might cause some unexpected behaviour. For example,\n consider the conversion to a list::\n\n f = AlignmentFile(\"file.bam\", \"rb\")\n result = list(f.pileup())\n\n Here, ``result`` will contain ``n`` objects of type\n :class:`~pysam.PileupColumn` for ``n`` columns, but each object in\n ``result`` will contain the same information.\n\n The desired behaviour can be achieved by list comprehension::\n\n result = [x.pileups() for x in f.pileup()]\n\n ``result`` will be a list of ``n`` lists of objects of type\n :class:`~pysam.PileupRead`.\n\n If the iterator is associated with a :class:`~pysam.Fastafile`\n using the :meth:`add_reference` method, then the iterator will\n export the current sequence via the methods :meth:`get_sequence`\n and :meth:`seq_len`.\n\n See :class:`~AlignmentFile.pileup` for kwargs to the iterator.\n ")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_iter, (void *)__pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_getset, (void *)__pyx_getsets_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorColumn_spec = { + "pysam.libcalignmentfile.IteratorColumn", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorColumn_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorColumn = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorColumn", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("abstract base class for iterators over columns.\n\n IteratorColumn objects wrap the pileup functionality of samtools.\n\n For reasons of efficiency, the iterator points to the current\n pileup buffer. The pileup buffer is updated at every iteration.\n This might cause some unexpected behaviour. For example,\n consider the conversion to a list::\n\n f = AlignmentFile(\"file.bam\", \"rb\")\n result = list(f.pileup())\n\n Here, ``result`` will contain ``n`` objects of type\n :class:`~pysam.PileupColumn` for ``n`` columns, but each object in\n ``result`` will contain the same information.\n\n The desired behaviour can be achieved by list comprehension::\n\n result = [x.pileups() for x in f.pileup()]\n\n ``result`` will be a list of ``n`` lists of objects of type\n :class:`~pysam.PileupRead`.\n\n If the iterator is associated with a :class:`~pysam.Fastafile`\n using the :meth:`add_reference` method, then the iterator will\n export the current sequence via the methods :meth:`get_sequence`\n and :meth:`seq_len`.\n\n See :class:`~AlignmentFile.pileup` for kwargs to the iterator.\n "), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorColumn, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_5pysam_17libcalignmentfile_IteratorColumn, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnRegion __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnRegion; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnRegion(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn*)__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion; + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnRegion[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_4__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_20IteratorColumnRegion_6__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion_slots[] = { + {Py_tp_doc, (void *)PyDoc_STR("iterates over a region only.\n ")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorColumnRegion}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnRegion}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion_spec = { + "pysam.libcalignmentfile.IteratorColumnRegion", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorColumnRegion", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnRegion), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("iterates over a region only.\n "), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + #if CYTHON_COMPILING_IN_PYPY || 0 + __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__, /*tp_iter*/ + #else + 0, /*tp_iter*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_20IteratorColumnRegion_3__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnRegion, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnRegion, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAllRefs __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAllRefs(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn*)__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAllRefs[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_4__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_6__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs_slots[] = { + {Py_tp_doc, (void *)PyDoc_STR("iterates over all columns by chaining iterators over each reference\n ")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAllRefs}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAllRefs}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs_spec = { + "pysam.libcalignmentfile.IteratorColumnAllRefs", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorColumnAllRefs", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAllRefs), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("iterates over all columns by chaining iterators over each reference\n "), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + #if CYTHON_COMPILING_IN_PYPY || 0 + __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__, /*tp_iter*/ + #else + 0, /*tp_iter*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_3__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAllRefs, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAllRefs, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif +static struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumnAll __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAll; + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAll(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *p; + PyObject *o = __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumn(t, a, k); + if (unlikely(!o)) return 0; + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll *)o); + p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_5pysam_17libcalignmentfile_IteratorColumn*)__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAll; + if (unlikely(__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_1__cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static PyObject *__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__(PyObject *self, CYTHON_UNUSED PyObject *arg) { + PyObject *res = __pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__(self); + if (!res && !PyErr_Occurred()) { PyErr_SetNone(PyExc_StopIteration); } + return res; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAll[] = { + {"__next__", (PyCFunction)__pyx_specialmethod___pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__, METH_NOARGS|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_4__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_17IteratorColumnAll_6__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll_slots[] = { + {Py_tp_doc, (void *)PyDoc_STR("iterates over all columns, without using an index\n ")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn}, + {Py_tp_iternext, (void *)__pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAll}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAll}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll_spec = { + "pysam.libcalignmentfile.IteratorColumnAll", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IteratorColumnAll", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumnAll), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IteratorColumn, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("iterates over all columns, without using an index\n "), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IteratorColumn, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IteratorColumn, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + #if CYTHON_COMPILING_IN_PYPY || 0 + __pyx_pw_5pysam_17libcalignmentfile_14IteratorColumn_3__iter__, /*tp_iter*/ + #else + 0, /*tp_iter*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_17IteratorColumnAll_3__next__, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IteratorColumnAll, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IteratorColumnAll, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_IndexedReads(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *p; + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + p = ((struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)o); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + p->index = Py_None; Py_INCREF(Py_None); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_IndexedReads(PyObject *o) { + struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && !__Pyx_PyObject_GC_IsFinalized(o)) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_IndexedReads) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + PyObject_GC_UnTrack(o); + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); + __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_7__dealloc__(o); + __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->samfile); + Py_CLEAR(p->index); + Py_CLEAR(p->header); + #if CYTHON_USE_TYPE_SLOTS + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static int __pyx_tp_traverse_5pysam_17libcalignmentfile_IndexedReads(PyObject *o, visitproc v, void *a) { + int e; + struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)o; + { + e = __Pyx_call_type_traverse(o, 1, v, a); + if (e) return e; + } + if (p->samfile) { + e = (*v)(((PyObject *)p->samfile), a); if (e) return e; + } + if (p->index) { + e = (*v)(p->index, a); if (e) return e; + } + if (p->header) { + e = (*v)(((PyObject *)p->header), a); if (e) return e; + } + return 0; +} + +static int __pyx_tp_clear_5pysam_17libcalignmentfile_IndexedReads(PyObject *o) { + PyObject* tmp; + struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *p = (struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads *)o; + tmp = ((PyObject*)p->samfile); + p->samfile = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->index); + p->index = Py_None; Py_INCREF(Py_None); + Py_XDECREF(tmp); + tmp = ((PyObject*)p->header); + p->header = ((struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)Py_None); Py_INCREF(Py_None); + Py_XDECREF(tmp); + return 0; +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_IndexedReads[] = { + {"build", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_3build, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_2build}, + {"find", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_5find, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_4find}, + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_8__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_12IndexedReads_10__setstate_cython__}, + {0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_IndexedReads_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_IndexedReads}, + {Py_tp_doc, (void *)PyDoc_STR("IndexedReads(AlignmentFile samfile, int multiple_iterators=True)\n\nIndex a Sam/BAM-file by query name while keeping the\noriginal sort order intact.\n\nThe index is kept in memory and can be substantial.\n\nBy default, the file is re-opened to avoid conflicts if multiple\noperators work on the same file. Set `multiple_iterators` = False\nto not re-open `samfile`.\n\nParameters\n----------\n\nsamfile : AlignmentFile\n File to be indexed.\n\nmultiple_iterators : bool\n Flag indicating whether the file should be reopened. Reopening prevents\n existing iterators being affected by the indexing.")}, + {Py_tp_traverse, (void *)__pyx_tp_traverse_5pysam_17libcalignmentfile_IndexedReads}, + {Py_tp_clear, (void *)__pyx_tp_clear_5pysam_17libcalignmentfile_IndexedReads}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_IndexedReads}, + {Py_tp_init, (void *)__pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_1__init__}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_IndexedReads}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_IndexedReads_spec = { + "pysam.libcalignmentfile.IndexedReads", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, + __pyx_type_5pysam_17libcalignmentfile_IndexedReads_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_IndexedReads = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""IndexedReads", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_IndexedReads), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_IndexedReads, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ + PyDoc_STR("IndexedReads(AlignmentFile samfile, int multiple_iterators=True)\n\nIndex a Sam/BAM-file by query name while keeping the\noriginal sort order intact.\n\nThe index is kept in memory and can be substantial.\n\nBy default, the file is re-opened to avoid conflicts if multiple\noperators work on the same file. Set `multiple_iterators` = False\nto not re-open `samfile`.\n\nParameters\n----------\n\nsamfile : AlignmentFile\n File to be indexed.\n\nmultiple_iterators : bool\n Flag indicating whether the file should be reopened. Reopening prevents\n existing iterators being affected by the indexing."), /*tp_doc*/ + __pyx_tp_traverse_5pysam_17libcalignmentfile_IndexedReads, /*tp_traverse*/ + __pyx_tp_clear_5pysam_17libcalignmentfile_IndexedReads, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_IndexedReads, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + __pyx_pw_5pysam_17libcalignmentfile_12IndexedReads_1__init__, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_IndexedReads, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyObject *__pyx_tp_new_5pysam_17libcalignmentfile_SNPCall(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { + PyObject *o; + #if CYTHON_COMPILING_IN_LIMITED_API + allocfunc alloc_func = (allocfunc)PyType_GetSlot(t, Py_tp_alloc); + o = alloc_func(t, 0); + #else + if (likely(!__Pyx_PyType_HasFeature(t, Py_TPFLAGS_IS_ABSTRACT))) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_mstate_global->__pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + #endif + return o; +} + +static void __pyx_tp_dealloc_5pysam_17libcalignmentfile_SNPCall(PyObject *o) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely((PY_VERSION_HEX >= 0x03080000 || __Pyx_PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE)) && __Pyx_PyObject_GetSlot(o, tp_finalize, destructor)) && (!PyType_IS_GC(Py_TYPE(o)) || !__Pyx_PyObject_GC_IsFinalized(o))) { + if (__Pyx_PyObject_GetSlot(o, tp_dealloc, destructor) == __pyx_tp_dealloc_5pysam_17libcalignmentfile_SNPCall) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + } + #endif + #if CYTHON_USE_TYPE_SLOTS + (*Py_TYPE(o)->tp_free)(o); + #else + { + freefunc tp_free = (freefunc)PyType_GetSlot(Py_TYPE(o), Py_tp_free); + if (tp_free) tp_free(o); + } + #endif +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_tid(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3tid_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_pos(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3pos_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_reference_base(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_14reference_base_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_genotype(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8genotype_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_consensus_quality(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_17consensus_quality_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_snp_quality(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_11snp_quality_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_mapping_quality(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_15mapping_quality_1__get__(o); +} + +static PyObject *__pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_coverage(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_8coverage_1__get__(o); +} + +static PyMethodDef __pyx_methods_5pysam_17libcalignmentfile_SNPCall[] = { + {"__reduce_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_7SNPCall_2__reduce_cython__}, + {"__setstate_cython__", (PyCFunction)(void(*)(void))(__Pyx_PyCFunction_FastCallWithKeywords)__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__, __Pyx_METH_FASTCALL|METH_KEYWORDS, __pyx_doc_5pysam_17libcalignmentfile_7SNPCall_4__setstate_cython__}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_5pysam_17libcalignmentfile_SNPCall[] = { + {"tid", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_tid, 0, PyDoc_STR("the chromosome ID as is defined in the header"), 0}, + {"pos", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_pos, 0, PyDoc_STR("nucleotide position of SNP."), 0}, + {"reference_base", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_reference_base, 0, PyDoc_STR("reference base at pos. ``N`` if no reference sequence supplied."), 0}, + {"genotype", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_genotype, 0, PyDoc_STR("the genotype called."), 0}, + {"consensus_quality", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_consensus_quality, 0, PyDoc_STR("the genotype quality (Phred-scaled)."), 0}, + {"snp_quality", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_snp_quality, 0, PyDoc_STR("the snp quality (Phred scaled) - probability of consensus being\n identical to reference sequence."), 0}, + {"mapping_quality", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_mapping_quality, 0, PyDoc_STR("the root mean square (rms) of the mapping quality of all reads\n involved in the call."), 0}, + {"coverage", __pyx_getprop_5pysam_17libcalignmentfile_7SNPCall_coverage, 0, PyDoc_STR("coverage or read depth - the number of reads involved in the call."), 0}, + {0, 0, 0, 0, 0} +}; +#if CYTHON_USE_TYPE_SPECS +static PyType_Slot __pyx_type_5pysam_17libcalignmentfile_SNPCall_slots[] = { + {Py_tp_dealloc, (void *)__pyx_tp_dealloc_5pysam_17libcalignmentfile_SNPCall}, + {Py_tp_str, (void *)__pyx_pw_5pysam_17libcalignmentfile_7SNPCall_1__str__}, + {Py_tp_doc, (void *)PyDoc_STR("the results of a SNP call.")}, + {Py_tp_methods, (void *)__pyx_methods_5pysam_17libcalignmentfile_SNPCall}, + {Py_tp_getset, (void *)__pyx_getsets_5pysam_17libcalignmentfile_SNPCall}, + {Py_tp_new, (void *)__pyx_tp_new_5pysam_17libcalignmentfile_SNPCall}, + {0, 0}, +}; +static PyType_Spec __pyx_type_5pysam_17libcalignmentfile_SNPCall_spec = { + "pysam.libcalignmentfile.SNPCall", + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall), + 0, + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, + __pyx_type_5pysam_17libcalignmentfile_SNPCall_slots, +}; +#else + +static PyTypeObject __pyx_type_5pysam_17libcalignmentfile_SNPCall = { + PyVarObject_HEAD_INIT(0, 0) + "pysam.libcalignmentfile.""SNPCall", /*tp_name*/ + sizeof(struct __pyx_obj_5pysam_17libcalignmentfile_SNPCall), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + __pyx_tp_dealloc_5pysam_17libcalignmentfile_SNPCall, /*tp_dealloc*/ + #if PY_VERSION_HEX < 0x030800b4 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030800b4 + 0, /*tp_vectorcall_offset*/ + #endif + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_as_async*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + __pyx_pw_5pysam_17libcalignmentfile_7SNPCall_1__str__, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ + PyDoc_STR("the results of a SNP call."), /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + __pyx_methods_5pysam_17libcalignmentfile_SNPCall, /*tp_methods*/ + 0, /*tp_members*/ + __pyx_getsets_5pysam_17libcalignmentfile_SNPCall, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + #if !CYTHON_USE_TYPE_SPECS + 0, /*tp_dictoffset*/ + #endif + 0, /*tp_init*/ + 0, /*tp_alloc*/ + __pyx_tp_new_5pysam_17libcalignmentfile_SNPCall, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ + 0, /*tp_bases*/ + 0, /*tp_mro*/ + 0, /*tp_cache*/ + 0, /*tp_subclasses*/ + 0, /*tp_weaklist*/ + 0, /*tp_del*/ + 0, /*tp_version_tag*/ + #if CYTHON_USE_TP_FINALIZE + 0, /*tp_finalize*/ + #else + NULL, /*tp_finalize*/ + #endif + #if PY_VERSION_HEX >= 0x030800b1 && (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800) + 0, /*tp_vectorcall*/ + #endif + #if __PYX_NEED_TP_PRINT_SLOT == 1 + 0, /*tp_print*/ + #endif + #if PY_VERSION_HEX >= 0x030C0000 + 0, /*tp_watched*/ + #endif + #if PY_VERSION_HEX >= 0x030d00A4 + 0, /*tp_versions_used*/ + #endif + #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX >= 0x03090000 && PY_VERSION_HEX < 0x030a0000 + 0, /*tp_pypy_flags*/ + #endif +}; +#endif + +static PyMethodDef __pyx_methods[] = { + {0, 0, 0, 0} +}; +/* #### Code section: initfunc_declarations ### */ +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate); /*proto*/ +static CYTHON_SMALL_CODE int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate); /*proto*/ +/* #### Code section: init_module ### */ + +static int __Pyx_modinit_global_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); + /*--- Global init code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_variable_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); + /*--- Variable export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_export_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); + /*--- Function export code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_type_init_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); + /*--- Type init code ---*/ + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader)) __PYX_ERR(0, 195, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader) < 0) __PYX_ERR(0, 195, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader = &__pyx_type_5pysam_17libcalignmentfile_AlignmentHeader; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader) < 0) __PYX_ERR(0, 195, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader->tp_getattro = PyObject_GenericGetAttr; + } + #endif + #if CYTHON_UPDATE_DESCRIPTOR_DOC + { + PyObject *wrapper = PyObject_GetAttrString((PyObject *)__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, "__str__"); if (unlikely(!wrapper)) __PYX_ERR(0, 195, __pyx_L1_error) + if (__Pyx_IS_TYPE(wrapper, &PyWrapperDescr_Type)) { + __pyx_wrapperbase_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__ = *((PyWrapperDescrObject *)wrapper)->d_base; + __pyx_wrapperbase_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__.doc = __pyx_doc_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__; + ((PyWrapperDescrObject *)wrapper)->d_base = &__pyx_wrapperbase_5pysam_17libcalignmentfile_15AlignmentHeader_32__str__; + } + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_AlignmentHeader, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader) < 0) __PYX_ERR(0, 195, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader) < 0) __PYX_ERR(0, 195, __pyx_L1_error) + __pyx_t_1 = PyImport_ImportModule("pysam.libchtslib"); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_5pysam_10libchtslib_HTSFile = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libchtslib", "HTSFile", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_10libchtslib_HTSFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_10libchtslib_HTSFile), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_10libchtslib_HTSFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_10libchtslib_HTSFile), + #else + sizeof(struct __pyx_obj_5pysam_10libchtslib_HTSFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_10libchtslib_HTSFile), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_10libchtslib_HTSFile) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_5pysam_10libchtslib_HTSFile = (struct __pyx_vtabstruct_5pysam_10libchtslib_HTSFile*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_10libchtslib_HTSFile); if (unlikely(!__pyx_vtabptr_5pysam_10libchtslib_HTSFile)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile = &__pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile; + __pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile.__pyx_base = *__pyx_vtabptr_5pysam_10libchtslib_HTSFile; + __pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile.getCurrent = (bam1_t *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *))__pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_getCurrent; + __pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *))__pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_cnext; + __pyx_vtable_5pysam_17libcalignmentfile_AlignmentFile.write = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentFile *, struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *, int __pyx_skip_dispatch))__pyx_f_5pysam_17libcalignmentfile_13AlignmentFile_write; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 582, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_AlignmentFile_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile)) __PYX_ERR(0, 582, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_AlignmentFile_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile = &__pyx_type_5pysam_17libcalignmentfile_AlignmentFile; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_10libchtslib_HTSFile; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_vtabptr_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_AlignmentFile, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile) < 0) __PYX_ERR(0, 582, __pyx_L1_error) + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRow_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow)) __PYX_ERR(0, 1967, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRow_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow) < 0) __PYX_ERR(0, 1967, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow = &__pyx_type_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow) < 0) __PYX_ERR(0, 1967, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRow, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow) < 0) __PYX_ERR(0, 1967, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow) < 0) __PYX_ERR(0, 1967, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorRowRegion; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowRegion.getCurrent = (bam1_t *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *))__pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_getCurrent; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowRegion.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowRegion *))__pyx_f_5pysam_17libcalignmentfile_17IteratorRowRegion_cnext; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2055, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion)) __PYX_ERR(0, 2055, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion = &__pyx_type_5pysam_17libcalignmentfile_IteratorRowRegion; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRowRegion, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowRegion) < 0) __PYX_ERR(0, 2055, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorRowHead; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowHead.getCurrent = (bam1_t *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *))__pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_getCurrent; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowHead.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowHead *))__pyx_f_5pysam_17libcalignmentfile_15IteratorRowHead_cnext; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead)) __PYX_ERR(0, 2116, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead = &__pyx_type_5pysam_17libcalignmentfile_IteratorRowHead; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRowHead, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowHead) < 0) __PYX_ERR(0, 2116, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorRowAll; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowAll.getCurrent = (bam1_t *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *))__pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_getCurrent; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowAll.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowAll *))__pyx_f_5pysam_17libcalignmentfile_14IteratorRowAll_cnext; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2167, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll)) __PYX_ERR(0, 2167, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll = &__pyx_type_5pysam_17libcalignmentfile_IteratorRowAll; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRowAll, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAll) < 0) __PYX_ERR(0, 2167, __pyx_L1_error) + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2209, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs)) __PYX_ERR(0, 2209, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs) < 0) __PYX_ERR(0, 2209, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs = &__pyx_type_5pysam_17libcalignmentfile_IteratorRowAllRefs; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs) < 0) __PYX_ERR(0, 2209, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRowAllRefs, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs) < 0) __PYX_ERR(0, 2209, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs) < 0) __PYX_ERR(0, 2209, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorRowSelection; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowSelection.getCurrent = (bam1_t *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *))__pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_getCurrent; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorRowSelection.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorRowSelection *))__pyx_f_5pysam_17libcalignmentfile_20IteratorRowSelection_cnext; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2271, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection)) __PYX_ERR(0, 2271, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection = &__pyx_type_5pysam_17libcalignmentfile_IteratorRowSelection; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRow; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorRowSelection, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowSelection) < 0) __PYX_ERR(0, 2271, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn.cnext = (int (*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_cnext; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn.get_sequence = (char *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_get_sequence; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn._setup_iterator = (PyObject *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, int, int, int, struct __pyx_opt_args_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator *__pyx_optional_args))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_iterator; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn._setup_raw_rest_iterator = (PyObject *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__setup_raw_rest_iterator; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn.reset = (PyObject *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *, PyObject *, PyObject *, PyObject *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_reset; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn._free_pileup_iter = (PyObject *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn__free_pileup_iter; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumn.getSequence = (char *(*)(struct __pyx_obj_5pysam_17libcalignmentfile_IteratorColumn *))__pyx_f_5pysam_17libcalignmentfile_14IteratorColumn_getSequence; + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorColumn_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn)) __PYX_ERR(0, 2443, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorColumn_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn = &__pyx_type_5pysam_17libcalignmentfile_IteratorColumn; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorColumn, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn) < 0) __PYX_ERR(0, 2443, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnRegion; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnRegion.__pyx_base = *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2693, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion)) __PYX_ERR(0, 2693, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion = &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnRegion; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorColumnRegion, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnRegion) < 0) __PYX_ERR(0, 2693, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAllRefs.__pyx_base = *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2743, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs)) __PYX_ERR(0, 2743, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs = &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAllRefs; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorColumnAllRefs, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAllRefs) < 0) __PYX_ERR(0, 2743, __pyx_L1_error) + __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAll = &__pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAll; + __pyx_vtable_5pysam_17libcalignmentfile_IteratorColumnAll.__pyx_base = *__pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumn; + #if CYTHON_USE_TYPE_SPECS + __pyx_t_2 = PyTuple_Pack(1, (PyObject *)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2785, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll_spec, __pyx_t_2); + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll)) __PYX_ERR(0, 2785, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll = &__pyx_type_5pysam_17libcalignmentfile_IteratorColumnAll; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll->tp_base = __pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn; + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (__Pyx_SetVtable(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll, __pyx_vtabptr_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + if (__Pyx_MergeVtables(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IteratorColumnAll, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumnAll) < 0) __PYX_ERR(0, 2785, __pyx_L1_error) + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_IndexedReads_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads)) __PYX_ERR(0, 2873, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_IndexedReads_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads) < 0) __PYX_ERR(0, 2873, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads = &__pyx_type_5pysam_17libcalignmentfile_IndexedReads; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads) < 0) __PYX_ERR(0, 2873, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_IndexedReads, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads) < 0) __PYX_ERR(0, 2873, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads) < 0) __PYX_ERR(0, 2873, __pyx_L1_error) + #if CYTHON_USE_TYPE_SPECS + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall = (PyTypeObject *) __Pyx_PyType_FromModuleAndSpec(__pyx_m, &__pyx_type_5pysam_17libcalignmentfile_SNPCall_spec, NULL); if (unlikely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall)) __PYX_ERR(0, 2814, __pyx_L1_error) + if (__Pyx_fix_up_extension_type_from_spec(&__pyx_type_5pysam_17libcalignmentfile_SNPCall_spec, __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall) < 0) __PYX_ERR(0, 2814, __pyx_L1_error) + #else + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall = &__pyx_type_5pysam_17libcalignmentfile_SNPCall; + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + #endif + #if !CYTHON_USE_TYPE_SPECS + if (__Pyx_PyType_Ready(__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall) < 0) __PYX_ERR(0, 2814, __pyx_L1_error) + #endif + #if !CYTHON_COMPILING_IN_LIMITED_API + if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall->tp_dictoffset && __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall->tp_getattro == PyObject_GenericGetAttr)) { + __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall->tp_getattro = PyObject_GenericGetAttr; + } + #endif + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_SNPCall, (PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall) < 0) __PYX_ERR(0, 2814, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject *) __pyx_mstate->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall) < 0) __PYX_ERR(0, 2814, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_2); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_type_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); + /*--- Type import code ---*/ + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_4type_type = __Pyx_ImportType_3_1_2(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyTypeObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyTypeObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyHeapTypeObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyHeapTypeObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_7cpython_4type_type) __PYX_ERR(5, 9, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(6, 8, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType_3_1_2(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "bool", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyLongObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyLongObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyLongObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyLongObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_7cpython_4bool_bool) __PYX_ERR(6, 8, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(7, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType_3_1_2(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "complex", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(PyComplexObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyComplexObject), + #elif CYTHON_COMPILING_IN_LIMITED_API + 0, 0, + #else + sizeof(PyComplexObject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(PyComplexObject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_7cpython_7complex_complex) __PYX_ERR(7, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("array"); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 69, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_7cpython_5array_array = __Pyx_ImportType_3_1_2(__pyx_t_1, "array", "array", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(arrayobject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(arrayobject), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(arrayobject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(arrayobject), + #else + sizeof(arrayobject), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(arrayobject), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_7cpython_5array_array) __PYX_ERR(2, 69, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("pysam.libcfaidx"); if (unlikely(!__pyx_t_1)) __PYX_ERR(8, 38, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastaFile = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "FastaFile", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastaFile), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastaFile) __PYX_ERR(8, 38, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_FastaFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastaFile*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastaFile); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastaFile)) __PYX_ERR(8, 38, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqProxy = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "FastqProxy", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqProxy), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqProxy) __PYX_ERR(8, 46, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_FastqProxy = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqProxy*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqProxy); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastqProxy)) __PYX_ERR(8, 46, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxRecord = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "FastxRecord", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxRecord), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxRecord) __PYX_ERR(8, 53, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_FastxRecord = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxRecord*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxRecord); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastxRecord)) __PYX_ERR(8, 53, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxFile = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "FastxFile", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastxFile), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxFile) __PYX_ERR(8, 62, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_FastxFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastxFile*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastxFile); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastxFile)) __PYX_ERR(8, 62, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqFile = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "FastqFile", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_FastqFile), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqFile) __PYX_ERR(8, 74, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_FastqFile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_FastqFile*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_FastqFile); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_FastqFile)) __PYX_ERR(8, 74, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_Fastafile = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcfaidx", "Fastafile", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), + #else + sizeof(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_9libcfaidx_Fastafile), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_Fastafile) __PYX_ERR(8, 79, __pyx_L1_error) + __pyx_vtabptr_5pysam_9libcfaidx_Fastafile = (struct __pyx_vtabstruct_5pysam_9libcfaidx_Fastafile*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_9libcfaidx_Fastafile); if (unlikely(!__pyx_vtabptr_5pysam_9libcfaidx_Fastafile)) __PYX_ERR(8, 79, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("pysam.libcalignedsegment"); if (unlikely(!__pyx_t_1)) __PYX_ERR(9, 34, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcalignedsegment", "_AlignedSegment_Cache", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), + #else + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment__AlignedSegment_Cache), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache) __PYX_ERR(9, 34, __pyx_L1_error) + __pyx_vtabptr_5pysam_18libcalignedsegment__AlignedSegment_Cache = (struct __pyx_vtabstruct_5pysam_18libcalignedsegment__AlignedSegment_Cache*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment__AlignedSegment_Cache); if (unlikely(!__pyx_vtabptr_5pysam_18libcalignedsegment__AlignedSegment_Cache)) __PYX_ERR(9, 34, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcalignedsegment", "AlignedSegment", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), + #else + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment) __PYX_ERR(9, 47, __pyx_L1_error) + __pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment = (struct __pyx_vtabstruct_5pysam_18libcalignedsegment_AlignedSegment*)__Pyx_GetVtable(__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_AlignedSegment); if (unlikely(!__pyx_vtabptr_5pysam_18libcalignedsegment_AlignedSegment)) __PYX_ERR(9, 47, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcalignedsegment", "PileupColumn", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), + #else + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_PileupColumn) __PYX_ERR(9, 79, __pyx_L1_error) + __pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_PileupRead = __Pyx_ImportType_3_1_2(__pyx_t_1, "pysam.libcalignedsegment", "PileupRead", + #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), + #elif CYTHON_COMPILING_IN_LIMITED_API + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), + #else + sizeof(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), __PYX_GET_STRUCT_ALIGNMENT_3_1_2(struct __pyx_obj_5pysam_18libcalignedsegment_PileupRead), + #endif + __Pyx_ImportType_CheckSize_Warn_3_1_2); if (!__pyx_mstate->__pyx_ptype_5pysam_18libcalignedsegment_PileupRead) __PYX_ERR(9, 89, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +static int __Pyx_modinit_variable_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); + /*--- Variable import code ---*/ + __Pyx_RefNannyFinishContext(); + return 0; +} + +static int __Pyx_modinit_function_import_code(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + PyObject *__pyx_t_1 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); + /*--- Function import code ---*/ + __pyx_t_1 = PyImport_ImportModule("pysam.libcalignedsegment"); if (!__pyx_t_1) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "makeAlignedSegment", (void (**)(void))&__pyx_f_5pysam_18libcalignedsegment_makeAlignedSegment, "struct __pyx_obj_5pysam_18libcalignedsegment_AlignedSegment *(bam1_t *, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "makePileupColumn", (void (**)(void))&__pyx_f_5pysam_18libcalignedsegment_makePileupColumn, "struct __pyx_obj_5pysam_18libcalignedsegment_PileupColumn *(bam_pileup1_t const **, int, int, int, uint32_t, char *, struct __pyx_obj_5pysam_17libcalignmentfile_AlignmentHeader *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = PyImport_ImportModule("pysam.libcutils"); if (!__pyx_t_1) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "OSError_from_errno", (void (**)(void))&__pyx_f_5pysam_9libcutils_OSError_from_errno, "PyObject *(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_OSError_from_errno *__pyx_optional_args)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "charptr_to_str", (void (**)(void))&__pyx_f_5pysam_9libcutils_charptr_to_str, "PyObject *(char const *, struct __pyx_opt_args_5pysam_9libcutils_charptr_to_str *__pyx_optional_args)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "force_str", (void (**)(void))&__pyx_f_5pysam_9libcutils_force_str, "PyObject *(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_force_str *__pyx_optional_args)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "force_bytes", (void (**)(void))&__pyx_f_5pysam_9libcutils_force_bytes, "PyObject *(PyObject *, struct __pyx_opt_args_5pysam_9libcutils_force_bytes *__pyx_optional_args)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "encode_filename", (void (**)(void))&__pyx_f_5pysam_9libcutils_encode_filename, "PyObject *(PyObject *)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_ImportFunction_3_1_2(__pyx_t_1, "from_string_and_size", (void (**)(void))&__pyx_f_5pysam_9libcutils_from_string_and_size, "PyObject *(char const *, size_t)") < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_RefNannyFinishContext(); + return -1; +} + +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_libcalignmentfile(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_libcalignmentfile}, + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + {Py_mod_gil, Py_MOD_GIL_USED}, + #endif + #if PY_VERSION_HEX >= 0x030C0000 && CYTHON_USE_MODULE_STATE + {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}, + #endif + {0, NULL} +}; +#endif + +#ifdef __cplusplus +namespace { + struct PyModuleDef __pyx_moduledef = + #else + static struct PyModuleDef __pyx_moduledef = + #endif + { + PyModuleDef_HEAD_INIT, + "libcalignmentfile", + 0, /* m_doc */ + #if CYTHON_USE_MODULE_STATE + sizeof(__pyx_mstatetype), /* m_size */ + #else + (CYTHON_PEP489_MULTI_PHASE_INIT) ? 0 : -1, /* m_size */ + #endif + __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else + NULL, /* m_reload */ + #endif + #if CYTHON_USE_MODULE_STATE + __pyx_m_traverse, /* m_traverse */ + __pyx_m_clear, /* m_clear */ + NULL /* m_free */ + #else + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ + #endif + }; + #ifdef __cplusplus +} /* anonymous namespace */ +#endif + +/* PyModInitFuncType */ +#ifndef CYTHON_NO_PYINIT_EXPORT + #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#else + #ifdef __cplusplus + #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * + #else + #define __Pyx_PyMODINIT_FUNC PyObject * + #endif +#endif + +__Pyx_PyMODINIT_FUNC PyInit_libcalignmentfile(void) CYTHON_SMALL_CODE; /*proto*/ +__Pyx_PyMODINIT_FUNC PyInit_libcalignmentfile(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +/* ModuleCreationPEP489 */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 +static PY_INT64_T __Pyx_GetCurrentInterpreterId(void) { + { + PyObject *module = PyImport_ImportModule("_interpreters"); // 3.13+ I think + if (!module) { + PyErr_Clear(); // just try the 3.8-3.12 version + module = PyImport_ImportModule("_xxsubinterpreters"); + if (!module) goto bad; + } + PyObject *current = PyObject_CallMethod(module, "get_current", NULL); + Py_DECREF(module); + if (!current) goto bad; + if (PyTuple_Check(current)) { + PyObject *new_current = PySequence_GetItem(current, 0); + Py_DECREF(current); + current = new_current; + if (!new_current) goto bad; + } + long long as_c_int = PyLong_AsLongLong(current); + Py_DECREF(current); + return as_c_int; + } + bad: + PySys_WriteStderr("__Pyx_GetCurrentInterpreterId failed. Try setting the C define CYTHON_PEP489_MULTI_PHASE_INIT=0\n"); + return -1; +} +#endif +#if !CYTHON_USE_MODULE_STATE +static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { + static PY_INT64_T main_interpreter_id = -1; +#if CYTHON_COMPILING_IN_GRAAL + PY_INT64_T current_id = PyInterpreterState_GetIDFromThreadState(PyThreadState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX >= 0x03090000 + PY_INT64_T current_id = PyInterpreterState_GetID(PyInterpreterState_Get()); +#elif CYTHON_COMPILING_IN_LIMITED_API + PY_INT64_T current_id = __Pyx_GetCurrentInterpreterId(); +#else + PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); +#endif + if (unlikely(current_id == -1)) { + return -1; + } + if (main_interpreter_id == -1) { + main_interpreter_id = current_id; + return 0; + } else if (unlikely(main_interpreter_id != current_id)) { + PyErr_SetString( + PyExc_ImportError, + "Interpreter change detected - this module can only be loaded into one interpreter per process."); + return -1; + } + return 0; +} +#endif +static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) +{ + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + if (allow_none || value != Py_None) { + result = PyDict_SetItemString(moddict, to_name, value); + } + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + CYTHON_UNUSED_VAR(def); + #if !CYTHON_USE_MODULE_STATE + if (__Pyx_check_single_interpreter()) + return NULL; + #endif + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static CYTHON_SMALL_CODE int __pyx_pymod_exec_libcalignmentfile(PyObject *__pyx_pyinit_module) +#endif +{ + int stringtab_initialized = 0; + #if CYTHON_USE_MODULE_STATE + int pystate_addmodule_run = 0; + #endif + __pyx_mstatetype *__pyx_mstate = NULL; + __Pyx_TraceDeclarationsFunc + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + int __pyx_t_6; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + int __pyx_lineno = 0; + const char *__pyx_filename = NULL; + int __pyx_clineno = 0; + __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module 'libcalignmentfile' has already been imported. Re-initialisation is not supported."); + return -1; + } + #else + if (__pyx_m) return __Pyx_NewRef(__pyx_m); + #endif + /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_t_1 = __pyx_pyinit_module; + Py_INCREF(__pyx_t_1); + #else + __pyx_t_1 = PyModule_Create(&__pyx_moduledef); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #if CYTHON_USE_MODULE_STATE + { + int add_module_result = __Pyx_State_AddModule(__pyx_t_1, &__pyx_moduledef); + __pyx_t_1 = 0; /* transfer ownership from __pyx_t_1 to "libcalignmentfile" pseudovariable */ + if (unlikely((add_module_result < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + pystate_addmodule_run = 1; + } + #else + __pyx_m = __pyx_t_1; + #endif + #if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + PyUnstable_Module_SetGIL(__pyx_m, Py_MOD_GIL_USED); + #endif + __pyx_mstate = __pyx_mstate_global; + CYTHON_UNUSED_VAR(__pyx_t_1); + __pyx_mstate->__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_mstate->__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) + Py_INCREF(__pyx_mstate->__pyx_d); + __pyx_mstate->__pyx_b = __Pyx_PyImport_AddModuleRef(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_mstate->__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_cython_runtime = __Pyx_PyImport_AddModuleRef("cython_runtime"); if (unlikely(!__pyx_mstate->__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_mstate->__pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /* ImportRefnannyAPI */ + #if CYTHON_REFNANNY +__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); +if (!__Pyx_RefNanny) { + PyErr_Clear(); + __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); + if (!__Pyx_RefNanny) + Py_FatalError("failed to import 'refnanny' module"); +} +#endif + +__Pyx_RefNannySetupContext("PyInit_libcalignmentfile", 0); + if (__Pyx_check_binary_version(__PYX_LIMITED_VERSION_HEX, __Pyx_get_runtime_version(), CYTHON_COMPILING_IN_LIMITED_API) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #ifdef __Pxy_PyFrame_Initialize_Offsets + __Pxy_PyFrame_Initialize_Offsets(); + #endif + __pyx_mstate->__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_mstate->__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_mstate->__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Initialize various global constants etc. ---*/ + if (__Pyx_InitConstants(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + stringtab_initialized = 1; + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #if 0 || defined(__Pyx_CyFunction_USED) || defined(__Pyx_FusedFunction_USED) || defined(__Pyx_Coroutine_USED) || defined(__Pyx_Generator_USED) || defined(__Pyx_AsyncGen_USED) + if (__pyx_CommonTypesMetaclass_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_CyFunction_USED + if (__pyx_CyFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_FusedFunction_USED + if (__pyx_FusedFunction_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Generator_USED + if (__pyx_Generator_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init(__pyx_m) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + /*--- Library function declarations ---*/ + if (__pyx_module_is_main_pysam__libcalignmentfile) { + if (PyObject_SetAttr(__pyx_m, __pyx_mstate_global->__pyx_n_u_name_2, __pyx_mstate_global->__pyx_n_u_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + } + { + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) + if (!PyDict_GetItemString(modules, "pysam.libcalignmentfile")) { + if (unlikely((PyDict_SetItemString(modules, "pysam.libcalignmentfile", __pyx_m) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + } + } + /*--- Builtin init code ---*/ + if (__Pyx_InitCachedBuiltins(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Constants init code ---*/ + if (__Pyx_InitCachedConstants(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + if (__Pyx_CreateCodeObjects(__pyx_mstate) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Global type/function init code ---*/ + (void)__Pyx_modinit_global_init_code(__pyx_mstate); + (void)__Pyx_modinit_variable_export_code(__pyx_mstate); + (void)__Pyx_modinit_function_export_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_type_init_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + if (unlikely((__Pyx_modinit_type_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + (void)__Pyx_modinit_variable_import_code(__pyx_mstate); + if (unlikely((__Pyx_modinit_function_import_code(__pyx_mstate) < 0))) __PYX_ERR(0, 1, __pyx_L1_error) + /*--- Execution code ---*/ + __Pyx_TraceStartFunc("PyInit_libcalignmentfile", __pyx_f[0], 1, 10, 0, 0, __PYX_ERR(0, 1, __pyx_L1_error)); + + /* "pysam/libcalignmentfile.pyx":58 + * # + * ######################################################## + * import os # <<<<<<<<<<<<<< + * import collections + * try: +*/ + __pyx_t_2 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_os, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_os, __pyx_t_2) < 0) __PYX_ERR(0, 58, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":59 + * ######################################################## + * import os + * import collections # <<<<<<<<<<<<<< + * try: + * from collections.abc import Sequence, Mapping # noqa +*/ + __pyx_t_2 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_collections, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_collections, __pyx_t_2) < 0) __PYX_ERR(0, 59, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":60 + * import os + * import collections + * try: # <<<<<<<<<<<<<< + * from collections.abc import Sequence, Mapping # noqa + * except ImportError: +*/ + { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_3, &__pyx_t_4); + __Pyx_XGOTREF(__pyx_t_1); + __Pyx_XGOTREF(__pyx_t_3); + __Pyx_XGOTREF(__pyx_t_4); + /*try:*/ { + + /* "pysam/libcalignmentfile.pyx":61 + * import collections + * try: + * from collections.abc import Sequence, Mapping # noqa # <<<<<<<<<<<<<< + * except ImportError: + * from collections import Sequence, Mapping # noqa +*/ + __pyx_t_2 = __Pyx_PyList_Pack(2, __pyx_mstate_global->__pyx_n_u_Sequence, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_5 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_collections_abc, __pyx_t_2, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Sequence, __pyx_t_2) < 0) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_5, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Mapping, __pyx_t_2) < 0) __PYX_ERR(0, 61, __pyx_L2_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "pysam/libcalignmentfile.pyx":60 + * import os + * import collections + * try: # <<<<<<<<<<<<<< + * from collections.abc import Sequence, Mapping # noqa + * except ImportError: +*/ + } + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + goto __pyx_L7_try_end; + __pyx_L2_error:; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_TraceException(__pyx_lineno, 0, 0); + + /* "pysam/libcalignmentfile.pyx":62 + * try: + * from collections.abc import Sequence, Mapping # noqa + * except ImportError: # <<<<<<<<<<<<<< + * from collections import Sequence, Mapping # noqa + * import re +*/ + __pyx_t_6 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_ImportError); + if (__pyx_t_6) { + __Pyx_AddTraceback("pysam.libcalignmentfile", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_TraceExceptionHandled(0); + if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_2, &__pyx_t_7) < 0) __PYX_ERR(0, 62, __pyx_L4_except_error) + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_2); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_TraceExceptionDone(); + + /* "pysam/libcalignmentfile.pyx":63 + * from collections.abc import Sequence, Mapping # noqa + * except ImportError: + * from collections import Sequence, Mapping # noqa # <<<<<<<<<<<<<< + * import re + * import warnings +*/ + __pyx_t_8 = __Pyx_PyList_Pack(2, __pyx_mstate_global->__pyx_n_u_Sequence, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_GOTREF(__pyx_t_8); + __pyx_t_9 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_collections, __pyx_t_8, 0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_ImportFrom(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Sequence, __pyx_t_8) < 0) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_8 = __Pyx_ImportFrom(__pyx_t_9, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_GOTREF(__pyx_t_8); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_Mapping, __pyx_t_8) < 0) __PYX_ERR(0, 63, __pyx_L4_except_error) + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L3_exception_handled; + } + goto __pyx_L4_except_error; + + /* "pysam/libcalignmentfile.pyx":60 + * import os + * import collections + * try: # <<<<<<<<<<<<<< + * from collections.abc import Sequence, Mapping # noqa + * except ImportError: +*/ + __pyx_L4_except_error:; + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_3, __pyx_t_4); + goto __pyx_L1_error; + __pyx_L3_exception_handled:; + __Pyx_XGIVEREF(__pyx_t_1); + __Pyx_XGIVEREF(__pyx_t_3); + __Pyx_XGIVEREF(__pyx_t_4); + __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_3, __pyx_t_4); + __pyx_L7_try_end:; + } + + /* "pysam/libcalignmentfile.pyx":64 + * except ImportError: + * from collections import Sequence, Mapping # noqa + * import re # <<<<<<<<<<<<<< + * import warnings + * import array +*/ + __pyx_t_7 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_re, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 64, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_re, __pyx_t_7) < 0) __PYX_ERR(0, 64, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":65 + * from collections import Sequence, Mapping # noqa + * import re + * import warnings # <<<<<<<<<<<<<< + * import array + * from libc.errno cimport errno, EPIPE +*/ + __pyx_t_7 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_warnings, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_warnings, __pyx_t_7) < 0) __PYX_ERR(0, 65, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":66 + * import re + * import warnings + * import array # <<<<<<<<<<<<<< + * from libc.errno cimport errno, EPIPE + * from libc.string cimport strcmp, strpbrk +*/ + __pyx_t_7 = __Pyx_ImportDottedModule(__pyx_mstate_global->__pyx_n_u_array, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_array, __pyx_t_7) < 0) __PYX_ERR(0, 66, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":79 + * HTS_IDX_SAVE_REMOTE, HTS_IDX_SILENT_FAIL + * + * from io import StringIO # <<<<<<<<<<<<<< + * + * cimport cython +*/ + __pyx_t_7 = __Pyx_PyList_Pack(1, __pyx_mstate_global->__pyx_n_u_StringIO); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_Import(__pyx_mstate_global->__pyx_n_u_io, __pyx_t_7, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_7 = __Pyx_ImportFrom(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_StringIO); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_StringIO, __pyx_t_7) < 0) __PYX_ERR(0, 79, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":84 + * + * + * __all__ = [ # <<<<<<<<<<<<<< + * "AlignmentFile", + * "AlignmentHeader", +*/ + __pyx_t_2 = __Pyx_PyList_Pack(5, __pyx_mstate_global->__pyx_n_u_AlignmentFile, __pyx_mstate_global->__pyx_n_u_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_IteratorRow, __pyx_mstate_global->__pyx_n_u_IteratorColumn, __pyx_mstate_global->__pyx_n_u_IndexedReads); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_all_2, __pyx_t_2) < 0) __PYX_ERR(0, 84, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":91 + * "IndexedReads"] + * + * IndexStats = collections.namedtuple("IndexStats", # <<<<<<<<<<<<<< + * ("contig", + * "mapped", +*/ + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_collections); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_namedtuple); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":92 + * + * IndexStats = collections.namedtuple("IndexStats", + * ("contig", # <<<<<<<<<<<<<< + * "mapped", + * "unmapped", +*/ + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_mstate_global->__pyx_tuple[3], NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_IndexStats, __pyx_t_2) < 0) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":101 + * # maximum genomic coordinace + * # for some reason, using 'int' causes overflow + * cdef int MAX_POS = (1 << 31) - 1 # <<<<<<<<<<<<<< + * + * # valid types for SAM headers +*/ + __pyx_v_5pysam_17libcalignmentfile_MAX_POS = 0x7fffffff; + + /* "pysam/libcalignmentfile.pyx":104 + * + * # valid types for SAM headers + * VALID_HEADER_TYPES = {"HD" : Mapping, # <<<<<<<<<<<<<< + * "SQ" : Sequence, + * "RG" : Sequence, +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Mapping); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_HD, __pyx_t_7) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":105 + * # valid types for SAM headers + * VALID_HEADER_TYPES = {"HD" : Mapping, + * "SQ" : Sequence, # <<<<<<<<<<<<<< + * "RG" : Sequence, + * "PG" : Sequence, +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 105, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_t_7) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":106 + * VALID_HEADER_TYPES = {"HD" : Mapping, + * "SQ" : Sequence, + * "RG" : Sequence, # <<<<<<<<<<<<<< + * "PG" : Sequence, + * "CO" : Sequence} +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 106, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_RG, __pyx_t_7) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":107 + * "SQ" : Sequence, + * "RG" : Sequence, + * "PG" : Sequence, # <<<<<<<<<<<<<< + * "CO" : Sequence} + * +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 107, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_PG, __pyx_t_7) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":108 + * "RG" : Sequence, + * "PG" : Sequence, + * "CO" : Sequence} # <<<<<<<<<<<<<< + * + * # order of records within SAM headers +*/ + __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_Sequence); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_CO, __pyx_t_7) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_TYPES, __pyx_t_2) < 0) __PYX_ERR(0, 104, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":111 + * + * # order of records within SAM headers + * VALID_HEADERS = ("HD", "SQ", "RG", "PG", "CO") # <<<<<<<<<<<<<< + * + * # default type conversions within SAM header records +*/ + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_VALID_HEADERS, __pyx_mstate_global->__pyx_tuple[4]) < 0) __PYX_ERR(0, 111, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":114 + * + * # default type conversions within SAM header records + * KNOWN_HEADER_FIELDS = {"HD" : {"VN" : str, "SO" : str, "GO" : str, # <<<<<<<<<<<<<< + * "SS" : str,}, + * "SQ" : {"SN" : str, "LN" : int, "AS" : str, +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_VN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_SO, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_GO, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":115 + * # default type conversions within SAM header records + * KNOWN_HEADER_FIELDS = {"HD" : {"VN" : str, "SO" : str, "GO" : str, + * "SS" : str,}, # <<<<<<<<<<<<<< + * "SQ" : {"SN" : str, "LN" : int, "AS" : str, + * "M5" : str, "SP" : str, "UR" : str, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_SS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_HD, __pyx_t_7) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":116 + * KNOWN_HEADER_FIELDS = {"HD" : {"VN" : str, "SO" : str, "GO" : str, + * "SS" : str,}, + * "SQ" : {"SN" : str, "LN" : int, "AS" : str, # <<<<<<<<<<<<<< + * "M5" : str, "SP" : str, "UR" : str, + * "AH" : str, "TP" : str, "DS" : str, +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(10); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 116, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_SN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_LN, ((PyObject *)(&PyLong_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_AS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":117 + * "SS" : str,}, + * "SQ" : {"SN" : str, "LN" : int, "AS" : str, + * "M5" : str, "SP" : str, "UR" : str, # <<<<<<<<<<<<<< + * "AH" : str, "TP" : str, "DS" : str, + * "AN" : str,}, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_M5, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_SP, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_UR, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":118 + * "SQ" : {"SN" : str, "LN" : int, "AS" : str, + * "M5" : str, "SP" : str, "UR" : str, + * "AH" : str, "TP" : str, "DS" : str, # <<<<<<<<<<<<<< + * "AN" : str,}, + * "RG" : {"ID" : str, "CN" : str, "DS" : str, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_AH, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_TP, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_DS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":119 + * "M5" : str, "SP" : str, "UR" : str, + * "AH" : str, "TP" : str, "DS" : str, + * "AN" : str,}, # <<<<<<<<<<<<<< + * "RG" : {"ID" : str, "CN" : str, "DS" : str, + * "DT" : str, "FO" : str, "KS" : str, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_AN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 116, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_t_7) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":120 + * "AH" : str, "TP" : str, "DS" : str, + * "AN" : str,}, + * "RG" : {"ID" : str, "CN" : str, "DS" : str, # <<<<<<<<<<<<<< + * "DT" : str, "FO" : str, "KS" : str, + * "LB" : str, "PG" : str, "PI" : str, +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(14); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 120, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_ID, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_CN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_DS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":121 + * "AN" : str,}, + * "RG" : {"ID" : str, "CN" : str, "DS" : str, + * "DT" : str, "FO" : str, "KS" : str, # <<<<<<<<<<<<<< + * "LB" : str, "PG" : str, "PI" : str, + * "PL" : str, "PM" : str, "PU" : str, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_DT, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_FO, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_KS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":122 + * "RG" : {"ID" : str, "CN" : str, "DS" : str, + * "DT" : str, "FO" : str, "KS" : str, + * "LB" : str, "PG" : str, "PI" : str, # <<<<<<<<<<<<<< + * "PL" : str, "PM" : str, "PU" : str, + * "SM" : str, "BC" : str,}, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_LB, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PG, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PI, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":123 + * "DT" : str, "FO" : str, "KS" : str, + * "LB" : str, "PG" : str, "PI" : str, + * "PL" : str, "PM" : str, "PU" : str, # <<<<<<<<<<<<<< + * "SM" : str, "BC" : str,}, + * "PG" : {"ID" : str, "PN" : str, "CL" : str, +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PL, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PM, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PU, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":124 + * "LB" : str, "PG" : str, "PI" : str, + * "PL" : str, "PM" : str, "PU" : str, + * "SM" : str, "BC" : str,}, # <<<<<<<<<<<<<< + * "PG" : {"ID" : str, "PN" : str, "CL" : str, + * "PP" : str, "DS" : str, "VN" : str,},} +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_SM, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_BC, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 120, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_RG, __pyx_t_7) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":125 + * "PL" : str, "PM" : str, "PU" : str, + * "SM" : str, "BC" : str,}, + * "PG" : {"ID" : str, "PN" : str, "CL" : str, # <<<<<<<<<<<<<< + * "PP" : str, "DS" : str, "VN" : str,},} + * +*/ + __pyx_t_7 = __Pyx_PyDict_NewPresized(6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 125, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_ID, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_CL, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":126 + * "SM" : str, "BC" : str,}, + * "PG" : {"ID" : str, "PN" : str, "CL" : str, + * "PP" : str, "DS" : str, "VN" : str,},} # <<<<<<<<<<<<<< + * + * # output order of fields within records. Ensure that CL is at +*/ + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_PP, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_DS, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_7, __pyx_mstate_global->__pyx_n_u_VN, ((PyObject *)(&PyUnicode_Type))) < 0) __PYX_ERR(0, 125, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_PG, __pyx_t_7) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_KNOWN_HEADER_FIELDS, __pyx_t_2) < 0) __PYX_ERR(0, 114, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":130 + * # output order of fields within records. Ensure that CL is at + * # the end as parsing a CL will ignore any subsequent records. + * VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "SS", "GO"), # <<<<<<<<<<<<<< + * "SQ" : ("SN", "LN", "AS", "M5", + * "UR", "SP", "AH", "TP", +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_HD, __pyx_mstate_global->__pyx_tuple[5]) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":131 + * # the end as parsing a CL will ignore any subsequent records. + * VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "SS", "GO"), + * "SQ" : ("SN", "LN", "AS", "M5", # <<<<<<<<<<<<<< + * "UR", "SP", "AH", "TP", + * "DS", "AN"), +*/ + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_mstate_global->__pyx_tuple[6]) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":134 + * "UR", "SP", "AH", "TP", + * "DS", "AN"), + * "RG" : ("ID", "CN", "SM", "LB", # <<<<<<<<<<<<<< + * "PU", "PI", "DT", "DS", + * "PL", "FO", "KS", "PG", +*/ + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_RG, __pyx_mstate_global->__pyx_tuple[7]) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + + /* "pysam/libcalignmentfile.pyx":138 + * "PL", "FO", "KS", "PG", + * "PM", "BC"), + * "PG" : ("PN", "ID", "VN", "PP", # <<<<<<<<<<<<<< + * "DS", "CL"),} + * +*/ + if (PyDict_SetItem(__pyx_t_2, __pyx_mstate_global->__pyx_n_u_PG, __pyx_mstate_global->__pyx_tuple[8]) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_VALID_HEADER_ORDER, __pyx_t_2) < 0) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":142 + * + * + * def build_header_line(fields, record): # <<<<<<<<<<<<<< + * '''build a header line from `fields` dictionary for `record`''' + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_1build_header_line, 0, __pyx_mstate_global->__pyx_n_u_build_header_line, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_build_header_line, __pyx_t_2) < 0) __PYX_ERR(0, 142, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":178 + * return header + * + * def read_failure_reason(code): # <<<<<<<<<<<<<< + * if code == -2: + * return 'truncated file' +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_3read_failure_reason, 0, __pyx_mstate_global->__pyx_n_u_read_failure_reason, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[2])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_read_failure_reason, __pyx_t_2) < 0) __PYX_ERR(0, 178, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":237 + * raise MemoryError("could not create header") + * + * @classmethod # <<<<<<<<<<<<<< + * def _from_text_and_lengths(cls, text, reference_names, reference_lengths): + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_5_from_text_and_lengths, __Pyx_CYFUNCTION_CLASSMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader__from_text_and_l, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[6])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text_and_lengths, __pyx_t_2) < 0) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GetNameInClass(__pyx_t_2, (PyObject*)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text_and_lengths); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_Method_ClassMethod(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text_and_lengths, __pyx_t_7) < 0) __PYX_ERR(0, 237, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":278 + * return self + * + * @classmethod # <<<<<<<<<<<<<< + * def from_text(cls, text): + * +*/ + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_7from_text, __Pyx_CYFUNCTION_CLASSMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_from_text, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[7])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 278, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text, __pyx_t_7) < 0) __PYX_ERR(0, 278, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GetNameInClass(__pyx_t_7, (PyObject*)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 278, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_Method_ClassMethod(__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 278, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_text, __pyx_t_2) < 0) __PYX_ERR(0, 278, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":295 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_dict(cls, header_dict): + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_9from_dict, __Pyx_CYFUNCTION_CLASSMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_from_dict, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[8])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 295, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_dict, __pyx_t_2) < 0) __PYX_ERR(0, 295, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GetNameInClass(__pyx_t_2, (PyObject*)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_dict); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 295, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_7 = __Pyx_Method_ClassMethod(__pyx_t_2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 295, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_dict, __pyx_t_7) < 0) __PYX_ERR(0, 295, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "pysam/libcalignmentfile.pyx":336 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * +*/ + __pyx_t_7 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_11from_references, __Pyx_CYFUNCTION_CLASSMETHOD | __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_from_references, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[9])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_7, __pyx_mstate_global->__pyx_tuple[9]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_references, __pyx_t_7) < 0) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GetNameInClass(__pyx_t_7, (PyObject*)__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_references); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_2 = __Pyx_Method_ClassMethod(__pyx_t_7); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_from_references, __pyx_t_2) < 0) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":356 + * return self.ptr != NULL + * + * def copy(self): # <<<<<<<<<<<<<< + * return makeAlignmentHeader(bam_hdr_dup(self.ptr)) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_17copy, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_copy, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[12])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_copy, __pyx_t_2) < 0) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":388 + * return tuple(t) + * + * def _build_sequence_section(self): # <<<<<<<<<<<<<< + * """return sequence section of header. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_19_build_sequence_section, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader__build_sequence, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[16])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 388, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_build_sequence_section, __pyx_t_2) < 0) __PYX_ERR(0, 388, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":404 + * return "".join(text) + * + * def to_dict(self): # <<<<<<<<<<<<<< + * """return two-level dictionary with header information from the file. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_21to_dict, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_to_dict, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[17])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 404, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_to_dict, __pyx_t_2) < 0) __PYX_ERR(0, 404, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":496 + * return result + * + * def as_dict(self): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`to_dict()` instead""" + * return self.to_dict() +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_23as_dict, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_as_dict, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[18])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 496, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_as_dict, __pyx_t_2) < 0) __PYX_ERR(0, 496, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":500 + * return self.to_dict() + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * if tid == -1: + * return None +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_25get_reference_name, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_get_reference_na, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[19])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 500, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_get_reference_name, __pyx_t_2) < 0) __PYX_ERR(0, 500, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":508 + * return charptr_to_str(self.ptr.target_name[tid]) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * cdef int tid = self.get_tid(reference) + * if tid < 0: +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_27get_reference_length, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_get_reference_le, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[20])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 508, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_get_reference_length, __pyx_t_2) < 0) __PYX_ERR(0, 508, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":515 + * return self.ptr.target_len[tid] + * + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_29is_valid_tid, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_is_valid_tid, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[21])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 515, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_is_valid_tid, __pyx_t_2) < 0) __PYX_ERR(0, 515, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":523 + * return 0 <= tid < self.ptr.n_targets + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_31get_tid, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_get_tid, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[22])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 523, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_get_tid, __pyx_t_2) < 0) __PYX_ERR(0, 523, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":559 + * return self.to_dict().__getitem__(key) + * + * def items(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_39items, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_items, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[26])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 559, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_items, __pyx_t_2) < 0) __PYX_ERR(0, 559, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":563 + * + * # PY2 compatibility + * def iteritems(self): # <<<<<<<<<<<<<< + * return self.to_dict().items() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_41iteritems, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_iteritems, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[27])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 563, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_iteritems, __pyx_t_2) < 0) __PYX_ERR(0, 563, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":566 + * return self.to_dict().items() + * + * def keys(self): # <<<<<<<<<<<<<< + * return self.to_dict().keys() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_43keys, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_keys, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[28])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 566, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_keys, __pyx_t_2) < 0) __PYX_ERR(0, 566, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":569 + * return self.to_dict().keys() + * + * def values(self): # <<<<<<<<<<<<<< + * return self.to_dict().values() + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_45values, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_values, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[29])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 569, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_values, __pyx_t_2) < 0) __PYX_ERR(0, 569, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":572 + * return self.to_dict().values() + * + * def get(self, *args): # <<<<<<<<<<<<<< + * return self.to_dict().get(*args) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_47get, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader_get, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[30])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 572, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentHeader, __pyx_mstate_global->__pyx_n_u_get, __pyx_t_2) < 0) __PYX_ERR(0, 572, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_53__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[33])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15AlignmentHeader_55__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentHeader___setstate_cytho, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[34])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":758 + * raise MemoryError("could not allocate memory of size {}".format(sizeof(bam1_t))) + * + * def has_index(self): # <<<<<<<<<<<<<< + * """return true if htsfile has an existing (and opened) index. + * """ +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_3has_index, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_has_index, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[36])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 758, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_has_index, __pyx_t_2) < 0) __PYX_ERR(0, 758, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":763 + * return self.index != NULL + * + * def check_index(self): # <<<<<<<<<<<<<< + * """return True if index is present. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_5check_index, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_check_index, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[37])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 763, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_check_index, __pyx_t_2) < 0) __PYX_ERR(0, 763, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":787 + * return True + * + * def _open(self, # <<<<<<<<<<<<<< + * filepath_or_object, + * mode=None, +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_7_open, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile__open, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[38])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 787, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[10]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_open, __pyx_t_2) < 0) __PYX_ERR(0, 787, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1028 + * self.start_offset = self.tell() + * + * def fetch(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_9fetch, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_fetch, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[39])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1028, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[11]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_fetch, __pyx_t_2) < 0) __PYX_ERR(0, 1028, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1133 + * multiple_iterators=multiple_iterators) + * + * def head(self, n, multiple_iterators=True): # <<<<<<<<<<<<<< + * '''return an iterator over the first n alignments. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_11head, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_head, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[40])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[12]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_head, __pyx_t_2) < 0) __PYX_ERR(0, 1133, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1155 + * multiple_iterators=multiple_iterators) + * + * def mate(self, AlignedSegment read): # <<<<<<<<<<<<<< + * '''return the mate of :class:`pysam.AlignedSegment` `read`. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_13mate, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_mate, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[41])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1155, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_mate, __pyx_t_2) < 0) __PYX_ERR(0, 1155, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1214 + * return mate + * + * def pileup(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_15pileup, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_pileup, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[42])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1214, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[13]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_pileup, __pyx_t_2) < 0) __PYX_ERR(0, 1214, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1354 + * return IteratorColumnAll(self, **kwargs) + * + * def count(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_17count, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_count, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[43])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1354, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[14]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_count, __pyx_t_2) < 0) __PYX_ERR(0, 1354, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1457 + * return counter + * + * @cython.boundscheck(False) # we do manual bounds checking # <<<<<<<<<<<<<< + * def count_coverage(self, + * contig, +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_19count_coverage, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_count_coverage, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[44])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1457, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_mstate_global->__pyx_tuple[15]); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_count_coverage, __pyx_t_2) < 0) __PYX_ERR(0, 1457, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1609 + * return count_a, count_c, count_g, count_t + * + * def find_introns_slow(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_21find_introns_slow, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_find_introns_slow, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[45])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1609, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_find_introns_slow, __pyx_t_2) < 0) __PYX_ERR(0, 1609, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1633 + * return res + * + * def find_introns(self, read_iterator): # <<<<<<<<<<<<<< + * """Return a dictionary {(start, stop): count} + * Listing the intronic sites in the reads (identified by 'N' in the cigar strings), +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_23find_introns, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_find_introns, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[46])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1633, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_find_introns, __pyx_t_2) < 0) __PYX_ERR(0, 1633, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1667 + * + * + * def close(self): # <<<<<<<<<<<<<< + * '''closes the :class:`pysam.AlignmentFile`.''' + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_25close, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_close, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[47])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1667, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_close, __pyx_t_2) < 0) __PYX_ERR(0, 1667, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1711 + * raise OSError_from_errno("Closing failed") + * + * cpdef int write(self, AlignedSegment read) except -1: # <<<<<<<<<<<<<< + * ''' + * write a single :class:`pysam.AlignedSegment` to disk. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_29write, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_write, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[49])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_write, __pyx_t_2) < 0) __PYX_ERR(0, 1711, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1748 + * + * # context manager interface + * def __enter__(self): # <<<<<<<<<<<<<< + * return self + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_31__enter__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile___enter, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[50])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1748, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_enter, __pyx_t_2) < 0) __PYX_ERR(0, 1748, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1751 + * return self + * + * def __exit__(self, exc_type, exc_value, traceback): # <<<<<<<<<<<<<< + * self.close() + * return False +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_33__exit__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile___exit, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[51])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1751, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_exit, __pyx_t_2) < 0) __PYX_ERR(0, 1751, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1810 + * return n + * + * def get_index_statistics(self): # <<<<<<<<<<<<<< + * """return statistics about mapped/unmapped reads per chromosome as + * they are stored in the index, similarly to the statistics printed +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_35get_index_statistics, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_get_index_statisti, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[55])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1810, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_get_index_statistics, __pyx_t_2) < 0) __PYX_ERR(0, 1810, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1881 + * ########################################### + * # methods/properties referencing the header + * def is_valid_tid(self, int tid): # <<<<<<<<<<<<<< + * """ + * return True if the numerical :term:`tid` is valid; False otherwise. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_41is_valid_tid, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_is_valid_tid, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[60])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1881, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_is_valid_tid, __pyx_t_2) < 0) __PYX_ERR(0, 1881, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1891 + * return self.header.is_valid_tid(tid) + * + * def get_tid(self, reference): # <<<<<<<<<<<<<< + * """ + * return the numerical :term:`tid` corresponding to +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_43get_tid, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_get_tid, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[61])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1891, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_get_tid, __pyx_t_2) < 0) __PYX_ERR(0, 1891, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1902 + * return self.header.get_tid(reference) + * + * def get_reference_name(self, tid): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` name corresponding to numerical :term:`tid` +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_45get_reference_name, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_get_reference_name, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[62])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1902, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_get_reference_name, __pyx_t_2) < 0) __PYX_ERR(0, 1902, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1910 + * return self.header.get_reference_name(tid) + * + * def get_reference_length(self, reference): # <<<<<<<<<<<<<< + * """ + * return :term:`reference` length corresponding to numerical :term:`tid` +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_47get_reference_length, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_get_reference_leng, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[63])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1910, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_get_reference_length, __pyx_t_2) < 0) __PYX_ERR(0, 1910, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1958 + * + * # Compatibility functions for pysam < 0.8.3 + * def gettid(self, reference): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_tid` instead""" + * return self.get_tid(reference) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_49gettid, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_gettid, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[68])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1958, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_gettid, __pyx_t_2) < 0) __PYX_ERR(0, 1958, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1962 + * return self.get_tid(reference) + * + * def getrname(self, tid): # <<<<<<<<<<<<<< + * """deprecated, use :meth:`get_reference_name` instead""" + * return self.get_reference_name(tid) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_51getrname, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile_getrname, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[69])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1962, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_AlignmentFile, __pyx_mstate_global->__pyx_n_u_getrname, __pyx_t_2) < 0) __PYX_ERR(0, 1962, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_53__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[72])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_13AlignmentFile_55__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_AlignmentFile___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[73])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_11IteratorRow_5__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRow___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[76])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_11IteratorRow_7__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRow___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[77])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_17IteratorRowRegion_9__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowRegion___reduce_cytho, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[84])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index,self.iter cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_17IteratorRowRegion_11__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowRegion___setstate_cyt, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[85])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15IteratorRowHead_7__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowHead___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[91])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_15IteratorRowHead_9__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowHead___setstate_cytho, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[92])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorRowAll_7__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowAll___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[98])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorRowAll_9__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowAll___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[99])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2228 + * self.tid = -1 + * + * def nextiter(self): # <<<<<<<<<<<<<< + * # get a new iterator for a chromosome. The file + * # will not be re-opened. +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_3nextiter, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowAllRefs_nextiter, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[101])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2228, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorRowAllRefs, __pyx_mstate_global->__pyx_n_u_nextiter, __pyx_t_2) < 0) __PYX_ERR(0, 2228, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_9__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowAllRefs___reduce_cyth, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[104])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_18IteratorRowAllRefs_11__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowAllRefs___setstate_cy, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[105])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_20IteratorRowSelection_7__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowSelection___reduce_cy, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[111])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.b,self.htsfile,self.index cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_20IteratorRowSelection_9__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorRowSelection___setstate, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[112])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2521 + * return self.iterdata.seq_len + * + * def add_reference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * ''' + * add reference sequences in `fastafile` to iterator.''' +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_5add_reference, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn_add_reference, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[123])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2521, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn, __pyx_mstate_global->__pyx_n_u_add_reference, __pyx_t_2) < 0) __PYX_ERR(0, 2521, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2530 + * self.iterdata.fastafile = self.fastafile.fastafile + * + * def has_reference(self): # <<<<<<<<<<<<<< + * ''' + * return true if iterator is associated with a reference''' +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_7has_reference, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn_has_reference, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[124])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2530, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn, __pyx_mstate_global->__pyx_n_u_has_reference, __pyx_t_2) < 0) __PYX_ERR(0, 2530, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2685 + * # backwards compatibility + * + * def hasReference(self): # <<<<<<<<<<<<<< + * return self.has_reference() + * cdef char * getSequence(self): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_11hasReference, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn_hasReference, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[130])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2685, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn, __pyx_mstate_global->__pyx_n_u_hasReference, __pyx_t_2) < 0) __PYX_ERR(0, 2685, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2689 + * cdef char * getSequence(self): + * return self.get_sequence() + * def addReference(self, FastaFile fastafile): # <<<<<<<<<<<<<< + * return self.add_reference(fastafile) + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_13addReference, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn_addReference, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[132])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2689, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IteratorColumn, __pyx_mstate_global->__pyx_n_u_addReference, __pyx_t_2) < 0) __PYX_ERR(0, 2689, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_15__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[133])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_14IteratorColumn_17__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumn___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[134])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2700 + * int tid = 0, + * int start = 0, + * int stop = MAX_POS, # <<<<<<<<<<<<<< + * int truncate = False, + * int multiple_iterators = True, +*/ + __pyx_mstate_global->__pyx_k__10 = __pyx_v_5pysam_17libcalignmentfile_MAX_POS; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_20IteratorColumnRegion_5__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnRegion___reduce_cy, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[137])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_20IteratorColumnRegion_7__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnRegion___setstate, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[138])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_5__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnAllRefs___reduce_c, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[141])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_21IteratorColumnAllRefs_7__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnAllRefs___setstate, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[142])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_17IteratorColumnAll_5__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnAll___reduce_cytho, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[145])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "no default __reduce__ due to non-trivial __cinit__" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_17IteratorColumnAll_7__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IteratorColumnAll___setstate_cyt, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[146])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_7SNPCall_3__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_SNPCall___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[156])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":16 + * else: + * return __pyx_unpickle_SNPCall, (type(self), 0xe45c101, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_SNPCall__set_state(self, __pyx_state) +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_7SNPCall_5__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_SNPCall___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[157])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_SNPCall, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 16, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2926 + * self.owns_samfile = False + * + * def build(self): # <<<<<<<<<<<<<< + * '''build the index.''' + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_3build, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IndexedReads_build, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[159])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2926, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads, __pyx_mstate_global->__pyx_n_u_build, __pyx_t_2) < 0) __PYX_ERR(0, 2926, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":2953 + * bam_destroy1(b) + * + * def find(self, query_name): # <<<<<<<<<<<<<< + * '''find `query_name` in index. + * +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_5find, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IndexedReads_find, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[160])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2953, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (__Pyx_SetItemOnTypeDict(__pyx_mstate_global->__pyx_ptype_5pysam_17libcalignmentfile_IndexedReads, __pyx_mstate_global->__pyx_n_u_find, __pyx_t_2) < 0) __PYX_ERR(0, 2953, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_9__reduce_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IndexedReads___reduce_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[162])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_reduce_cython, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError, "self.htsfile cannot be converted to a Python object for pickling" +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_12IndexedReads_11__setstate_cython__, __Pyx_CYFUNCTION_CCLASS, __pyx_mstate_global->__pyx_n_u_IndexedReads___setstate_cython, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[163])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_setstate_cython, __pyx_t_2) < 0) __PYX_ERR(3, 3, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "(tree fragment)":1 + * def __pyx_unpickle_SNPCall(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result +*/ + __pyx_t_2 = __Pyx_CyFunction_New(&__pyx_mdef_5pysam_17libcalignmentfile_5__pyx_unpickle_SNPCall, 0, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_SNPCall, NULL, __pyx_mstate_global->__pyx_n_u_pysam_libcalignmentfile, __pyx_mstate_global->__pyx_d, ((PyObject *)__pyx_mstate_global->__pyx_codeobj_tab[164])); if (unlikely(!__pyx_t_2)) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_pyx_unpickle_SNPCall, __pyx_t_2) < 0) __PYX_ERR(3, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "pysam/libcalignmentfile.pyx":1 + * # cython: embedsignature=True # <<<<<<<<<<<<<< + * # cython: profile=True + * ######################################################## +*/ + __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_mstate_global->__pyx_d, __pyx_mstate_global->__pyx_n_u_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_TraceReturnValue(Py_None, 10, 0, __PYX_ERR(0, 1, __pyx_L1_error)); + __Pyx_PyMonitoring_ExitScope(0); + + /*--- Wrapped vars code ---*/ + + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_TraceException(__pyx_lineno, 0, 0); + __Pyx_TraceExceptionUnwind(10, 0); + if (__pyx_m) { + if (__pyx_mstate->__pyx_d && stringtab_initialized) { + __Pyx_AddTraceback("init pysam.libcalignmentfile", __pyx_clineno, __pyx_lineno, __pyx_filename); + } + #if !CYTHON_USE_MODULE_STATE + Py_CLEAR(__pyx_m); + #else + Py_DECREF(__pyx_m); + if (pystate_addmodule_run) { + PyObject *tp, *value, *tb; + PyErr_Fetch(&tp, &value, &tb); + PyState_RemoveModule(&__pyx_moduledef); + PyErr_Restore(tp, value, tb); + } + #endif + } else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_ImportError, "init pysam.libcalignmentfile"); + } + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #else + return __pyx_m; + #endif +} +/* #### Code section: pystring_table ### */ + +typedef struct { + const char *s; +#if 179 <= 65535 + const unsigned short n; +#elif 179 / 2 < INT_MAX + const unsigned int n; +#elif 179 / 2 < LONG_MAX + const unsigned long n; +#else + const Py_ssize_t n; +#endif +#if 1 <= 31 + const unsigned int encoding : 5; +#elif 1 <= 255 + const unsigned char encoding; +#elif 1 <= 65535 + const unsigned short encoding; +#else + const Py_ssize_t encoding; +#endif + const unsigned int is_unicode : 1; + const unsigned int intern : 1; +} __Pyx_StringTabEntry; +static const char * const __pyx_string_tab_encodings[] = { 0 }; +static const __Pyx_StringTabEntry __pyx_string_tab[] = { + {__pyx_k_, sizeof(__pyx_k_), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_ */ + {__pyx_k_AH, sizeof(__pyx_k_AH), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AH */ + {__pyx_k_AN, sizeof(__pyx_k_AN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AN */ + {__pyx_k_AS, sizeof(__pyx_k_AS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AS */ + {__pyx_k_AlignedSegment_refers_to_referen, sizeof(__pyx_k_AlignedSegment_refers_to_referen), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_AlignedSegment_refers_to_referen */ + {__pyx_k_AlignmentFile, sizeof(__pyx_k_AlignmentFile), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile */ + {__pyx_k_AlignmentFile___enter, sizeof(__pyx_k_AlignmentFile___enter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile___enter */ + {__pyx_k_AlignmentFile___exit, sizeof(__pyx_k_AlignmentFile___exit), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile___exit */ + {__pyx_k_AlignmentFile___reduce_cython, sizeof(__pyx_k_AlignmentFile___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile___reduce_cython */ + {__pyx_k_AlignmentFile___setstate_cython, sizeof(__pyx_k_AlignmentFile___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile___setstate_cython */ + {__pyx_k_AlignmentFile__open, sizeof(__pyx_k_AlignmentFile__open), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile__open */ + {__pyx_k_AlignmentFile_check_index, sizeof(__pyx_k_AlignmentFile_check_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_check_index */ + {__pyx_k_AlignmentFile_close, sizeof(__pyx_k_AlignmentFile_close), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_close */ + {__pyx_k_AlignmentFile_count, sizeof(__pyx_k_AlignmentFile_count), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_count */ + {__pyx_k_AlignmentFile_count_coverage, sizeof(__pyx_k_AlignmentFile_count_coverage), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_count_coverage */ + {__pyx_k_AlignmentFile_fetch, sizeof(__pyx_k_AlignmentFile_fetch), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_fetch */ + {__pyx_k_AlignmentFile_find_introns, sizeof(__pyx_k_AlignmentFile_find_introns), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_find_introns */ + {__pyx_k_AlignmentFile_find_introns_slow, sizeof(__pyx_k_AlignmentFile_find_introns_slow), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_find_introns_slow */ + {__pyx_k_AlignmentFile_get_index_statisti, sizeof(__pyx_k_AlignmentFile_get_index_statisti), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_get_index_statisti */ + {__pyx_k_AlignmentFile_get_reference_leng, sizeof(__pyx_k_AlignmentFile_get_reference_leng), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_get_reference_leng */ + {__pyx_k_AlignmentFile_get_reference_name, sizeof(__pyx_k_AlignmentFile_get_reference_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_get_reference_name */ + {__pyx_k_AlignmentFile_get_tid, sizeof(__pyx_k_AlignmentFile_get_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_get_tid */ + {__pyx_k_AlignmentFile_getrname, sizeof(__pyx_k_AlignmentFile_getrname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_getrname */ + {__pyx_k_AlignmentFile_gettid, sizeof(__pyx_k_AlignmentFile_gettid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_gettid */ + {__pyx_k_AlignmentFile_has_index, sizeof(__pyx_k_AlignmentFile_has_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_has_index */ + {__pyx_k_AlignmentFile_head, sizeof(__pyx_k_AlignmentFile_head), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_head */ + {__pyx_k_AlignmentFile_is_valid_tid, sizeof(__pyx_k_AlignmentFile_is_valid_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_is_valid_tid */ + {__pyx_k_AlignmentFile_mapped_only_availa, sizeof(__pyx_k_AlignmentFile_mapped_only_availa), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_AlignmentFile_mapped_only_availa */ + {__pyx_k_AlignmentFile_mate, sizeof(__pyx_k_AlignmentFile_mate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_mate */ + {__pyx_k_AlignmentFile_pileup, sizeof(__pyx_k_AlignmentFile_pileup), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_pileup */ + {__pyx_k_AlignmentFile_write, sizeof(__pyx_k_AlignmentFile_write), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentFile_write */ + {__pyx_k_AlignmentHeader, sizeof(__pyx_k_AlignmentHeader), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader */ + {__pyx_k_AlignmentHeader___reduce_cython, sizeof(__pyx_k_AlignmentHeader___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader___reduce_cython */ + {__pyx_k_AlignmentHeader___setstate_cytho, sizeof(__pyx_k_AlignmentHeader___setstate_cytho), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader___setstate_cytho */ + {__pyx_k_AlignmentHeader__build_sequence, sizeof(__pyx_k_AlignmentHeader__build_sequence), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader__build_sequence */ + {__pyx_k_AlignmentHeader__from_text_and_l, sizeof(__pyx_k_AlignmentHeader__from_text_and_l), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader__from_text_and_l */ + {__pyx_k_AlignmentHeader_as_dict, sizeof(__pyx_k_AlignmentHeader_as_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_as_dict */ + {__pyx_k_AlignmentHeader_copy, sizeof(__pyx_k_AlignmentHeader_copy), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_copy */ + {__pyx_k_AlignmentHeader_does_not_support, sizeof(__pyx_k_AlignmentHeader_does_not_support), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_AlignmentHeader_does_not_support */ + {__pyx_k_AlignmentHeader_from_dict, sizeof(__pyx_k_AlignmentHeader_from_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_from_dict */ + {__pyx_k_AlignmentHeader_from_references, sizeof(__pyx_k_AlignmentHeader_from_references), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_from_references */ + {__pyx_k_AlignmentHeader_from_text, sizeof(__pyx_k_AlignmentHeader_from_text), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_from_text */ + {__pyx_k_AlignmentHeader_get, sizeof(__pyx_k_AlignmentHeader_get), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_get */ + {__pyx_k_AlignmentHeader_get_reference_le, sizeof(__pyx_k_AlignmentHeader_get_reference_le), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_get_reference_le */ + {__pyx_k_AlignmentHeader_get_reference_na, sizeof(__pyx_k_AlignmentHeader_get_reference_na), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_get_reference_na */ + {__pyx_k_AlignmentHeader_get_tid, sizeof(__pyx_k_AlignmentHeader_get_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_get_tid */ + {__pyx_k_AlignmentHeader_is_valid_tid, sizeof(__pyx_k_AlignmentHeader_is_valid_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_is_valid_tid */ + {__pyx_k_AlignmentHeader_items, sizeof(__pyx_k_AlignmentHeader_items), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_items */ + {__pyx_k_AlignmentHeader_iteritems, sizeof(__pyx_k_AlignmentHeader_iteritems), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_iteritems */ + {__pyx_k_AlignmentHeader_keys, sizeof(__pyx_k_AlignmentHeader_keys), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_keys */ + {__pyx_k_AlignmentHeader_to_dict, sizeof(__pyx_k_AlignmentHeader_to_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_to_dict */ + {__pyx_k_AlignmentHeader_values, sizeof(__pyx_k_AlignmentHeader_values), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AlignmentHeader_values */ + {__pyx_k_AssertionError, sizeof(__pyx_k_AssertionError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AssertionError */ + {__pyx_k_AttributeError, sizeof(__pyx_k_AttributeError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_AttributeError */ + {__pyx_k_BAM_CREF_SKIP, sizeof(__pyx_k_BAM_CREF_SKIP), 0, 1, 1}, /* PyObject cname: __pyx_n_u_BAM_CREF_SKIP */ + {__pyx_k_BC, sizeof(__pyx_k_BC), 0, 1, 1}, /* PyObject cname: __pyx_n_u_BC */ + {__pyx_k_CL, sizeof(__pyx_k_CL), 0, 1, 1}, /* PyObject cname: __pyx_n_u_CL */ + {__pyx_k_CN, sizeof(__pyx_k_CN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_CN */ + {__pyx_k_CO, sizeof(__pyx_k_CO), 0, 1, 1}, /* PyObject cname: __pyx_n_u_CO */ + {__pyx_k_Can_t_seek, sizeof(__pyx_k_Can_t_seek), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Can_t_seek */ + {__pyx_k_Cannot_add_extra_threads_when_ig, sizeof(__pyx_k_Cannot_add_extra_threads_when_ig), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Cannot_add_extra_threads_when_ig */ + {__pyx_k_Closing_failed, sizeof(__pyx_k_Closing_failed), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Closing_failed */ + {__pyx_k_Could_not_open_alignment_file, sizeof(__pyx_k_Could_not_open_alignment_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Could_not_open_alignment_file */ + {__pyx_k_Could_not_open_index_file, sizeof(__pyx_k_Could_not_open_index_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Could_not_open_index_file */ + {__pyx_k_Could_not_write_headers, sizeof(__pyx_k_Could_not_write_headers), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Could_not_write_headers */ + {__pyx_k_Counter, sizeof(__pyx_k_Counter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_Counter */ + {__pyx_k_DS, sizeof(__pyx_k_DS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_DS */ + {__pyx_k_DT, sizeof(__pyx_k_DT), 0, 1, 1}, /* PyObject cname: __pyx_n_u_DT */ + {__pyx_k_FO, sizeof(__pyx_k_FO), 0, 1, 1}, /* PyObject cname: __pyx_n_u_FO */ + {__pyx_k_GO, sizeof(__pyx_k_GO), 0, 1, 1}, /* PyObject cname: __pyx_n_u_GO */ + {__pyx_k_HD, sizeof(__pyx_k_HD), 0, 1, 1}, /* PyObject cname: __pyx_n_u_HD */ + {__pyx_k_ID, sizeof(__pyx_k_ID), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ID */ + {__pyx_k_IOError, sizeof(__pyx_k_IOError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IOError */ + {__pyx_k_I_O_operation_on_closed_file, sizeof(__pyx_k_I_O_operation_on_closed_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_I_O_operation_on_closed_file */ + {__pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ImportError */ + {__pyx_k_Incompatible_checksums_0x_x_vs_0, sizeof(__pyx_k_Incompatible_checksums_0x_x_vs_0), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Incompatible_checksums_0x_x_vs_0 */ + {__pyx_k_IndexStats, sizeof(__pyx_k_IndexStats), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexStats */ + {__pyx_k_IndexedReads, sizeof(__pyx_k_IndexedReads), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexedReads */ + {__pyx_k_IndexedReads___reduce_cython, sizeof(__pyx_k_IndexedReads___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexedReads___reduce_cython */ + {__pyx_k_IndexedReads___setstate_cython, sizeof(__pyx_k_IndexedReads___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexedReads___setstate_cython */ + {__pyx_k_IndexedReads_build, sizeof(__pyx_k_IndexedReads_build), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexedReads_build */ + {__pyx_k_IndexedReads_find, sizeof(__pyx_k_IndexedReads_find), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IndexedReads_find */ + {__pyx_k_IteratorColumn, sizeof(__pyx_k_IteratorColumn), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn */ + {__pyx_k_IteratorColumnAll, sizeof(__pyx_k_IteratorColumnAll), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAll */ + {__pyx_k_IteratorColumnAllRefs, sizeof(__pyx_k_IteratorColumnAllRefs), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAllRefs */ + {__pyx_k_IteratorColumnAllRefs___reduce_c, sizeof(__pyx_k_IteratorColumnAllRefs___reduce_c), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAllRefs___reduce_c */ + {__pyx_k_IteratorColumnAllRefs___setstate, sizeof(__pyx_k_IteratorColumnAllRefs___setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAllRefs___setstate */ + {__pyx_k_IteratorColumnAll___reduce_cytho, sizeof(__pyx_k_IteratorColumnAll___reduce_cytho), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAll___reduce_cytho */ + {__pyx_k_IteratorColumnAll___setstate_cyt, sizeof(__pyx_k_IteratorColumnAll___setstate_cyt), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnAll___setstate_cyt */ + {__pyx_k_IteratorColumnRegion, sizeof(__pyx_k_IteratorColumnRegion), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnRegion */ + {__pyx_k_IteratorColumnRegion___reduce_cy, sizeof(__pyx_k_IteratorColumnRegion___reduce_cy), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnRegion___reduce_cy */ + {__pyx_k_IteratorColumnRegion___setstate, sizeof(__pyx_k_IteratorColumnRegion___setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumnRegion___setstate */ + {__pyx_k_IteratorColumn___reduce_cython, sizeof(__pyx_k_IteratorColumn___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn___reduce_cython */ + {__pyx_k_IteratorColumn___setstate_cython, sizeof(__pyx_k_IteratorColumn___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn___setstate_cython */ + {__pyx_k_IteratorColumn_addReference, sizeof(__pyx_k_IteratorColumn_addReference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn_addReference */ + {__pyx_k_IteratorColumn_add_reference, sizeof(__pyx_k_IteratorColumn_add_reference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn_add_reference */ + {__pyx_k_IteratorColumn_hasReference, sizeof(__pyx_k_IteratorColumn_hasReference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn_hasReference */ + {__pyx_k_IteratorColumn_has_reference, sizeof(__pyx_k_IteratorColumn_has_reference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorColumn_has_reference */ + {__pyx_k_IteratorRow, sizeof(__pyx_k_IteratorRow), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRow */ + {__pyx_k_IteratorRowAll, sizeof(__pyx_k_IteratorRowAll), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAll */ + {__pyx_k_IteratorRowAllRefs, sizeof(__pyx_k_IteratorRowAllRefs), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAllRefs */ + {__pyx_k_IteratorRowAllRefs___reduce_cyth, sizeof(__pyx_k_IteratorRowAllRefs___reduce_cyth), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAllRefs___reduce_cyth */ + {__pyx_k_IteratorRowAllRefs___setstate_cy, sizeof(__pyx_k_IteratorRowAllRefs___setstate_cy), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAllRefs___setstate_cy */ + {__pyx_k_IteratorRowAllRefs_nextiter, sizeof(__pyx_k_IteratorRowAllRefs_nextiter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAllRefs_nextiter */ + {__pyx_k_IteratorRowAll___reduce_cython, sizeof(__pyx_k_IteratorRowAll___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAll___reduce_cython */ + {__pyx_k_IteratorRowAll___setstate_cython, sizeof(__pyx_k_IteratorRowAll___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowAll___setstate_cython */ + {__pyx_k_IteratorRowHead, sizeof(__pyx_k_IteratorRowHead), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowHead */ + {__pyx_k_IteratorRowHead___reduce_cython, sizeof(__pyx_k_IteratorRowHead___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowHead___reduce_cython */ + {__pyx_k_IteratorRowHead___setstate_cytho, sizeof(__pyx_k_IteratorRowHead___setstate_cytho), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowHead___setstate_cytho */ + {__pyx_k_IteratorRowRegion, sizeof(__pyx_k_IteratorRowRegion), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowRegion */ + {__pyx_k_IteratorRowRegion___reduce_cytho, sizeof(__pyx_k_IteratorRowRegion___reduce_cytho), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowRegion___reduce_cytho */ + {__pyx_k_IteratorRowRegion___setstate_cyt, sizeof(__pyx_k_IteratorRowRegion___setstate_cyt), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowRegion___setstate_cyt */ + {__pyx_k_IteratorRowSelection, sizeof(__pyx_k_IteratorRowSelection), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowSelection */ + {__pyx_k_IteratorRowSelection___reduce_cy, sizeof(__pyx_k_IteratorRowSelection___reduce_cy), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowSelection___reduce_cy */ + {__pyx_k_IteratorRowSelection___setstate, sizeof(__pyx_k_IteratorRowSelection___setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRowSelection___setstate */ + {__pyx_k_IteratorRow___reduce_cython, sizeof(__pyx_k_IteratorRow___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRow___reduce_cython */ + {__pyx_k_IteratorRow___setstate_cython, sizeof(__pyx_k_IteratorRow___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_IteratorRow___setstate_cython */ + {__pyx_k_KNOWN_HEADER_FIELDS, sizeof(__pyx_k_KNOWN_HEADER_FIELDS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_KNOWN_HEADER_FIELDS */ + {__pyx_k_KS, sizeof(__pyx_k_KS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_KS */ + {__pyx_k_KeyError, sizeof(__pyx_k_KeyError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_KeyError */ + {__pyx_k_L, sizeof(__pyx_k_L), 0, 1, 1}, /* PyObject cname: __pyx_n_u_L */ + {__pyx_k_LB, sizeof(__pyx_k_LB), 0, 1, 1}, /* PyObject cname: __pyx_n_u_LB */ + {__pyx_k_LN, sizeof(__pyx_k_LN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_LN */ + {__pyx_k_M5, sizeof(__pyx_k_M5), 0, 1, 1}, /* PyObject cname: __pyx_n_u_M5 */ + {__pyx_k_MAX_POS, sizeof(__pyx_k_MAX_POS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_MAX_POS */ + {__pyx_k_Mapping, sizeof(__pyx_k_Mapping), 0, 1, 1}, /* PyObject cname: __pyx_n_u_Mapping */ + {__pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_MemoryError */ + {__pyx_k_N, sizeof(__pyx_k_N), 0, 1, 1}, /* PyObject cname: __pyx_n_u_N */ + {__pyx_k_NotImplementedError, sizeof(__pyx_k_NotImplementedError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_NotImplementedError */ + {__pyx_k_Note_that_Cython_is_deliberately, sizeof(__pyx_k_Note_that_Cython_is_deliberately), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Note_that_Cython_is_deliberately */ + {__pyx_k_OSError, sizeof(__pyx_k_OSError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_OSError */ + {__pyx_k_OrderedDict, sizeof(__pyx_k_OrderedDict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_OrderedDict */ + {__pyx_k_PG, sizeof(__pyx_k_PG), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PG */ + {__pyx_k_PI, sizeof(__pyx_k_PI), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PI */ + {__pyx_k_PL, sizeof(__pyx_k_PL), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PL */ + {__pyx_k_PM, sizeof(__pyx_k_PM), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PM */ + {__pyx_k_PN, sizeof(__pyx_k_PN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PN */ + {__pyx_k_PP, sizeof(__pyx_k_PP), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PP */ + {__pyx_k_PU, sizeof(__pyx_k_PU), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PU */ + {__pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_PickleError */ + {__pyx_k_RG, sizeof(__pyx_k_RG), 0, 1, 1}, /* PyObject cname: __pyx_n_u_RG */ + {__pyx_k_Raw_iterator_set_up_without_regi, sizeof(__pyx_k_Raw_iterator_set_up_without_regi), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Raw_iterator_set_up_without_regi */ + {__pyx_k_SAM_file_does_not_have_a_valid_h, sizeof(__pyx_k_SAM_file_does_not_have_a_valid_h), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_SAM_file_does_not_have_a_valid_h */ + {__pyx_k_SM, sizeof(__pyx_k_SM), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SM */ + {__pyx_k_SN, sizeof(__pyx_k_SN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SN */ + {__pyx_k_SNPCall, sizeof(__pyx_k_SNPCall), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SNPCall */ + {__pyx_k_SNPCall___reduce_cython, sizeof(__pyx_k_SNPCall___reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SNPCall___reduce_cython */ + {__pyx_k_SNPCall___setstate_cython, sizeof(__pyx_k_SNPCall___setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SNPCall___setstate_cython */ + {__pyx_k_SO, sizeof(__pyx_k_SO), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SO */ + {__pyx_k_SP, sizeof(__pyx_k_SP), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SP */ + {__pyx_k_SQ, sizeof(__pyx_k_SQ), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_SQ */ + {__pyx_k_SQ_2, sizeof(__pyx_k_SQ_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SQ_2 */ + {__pyx_k_SQ_SN_LN, sizeof(__pyx_k_SQ_SN_LN), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_SQ_SN_LN */ + {__pyx_k_SS, sizeof(__pyx_k_SS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_SS */ + {__pyx_k_Sequence, sizeof(__pyx_k_Sequence), 0, 1, 1}, /* PyObject cname: __pyx_n_u_Sequence */ + {__pyx_k_StopIteration, sizeof(__pyx_k_StopIteration), 0, 1, 1}, /* PyObject cname: __pyx_n_u_StopIteration */ + {__pyx_k_StringIO, sizeof(__pyx_k_StringIO), 0, 1, 1}, /* PyObject cname: __pyx_n_u_StringIO */ + {__pyx_k_TP, sizeof(__pyx_k_TP), 0, 1, 1}, /* PyObject cname: __pyx_n_u_TP */ + {__pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_TypeError */ + {__pyx_k_UR, sizeof(__pyx_k_UR), 0, 1, 1}, /* PyObject cname: __pyx_n_u_UR */ + {__pyx_k_Unable_to_reopen_file, sizeof(__pyx_k_Unable_to_reopen_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_Unable_to_reopen_file */ + {__pyx_k_VALID_HEADERS, sizeof(__pyx_k_VALID_HEADERS), 0, 1, 1}, /* PyObject cname: __pyx_n_u_VALID_HEADERS */ + {__pyx_k_VALID_HEADER_ORDER, sizeof(__pyx_k_VALID_HEADER_ORDER), 0, 1, 1}, /* PyObject cname: __pyx_n_u_VALID_HEADER_ORDER */ + {__pyx_k_VALID_HEADER_TYPES, sizeof(__pyx_k_VALID_HEADER_TYPES), 0, 1, 1}, /* PyObject cname: __pyx_n_u_VALID_HEADER_TYPES */ + {__pyx_k_VN, sizeof(__pyx_k_VN), 0, 1, 1}, /* PyObject cname: __pyx_n_u_VN */ + {__pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ValueError */ + {__pyx_k__11, sizeof(__pyx_k__11), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__11 */ + {__pyx_k__12, sizeof(__pyx_k__12), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__12 */ + {__pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__2 */ + {__pyx_k__3, sizeof(__pyx_k__3), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__3 */ + {__pyx_k__4, sizeof(__pyx_k__4), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__4 */ + {__pyx_k__5, sizeof(__pyx_k__5), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__5 */ + {__pyx_k__6, sizeof(__pyx_k__6), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__6 */ + {__pyx_k__7, sizeof(__pyx_k__7), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__7 */ + {__pyx_k__8, sizeof(__pyx_k__8), 0, 1, 0}, /* PyObject cname: __pyx_kp_u__8 */ + {__pyx_k__9, sizeof(__pyx_k__9), 0, 0, 0}, /* PyObject cname: __pyx_kp_b__9 */ + {__pyx_k_access_from_StringIO_objects_not, sizeof(__pyx_k_access_from_StringIO_objects_not), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_access_from_StringIO_objects_not */ + {__pyx_k_addReference, sizeof(__pyx_k_addReference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_addReference */ + {__pyx_k_add_hts_options, sizeof(__pyx_k_add_hts_options), 0, 1, 1}, /* PyObject cname: __pyx_n_u_add_hts_options */ + {__pyx_k_add_note, sizeof(__pyx_k_add_note), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_add_note */ + {__pyx_k_add_reference, sizeof(__pyx_k_add_reference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_add_reference */ + {__pyx_k_add_sam_header, sizeof(__pyx_k_add_sam_header), 0, 1, 1}, /* PyObject cname: __pyx_n_u_add_sam_header */ + {__pyx_k_add_sq_text, sizeof(__pyx_k_add_sq_text), 0, 1, 1}, /* PyObject cname: __pyx_n_u_add_sq_text */ + {__pyx_k_adjust_capq_threshold, sizeof(__pyx_k_adjust_capq_threshold), 0, 1, 1}, /* PyObject cname: __pyx_n_u_adjust_capq_threshold */ + {__pyx_k_advance_all, sizeof(__pyx_k_advance_all), 0, 1, 1}, /* PyObject cname: __pyx_n_u_advance_all */ + {__pyx_k_advance_nofilter, sizeof(__pyx_k_advance_nofilter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_advance_nofilter */ + {__pyx_k_advance_raw_all, sizeof(__pyx_k_advance_raw_all), 0, 1, 1}, /* PyObject cname: __pyx_n_u_advance_raw_all */ + {__pyx_k_advance_raw_nofilter, sizeof(__pyx_k_advance_raw_nofilter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_advance_raw_nofilter */ + {__pyx_k_advance_samtools, sizeof(__pyx_k_advance_samtools), 0, 1, 1}, /* PyObject cname: __pyx_n_u_advance_samtools */ + {__pyx_k_all, sizeof(__pyx_k_all), 0, 1, 1}, /* PyObject cname: __pyx_n_u_all */ + {__pyx_k_all_2, sizeof(__pyx_k_all_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_all_2 */ + {__pyx_k_append, sizeof(__pyx_k_append), 0, 1, 1}, /* PyObject cname: __pyx_n_u_append */ + {__pyx_k_args, sizeof(__pyx_k_args), 0, 1, 1}, /* PyObject cname: __pyx_n_u_args */ + {__pyx_k_array, sizeof(__pyx_k_array), 0, 1, 1}, /* PyObject cname: __pyx_n_u_array */ + {__pyx_k_as_dict, sizeof(__pyx_k_as_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_as_dict */ + {__pyx_k_asyncio_coroutines, sizeof(__pyx_k_asyncio_coroutines), 0, 1, 1}, /* PyObject cname: __pyx_n_u_asyncio_coroutines */ + {__pyx_k_b, sizeof(__pyx_k_b), 0, 1, 1}, /* PyObject cname: __pyx_n_u_b */ + {__pyx_k_base_position, sizeof(__pyx_k_base_position), 0, 1, 1}, /* PyObject cname: __pyx_n_u_base_position */ + {__pyx_k_beg, sizeof(__pyx_k_beg), 0, 1, 1}, /* PyObject cname: __pyx_n_u_beg */ + {__pyx_k_bfile_name, sizeof(__pyx_k_bfile_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_bfile_name */ + {__pyx_k_bindex_filename, sizeof(__pyx_k_bindex_filename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_bindex_filename */ + {__pyx_k_bool, sizeof(__pyx_k_bool), 0, 1, 1}, /* PyObject cname: __pyx_n_u_bool */ + {__pyx_k_btext, sizeof(__pyx_k_btext), 0, 1, 1}, /* PyObject cname: __pyx_n_u_btext */ + {__pyx_k_build, sizeof(__pyx_k_build), 0, 1, 1}, /* PyObject cname: __pyx_n_u_build */ + {__pyx_k_build_header_line, sizeof(__pyx_k_build_header_line), 0, 1, 1}, /* PyObject cname: __pyx_n_u_build_header_line */ + {__pyx_k_build_sequence_section, sizeof(__pyx_k_build_sequence_section), 0, 1, 1}, /* PyObject cname: __pyx_n_u_build_sequence_section */ + {__pyx_k_c, sizeof(__pyx_k_c), 0, 1, 1}, /* PyObject cname: __pyx_n_u_c */ + {__pyx_k_can_not_iterate_over_samfile_wit, sizeof(__pyx_k_can_not_iterate_over_samfile_wit), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_can_not_iterate_over_samfile_wit */ + {__pyx_k_can_only_apply_IndexReads_on_bam, sizeof(__pyx_k_can_only_apply_IndexReads_on_bam), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_can_only_apply_IndexReads_on_bam */ + {__pyx_k_cannot_create_AlignmentHeader_re, sizeof(__pyx_k_cannot_create_AlignmentHeader_re), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_cannot_create_AlignmentHeader_re */ + {__pyx_k_cfilename, sizeof(__pyx_k_cfilename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cfilename */ + {__pyx_k_check_header, sizeof(__pyx_k_check_header), 0, 1, 1}, /* PyObject cname: __pyx_n_u_check_header */ + {__pyx_k_check_index, sizeof(__pyx_k_check_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_check_index */ + {__pyx_k_check_sq, sizeof(__pyx_k_check_sq), 0, 1, 1}, /* PyObject cname: __pyx_n_u_check_sq */ + {__pyx_k_check_truncation, sizeof(__pyx_k_check_truncation), 0, 1, 1}, /* PyObject cname: __pyx_n_u_check_truncation */ + {__pyx_k_cigar, sizeof(__pyx_k_cigar), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cigar */ + {__pyx_k_cigarstring, sizeof(__pyx_k_cigarstring), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cigarstring */ + {__pyx_k_cigartuples, sizeof(__pyx_k_cigartuples), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cigartuples */ + {__pyx_k_cindexname, sizeof(__pyx_k_cindexname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cindexname */ + {__pyx_k_cinit, sizeof(__pyx_k_cinit), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cinit */ + {__pyx_k_class_getitem, sizeof(__pyx_k_class_getitem), 0, 1, 1}, /* PyObject cname: __pyx_n_u_class_getitem */ + {__pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cline_in_traceback */ + {__pyx_k_close, sizeof(__pyx_k_close), 0, 1, 1}, /* PyObject cname: __pyx_n_u_close */ + {__pyx_k_closed, sizeof(__pyx_k_closed), 0, 1, 1}, /* PyObject cname: __pyx_n_u_closed */ + {__pyx_k_cls, sizeof(__pyx_k_cls), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cls */ + {__pyx_k_cmode, sizeof(__pyx_k_cmode), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cmode */ + {__pyx_k_cnext, sizeof(__pyx_k_cnext), 0, 1, 1}, /* PyObject cname: __pyx_n_u_cnext */ + {__pyx_k_code, sizeof(__pyx_k_code), 0, 1, 1}, /* PyObject cname: __pyx_n_u_code */ + {__pyx_k_collections, sizeof(__pyx_k_collections), 0, 1, 1}, /* PyObject cname: __pyx_n_u_collections */ + {__pyx_k_collections_abc, sizeof(__pyx_k_collections_abc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_collections_abc */ + {__pyx_k_compute_baq, sizeof(__pyx_k_compute_baq), 0, 1, 1}, /* PyObject cname: __pyx_n_u_compute_baq */ + {__pyx_k_consensus_quality, sizeof(__pyx_k_consensus_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_consensus_quality */ + {__pyx_k_contains, sizeof(__pyx_k_contains), 0, 1, 1}, /* PyObject cname: __pyx_n_u_contains */ + {__pyx_k_contig, sizeof(__pyx_k_contig), 0, 1, 1}, /* PyObject cname: __pyx_n_u_contig */ + {__pyx_k_contig_length, sizeof(__pyx_k_contig_length), 0, 1, 1}, /* PyObject cname: __pyx_n_u_contig_length */ + {__pyx_k_copy, sizeof(__pyx_k_copy), 0, 1, 1}, /* PyObject cname: __pyx_n_u_copy */ + {__pyx_k_could_not_allocate_bytes, sizeof(__pyx_k_could_not_allocate_bytes), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_could_not_allocate_bytes */ + {__pyx_k_could_not_allocate_memory_of_siz, sizeof(__pyx_k_could_not_allocate_memory_of_siz), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_could_not_allocate_memory_of_siz */ + {__pyx_k_could_not_create_header, sizeof(__pyx_k_could_not_create_header), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_could_not_create_header */ + {__pyx_k_could_not_open_alignment_file, sizeof(__pyx_k_could_not_open_alignment_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_could_not_open_alignment_file */ + {__pyx_k_could_not_parse_header, sizeof(__pyx_k_could_not_parse_header), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_could_not_parse_header */ + {__pyx_k_count, sizeof(__pyx_k_count), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count */ + {__pyx_k_count_a, sizeof(__pyx_k_count_a), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count_a */ + {__pyx_k_count_c, sizeof(__pyx_k_count_c), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count_c */ + {__pyx_k_count_coverage, sizeof(__pyx_k_count_coverage), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count_coverage */ + {__pyx_k_count_g, sizeof(__pyx_k_count_g), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count_g */ + {__pyx_k_count_t, sizeof(__pyx_k_count_t), 0, 1, 1}, /* PyObject cname: __pyx_n_u_count_t */ + {__pyx_k_counter, sizeof(__pyx_k_counter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_counter */ + {__pyx_k_coverage, sizeof(__pyx_k_coverage), 0, 1, 1}, /* PyObject cname: __pyx_n_u_coverage */ + {__pyx_k_creference_filename, sizeof(__pyx_k_creference_filename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_creference_filename */ + {__pyx_k_ctext, sizeof(__pyx_k_ctext), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ctext */ + {__pyx_k_current_pos, sizeof(__pyx_k_current_pos), 0, 1, 1}, /* PyObject cname: __pyx_n_u_current_pos */ + {__pyx_k_current_row, sizeof(__pyx_k_current_row), 0, 1, 1}, /* PyObject cname: __pyx_n_u_current_row */ + {__pyx_k_data, sizeof(__pyx_k_data), 0, 1, 1}, /* PyObject cname: __pyx_n_u_data */ + {__pyx_k_dealloc, sizeof(__pyx_k_dealloc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_dealloc */ + {__pyx_k_defaultdict, sizeof(__pyx_k_defaultdict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_defaultdict */ + {__pyx_k_dest, sizeof(__pyx_k_dest), 0, 1, 1}, /* PyObject cname: __pyx_n_u_dest */ + {__pyx_k_dict, sizeof(__pyx_k_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_dict */ + {__pyx_k_dict_2, sizeof(__pyx_k_dict_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_dict_2 */ + {__pyx_k_disable, sizeof(__pyx_k_disable), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_disable */ + {__pyx_k_duplicate_filehandle, sizeof(__pyx_k_duplicate_filehandle), 0, 1, 1}, /* PyObject cname: __pyx_n_u_duplicate_filehandle */ + {__pyx_k_either_supply_options_template_h, sizeof(__pyx_k_either_supply_options_template_h), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_either_supply_options_template_h */ + {__pyx_k_enable, sizeof(__pyx_k_enable), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_enable */ + {__pyx_k_end, sizeof(__pyx_k_end), 0, 1, 1}, /* PyObject cname: __pyx_n_u_end */ + {__pyx_k_enter, sizeof(__pyx_k_enter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_enter */ + {__pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_enumerate */ + {__pyx_k_error_during_iteration, sizeof(__pyx_k_error_during_iteration), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_error_during_iteration */ + {__pyx_k_error_while_reading_file, sizeof(__pyx_k_error_while_reading_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_error_while_reading_file */ + {__pyx_k_error_while_reading_file_2, sizeof(__pyx_k_error_while_reading_file_2), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_error_while_reading_file_2 */ + {__pyx_k_exc_type, sizeof(__pyx_k_exc_type), 0, 1, 1}, /* PyObject cname: __pyx_n_u_exc_type */ + {__pyx_k_exc_value, sizeof(__pyx_k_exc_value), 0, 1, 1}, /* PyObject cname: __pyx_n_u_exc_value */ + {__pyx_k_exit, sizeof(__pyx_k_exit), 0, 1, 1}, /* PyObject cname: __pyx_n_u_exit */ + {__pyx_k_failure_when_setting_reference_f, sizeof(__pyx_k_failure_when_setting_reference_f), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_failure_when_setting_reference_f */ + {__pyx_k_fastafile, sizeof(__pyx_k_fastafile), 0, 1, 1}, /* PyObject cname: __pyx_n_u_fastafile */ + {__pyx_k_fetch, sizeof(__pyx_k_fetch), 0, 1, 1}, /* PyObject cname: __pyx_n_u_fetch */ + {__pyx_k_fetch_called_on_bamfile_without, sizeof(__pyx_k_fetch_called_on_bamfile_without), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_fetch_called_on_bamfile_without */ + {__pyx_k_fetching_by_region_is_not_availa, sizeof(__pyx_k_fetching_by_region_is_not_availa), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_fetching_by_region_is_not_availa */ + {__pyx_k_field, sizeof(__pyx_k_field), 0, 1, 1}, /* PyObject cname: __pyx_n_u_field */ + {__pyx_k_fields, sizeof(__pyx_k_fields), 0, 1, 1}, /* PyObject cname: __pyx_n_u_fields */ + {__pyx_k_file_does_not_contain_alignment, sizeof(__pyx_k_file_does_not_contain_alignment), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_file_does_not_contain_alignment */ + {__pyx_k_file_does_not_have_a_valid_heade, sizeof(__pyx_k_file_does_not_have_a_valid_heade), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_file_does_not_have_a_valid_heade */ + {__pyx_k_file_has_no_sequences_defined_mo, sizeof(__pyx_k_file_has_no_sequences_defined_mo), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_file_has_no_sequences_defined_mo */ + {__pyx_k_filename, sizeof(__pyx_k_filename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_filename */ + {__pyx_k_fileno, sizeof(__pyx_k_fileno), 0, 1, 1}, /* PyObject cname: __pyx_n_u_fileno */ + {__pyx_k_filepath_index, sizeof(__pyx_k_filepath_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_filepath_index */ + {__pyx_k_filepath_or_object, sizeof(__pyx_k_filepath_or_object), 0, 1, 1}, /* PyObject cname: __pyx_n_u_filepath_or_object */ + {__pyx_k_fill_AlignmentHeader_from_list, sizeof(__pyx_k_fill_AlignmentHeader_from_list), 0, 1, 1}, /* PyObject cname: __pyx_n_u_fill_AlignmentHeader_from_list */ + {__pyx_k_filter_method, sizeof(__pyx_k_filter_method), 0, 1, 1}, /* PyObject cname: __pyx_n_u_filter_method */ + {__pyx_k_find, sizeof(__pyx_k_find), 0, 1, 1}, /* PyObject cname: __pyx_n_u_find */ + {__pyx_k_find_introns, sizeof(__pyx_k_find_introns), 0, 1, 1}, /* PyObject cname: __pyx_n_u_find_introns */ + {__pyx_k_find_introns_slow, sizeof(__pyx_k_find_introns_slow), 0, 1, 1}, /* PyObject cname: __pyx_n_u_find_introns_slow */ + {__pyx_k_flag, sizeof(__pyx_k_flag), 0, 1, 1}, /* PyObject cname: __pyx_n_u_flag */ + {__pyx_k_flag_filter, sizeof(__pyx_k_flag_filter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_flag_filter */ + {__pyx_k_flag_require, sizeof(__pyx_k_flag_require), 0, 1, 1}, /* PyObject cname: __pyx_n_u_flag_require */ + {__pyx_k_format, sizeof(__pyx_k_format), 0, 1, 1}, /* PyObject cname: __pyx_n_u_format */ + {__pyx_k_format_options, sizeof(__pyx_k_format_options), 0, 1, 1}, /* PyObject cname: __pyx_n_u_format_options */ + {__pyx_k_free_pileup_iter, sizeof(__pyx_k_free_pileup_iter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_free_pileup_iter */ + {__pyx_k_from_dict, sizeof(__pyx_k_from_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_from_dict */ + {__pyx_k_from_references, sizeof(__pyx_k_from_references), 0, 1, 1}, /* PyObject cname: __pyx_n_u_from_references */ + {__pyx_k_from_text, sizeof(__pyx_k_from_text), 0, 1, 1}, /* PyObject cname: __pyx_n_u_from_text */ + {__pyx_k_from_text_and_lengths, sizeof(__pyx_k_from_text_and_lengths), 0, 1, 1}, /* PyObject cname: __pyx_n_u_from_text_and_lengths */ + {__pyx_k_func, sizeof(__pyx_k_func), 0, 1, 1}, /* PyObject cname: __pyx_n_u_func */ + {__pyx_k_gc, sizeof(__pyx_k_gc), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_gc */ + {__pyx_k_genome_loc, sizeof(__pyx_k_genome_loc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_genome_loc */ + {__pyx_k_genotype, sizeof(__pyx_k_genotype), 0, 1, 1}, /* PyObject cname: __pyx_n_u_genotype */ + {__pyx_k_get, sizeof(__pyx_k_get), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get */ + {__pyx_k_getCurrent, sizeof(__pyx_k_getCurrent), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getCurrent */ + {__pyx_k_getSequence, sizeof(__pyx_k_getSequence), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getSequence */ + {__pyx_k_get_2, sizeof(__pyx_k_get_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_2 */ + {__pyx_k_get_aligned_pairs, sizeof(__pyx_k_get_aligned_pairs), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_aligned_pairs */ + {__pyx_k_get_index_statistics, sizeof(__pyx_k_get_index_statistics), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_index_statistics */ + {__pyx_k_get_reference_length, sizeof(__pyx_k_get_reference_length), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_reference_length */ + {__pyx_k_get_reference_name, sizeof(__pyx_k_get_reference_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_reference_name */ + {__pyx_k_get_sequence, sizeof(__pyx_k_get_sequence), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_sequence */ + {__pyx_k_get_tid, sizeof(__pyx_k_get_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_get_tid */ + {__pyx_k_getitem, sizeof(__pyx_k_getitem), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getitem */ + {__pyx_k_getrname, sizeof(__pyx_k_getrname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getrname */ + {__pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_getstate */ + {__pyx_k_gettid, sizeof(__pyx_k_gettid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_gettid */ + {__pyx_k_h, sizeof(__pyx_k_h), 0, 1, 1}, /* PyObject cname: __pyx_n_u_h */ + {__pyx_k_hasReference, sizeof(__pyx_k_hasReference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_hasReference */ + {__pyx_k_has_coord, sizeof(__pyx_k_has_coord), 0, 1, 1}, /* PyObject cname: __pyx_n_u_has_coord */ + {__pyx_k_has_index, sizeof(__pyx_k_has_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_has_index */ + {__pyx_k_has_reference, sizeof(__pyx_k_has_reference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_has_reference */ + {__pyx_k_hdr, sizeof(__pyx_k_hdr), 0, 1, 1}, /* PyObject cname: __pyx_n_u_hdr */ + {__pyx_k_head, sizeof(__pyx_k_head), 0, 1, 1}, /* PyObject cname: __pyx_n_u_head */ + {__pyx_k_header, sizeof(__pyx_k_header), 0, 1, 1}, /* PyObject cname: __pyx_n_u_header */ + {__pyx_k_header_dict, sizeof(__pyx_k_header_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_header_dict */ + {__pyx_k_header_line_with_invalid_type, sizeof(__pyx_k_header_line_with_invalid_type), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_header_line_with_invalid_type */ + {__pyx_k_header_line_without_s, sizeof(__pyx_k_header_line_without_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_header_line_without_s */ + {__pyx_k_header_not_available_in_closed_f, sizeof(__pyx_k_header_not_available_in_closed_f), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_header_not_available_in_closed_f */ + {__pyx_k_idx, sizeof(__pyx_k_idx), 0, 1, 1}, /* PyObject cname: __pyx_n_u_idx */ + {__pyx_k_ignore_orphans, sizeof(__pyx_k_ignore_orphans), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ignore_orphans */ + {__pyx_k_ignore_overlaps, sizeof(__pyx_k_ignore_overlaps), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ignore_overlaps */ + {__pyx_k_ignore_truncation, sizeof(__pyx_k_ignore_truncation), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ignore_truncation */ + {__pyx_k_incomplete_sequence_information, sizeof(__pyx_k_incomplete_sequence_information), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_incomplete_sequence_information */ + {__pyx_k_index, sizeof(__pyx_k_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_index */ + {__pyx_k_index_filename, sizeof(__pyx_k_index_filename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_index_filename */ + {__pyx_k_init, sizeof(__pyx_k_init), 0, 1, 1}, /* PyObject cname: __pyx_n_u_init */ + {__pyx_k_initializing, sizeof(__pyx_k_initializing), 0, 1, 1}, /* PyObject cname: __pyx_n_u_initializing */ + {__pyx_k_int_array_template, sizeof(__pyx_k_int_array_template), 0, 1, 1}, /* PyObject cname: __pyx_n_u_int_array_template */ + {__pyx_k_interval_of_size_0, sizeof(__pyx_k_interval_of_size_0), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_interval_of_size_0 */ + {__pyx_k_interval_of_size_less_than_0, sizeof(__pyx_k_interval_of_size_less_than_0), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_interval_of_size_less_than_0 */ + {__pyx_k_invalid_file_opening_mode_s, sizeof(__pyx_k_invalid_file_opening_mode_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_invalid_file_opening_mode_s */ + {__pyx_k_invalid_type_for_record_expected, sizeof(__pyx_k_invalid_type_for_record_expected), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_invalid_type_for_record_expected */ + {__pyx_k_io, sizeof(__pyx_k_io), 0, 1, 1}, /* PyObject cname: __pyx_n_u_io */ + {__pyx_k_is_bam, sizeof(__pyx_k_is_bam), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_bam */ + {__pyx_k_is_coroutine, sizeof(__pyx_k_is_coroutine), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_coroutine */ + {__pyx_k_is_cram, sizeof(__pyx_k_is_cram), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_cram */ + {__pyx_k_is_open, sizeof(__pyx_k_is_open), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_open */ + {__pyx_k_is_valid_tid, sizeof(__pyx_k_is_valid_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_is_valid_tid */ + {__pyx_k_isenabled, sizeof(__pyx_k_isenabled), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_isenabled */ + {__pyx_k_islower, sizeof(__pyx_k_islower), 0, 1, 1}, /* PyObject cname: __pyx_n_u_islower */ + {__pyx_k_isupper, sizeof(__pyx_k_isupper), 0, 1, 1}, /* PyObject cname: __pyx_n_u_isupper */ + {__pyx_k_items, sizeof(__pyx_k_items), 0, 1, 1}, /* PyObject cname: __pyx_n_u_items */ + {__pyx_k_iter, sizeof(__pyx_k_iter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_iter */ + {__pyx_k_iter_2, sizeof(__pyx_k_iter_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_iter_2 */ + {__pyx_k_iterdata, sizeof(__pyx_k_iterdata), 0, 1, 1}, /* PyObject cname: __pyx_n_u_iterdata */ + {__pyx_k_iteritems, sizeof(__pyx_k_iteritems), 0, 1, 1}, /* PyObject cname: __pyx_n_u_iteritems */ + {__pyx_k_junc_start, sizeof(__pyx_k_junc_start), 0, 1, 1}, /* PyObject cname: __pyx_n_u_junc_start */ + {__pyx_k_key, sizeof(__pyx_k_key), 0, 1, 1}, /* PyObject cname: __pyx_n_u_key */ + {__pyx_k_keys, sizeof(__pyx_k_keys), 0, 1, 1}, /* PyObject cname: __pyx_n_u_keys */ + {__pyx_k_kwargs, sizeof(__pyx_k_kwargs), 0, 1, 1}, /* PyObject cname: __pyx_n_u_kwargs */ + {__pyx_k_l_text, sizeof(__pyx_k_l_text), 0, 1, 1}, /* PyObject cname: __pyx_n_u_l_text */ + {__pyx_k_last_read_pos, sizeof(__pyx_k_last_read_pos), 0, 1, 1}, /* PyObject cname: __pyx_n_u_last_read_pos */ + {__pyx_k_len, sizeof(__pyx_k_len), 0, 1, 1}, /* PyObject cname: __pyx_n_u_len */ + {__pyx_k_length, sizeof(__pyx_k_length), 0, 1, 1}, /* PyObject cname: __pyx_n_u_length */ + {__pyx_k_lengths, sizeof(__pyx_k_lengths), 0, 1, 1}, /* PyObject cname: __pyx_n_u_lengths */ + {__pyx_k_line, sizeof(__pyx_k_line), 0, 1, 1}, /* PyObject cname: __pyx_n_u_line */ + {__pyx_k_lines, sizeof(__pyx_k_lines), 0, 1, 1}, /* PyObject cname: __pyx_n_u_lines */ + {__pyx_k_main, sizeof(__pyx_k_main), 0, 1, 1}, /* PyObject cname: __pyx_n_u_main */ + {__pyx_k_make, sizeof(__pyx_k_make), 0, 1, 1}, /* PyObject cname: __pyx_n_u_make */ + {__pyx_k_makeAlignmentHeader, sizeof(__pyx_k_makeAlignmentHeader), 0, 1, 1}, /* PyObject cname: __pyx_n_u_makeAlignmentHeader */ + {__pyx_k_malformatted_header_no_in_field, sizeof(__pyx_k_malformatted_header_no_in_field), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_malformatted_header_no_in_field */ + {__pyx_k_map, sizeof(__pyx_k_map), 0, 1, 1}, /* PyObject cname: __pyx_n_u_map */ + {__pyx_k_mapped, sizeof(__pyx_k_mapped), 0, 1, 1}, /* PyObject cname: __pyx_n_u_mapped */ + {__pyx_k_mapping_information_not_recorded, sizeof(__pyx_k_mapping_information_not_recorded), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_mapping_information_not_recorded */ + {__pyx_k_mapping_quality, sizeof(__pyx_k_mapping_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_mapping_quality */ + {__pyx_k_match_or_deletion, sizeof(__pyx_k_match_or_deletion), 0, 1, 1}, /* PyObject cname: __pyx_n_u_match_or_deletion */ + {__pyx_k_mate, sizeof(__pyx_k_mate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_mate */ + {__pyx_k_mate_not_found, sizeof(__pyx_k_mate_not_found), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_mate_not_found */ + {__pyx_k_mate_s_is_unmapped, sizeof(__pyx_k_mate_s_is_unmapped), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_mate_s_is_unmapped */ + {__pyx_k_max_depth, sizeof(__pyx_k_max_depth), 0, 1, 1}, /* PyObject cname: __pyx_n_u_max_depth */ + {__pyx_k_max_rows, sizeof(__pyx_k_max_rows), 0, 1, 1}, /* PyObject cname: __pyx_n_u_max_rows */ + {__pyx_k_min_base_quality, sizeof(__pyx_k_min_base_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_min_base_quality */ + {__pyx_k_min_mapping_quality, sizeof(__pyx_k_min_mapping_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_min_mapping_quality */ + {__pyx_k_mode, sizeof(__pyx_k_mode), 0, 1, 1}, /* PyObject cname: __pyx_n_u_mode */ + {__pyx_k_module, sizeof(__pyx_k_module), 0, 1, 1}, /* PyObject cname: __pyx_n_u_module */ + {__pyx_k_multiple_iterators, sizeof(__pyx_k_multiple_iterators), 0, 1, 1}, /* PyObject cname: __pyx_n_u_multiple_iterators */ + {__pyx_k_multiple_iterators_not_implement, sizeof(__pyx_k_multiple_iterators_not_implement), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_multiple_iterators_not_implement */ + {__pyx_k_multiple_iterators_not_implement_2, sizeof(__pyx_k_multiple_iterators_not_implement_2), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_multiple_iterators_not_implement_2 */ + {__pyx_k_multiple_s_lines_are_not_permitt, sizeof(__pyx_k_multiple_s_lines_are_not_permitt), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_multiple_s_lines_are_not_permitt */ + {__pyx_k_n, sizeof(__pyx_k_n), 0, 1, 1}, /* PyObject cname: __pyx_n_u_n */ + {__pyx_k_n_plp, sizeof(__pyx_k_n_plp), 0, 1, 1}, /* PyObject cname: __pyx_n_u_n_plp */ + {__pyx_k_name, sizeof(__pyx_k_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_name */ + {__pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_name_2 */ + {__pyx_k_namedtuple, sizeof(__pyx_k_namedtuple), 0, 1, 1}, /* PyObject cname: __pyx_n_u_namedtuple */ + {__pyx_k_new, sizeof(__pyx_k_new), 0, 1, 1}, /* PyObject cname: __pyx_n_u_new */ + {__pyx_k_next, sizeof(__pyx_k_next), 0, 1, 1}, /* PyObject cname: __pyx_n_u_next */ + {__pyx_k_nextiter, sizeof(__pyx_k_nextiter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_nextiter */ + {__pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_no_default___reduce___due_to_non */ + {__pyx_k_no_index_available_for_fetch, sizeof(__pyx_k_no_index_available_for_fetch), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_no_index_available_for_fetch */ + {__pyx_k_no_index_available_for_iteration, sizeof(__pyx_k_no_index_available_for_iteration), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_no_index_available_for_iteration */ + {__pyx_k_no_index_available_for_pileup, sizeof(__pyx_k_no_index_available_for_pileup), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_no_index_available_for_pileup */ + {__pyx_k_nofilter, sizeof(__pyx_k_nofilter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_nofilter */ + {__pyx_k_not_enough_information_to_constr, sizeof(__pyx_k_not_enough_information_to_constr), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_not_enough_information_to_constr */ + {__pyx_k_nreferences, sizeof(__pyx_k_nreferences), 0, 1, 1}, /* PyObject cname: __pyx_n_u_nreferences */ + {__pyx_k_nt, sizeof(__pyx_k_nt), 0, 1, 1}, /* PyObject cname: __pyx_n_u_nt */ + {__pyx_k_number_of_reference_names_and_le, sizeof(__pyx_k_number_of_reference_names_and_le), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_number_of_reference_names_and_le */ + {__pyx_k_op, sizeof(__pyx_k_op), 0, 1, 1}, /* PyObject cname: __pyx_n_u_op */ + {__pyx_k_open, sizeof(__pyx_k_open), 0, 1, 1}, /* PyObject cname: __pyx_n_u_open */ + {__pyx_k_os, sizeof(__pyx_k_os), 0, 1, 1}, /* PyObject cname: __pyx_n_u_os */ + {__pyx_k_parse_region, sizeof(__pyx_k_parse_region), 0, 1, 1}, /* PyObject cname: __pyx_n_u_parse_region */ + {__pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pickle */ + {__pyx_k_pileup, sizeof(__pyx_k_pileup), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pileup */ + {__pyx_k_pileup_iter, sizeof(__pyx_k_pileup_iter), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pileup_iter */ + {__pyx_k_plp, sizeof(__pyx_k_plp), 0, 1, 1}, /* PyObject cname: __pyx_n_u_plp */ + {__pyx_k_pop, sizeof(__pyx_k_pop), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pop */ + {__pyx_k_port, sizeof(__pyx_k_port), 0, 1, 1}, /* PyObject cname: __pyx_n_u_port */ + {__pyx_k_pos, sizeof(__pyx_k_pos), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pos */ + {__pyx_k_positions, sizeof(__pyx_k_positions), 0, 1, 1}, /* PyObject cname: __pyx_n_u_positions */ + {__pyx_k_pysam_libcalignmentfile, sizeof(__pyx_k_pysam_libcalignmentfile), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pysam_libcalignmentfile */ + {__pyx_k_pysam_libcalignmentfile_pxd, sizeof(__pyx_k_pysam_libcalignmentfile_pxd), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_pysam_libcalignmentfile_pxd */ + {__pyx_k_pysam_libcalignmentfile_pyx, sizeof(__pyx_k_pysam_libcalignmentfile_pyx), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_pysam_libcalignmentfile_pyx */ + {__pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_PickleError */ + {__pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_checksum */ + {__pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_result */ + {__pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_state */ + {__pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_type */ + {__pyx_k_pyx_unpickle_SNPCall, sizeof(__pyx_k_pyx_unpickle_SNPCall), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_unpickle_SNPCall */ + {__pyx_k_pyx_unpickle_SNPCall__set_stat, sizeof(__pyx_k_pyx_unpickle_SNPCall__set_stat), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_unpickle_SNPCall__set_stat */ + {__pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 1, 1}, /* PyObject cname: __pyx_n_u_pyx_vtable */ + {__pyx_k_qname, sizeof(__pyx_k_qname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_qname */ + {__pyx_k_qpos, sizeof(__pyx_k_qpos), 0, 1, 1}, /* PyObject cname: __pyx_n_u_qpos */ + {__pyx_k_quality, sizeof(__pyx_k_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_quality */ + {__pyx_k_quality_threshold, sizeof(__pyx_k_quality_threshold), 0, 1, 1}, /* PyObject cname: __pyx_n_u_quality_threshold */ + {__pyx_k_qualname, sizeof(__pyx_k_qualname), 0, 1, 1}, /* PyObject cname: __pyx_n_u_qualname */ + {__pyx_k_query_name, sizeof(__pyx_k_query_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_query_name */ + {__pyx_k_query_qualities, sizeof(__pyx_k_query_qualities), 0, 1, 1}, /* PyObject cname: __pyx_n_u_query_qualities */ + {__pyx_k_r, sizeof(__pyx_k_r), 0, 1, 1}, /* PyObject cname: __pyx_n_u_r */ + {__pyx_k_rU, sizeof(__pyx_k_rU), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rU */ + {__pyx_k_range, sizeof(__pyx_k_range), 0, 1, 1}, /* PyObject cname: __pyx_n_u_range */ + {__pyx_k_rb, sizeof(__pyx_k_rb), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rb */ + {__pyx_k_rc, sizeof(__pyx_k_rc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rc */ + {__pyx_k_re, sizeof(__pyx_k_re), 0, 1, 1}, /* PyObject cname: __pyx_n_u_re */ + {__pyx_k_read, sizeof(__pyx_k_read), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read */ + {__pyx_k_read_callback, sizeof(__pyx_k_read_callback), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read_callback */ + {__pyx_k_read_failure_reason, sizeof(__pyx_k_read_failure_reason), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read_failure_reason */ + {__pyx_k_read_iterator, sizeof(__pyx_k_read_iterator), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read_iterator */ + {__pyx_k_read_loc, sizeof(__pyx_k_read_loc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_read_loc */ + {__pyx_k_read_s_is_unpaired, sizeof(__pyx_k_read_s_is_unpaired), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_read_s_is_unpaired */ + {__pyx_k_read_s_not_found, sizeof(__pyx_k_read_s_not_found), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_read_s_not_found */ + {__pyx_k_record, sizeof(__pyx_k_record), 0, 1, 1}, /* PyObject cname: __pyx_n_u_record */ + {__pyx_k_redo_baq, sizeof(__pyx_k_redo_baq), 0, 1, 1}, /* PyObject cname: __pyx_n_u_redo_baq */ + {__pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce */ + {__pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce_cython */ + {__pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reduce_ex */ + {__pyx_k_ref, sizeof(__pyx_k_ref), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ref */ + {__pyx_k_reference, sizeof(__pyx_k_reference), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reference */ + {__pyx_k_reference_base, sizeof(__pyx_k_reference_base), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reference_base */ + {__pyx_k_reference_filename, sizeof(__pyx_k_reference_filename), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reference_filename */ + {__pyx_k_reference_id_i_out_of_range_0_ti, sizeof(__pyx_k_reference_id_i_out_of_range_0_ti), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_reference_id_i_out_of_range_0_ti */ + {__pyx_k_reference_lengths, sizeof(__pyx_k_reference_lengths), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reference_lengths */ + {__pyx_k_reference_names, sizeof(__pyx_k_reference_names), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reference_names */ + {__pyx_k_reference_sequence_for_tid_not_f, sizeof(__pyx_k_reference_sequence_for_tid_not_f), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_reference_sequence_for_tid_not_f */ + {__pyx_k_referencelengths, sizeof(__pyx_k_referencelengths), 0, 1, 1}, /* PyObject cname: __pyx_n_u_referencelengths */ + {__pyx_k_referencenames, sizeof(__pyx_k_referencenames), 0, 1, 1}, /* PyObject cname: __pyx_n_u_referencenames */ + {__pyx_k_references, sizeof(__pyx_k_references), 0, 1, 1}, /* PyObject cname: __pyx_n_u_references */ + {__pyx_k_refpos, sizeof(__pyx_k_refpos), 0, 1, 1}, /* PyObject cname: __pyx_n_u_refpos */ + {__pyx_k_region, sizeof(__pyx_k_region), 0, 1, 1}, /* PyObject cname: __pyx_n_u_region */ + {__pyx_k_require_index, sizeof(__pyx_k_require_index), 0, 1, 1}, /* PyObject cname: __pyx_n_u_require_index */ + {__pyx_k_res, sizeof(__pyx_k_res), 0, 1, 1}, /* PyObject cname: __pyx_n_u_res */ + {__pyx_k_reset, sizeof(__pyx_k_reset), 0, 1, 1}, /* PyObject cname: __pyx_n_u_reset */ + {__pyx_k_result, sizeof(__pyx_k_result), 0, 1, 1}, /* PyObject cname: __pyx_n_u_result */ + {__pyx_k_results, sizeof(__pyx_k_results), 0, 1, 1}, /* PyObject cname: __pyx_n_u_results */ + {__pyx_k_ret, sizeof(__pyx_k_ret), 0, 1, 1}, /* PyObject cname: __pyx_n_u_ret */ + {__pyx_k_rstart, sizeof(__pyx_k_rstart), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rstart */ + {__pyx_k_rstop, sizeof(__pyx_k_rstop), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rstop */ + {__pyx_k_rtid, sizeof(__pyx_k_rtid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_rtid */ + {__pyx_k_s, sizeof(__pyx_k_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_s */ + {__pyx_k_sam_write1_failed_with_error_cod, sizeof(__pyx_k_sam_write1_failed_with_error_cod), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_sam_write1_failed_with_error_cod */ + {__pyx_k_samfile, sizeof(__pyx_k_samfile), 0, 1, 1}, /* PyObject cname: __pyx_n_u_samfile */ + {__pyx_k_samtools, sizeof(__pyx_k_samtools), 0, 1, 1}, /* PyObject cname: __pyx_n_u_samtools */ + {__pyx_k_self, sizeof(__pyx_k_self), 0, 1, 1}, /* PyObject cname: __pyx_n_u_self */ + {__pyx_k_self_b_self_htsfile_self_index_c, sizeof(__pyx_k_self_b_self_htsfile_self_index_c), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_self_b_self_htsfile_self_index_c */ + {__pyx_k_self_b_self_htsfile_self_index_s, sizeof(__pyx_k_self_b_self_htsfile_self_index_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_self_b_self_htsfile_self_index_s */ + {__pyx_k_self_htsfile_cannot_be_converted, sizeof(__pyx_k_self_htsfile_cannot_be_converted), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_self_htsfile_cannot_be_converted */ + {__pyx_k_seq, sizeof(__pyx_k_seq), 0, 1, 1}, /* PyObject cname: __pyx_n_u_seq */ + {__pyx_k_set_name, sizeof(__pyx_k_set_name), 0, 1, 1}, /* PyObject cname: __pyx_n_u_set_name */ + {__pyx_k_setitem, sizeof(__pyx_k_setitem), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setitem */ + {__pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setstate */ + {__pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setstate_cython */ + {__pyx_k_setup_iterator, sizeof(__pyx_k_setup_iterator), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setup_iterator */ + {__pyx_k_setup_raw_rest_iterator, sizeof(__pyx_k_setup_raw_rest_iterator), 0, 1, 1}, /* PyObject cname: __pyx_n_u_setup_raw_rest_iterator */ + {__pyx_k_snp_quality, sizeof(__pyx_k_snp_quality), 0, 1, 1}, /* PyObject cname: __pyx_n_u_snp_quality */ + {__pyx_k_spec, sizeof(__pyx_k_spec), 0, 1, 1}, /* PyObject cname: __pyx_n_u_spec */ + {__pyx_k_split, sizeof(__pyx_k_split), 0, 1, 1}, /* PyObject cname: __pyx_n_u_split */ + {__pyx_k_splitlines, sizeof(__pyx_k_splitlines), 0, 1, 1}, /* PyObject cname: __pyx_n_u_splitlines */ + {__pyx_k_sq, sizeof(__pyx_k_sq), 0, 1, 1}, /* PyObject cname: __pyx_n_u_sq */ + {__pyx_k_start, sizeof(__pyx_k_start), 0, 1, 1}, /* PyObject cname: __pyx_n_u_start */ + {__pyx_k_start_2, sizeof(__pyx_k_start_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_start_2 */ + {__pyx_k_startswith, sizeof(__pyx_k_startswith), 0, 1, 1}, /* PyObject cname: __pyx_n_u_startswith */ + {__pyx_k_state, sizeof(__pyx_k_state), 0, 1, 1}, /* PyObject cname: __pyx_n_u_state */ + {__pyx_k_stepper, sizeof(__pyx_k_stepper), 0, 1, 1}, /* PyObject cname: __pyx_n_u_stepper */ + {__pyx_k_stop, sizeof(__pyx_k_stop), 0, 1, 1}, /* PyObject cname: __pyx_n_u_stop */ + {__pyx_k_stop_2, sizeof(__pyx_k_stop_2), 0, 1, 1}, /* PyObject cname: __pyx_n_u_stop_2 */ + {__pyx_k_str, sizeof(__pyx_k_str), 0, 1, 1}, /* PyObject cname: __pyx_n_u_str */ + {__pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_stringsource */ + {__pyx_k_strip, sizeof(__pyx_k_strip), 0, 1, 1}, /* PyObject cname: __pyx_n_u_strip */ + {__pyx_k_sum, sizeof(__pyx_k_sum), 0, 1, 1}, /* PyObject cname: __pyx_n_u_sum */ + {__pyx_k_super, sizeof(__pyx_k_super), 0, 1, 1}, /* PyObject cname: __pyx_n_u_super */ + {__pyx_k_t, sizeof(__pyx_k_t), 0, 1, 1}, /* PyObject cname: __pyx_n_u_t */ + {__pyx_k_tell, sizeof(__pyx_k_tell), 0, 1, 1}, /* PyObject cname: __pyx_n_u_tell */ + {__pyx_k_template, sizeof(__pyx_k_template), 0, 1, 1}, /* PyObject cname: __pyx_n_u_template */ + {__pyx_k_test, sizeof(__pyx_k_test), 0, 1, 1}, /* PyObject cname: __pyx_n_u_test */ + {__pyx_k_text, sizeof(__pyx_k_text), 0, 1, 1}, /* PyObject cname: __pyx_n_u_text */ + {__pyx_k_threads, sizeof(__pyx_k_threads), 0, 1, 1}, /* PyObject cname: __pyx_n_u_threads */ + {__pyx_k_threshold, sizeof(__pyx_k_threshold), 0, 1, 1}, /* PyObject cname: __pyx_n_u_threshold */ + {__pyx_k_tid, sizeof(__pyx_k_tid), 0, 1, 1}, /* PyObject cname: __pyx_n_u_tid */ + {__pyx_k_to_dict, sizeof(__pyx_k_to_dict), 0, 1, 1}, /* PyObject cname: __pyx_n_u_to_dict */ + {__pyx_k_total, sizeof(__pyx_k_total), 0, 1, 1}, /* PyObject cname: __pyx_n_u_total */ + {__pyx_k_traceback, sizeof(__pyx_k_traceback), 0, 1, 1}, /* PyObject cname: __pyx_n_u_traceback */ + {__pyx_k_truncate, sizeof(__pyx_k_truncate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_truncate */ + {__pyx_k_truncated_file, sizeof(__pyx_k_truncated_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_truncated_file */ + {__pyx_k_unable_to_open_index_file, sizeof(__pyx_k_unable_to_open_index_file), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_unable_to_open_index_file */ + {__pyx_k_unable_to_open_index_file_s, sizeof(__pyx_k_unable_to_open_index_file_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_unable_to_open_index_file_s */ + {__pyx_k_unable_to_read_header_informatio, sizeof(__pyx_k_unable_to_read_header_informatio), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_unable_to_read_header_informatio */ + {__pyx_k_unknown_reference, sizeof(__pyx_k_unknown_reference), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_unknown_reference */ + {__pyx_k_unknown_stepper_option_s_in_Iter, sizeof(__pyx_k_unknown_stepper_option_s_in_Iter), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_unknown_stepper_option_s_in_Iter */ + {__pyx_k_unmapped, sizeof(__pyx_k_unmapped), 0, 1, 1}, /* PyObject cname: __pyx_n_u_unmapped */ + {__pyx_k_until_eof, sizeof(__pyx_k_until_eof), 0, 1, 1}, /* PyObject cname: __pyx_n_u_until_eof */ + {__pyx_k_update, sizeof(__pyx_k_update), 0, 1, 1}, /* PyObject cname: __pyx_n_u_update */ + {__pyx_k_use_setstate, sizeof(__pyx_k_use_setstate), 0, 1, 1}, /* PyObject cname: __pyx_n_u_use_setstate */ + {__pyx_k_value, sizeof(__pyx_k_value), 0, 1, 1}, /* PyObject cname: __pyx_n_u_value */ + {__pyx_k_values, sizeof(__pyx_k_values), 0, 1, 1}, /* PyObject cname: __pyx_n_u_values */ + {__pyx_k_w, sizeof(__pyx_k_w), 0, 1, 1}, /* PyObject cname: __pyx_n_u_w */ + {__pyx_k_warn, sizeof(__pyx_k_warn), 0, 1, 1}, /* PyObject cname: __pyx_n_u_warn */ + {__pyx_k_warnings, sizeof(__pyx_k_warnings), 0, 1, 1}, /* PyObject cname: __pyx_n_u_warnings */ + {__pyx_k_wb, sizeof(__pyx_k_wb), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wb */ + {__pyx_k_wb0, sizeof(__pyx_k_wb0), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wb0 */ + {__pyx_k_wbu, sizeof(__pyx_k_wbu), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wbu */ + {__pyx_k_wc, sizeof(__pyx_k_wc), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wc */ + {__pyx_k_wh, sizeof(__pyx_k_wh), 0, 1, 1}, /* PyObject cname: __pyx_n_u_wh */ + {__pyx_k_write, sizeof(__pyx_k_write), 0, 1, 1}, /* PyObject cname: __pyx_n_u_write */ + {__pyx_k_wrong_sequence_information_in_s, sizeof(__pyx_k_wrong_sequence_information_in_s), 0, 1, 0}, /* PyObject cname: __pyx_kp_u_wrong_sequence_information_in_s */ + {__pyx_k_x, sizeof(__pyx_k_x), 0, 1, 1}, /* PyObject cname: __pyx_n_u_x */ + {__pyx_k_y, sizeof(__pyx_k_y), 0, 1, 1}, /* PyObject cname: __pyx_n_u_y */ + {__pyx_k_zip, sizeof(__pyx_k_zip), 0, 1, 1}, /* PyObject cname: __pyx_n_u_zip */ + {0, 0, 0, 0, 0} +}; +/* InitStrings.proto */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry const *t, PyObject **target, const char* const* encoding_names); + +/* #### Code section: cached_builtins ### */ + +static int __Pyx_InitCachedBuiltins(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(0, 62, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 170, __pyx_L1_error) + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 235, __pyx_L1_error) + __pyx_builtin_sum = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_sum); if (!__pyx_builtin_sum) __PYX_ERR(0, 259, __pyx_L1_error) + __pyx_builtin_KeyError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_KeyError); if (!__pyx_builtin_KeyError) __PYX_ERR(0, 288, __pyx_L1_error) + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 344, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_range); if (!__pyx_builtin_range) __PYX_ERR(0, 372, __pyx_L1_error) + __pyx_builtin_AssertionError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_AssertionError); if (!__pyx_builtin_AssertionError) __PYX_ERR(0, 435, __pyx_L1_error) + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(0, 451, __pyx_L1_error) + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(0, 554, __pyx_L1_error) + __pyx_builtin_AttributeError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_AttributeError); if (!__pyx_builtin_AttributeError) __PYX_ERR(0, 779, __pyx_L1_error) + __pyx_builtin_NotImplementedError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_NotImplementedError); if (!__pyx_builtin_NotImplementedError) __PYX_ERR(0, 858, __pyx_L1_error) + __pyx_builtin_IOError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_IOError); if (!__pyx_builtin_IOError) __PYX_ERR(0, 1019, __pyx_L1_error) + __pyx_builtin_StopIteration = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_StopIteration); if (!__pyx_builtin_StopIteration) __PYX_ERR(0, 1875, __pyx_L1_error) + __pyx_builtin_super = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_super); if (!__pyx_builtin_super) __PYX_ERR(0, 2076, __pyx_L1_error) + __pyx_builtin_map = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_map); if (!__pyx_builtin_map) __PYX_ERR(0, 2862, __pyx_L1_error) + __pyx_builtin_OSError = __Pyx_GetBuiltinName(__pyx_mstate->__pyx_n_u_OSError); if (!__pyx_builtin_OSError) __PYX_ERR(0, 2918, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cached_constants ### */ + +static int __Pyx_InitCachedConstants(__pyx_mstatetype *__pyx_mstate) { + __Pyx_RefNannyDeclarations + CYTHON_UNUSED_VAR(__pyx_mstate); + __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); + + /* "pysam/libcalignmentfile.pyx":284 + * for line in text.splitlines(): + * if line.startswith("@SQ"): + * fields = dict([x.split(":", 1) for x in line.split("\t")[1:]]) # <<<<<<<<<<<<<< + * try: + * reference_names.append(fields["SN"]) +*/ + __pyx_mstate_global->__pyx_slice[0] = PySlice_New(__pyx_mstate_global->__pyx_int_1, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_slice[0])) __PYX_ERR(0, 284, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_slice[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_slice[0]); + __pyx_mstate_global->__pyx_tuple[0] = PyTuple_Pack(2, __pyx_mstate_global->__pyx_kp_u_, __pyx_mstate_global->__pyx_int_1); if (unlikely(!__pyx_mstate_global->__pyx_tuple[0])) __PYX_ERR(0, 284, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[0]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[0]); + + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result + * if __pyx_checksum not in (0xe45c101, 0x1134a9c, 0x50b2281): # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError, "Incompatible checksums (0x%x vs (0xe45c101, 0x1134a9c, 0x50b2281) = (_consensus_quality, _coverage, _genotype, _pos, _reference_base, _rms_mapping_quality, _snp_quality, _tid))" % __pyx_checksum +*/ + __pyx_mstate_global->__pyx_tuple[1] = PyTuple_Pack(3, __pyx_mstate_global->__pyx_int_239452417, __pyx_mstate_global->__pyx_int_18041500, __pyx_mstate_global->__pyx_int_84615809); if (unlikely(!__pyx_mstate_global->__pyx_tuple[1])) __PYX_ERR(3, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[1]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[1]); + + /* "pysam/libcalignmentfile.pyx":92 + * + * IndexStats = collections.namedtuple("IndexStats", + * ("contig", # <<<<<<<<<<<<<< + * "mapped", + * "unmapped", +*/ + __pyx_mstate_global->__pyx_tuple[2] = PyTuple_Pack(4, __pyx_mstate_global->__pyx_n_u_contig, __pyx_mstate_global->__pyx_n_u_mapped, __pyx_mstate_global->__pyx_n_u_unmapped, __pyx_mstate_global->__pyx_n_u_total); if (unlikely(!__pyx_mstate_global->__pyx_tuple[2])) __PYX_ERR(0, 92, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[2]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[2]); + + /* "pysam/libcalignmentfile.pyx":91 + * "IndexedReads"] + * + * IndexStats = collections.namedtuple("IndexStats", # <<<<<<<<<<<<<< + * ("contig", + * "mapped", +*/ + __pyx_mstate_global->__pyx_tuple[3] = PyTuple_Pack(2, __pyx_mstate_global->__pyx_n_u_IndexStats, __pyx_mstate_global->__pyx_tuple[2]); if (unlikely(!__pyx_mstate_global->__pyx_tuple[3])) __PYX_ERR(0, 91, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[3]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[3]); + + /* "pysam/libcalignmentfile.pyx":111 + * + * # order of records within SAM headers + * VALID_HEADERS = ("HD", "SQ", "RG", "PG", "CO") # <<<<<<<<<<<<<< + * + * # default type conversions within SAM header records +*/ + __pyx_mstate_global->__pyx_tuple[4] = PyTuple_Pack(5, __pyx_mstate_global->__pyx_n_u_HD, __pyx_mstate_global->__pyx_n_u_SQ_2, __pyx_mstate_global->__pyx_n_u_RG, __pyx_mstate_global->__pyx_n_u_PG, __pyx_mstate_global->__pyx_n_u_CO); if (unlikely(!__pyx_mstate_global->__pyx_tuple[4])) __PYX_ERR(0, 111, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[4]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[4]); + + /* "pysam/libcalignmentfile.pyx":130 + * # output order of fields within records. Ensure that CL is at + * # the end as parsing a CL will ignore any subsequent records. + * VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "SS", "GO"), # <<<<<<<<<<<<<< + * "SQ" : ("SN", "LN", "AS", "M5", + * "UR", "SP", "AH", "TP", +*/ + __pyx_mstate_global->__pyx_tuple[5] = PyTuple_Pack(4, __pyx_mstate_global->__pyx_n_u_VN, __pyx_mstate_global->__pyx_n_u_SO, __pyx_mstate_global->__pyx_n_u_SS, __pyx_mstate_global->__pyx_n_u_GO); if (unlikely(!__pyx_mstate_global->__pyx_tuple[5])) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[5]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[5]); + + /* "pysam/libcalignmentfile.pyx":131 + * # the end as parsing a CL will ignore any subsequent records. + * VALID_HEADER_ORDER = {"HD" : ("VN", "SO", "SS", "GO"), + * "SQ" : ("SN", "LN", "AS", "M5", # <<<<<<<<<<<<<< + * "UR", "SP", "AH", "TP", + * "DS", "AN"), +*/ + __pyx_mstate_global->__pyx_tuple[6] = PyTuple_Pack(10, __pyx_mstate_global->__pyx_n_u_SN, __pyx_mstate_global->__pyx_n_u_LN, __pyx_mstate_global->__pyx_n_u_AS, __pyx_mstate_global->__pyx_n_u_M5, __pyx_mstate_global->__pyx_n_u_UR, __pyx_mstate_global->__pyx_n_u_SP, __pyx_mstate_global->__pyx_n_u_AH, __pyx_mstate_global->__pyx_n_u_TP, __pyx_mstate_global->__pyx_n_u_DS, __pyx_mstate_global->__pyx_n_u_AN); if (unlikely(!__pyx_mstate_global->__pyx_tuple[6])) __PYX_ERR(0, 131, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[6]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[6]); + + /* "pysam/libcalignmentfile.pyx":134 + * "UR", "SP", "AH", "TP", + * "DS", "AN"), + * "RG" : ("ID", "CN", "SM", "LB", # <<<<<<<<<<<<<< + * "PU", "PI", "DT", "DS", + * "PL", "FO", "KS", "PG", +*/ + __pyx_mstate_global->__pyx_tuple[7] = PyTuple_Pack(14, __pyx_mstate_global->__pyx_n_u_ID, __pyx_mstate_global->__pyx_n_u_CN, __pyx_mstate_global->__pyx_n_u_SM, __pyx_mstate_global->__pyx_n_u_LB, __pyx_mstate_global->__pyx_n_u_PU, __pyx_mstate_global->__pyx_n_u_PI, __pyx_mstate_global->__pyx_n_u_DT, __pyx_mstate_global->__pyx_n_u_DS, __pyx_mstate_global->__pyx_n_u_PL, __pyx_mstate_global->__pyx_n_u_FO, __pyx_mstate_global->__pyx_n_u_KS, __pyx_mstate_global->__pyx_n_u_PG, __pyx_mstate_global->__pyx_n_u_PM, __pyx_mstate_global->__pyx_n_u_BC); if (unlikely(!__pyx_mstate_global->__pyx_tuple[7])) __PYX_ERR(0, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[7]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[7]); + + /* "pysam/libcalignmentfile.pyx":138 + * "PL", "FO", "KS", "PG", + * "PM", "BC"), + * "PG" : ("PN", "ID", "VN", "PP", # <<<<<<<<<<<<<< + * "DS", "CL"),} + * +*/ + __pyx_mstate_global->__pyx_tuple[8] = PyTuple_Pack(6, __pyx_mstate_global->__pyx_n_u_PN, __pyx_mstate_global->__pyx_n_u_ID, __pyx_mstate_global->__pyx_n_u_VN, __pyx_mstate_global->__pyx_n_u_PP, __pyx_mstate_global->__pyx_n_u_DS, __pyx_mstate_global->__pyx_n_u_CL); if (unlikely(!__pyx_mstate_global->__pyx_tuple[8])) __PYX_ERR(0, 138, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[8]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[8]); + + /* "pysam/libcalignmentfile.pyx":336 + * return cls._from_text_and_lengths(text, reference_names, reference_lengths) + * + * @classmethod # <<<<<<<<<<<<<< + * def from_references(cls, reference_names, reference_lengths, text=None, add_sq_text=True): + * +*/ + __pyx_mstate_global->__pyx_tuple[9] = PyTuple_Pack(2, Py_None, Py_True); if (unlikely(!__pyx_mstate_global->__pyx_tuple[9])) __PYX_ERR(0, 336, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[9]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[9]); + + /* "pysam/libcalignmentfile.pyx":787 + * return True + * + * def _open(self, # <<<<<<<<<<<<<< + * filepath_or_object, + * mode=None, +*/ + __pyx_mstate_global->__pyx_tuple[10] = PyTuple_Pack(21, Py_None, Py_None, Py_None, Py_None, Py_None, Py_None, Py_None, Py_None, Py_True, Py_True, Py_True, Py_True, Py_None, Py_None, Py_False, Py_None, Py_None, Py_True, Py_False, Py_None, __pyx_mstate_global->__pyx_int_1); if (unlikely(!__pyx_mstate_global->__pyx_tuple[10])) __PYX_ERR(0, 787, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[10]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[10]); + + /* "pysam/libcalignmentfile.pyx":1028 + * self.start_offset = self.tell() + * + * def fetch(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_mstate_global->__pyx_tuple[11] = PyTuple_Pack(9, Py_None, Py_None, Py_None, Py_None, Py_None, Py_False, Py_False, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[11])) __PYX_ERR(0, 1028, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[11]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[11]); + + /* "pysam/libcalignmentfile.pyx":1133 + * multiple_iterators=multiple_iterators) + * + * def head(self, n, multiple_iterators=True): # <<<<<<<<<<<<<< + * '''return an iterator over the first n alignments. + * +*/ + __pyx_mstate_global->__pyx_tuple[12] = PyTuple_Pack(1, Py_True); if (unlikely(!__pyx_mstate_global->__pyx_tuple[12])) __PYX_ERR(0, 1133, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[12]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[12]); + + /* "pysam/libcalignmentfile.pyx":1214 + * return mate + * + * def pileup(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_mstate_global->__pyx_tuple[13] = PyTuple_Pack(6, Py_None, Py_None, Py_None, Py_None, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[13])) __PYX_ERR(0, 1214, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[13]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[13]); + + /* "pysam/libcalignmentfile.pyx":1354 + * return IteratorColumnAll(self, **kwargs) + * + * def count(self, # <<<<<<<<<<<<<< + * contig=None, + * start=None, +*/ + __pyx_mstate_global->__pyx_tuple[14] = PyTuple_Pack(8, Py_None, Py_None, Py_None, Py_None, Py_False, __pyx_mstate_global->__pyx_n_u_nofilter, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[14])) __PYX_ERR(0, 1354, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[14]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[14]); + + /* "pysam/libcalignmentfile.pyx":1457 + * return counter + * + * @cython.boundscheck(False) # we do manual bounds checking # <<<<<<<<<<<<<< + * def count_coverage(self, + * contig, +*/ + __pyx_mstate_global->__pyx_tuple[15] = PyTuple_Pack(7, Py_None, Py_None, Py_None, __pyx_mstate_global->__pyx_int_15, __pyx_mstate_global->__pyx_n_u_all, Py_None, Py_None); if (unlikely(!__pyx_mstate_global->__pyx_tuple[15])) __PYX_ERR(0, 1457, __pyx_L1_error) + __Pyx_GOTREF(__pyx_mstate_global->__pyx_tuple[15]); + __Pyx_GIVEREF(__pyx_mstate_global->__pyx_tuple[15]); + __Pyx_RefNannyFinishContext(); + return 0; + __pyx_L1_error:; + __Pyx_RefNannyFinishContext(); + return -1; +} +/* #### Code section: init_constants ### */ + +static int __Pyx_InitConstants(__pyx_mstatetype *__pyx_mstate) { + CYTHON_UNUSED_VAR(__pyx_mstate); + __pyx_mstate->__pyx_umethod_PyDict_Type_get.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_get.method_name = &__pyx_mstate->__pyx_n_u_get; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.type = (PyObject*)&PyDict_Type; + __pyx_mstate->__pyx_umethod_PyDict_Type_pop.method_name = &__pyx_mstate->__pyx_n_u_pop; + if (__Pyx_InitStrings(__pyx_string_tab, __pyx_mstate->__pyx_string_tab, __pyx_string_tab_encodings) < 0) __PYX_ERR(0, 1, __pyx_L1_error); + __pyx_mstate->__pyx_int_0 = PyLong_FromLong(0); if (unlikely(!__pyx_mstate->__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_1 = PyLong_FromLong(1); if (unlikely(!__pyx_mstate->__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_2 = PyLong_FromLong(2); if (unlikely(!__pyx_mstate->__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_7 = PyLong_FromLong(7); if (unlikely(!__pyx_mstate->__pyx_int_7)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_8 = PyLong_FromLong(8); if (unlikely(!__pyx_mstate->__pyx_int_8)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_13 = PyLong_FromLong(13); if (unlikely(!__pyx_mstate->__pyx_int_13)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_15 = PyLong_FromLong(15); if (unlikely(!__pyx_mstate->__pyx_int_15)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_1796 = PyLong_FromLong(1796); if (unlikely(!__pyx_mstate->__pyx_int_1796)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_8000 = PyLong_FromLong(8000); if (unlikely(!__pyx_mstate->__pyx_int_8000)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_18041500 = PyLong_FromLong(18041500L); if (unlikely(!__pyx_mstate->__pyx_int_18041500)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_84615809 = PyLong_FromLong(84615809L); if (unlikely(!__pyx_mstate->__pyx_int_84615809)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_239452417 = PyLong_FromLong(239452417L); if (unlikely(!__pyx_mstate->__pyx_int_239452417)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_neg_1 = PyLong_FromLong(-1); if (unlikely(!__pyx_mstate->__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_mstate->__pyx_int_neg_2 = PyLong_FromLong(-2); if (unlikely(!__pyx_mstate->__pyx_int_neg_2)) __PYX_ERR(0, 1, __pyx_L1_error) + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: init_codeobjects ### */ +\ + typedef struct { + unsigned int argcount : 5; + unsigned int num_posonly_args : 1; + unsigned int num_kwonly_args : 1; + unsigned int nlocals : 5; + unsigned int flags : 10; + unsigned int first_line : 12; + unsigned int line_table_length : 15; + } __Pyx_PyCode_New_function_description; +/* NewCodeObj.proto */ +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + const char *line_table, + PyObject *tuple_dedup_map +); + + +static int __Pyx_CreateCodeObjects(__pyx_mstatetype *__pyx_mstate) { + PyObject* tuple_dedup_map = PyDict_New(); + if (unlikely(!tuple_dedup_map)) return -1; + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 142, 166}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_fields, __pyx_mstate->__pyx_n_u_record, __pyx_mstate->__pyx_n_u_line, __pyx_mstate->__pyx_n_u_key}; + __pyx_mstate_global->__pyx_codeobj_tab[0] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_build_header_line, __pyx_k_1F_A_wc_G1A_xq_G6_q_5_1F_1_G_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[0])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 168, 43}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_hdr, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[1] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_makeAlignmentHeader, __pyx_k_t1_j_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[1])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 178, 28}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_code}; + __pyx_mstate_global->__pyx_codeobj_tab[2] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_read_failure_reason, __pyx_k_uD_q_G1A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[2])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {5, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 187, 12}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_dest, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths, __pyx_mstate->__pyx_n_u_add_sq_text, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[3] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_fill_AlignmentHeader_from_list, __pyx_k_56_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[3])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 228, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[4] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_G1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[4])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 232, 31}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[5] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_A_G_q_4uCq_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[5])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 12, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 237, 430}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_cls, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths, __pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ctext, __pyx_mstate->__pyx_n_u_l_text, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_btext, __pyx_mstate->__pyx_n_u_name, __pyx_mstate->__pyx_n_u_ref}; + __pyx_mstate_global->__pyx_codeobj_tab[6] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_from_text_and_lengths, __pyx_k_A_O1_5_q_Kq_A_S_HG6_3a_t4vS_k_wa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[6])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 7, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 278, 166}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_cls, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths, __pyx_mstate->__pyx_n_u_line, __pyx_mstate->__pyx_n_u_fields, __pyx_mstate->__pyx_n_u_x}; + __pyx_mstate_global->__pyx_codeobj_tab[7] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_from_text, __pyx_k_A_T_HD_1_t_aq_Qaq_auCt5_F_5_7_6, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[7])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 9, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 295, 335}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_cls, __pyx_mstate->__pyx_n_u_header_dict, __pyx_mstate->__pyx_n_u_lines, __pyx_mstate->__pyx_n_u_record, __pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_fields, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths}; + __pyx_mstate_global->__pyx_codeobj_tab[8] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_from_dict, __pyx_k_A_Ja_wc_1_4z_1_A_EWA_D_0B_1_QfA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[8])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {5, 0, 0, 7, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 336, 104}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_cls, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_add_sq_text, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_y}; + __pyx_mstate_global->__pyx_codeobj_tab[9] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_from_references, __pyx_k_AFXXY_3a_3aq_AQ_5_5_A_2U_1_1_Ct3, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[9])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 349, 18}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[10] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_q_A_G1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[10])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 353, 13}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[11] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_bool, __pyx_k_A_t5_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[11])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 356, 18}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[12] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_copy, __pyx_k_A_at1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[12])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 363, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[13] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_4t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[13])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 369, 52}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_t, __pyx_mstate->__pyx_n_u_x}; + __pyx_mstate_global->__pyx_codeobj_tab[14] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_U_4t1_q_D_AQ_5, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[14])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 381, 48}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_t, __pyx_mstate->__pyx_n_u_x}; + __pyx_mstate_global->__pyx_codeobj_tab[15] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_U_4t1_T_AQ_5, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[15])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 388, 75}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_text}; + __pyx_mstate_global->__pyx_codeobj_tab[16] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_build_sequence_section, __pyx_k_A_q_E_at4q_q_WA_d_aq_D_1A_r_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[16])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 404, 470}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_result, __pyx_mstate->__pyx_n_u_t, __pyx_mstate->__pyx_n_u_line, __pyx_mstate->__pyx_n_u_fields, __pyx_mstate->__pyx_n_u_record, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_idx, __pyx_mstate->__pyx_n_u_field, __pyx_mstate->__pyx_n_u_key, __pyx_mstate->__pyx_n_u_value, __pyx_mstate->__pyx_n_u_sq, __pyx_mstate->__pyx_n_u_ref, __pyx_mstate->__pyx_n_u_length}; + __pyx_mstate_global->__pyx_codeobj_tab[17] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_to_dict, __pyx_k_A_L_D_HAV1A_4vQa_t1_4_1_0_T_V1A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[17])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 496, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[18] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_as_dict, __pyx_k_A_t81, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[18])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 500, 71}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[19] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_reference_name, __pyx_k_A_4t1_1_4r_F_d_A_Fa_4t1_Qd_l_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[19])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 508, 51}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[20] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_reference_length, __pyx_k_A_t81A_4r_1_4t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[20])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 515, 19}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[21] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_is_valid_tid, __pyx_k_A_r_F_d, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[21])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 523, 49}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[22] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_tid, __pyx_k_A_Kq_k_fA_4s_AQ_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[22])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 536, 52}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_text}; + __pyx_mstate_global->__pyx_codeobj_tab[23] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_str, __pyx_k_A_1D_G4t1_6_E_4_7q_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[23])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 553, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_key, __pyx_mstate->__pyx_n_u_value}; + __pyx_mstate_global->__pyx_codeobj_tab[24] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_setitem, __pyx_k_A_iq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[24])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 556, 17}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_key}; + __pyx_mstate_global->__pyx_codeobj_tab[25] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getitem, __pyx_k_A_t82, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[25])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 559, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[26] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_items, __pyx_k_A_t82V1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[26])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 563, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[27] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iteritems, __pyx_k_A_t82V1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[27])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 566, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[28] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_keys, __pyx_k_A_t82U, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[28])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 569, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[29] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_values, __pyx_k_A_t82WA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[29])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS), 572, 17}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_args}; + __pyx_mstate_global->__pyx_codeobj_tab[30] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get, __pyx_k_A_t82T_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[30])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 575, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[31] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_len, __pyx_k_A_t82XQ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[31])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 578, 17}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_key}; + __pyx_mstate_global->__pyx_codeobj_tab[32] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_contains, __pyx_k_A_t82_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[32])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[33] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[33])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[34] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[34])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARARGS|CO_VARKEYWORDS), 738, 135}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_args, __pyx_mstate->__pyx_n_u_kwargs}; + __pyx_mstate_global->__pyx_codeobj_tab[35] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_Kq_L_HA_Kq_M_M_IQ_c_1F_1_aq_F, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[35])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 758, 15}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[36] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_has_index, __pyx_k_A_t7_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[36])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 763, 75}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[37] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_check_index, __pyx_k_A_4t1_AQ_4t84t4q_4wc_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[37])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {23, 0, 0, 31, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 787, 1384}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_filepath_or_object, __pyx_mstate->__pyx_n_u_mode, __pyx_mstate->__pyx_n_u_template, __pyx_mstate->__pyx_n_u_reference_names, __pyx_mstate->__pyx_n_u_reference_lengths, __pyx_mstate->__pyx_n_u_reference_filename, __pyx_mstate->__pyx_n_u_text, __pyx_mstate->__pyx_n_u_header, __pyx_mstate->__pyx_n_u_port, __pyx_mstate->__pyx_n_u_add_sq_text, __pyx_mstate->__pyx_n_u_add_sam_header, __pyx_mstate->__pyx_n_u_check_header, __pyx_mstate->__pyx_n_u_check_sq, __pyx_mstate->__pyx_n_u_index_filename, __pyx_mstate->__pyx_n_u_filepath_index, __pyx_mstate->__pyx_n_u_require_index, __pyx_mstate->__pyx_n_u_referencenames, __pyx_mstate->__pyx_n_u_referencelengths, __pyx_mstate->__pyx_n_u_duplicate_filehandle, __pyx_mstate->__pyx_n_u_ignore_truncation, __pyx_mstate->__pyx_n_u_format_options, __pyx_mstate->__pyx_n_u_threads, __pyx_mstate->__pyx_n_u_cfilename, __pyx_mstate->__pyx_n_u_creference_filename, __pyx_mstate->__pyx_n_u_cindexname, __pyx_mstate->__pyx_n_u_cmode, __pyx_mstate->__pyx_n_u_hdr, __pyx_mstate->__pyx_n_u_ret, __pyx_mstate->__pyx_n_u_filename, __pyx_mstate->__pyx_n_u_bfile_name}; + __pyx_mstate_global->__pyx_codeobj_tab[38] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_open, __pyx_k_A_q_1_q_82Rt1_1A_Kq_a_G1_4q_a_5, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[38])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {10, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1028, 262}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_contig, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_region, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_until_eof, __pyx_mstate->__pyx_n_u_multiple_iterators, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_rtid, __pyx_mstate->__pyx_n_u_rstart, __pyx_mstate->__pyx_n_u_rstop, __pyx_mstate->__pyx_n_u_has_coord}; + __pyx_mstate_global->__pyx_codeobj_tab[39] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_fetch, __pyx_k_A_h_4t1_Ba_6_G6_Zq_4q_4xs_a_t_T, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[39])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1133, 23}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[40] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_head, __pyx_k_avQ_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[40])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1155, 195}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_n_u_flag, __pyx_mstate->__pyx_n_u_x, __pyx_mstate->__pyx_n_u_mate}; + __pyx_mstate_global->__pyx_codeobj_tab[41] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_mate, __pyx_k_A6_T_5_5_c_A_4A_5_c_A_4A_Rs_A_HD, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[41])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {7, 0, 0, 12, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARKEYWORDS), 1214, 159}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_contig, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_region, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_kwargs, __pyx_mstate->__pyx_n_u_rtid, __pyx_mstate->__pyx_n_u_has_coord, __pyx_mstate->__pyx_n_u_rstart, __pyx_mstate->__pyx_n_u_rstop}; + __pyx_mstate_global->__pyx_codeobj_tab[42] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_pileup, __pyx_k_A_b_4t1_AQ_6_G6_d_1_t4z_j_q_A_a, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[42])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {9, 0, 0, 12, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1354, 185}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_contig, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_region, __pyx_mstate->__pyx_n_u_until_eof, __pyx_mstate->__pyx_n_u_read_callback, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_n_u_counter, __pyx_mstate->__pyx_n_u_filter_method}; + __pyx_mstate_global->__pyx_codeobj_tab[43] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_count, __pyx_k_A_A_4t1_AQ_A_A_3a_A_HD_awa_Q_A_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[43])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {9, 0, 0, 26, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1457, 566}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_contig, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_region, __pyx_mstate->__pyx_n_u_quality_threshold, __pyx_mstate->__pyx_n_u_read_callback, __pyx_mstate->__pyx_n_u_reference, __pyx_mstate->__pyx_n_u_end, __pyx_mstate->__pyx_n_u_contig_length, __pyx_mstate->__pyx_n_u_start_2, __pyx_mstate->__pyx_n_u_stop_2, __pyx_mstate->__pyx_n_u_length, __pyx_mstate->__pyx_n_u_int_array_template, __pyx_mstate->__pyx_n_u_count_a, __pyx_mstate->__pyx_n_u_count_c, __pyx_mstate->__pyx_n_u_count_g, __pyx_mstate->__pyx_n_u_count_t, __pyx_mstate->__pyx_n_u_read, __pyx_mstate->__pyx_n_u_seq, __pyx_mstate->__pyx_n_u_quality, __pyx_mstate->__pyx_n_u_qpos, __pyx_mstate->__pyx_n_u_refpos, __pyx_mstate->__pyx_n_u_c, __pyx_mstate->__pyx_n_u_filter_method, __pyx_mstate->__pyx_n_u_threshold}; + __pyx_mstate_global->__pyx_codeobj_tab[44] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_count_coverage, __pyx_k_A_D_d_q_6_gZq_r_4A_6_A_AQ_6_1_AQ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[44])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 9, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1609, 115}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_read_iterator, __pyx_mstate->__pyx_n_u_res, __pyx_mstate->__pyx_n_u_r, __pyx_mstate->__pyx_n_u_last_read_pos, __pyx_mstate->__pyx_n_u_read_loc, __pyx_mstate->__pyx_n_u_genome_loc, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop}; + __pyx_mstate_global->__pyx_codeobj_tab[45] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_find_introns_slow, __pyx_k_A_k_E_t3aq_JnA_q_y_5_A_nCq_q_2WJ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[45])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 11, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1633, 119}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_read_iterator, __pyx_mstate->__pyx_n_u_base_position, __pyx_mstate->__pyx_n_u_junc_start, __pyx_mstate->__pyx_n_u_nt, __pyx_mstate->__pyx_n_u_op, __pyx_mstate->__pyx_n_u_r, __pyx_mstate->__pyx_n_u_BAM_CREF_SKIP, __pyx_mstate->__pyx_n_u_res, __pyx_mstate->__pyx_n_u_match_or_deletion, __pyx_mstate->__pyx_n_u_cigar}; + __pyx_mstate_global->__pyx_codeobj_tab[46] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_find_introns, __pyx_k_A_k_S_3a_E_AQ_AQ_vS_F_3c_Q_1_Q_r, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[46])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1667, 127}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[47] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_close, __pyx_k_A_4y_1_4wc_1D_y_Q_Kq_Ja_4r_4vS_z, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[47])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1688, 150}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[48] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_q_4wc_1D_4y_1_1D_1_Ja_4q_Q_Q_4, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[48])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1711, 135}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_read}; + __pyx_mstate_global->__pyx_codeobj_tab[49] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_write, __pyx_k_7q_4t1_1_4wd_S_Je1_A_LSST_vT_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[49])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1748, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[50] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_enter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[50])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1751, 14}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_exc_type, __pyx_mstate->__pyx_n_u_exc_value, __pyx_mstate->__pyx_n_u_traceback}; + __pyx_mstate_global->__pyx_codeobj_tab[51] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_exit, __pyx_k_A_F_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[51])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1767, 59}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_total, __pyx_mstate->__pyx_n_u_mapped, __pyx_mstate->__pyx_n_u_unmapped}; + __pyx_mstate_global->__pyx_codeobj_tab[52] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_A_D_q_AT_axq_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[52])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1785, 66}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_total, __pyx_mstate->__pyx_n_u_mapped, __pyx_mstate->__pyx_n_u_unmapped}; + __pyx_mstate_global->__pyx_codeobj_tab[53] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_A_7q_A_D_q_AT_axq_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[53])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1803, 29}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_n}; + __pyx_mstate_global->__pyx_codeobj_tab[54] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_A_a_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[54])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1810, 93}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_mapped, __pyx_mstate->__pyx_n_u_unmapped, __pyx_mstate->__pyx_n_u_results}; + __pyx_mstate_global->__pyx_codeobj_tab[55] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_index_statistics, __pyx_k_A_L_I_A_XU_81A_7_1A_2Q_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[55])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1846, 57}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[56] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_4t1_AQ_4t84t7_s_Q_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[56])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1855, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference_filename, __pyx_mstate->__pyx_n_u_header, __pyx_mstate->__pyx_n_u_index, __pyx_mstate->__pyx_n_u_b}; + __pyx_mstate_global->__pyx_codeobj_tab[57] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getCurrent, __pyx_k_A_t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[57])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1858, 40}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference_filename, __pyx_mstate->__pyx_n_u_header, __pyx_mstate->__pyx_n_u_index, __pyx_mstate->__pyx_n_u_b}; + __pyx_mstate_global->__pyx_codeobj_tab[58] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_t7_1D_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[58])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1870, 60}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[59] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_t6_4s_Qd_d_Q_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[59])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1881, 37}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[60] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_is_valid_tid, __pyx_k_A_4xs_AQ_t7_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[60])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1891, 37}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference}; + __pyx_mstate_global->__pyx_codeobj_tab[61] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_tid, __pyx_k_A_4xs_AQ_t7_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[61])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1902, 38}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[62] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_reference_name, __pyx_k_A_4xs_AQ_t7_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[62])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1910, 38}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference}; + __pyx_mstate_global->__pyx_codeobj_tab[63] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_reference_length, __pyx_k_A_4xs_AQ_t7_q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[63])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1921, 27}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[64] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_t1_t7_j, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[64])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1930, 27}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[65] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_t1_t7_j, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[65])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1942, 27}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[66] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_t1_t7_j, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[66])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1951, 29}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[67] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_t1_t7_j_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[67])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1958, 13}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_reference}; + __pyx_mstate_global->__pyx_codeobj_tab[68] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_gettid, __pyx_k_A_t81A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[68])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1962, 14}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid}; + __pyx_mstate_global->__pyx_codeobj_tab[69] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getrname, __pyx_k_A_t_aq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[69])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 46, 2}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[70] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pxd, __pyx_mstate->__pyx_n_u_get_2, __pyx_k__13, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[70])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 47, 2}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[71] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pxd, __pyx_mstate->__pyx_n_u_get_2, __pyx_k__14, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[71])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[72] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[72])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[73] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[73])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 8, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1992, 281}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_multiple_iterators, __pyx_mstate->__pyx_n_u_cfilename, __pyx_mstate->__pyx_n_u_creference_filename, __pyx_mstate->__pyx_n_u_cindexname, __pyx_mstate->__pyx_n_u_bindex_filename, __pyx_mstate->__pyx_n_u_hdr}; + __pyx_mstate_global->__pyx_codeobj_tab[74] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_EQ_4wa_AQ_Kq_1_q_Kxq_1_4y_1_wj, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[74])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2048, 36}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[75] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_AT_4q_1D_Qd, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[75])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[76] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[76])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[77] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[77])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {6, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2069, 67}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_beg, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[78] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_A_4wj_AQ_Ry_5Q_a_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[78])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2084, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[79] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[79])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2087, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2}; + __pyx_mstate_global->__pyx_codeobj_tab[80] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getCurrent, __pyx_k_A_t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[80])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2090, 37}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2}; + __pyx_mstate_global->__pyx_codeobj_tab[81] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_a_AT_1_1_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[81])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2098, 94}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[82] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_F_4xs_Qd_d_Q_Q_7_4x_Z, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[82])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2112, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[83] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_q_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[83])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[84] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[84])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[85] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[85])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2128, 37}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_n, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[86] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_A_Ry_5Q_L_O1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[86])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2137, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[87] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[87])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2140, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_max_rows, __pyx_mstate->__pyx_n_u_current_row}; + __pyx_mstate_global->__pyx_codeobj_tab[88] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getCurrent, __pyx_k_A_t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[88])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2143, 40}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_max_rows, __pyx_mstate->__pyx_n_u_current_row}; + __pyx_mstate_global->__pyx_codeobj_tab[89] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_t7_1D_q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[89])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2153, 84}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[90] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_4_Ct1_t6_4s_Qd_d_Q_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[90])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[91] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[91])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[92] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[92])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2180, 21}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[93] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_EQ_Ry_5Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[93])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2183, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[94] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[94])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2186, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[95] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getCurrent, __pyx_k_A_t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[95])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2189, 40}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[96] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_t7_1D_q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[96])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2199, 60}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[97] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_t6_4s_Qd_d_Q_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[97])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[98] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[98])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[99] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[99])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2220, 48}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[100] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_A_Ry_5Q_4wj_AQ_HA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[100])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2228, 65}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[101] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_nextiter, __pyx_k_A_K_Q_Q_HKt1_HJd_H_A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[101])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2244, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[102] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[102])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2247, 120}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[103] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_4uD_t4xq_q_a_t882Q_hd_a_t5_ha, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[103])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[104] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[104])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[105] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[105])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2281, 36}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_positions, __pyx_mstate->__pyx_n_u_multiple_iterators}; + __pyx_mstate_global->__pyx_codeobj_tab[106] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_PPQ_Ry_5Q_M_O1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[106])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2287, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[107] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[107])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2290, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_current_pos, __pyx_mstate->__pyx_n_u_positions}; + __pyx_mstate_global->__pyx_codeobj_tab[108] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getCurrent, __pyx_k_A_t1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[108])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2293, 131}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_current_pos, __pyx_mstate->__pyx_n_u_positions}; + __pyx_mstate_global->__pyx_codeobj_tab[109] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_4_Cs_4_HA_D_4q_1M_k_a_4r_A_4xq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[109])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2313, 60}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret}; + __pyx_mstate_global->__pyx_codeobj_tab[110] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_t6_4s_Qd_d_Q_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[110])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[111] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[111])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[112] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[112])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2323, 39}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[113] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_advance_nofilter, __pyx_k_1_q_l_1Jawa_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[113])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2333, 39}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[114] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_advance_raw_nofilter, __pyx_k_q_q_iq_1IQ_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[114])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2343, 92}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[115] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_advance_all, __pyx_k_a_q_2_Bl_A_aq_7_4r_1E_r_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[115])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2363, 75}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[116] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_advance_raw_all, __pyx_k_q_1AZq_4r_1E_r_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[116])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2382, 459}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_data, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[117] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_advance_samtools, __pyx_k_1_q_aq_7_IQazYZZccd_4r_1E_r_1N, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[117])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARKEYWORDS), 2475, 278}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_kwargs}; + __pyx_mstate_global->__pyx_codeobj_tab[118] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_Kq_M_t1M_KvT_Q_M_t1M_vT_Q_d_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[118])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2497, 7}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[119] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_iter, __pyx_k_A_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[119])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2500, 48}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[120] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cnext, __pyx_k_A_AT_d_d_d_d_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[120])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2511, 13}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[121] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_sequence, __pyx_k_A_t9A, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[121])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2518, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[122] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_4y, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[122])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2521, 57}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_fastafile}; + __pyx_mstate_global->__pyx_codeobj_tab[123] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_add_reference, __pyx_k_A_iuCq_q_IQ_9HA_9M_Zq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[123])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2530, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[124] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_has_reference, __pyx_k_A_t1_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[124])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {5, 0, 0, 18, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2535, 319}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_multiple_iterators, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[125] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_setup_iterator, __pyx_k_A_12_H_Qd_E_a_I_HA_IXT_a_IWA_IXQ, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[125])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2588, 295}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[126] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_setup_raw_rest_iterator, __pyx_k_A_HA_IXQ_I_HA_IWA_IXQ_IZt87_4_d, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[126])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {4, 0, 0, 17, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2637, 132}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[127] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_reset, __pyx_k_A_4vS_1A_H_Qd_E_FYYZ_IXT_a_4uCq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[127])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2662, 47}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[128] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_free_pileup_iter, __pyx_k_A_4_C_1_at1_Q_O_q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[128])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2673, 55}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[129] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_a_G_4y_S_Ya, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[129])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2685, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[130] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_hasReference, __pyx_k_A_t, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[130])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 14, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2687, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_iter_2, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_n_plp, __pyx_mstate->__pyx_n_u_min_base_quality, __pyx_mstate->__pyx_n_u_plp, __pyx_mstate->__pyx_n_u_pileup_iter, __pyx_mstate->__pyx_n_u_iterdata, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_fastafile, __pyx_mstate->__pyx_n_u_stepper, __pyx_mstate->__pyx_n_u_max_depth, __pyx_mstate->__pyx_n_u_ignore_overlaps}; + __pyx_mstate_global->__pyx_codeobj_tab[131] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_getSequence, __pyx_k_A_t_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[131])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2689, 13}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_fastafile}; + __pyx_mstate_global->__pyx_codeobj_tab[132] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_addReference, __pyx_k_A_t_3, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[132])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[133] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[133])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[134] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[134])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {7, 0, 0, 8, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARKEYWORDS), 2696, 82}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_tid, __pyx_mstate->__pyx_n_u_start, __pyx_mstate->__pyx_n_u_stop, __pyx_mstate->__pyx_n_u_truncate, __pyx_mstate->__pyx_n_u_multiple_iterators, __pyx_mstate->__pyx_n_u_kwargs}; + __pyx_mstate_global->__pyx_codeobj_tab[135] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_d_E_AU_q_IQ_HA_L, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[135])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2716, 133}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_n}; + __pyx_mstate_global->__pyx_codeobj_tab[136] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_F_r_1_j_r_A_t1_4wb_A_4uCt1_1AT, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[136])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[137] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[137])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[138] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[138])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARKEYWORDS), 2747, 38}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_kwargs}; + __pyx_mstate_global->__pyx_codeobj_tab[139] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_4wa_AT_s_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[139])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2758, 141}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_n}; + __pyx_mstate_global->__pyx_codeobj_tab[140] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_F_r_1_j_r_A_HA_4uBd_V3iq_1AT, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[140])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[141] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[141])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[142] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[142])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS|CO_VARKEYWORDS), 2789, 12}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_kwargs}; + __pyx_mstate_global->__pyx_codeobj_tab[143] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_cinit, __pyx_k_A_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[143])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2795, 91}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_n}; + __pyx_mstate_global->__pyx_codeobj_tab[144] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_next, __pyx_k_A_D_a_2Rq_AQ_2S_q_Q_A_A_A_A_IQ_H, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[144])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[145] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[145])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[146] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[146])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2827, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[147] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_4q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[147])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2832, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[148] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_Q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[148])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2836, 19}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[149] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_5Rq_Na, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[149])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2840, 18}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[150] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_5Rq_L, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[150])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2844, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[151] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_Q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[151])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2849, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[152] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_Q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[152])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2854, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[153] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_Q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[153])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2858, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[154] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_get_2, __pyx_k_Q_2, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[154])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2860, 57}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[155] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_str, __pyx_k_A_t5_Qa, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[155])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 4, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 144}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_state, __pyx_mstate->__pyx_n_u_dict_2, __pyx_mstate->__pyx_n_u_use_setstate}; + __pyx_mstate_global->__pyx_codeobj_tab[156] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_T_d_d_d_QUUggk_l_C_C_G_G_V_V_Z, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[156])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 16, 11}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[157] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_QfA, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[157])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2895, 164}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_samfile, __pyx_mstate->__pyx_n_u_multiple_iterators, __pyx_mstate->__pyx_n_u_cfilename, __pyx_mstate->__pyx_n_u_hdr}; + __pyx_mstate_global->__pyx_codeobj_tab[158] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_init, __pyx_k_EQ_Kq_q_wiq_1_q_Kxq_1_t9Cq_B_l, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[158])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 6, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2926, 162}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_ret, __pyx_mstate->__pyx_n_u_b, __pyx_mstate->__pyx_n_u_pos, __pyx_mstate->__pyx_n_u_hdr, __pyx_mstate->__pyx_n_u_qname}; + __pyx_mstate_global->__pyx_codeobj_tab[159] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_build, __pyx_k_A_I_AQ_q_6_Q_2S_Q_7_1_t7_d_A_iq, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[159])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2953, 56}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_query_name}; + __pyx_mstate_global->__pyx_codeobj_tab[160] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_find, __pyx_k_A_c_Q_q_A_F_1_Q_r, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[160])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 2977, 18}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[161] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_pysam_libcalignmentfile_pyx, __pyx_mstate->__pyx_n_u_dealloc, __pyx_k_A_4q_Qd, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[161])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {1, 0, 0, 1, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self}; + __pyx_mstate_global->__pyx_codeobj_tab[162] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_reduce_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[162])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 2, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 3, 9}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_self, __pyx_mstate->__pyx_n_u_pyx_state}; + __pyx_mstate_global->__pyx_codeobj_tab[163] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_setstate_cython, __pyx_k_Q, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[163])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {3, 0, 0, 5, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 1, 86}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_type, __pyx_mstate->__pyx_n_u_pyx_checksum, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_pyx_PickleError, __pyx_mstate->__pyx_n_u_pyx_result}; + __pyx_mstate_global->__pyx_codeobj_tab[164] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_SNPCall, __pyx_k_hk_A_1_U_U_W_W_X_7_1_7_N_1, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[164])) goto bad; + } + { + const __Pyx_PyCode_New_function_description descr = {2, 0, 0, 3, (unsigned int)(CO_OPTIMIZED|CO_NEWLOCALS), 11, 266}; + PyObject* const varnames[] = {__pyx_mstate->__pyx_n_u_pyx_result, __pyx_mstate->__pyx_n_u_pyx_state, __pyx_mstate->__pyx_n_u_MAX_POS}; + __pyx_mstate_global->__pyx_codeobj_tab[165] = __Pyx_PyCode_New(descr, varnames, __pyx_mstate->__pyx_kp_u_stringsource, __pyx_mstate->__pyx_n_u_pyx_unpickle_SNPCall__set_stat, __pyx_k_k_l_Z___kkx_y_D_D_E_E_I_I_U_U_h, tuple_dedup_map); if (unlikely(!__pyx_mstate_global->__pyx_codeobj_tab[165])) goto bad; + } + Py_DECREF(tuple_dedup_map); + return 0; + bad: + Py_DECREF(tuple_dedup_map); + return -1; +} +/* #### Code section: init_globals ### */ + +static int __Pyx_InitGlobals(void) { + /* PythonCompatibility.init */ + if (likely(__Pyx_init_co_variables() == 0)); else + +if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* AssertionsEnabled.init */ + if (likely(__Pyx_init_assertions_enabled() == 0)); else + +if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + /* CachedMethodType.init */ + #if CYTHON_COMPILING_IN_LIMITED_API +{ + PyObject *typesModule=NULL; + typesModule = PyImport_ImportModule("types"); + if (typesModule) { + __pyx_mstate_global->__Pyx_CachedMethodType = PyObject_GetAttrString(typesModule, "MethodType"); + Py_DECREF(typesModule); + } +} // error handling follows +#endif + +if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) + + return 0; + __pyx_L1_error:; + return -1; +} +/* #### Code section: cleanup_globals ### */ +/* #### Code section: cleanup_module ### */ +/* #### Code section: main_method ### */ +/* #### Code section: utility_code_pragmas ### */ +#ifdef _MSC_VER +#pragma warning( push ) +/* Warning 4127: conditional expression is constant + * Cython uses constant conditional expressions to allow in inline functions to be optimized at + * compile-time, so this warning is not useful + */ +#pragma warning( disable : 4127 ) +#endif + + + +/* #### Code section: utility_code_def ### */ + +/* --- Runtime support code --- */ +/* Refnanny */ +#if CYTHON_REFNANNY +static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { + PyObject *m = NULL, *p = NULL; + void *r = NULL; + m = PyImport_ImportModule(modname); + if (!m) goto end; + p = PyObject_GetAttrString(m, "RefNannyAPI"); + if (!p) goto end; + r = PyLong_AsVoidPtr(p); +end: + Py_XDECREF(p); + Py_XDECREF(m); + return (__Pyx_RefNannyAPIStruct *)r; +} +#endif + +/* PyErrExceptionMatches */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030C00A6 + PyObject *current_exception = tstate->current_exception; + if (unlikely(!current_exception)) return 0; + exc_type = (PyObject*) Py_TYPE(current_exception); + if (exc_type == err) return 1; +#else + exc_type = tstate->curexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; +#endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(exc_type); + #endif + if (unlikely(PyTuple_Check(err))) { + result = __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + } else { + result = __Pyx_PyErr_GivenExceptionMatches(exc_type, err); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(exc_type); + #endif + return result; +} +#endif + +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject *tmp_value; + assert(type == NULL || (value != NULL && type == (PyObject*) Py_TYPE(value))); + if (value) { + #if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(((PyBaseExceptionObject*) value)->traceback != tb)) + #endif + PyException_SetTraceback(value, tb); + } + tmp_value = tstate->current_exception; + tstate->current_exception = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + tmp_type = tstate->curexc_type; + tmp_value = tstate->curexc_value; + tmp_tb = tstate->curexc_traceback; + tstate->curexc_type = type; + tstate->curexc_value = value; + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#endif +} +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyObject* exc_value; + exc_value = tstate->current_exception; + tstate->current_exception = 0; + *value = exc_value; + *type = NULL; + *tb = NULL; + if (exc_value) { + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + #if CYTHON_COMPILING_IN_CPYTHON + *tb = ((PyBaseExceptionObject*) exc_value)->traceback; + Py_XINCREF(*tb); + #else + *tb = PyException_GetTraceback(exc_value); + #endif + } +#else + *type = tstate->curexc_type; + *value = tstate->curexc_value; + *tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#endif +} +#endif + +/* PyObjectGetAttrStr */ +#if CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro)) + return tp->tp_getattro(obj, attr_name); + return PyObject_GetAttr(obj, attr_name); +} +#endif + +/* PyObjectGetAttrStrNoError */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + __Pyx_PyErr_Clear(); +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { + PyObject *result; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + (void) PyObject_GetOptionalAttr(obj, attr_name, &result); + return result; +#else +#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS + PyTypeObject* tp = Py_TYPE(obj); + if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { + return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); + } +#endif + result = __Pyx_PyObject_GetAttrStr(obj, attr_name); + if (unlikely(!result)) { + __Pyx_PyObject_GetAttrStr_ClearAttributeError(); + } + return result; +#endif +} + +/* GetBuiltinName */ +static PyObject *__Pyx_GetBuiltinName(PyObject *name) { + PyObject* result = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_b, name); + if (unlikely(!result) && !PyErr_Occurred()) { + PyErr_Format(PyExc_NameError, + "name '%U' is not defined", name); + } + return result; +} + +/* TupleAndListFromArray */ +#if !CYTHON_COMPILING_IN_CPYTHON && CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + Py_ssize_t i; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + for (i = 0; i < n; i++) { + if (unlikely(__Pyx_PyTuple_SET_ITEM(res, i, src[i]) < 0)) { + Py_DECREF(res); + return NULL; + } + Py_INCREF(src[i]); + } + return res; +} +#elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE void __Pyx_copy_object_array(PyObject *const *CYTHON_RESTRICT src, PyObject** CYTHON_RESTRICT dest, Py_ssize_t length) { + PyObject *v; + Py_ssize_t i; + for (i = 0; i < length; i++) { + v = dest[i] = src[i]; + Py_INCREF(v); + } +} +static CYTHON_INLINE PyObject * +__Pyx_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return __Pyx_NewRef(__pyx_mstate_global->__pyx_empty_tuple); + } + res = PyTuple_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyTupleObject*)res)->ob_item, n); + return res; +} +static CYTHON_INLINE PyObject * +__Pyx_PyList_FromArray(PyObject *const *src, Py_ssize_t n) +{ + PyObject *res; + if (n <= 0) { + return PyList_New(0); + } + res = PyList_New(n); + if (unlikely(res == NULL)) return NULL; + __Pyx_copy_object_array(src, ((PyListObject*)res)->ob_item, n); + return res; +} +#endif + +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL ||\ + !(CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS && (PY_VERSION_HEX < 0x030B0000) + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_GRAAL + return PyObject_RichCompareBool(s1, s2, equals); +#else + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length, length2; + int kind; + void *data1, *data2; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + #endif + length = __Pyx_PyUnicode_GET_LENGTH(s1); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return -1; + #endif + length2 = __Pyx_PyUnicode_GET_LENGTH(s2); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length2 < 0)) return -1; + #endif + if (length != length2) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + return (equals == Py_EQ); +return_ne: + return (equals == Py_NE); +#endif +} + +/* fastcall */ +#if CYTHON_METH_FASTCALL +static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s) +{ + Py_ssize_t i, n = __Pyx_PyTuple_GET_SIZE(kwnames); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(n == -1)) return NULL; + #endif + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + if (s == namei) return kwvalues[i]; + } + for (i = 0; i < n; i++) + { + PyObject *namei = __Pyx_PyTuple_GET_ITEM(kwnames, i); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!namei)) return NULL; + #endif + int eq = __Pyx_PyUnicode_Equals(s, namei, Py_EQ); + if (unlikely(eq != 0)) { + if (unlikely(eq < 0)) return NULL; + return kwvalues[i]; + } + } + return NULL; +} +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030d0000 || CYTHON_COMPILING_IN_LIMITED_API +CYTHON_UNUSED static PyObject *__Pyx_KwargsAsDict_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues) { + Py_ssize_t i, nkwargs; + PyObject *dict; +#if !CYTHON_ASSUME_SAFE_SIZE + nkwargs = PyTuple_Size(kwnames); + if (unlikely(nkwargs < 0)) return NULL; +#else + nkwargs = PyTuple_GET_SIZE(kwnames); +#endif + dict = PyDict_New(); + if (unlikely(!dict)) + return NULL; + for (i=0; irecursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; + PyObject *kwdefs; + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) { + return NULL; + } + if ( + co->co_kwonlyargcount == 0 && + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); + kwdefs = PyFunction_GET_KW_DEFAULTS(func); + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, (int)nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif + +/* PyObjectCall */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *result; + ternaryfunc call = Py_TYPE(func)->tp_call; + if (unlikely(!call)) + return PyObject_Call(func, arg, kw); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectCallMethO */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { + PyObject *self, *result; + PyCFunction cfunc; + cfunc = __Pyx_CyOrPyCFunction_GET_FUNCTION(func); + self = __Pyx_CyOrPyCFunction_GET_SELF(func); + if (unlikely(Py_EnterRecursiveCall(" while calling a Python object"))) + return NULL; + result = cfunc(self, arg); + Py_LeaveRecursiveCall(); + if (unlikely(!result) && unlikely(!PyErr_Occurred())) { + PyErr_SetString( + PyExc_SystemError, + "NULL result without error in PyObject_Call"); + } + return result; +} +#endif + +/* PyObjectFastCall */ +#if PY_VERSION_HEX < 0x03090000 || CYTHON_COMPILING_IN_LIMITED_API +static PyObject* __Pyx_PyObject_FastCall_fallback(PyObject *func, PyObject * const*args, size_t nargs, PyObject *kwargs) { + PyObject *argstuple; + PyObject *result = 0; + size_t i; + argstuple = PyTuple_New((Py_ssize_t)nargs); + if (unlikely(!argstuple)) return NULL; + for (i = 0; i < nargs; i++) { + Py_INCREF(args[i]); + if (__Pyx_PyTuple_SET_ITEM(argstuple, (Py_ssize_t)i, args[i]) != (0)) goto bad; + } + result = __Pyx_PyObject_Call(func, argstuple, kwargs); + bad: + Py_DECREF(argstuple); + return result; +} +#endif +#if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + #if PY_VERSION_HEX < 0x03090000 + #define __Pyx_PyVectorcall_Function(callable) _PyVectorcall_Function(callable) + #elif CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE vectorcallfunc __Pyx_PyVectorcall_Function(PyObject *callable) { + PyTypeObject *tp = Py_TYPE(callable); + #if defined(__Pyx_CyFunction_USED) + if (__Pyx_CyFunction_CheckExact(callable)) { + return __Pyx_CyFunction_func_vectorcall(callable); + } + #endif + if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) { + return NULL; + } + assert(PyCallable_Check(callable)); + Py_ssize_t offset = tp->tp_vectorcall_offset; + assert(offset > 0); + vectorcallfunc ptr; + memcpy(&ptr, (char *) callable + offset, sizeof(ptr)); + return ptr; +} + #else + #define __Pyx_PyVectorcall_Function(callable) PyVectorcall_Function(callable) + #endif +#endif +static CYTHON_INLINE PyObject* __Pyx_PyObject_FastCallDict(PyObject *func, PyObject *const *args, size_t _nargs, PyObject *kwargs) { + Py_ssize_t nargs = __Pyx_PyVectorcall_NARGS(_nargs); +#if CYTHON_COMPILING_IN_CPYTHON + if (nargs == 0 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_NOARGS)) + return __Pyx_PyObject_CallMethO(func, NULL); + } + else if (nargs == 1 && kwargs == NULL) { + if (__Pyx_CyOrPyCFunction_Check(func) && likely( __Pyx_CyOrPyCFunction_GET_FLAGS(func) & METH_O)) + return __Pyx_PyObject_CallMethO(func, args[0]); + } +#endif + #if PY_VERSION_HEX < 0x030800B1 + #if CYTHON_FAST_PYCCALL + if (PyCFunction_Check(func)) { + if (kwargs) { + return _PyCFunction_FastCallDict(func, args, nargs, kwargs); + } else { + return _PyCFunction_FastCallKeywords(func, args, nargs, NULL); + } + } + if (!kwargs && __Pyx_IS_TYPE(func, &PyMethodDescr_Type)) { + return _PyMethodDescr_FastCallKeywords(func, args, nargs, NULL); + } + #endif + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs); + } + #endif + #endif + if (kwargs == NULL) { + #if CYTHON_VECTORCALL && !CYTHON_COMPILING_IN_LIMITED_API + vectorcallfunc f = __Pyx_PyVectorcall_Function(func); + if (f) { + return f(func, args, _nargs, NULL); + } + #elif defined(__Pyx_CyFunction_USED) && CYTHON_BACKPORT_VECTORCALL + if (__Pyx_CyFunction_CheckExact(func)) { + __pyx_vectorcallfunc f = __Pyx_CyFunction_func_vectorcall(func); + if (f) return f(func, args, _nargs, NULL); + } + #elif CYTHON_COMPILING_IN_LIMITED_API && CYTHON_VECTORCALL + return PyObject_Vectorcall(func, args, _nargs, NULL); + #endif + } + if (nargs == 0) { + return __Pyx_PyObject_Call(func, __pyx_mstate_global->__pyx_empty_tuple, kwargs); + } + #if PY_VERSION_HEX >= 0x03090000 && !CYTHON_COMPILING_IN_LIMITED_API + return PyObject_VectorcallDict(func, args, (size_t)nargs, kwargs); + #else + return __Pyx_PyObject_FastCall_fallback(func, args, (size_t)nargs, kwargs); + #endif +} + +/* UnpackUnboundCMethod */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + PyObject *result; + PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); + if (unlikely(!selfless_args)) return NULL; + result = PyObject_Call(method, selfless_args, kwargs); + Py_DECREF(selfless_args); + return result; +} +#elif CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { + return _PyObject_Vectorcall + (method, args ? args+1 : NULL, nargs ? nargs-1 : 0, kwnames); +} +#else +static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { + return +#if PY_VERSION_HEX < 0x03090000 + _PyObject_Vectorcall +#else + PyObject_Vectorcall +#endif + (method, args ? args+1 : NULL, nargs ? (size_t) nargs-1 : 0, kwnames); +} +#endif +static PyMethodDef __Pyx_UnboundCMethod_Def = { + "CythonUnboundCMethod", + __PYX_REINTERPRET_FUNCION(PyCFunction, __Pyx_SelflessCall), +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030C0000 + METH_VARARGS | METH_KEYWORDS, +#else + METH_FASTCALL | METH_KEYWORDS, +#endif + NULL +}; +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { + PyObject *method, *result=NULL; + method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); + if (unlikely(!method)) + return -1; + result = method; +#if CYTHON_COMPILING_IN_CPYTHON + if (likely(__Pyx_TypeCheck(method, &PyMethodDescr_Type))) + { + PyMethodDescrObject *descr = (PyMethodDescrObject*) method; + target->func = descr->d_method->ml_meth; + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); + } else +#endif +#if CYTHON_COMPILING_IN_PYPY +#else + if (PyCFunction_Check(method)) +#endif + { + PyObject *self; + int self_found; +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + self = PyObject_GetAttrString(method, "__self__"); + if (!self) { + PyErr_Clear(); + } +#else + self = PyCFunction_GET_SELF(method); +#endif + self_found = (self && self != Py_None); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_COMPILING_IN_PYPY + Py_XDECREF(self); +#endif + if (self_found) { + PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); + if (unlikely(!unbound_method)) return -1; + Py_DECREF(method); + result = unbound_method; + } + } +#if !CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + if (unlikely(target->method)) { + Py_DECREF(result); + } else +#endif + target->method = result; + return 0; +} + +/* CallUnboundCMethod2 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject *__Pyx_CallUnboundCMethod2(__Pyx_CachedCFunction *cfunc, PyObject *self, PyObject *arg1, PyObject *arg2) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + PyObject *args[2] = {arg1, arg2}; + if (cfunc->flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, args, 2); + } + if (cfunc->flag == (METH_FASTCALL | METH_KEYWORDS)) + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, args, 2, NULL); + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod2(&tmp_cfunc, self, arg1, arg2); + } +#endif + PyObject *result = __Pyx__CallUnboundCMethod2(cfunc, self, arg1, arg2); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod2(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg1, PyObject* arg2){ + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *result = NULL; + PyObject *args = PyTuple_New(2); + if (unlikely(!args)) return NULL; + Py_INCREF(arg1); + PyTuple_SET_ITEM(args, 0, arg1); + Py_INCREF(arg2); + PyTuple_SET_ITEM(args, 1, arg2); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + return result; + } +#endif + { + PyObject *args[4] = {NULL, self, arg1, arg2}; + return __Pyx_PyObject_FastCall(cfunc->method, args+1, 3 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); + } +} + +/* ParseKeywords */ +static int __Pyx_ValidateDuplicatePosArgs( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char* function_name) +{ + PyObject ** const *name = argnames; + while (name != first_kw_arg) { + PyObject *key = **name; + int found = PyDict_Contains(kwds, key); + if (unlikely(found)) { + if (found == 1) __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; + } + name++; + } + return 0; +bad: + return -1; +} +#if CYTHON_USE_UNICODE_INTERNALS +static CYTHON_INLINE int __Pyx_UnicodeKeywordsEqual(PyObject *s1, PyObject *s2) { + int kind; + Py_ssize_t len = PyUnicode_GET_LENGTH(s1); + if (len != PyUnicode_GET_LENGTH(s2)) return 0; + kind = PyUnicode_KIND(s1); + if (kind != PyUnicode_KIND(s2)) return 0; + const void *data1 = PyUnicode_DATA(s1); + const void *data2 = PyUnicode_DATA(s2); + return (memcmp(data1, data2, (size_t) len * (size_t) kind) == 0); +} +#endif +static int __Pyx_MatchKeywordArg_str( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + #if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t key_hash = ((PyASCIIObject*)key)->hash; + if (unlikely(key_hash == -1)) { + key_hash = PyObject_Hash(key); + if (unlikely(key_hash == -1)) + goto bad; + } + #endif + name = first_kw_arg; + while (*name) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (key_hash == ((PyASCIIObject*)name_str)->hash && __Pyx_UnicodeKeywordsEqual(name_str, key)) { + *index_found = (size_t) (name - argnames); + return 1; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) { + *index_found = (size_t) (name - argnames); + return 1; + } + } + #endif + name++; + } + name = argnames; + while (name != first_kw_arg) { + PyObject *name_str = **name; + #if CYTHON_USE_UNICODE_INTERNALS + if (unlikely(key_hash == ((PyASCIIObject*)name_str)->hash)) { + if (__Pyx_UnicodeKeywordsEqual(name_str, key)) + goto arg_passed_twice; + } + #else + #if CYTHON_ASSUME_SAFE_SIZE + if (PyUnicode_GET_LENGTH(name_str) == PyUnicode_GET_LENGTH(key)) + #endif + { + if (unlikely(name_str == key)) goto arg_passed_twice; + int cmp = PyUnicode_Compare(name_str, key); + if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; + if (cmp == 0) goto arg_passed_twice; + } + #endif + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +bad: + return -1; +} +static int __Pyx_MatchKeywordArg_nostr( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + PyObject ** const *name; + if (unlikely(!PyUnicode_Check(key))) goto invalid_keyword_type; + name = first_kw_arg; + while (*name) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (cmp == 1) { + *index_found = (size_t) (name - argnames); + return 1; + } + if (unlikely(cmp == -1)) goto bad; + name++; + } + name = argnames; + while (name != first_kw_arg) { + int cmp = PyObject_RichCompareBool(**name, key, Py_EQ); + if (unlikely(cmp != 0)) { + if (cmp == 1) goto arg_passed_twice; + else goto bad; + } + name++; + } + return 0; +arg_passed_twice: + __Pyx_RaiseDoubleKeywordsError(function_name, key); + goto bad; +invalid_keyword_type: + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + goto bad; +bad: + return -1; +} +static CYTHON_INLINE int __Pyx_MatchKeywordArg( + PyObject *key, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + size_t *index_found, + const char *function_name) +{ + return likely(PyUnicode_CheckExact(key)) ? + __Pyx_MatchKeywordArg_str(key, argnames, first_kw_arg, index_found, function_name) : + __Pyx_MatchKeywordArg_nostr(key, argnames, first_kw_arg, index_found, function_name); +} +static void __Pyx_RejectUnknownKeyword( + PyObject *kwds, + PyObject ** const argnames[], + PyObject ** const *first_kw_arg, + const char *function_name) +{ + Py_ssize_t pos = 0; + PyObject *key = NULL; + __Pyx_BEGIN_CRITICAL_SECTION(kwds); + while (PyDict_Next(kwds, &pos, &key, NULL)) { + PyObject** const *name = first_kw_arg; + while (*name && (**name != key)) name++; + if (!*name) { + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(key); + #endif + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp != 1) { + if (cmp == 0) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + break; + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + #endif + } + } + __Pyx_END_CRITICAL_SECTION(); + assert(PyErr_Occurred()); +} +static int __Pyx_ParseKeywordDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t extracted = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + name = first_kw_arg; + while (*name && num_kwargs > extracted) { + PyObject * key = **name; + PyObject *value; + int found = 0; + #if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + found = PyDict_GetItemRef(kwds, key, &value); + #else + value = PyDict_GetItemWithError(kwds, key); + if (value) { + Py_INCREF(value); + found = 1; + } else { + if (unlikely(PyErr_Occurred())) goto bad; + } + #endif + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + extracted++; + } + name++; + } + if (num_kwargs > extracted) { + if (ignore_unknown_kwargs) { + if (unlikely(__Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name) == -1)) + goto bad; + } else { + __Pyx_RejectUnknownKeyword(kwds, argnames, first_kw_arg, function_name); + goto bad; + } + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordDictToDict( + PyObject *kwds, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + const char* function_name) +{ + PyObject** const *name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + Py_ssize_t len; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return -1; +#endif + if (PyDict_Update(kwds2, kwds) < 0) goto bad; + name = first_kw_arg; + while (*name) { + PyObject *key = **name; + PyObject *value; +#if !CYTHON_COMPILING_IN_LIMITED_API && (PY_VERSION_HEX >= 0x030d00A2 || defined(PyDict_Pop)) + int found = PyDict_Pop(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + } +#elif __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int found = PyDict_GetItemRef(kwds2, key, &value); + if (found) { + if (unlikely(found < 0)) goto bad; + values[name-argnames] = value; + if (unlikely(PyDict_DelItem(kwds2, key) < 0)) goto bad; + } +#else + #if CYTHON_COMPILING_IN_CPYTHON + value = _PyDict_Pop(kwds2, key, kwds2); + #else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_pop, kwds2, key, kwds2); + #endif + if (value == kwds2) { + Py_DECREF(value); + } else { + if (unlikely(!value)) goto bad; + values[name-argnames] = value; + } +#endif + name++; + } + len = PyDict_Size(kwds2); + if (len > 0) { + return __Pyx_ValidateDuplicatePosArgs(kwds, argnames, first_kw_arg, function_name); + } else if (unlikely(len == -1)) { + goto bad; + } + return 0; +bad: + return -1; +} +static int __Pyx_ParseKeywordsTuple( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + PyObject *key = NULL; + PyObject** const * name; + PyObject** const *first_kw_arg = argnames + num_pos_args; + for (Py_ssize_t pos = 0; pos < num_kwargs; pos++) { +#if CYTHON_AVOID_BORROWED_REFS + key = __Pyx_PySequence_ITEM(kwds, pos); +#else + key = __Pyx_PyTuple_GET_ITEM(kwds, pos); +#endif +#if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(!key)) goto bad; +#endif + name = first_kw_arg; + while (*name && (**name != key)) name++; + if (*name) { + PyObject *value = kwvalues[pos]; + values[name-argnames] = __Pyx_NewRef(value); + } else { + size_t index_found = 0; + int cmp = __Pyx_MatchKeywordArg(key, argnames, first_kw_arg, &index_found, function_name); + if (cmp == 1) { + PyObject *value = kwvalues[pos]; + values[index_found] = __Pyx_NewRef(value); + } else { + if (unlikely(cmp == -1)) goto bad; + if (kwds2) { + PyObject *value = kwvalues[pos]; + if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; + } else if (!ignore_unknown_kwargs) { + goto invalid_keyword; + } + } + } + #if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(key); + key = NULL; + #endif + } + return 0; +invalid_keyword: + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + goto bad; +bad: + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(key); + #endif + return -1; +} +static int __Pyx_ParseKeywords( + PyObject *kwds, + PyObject * const *kwvalues, + PyObject ** const argnames[], + PyObject *kwds2, + PyObject *values[], + Py_ssize_t num_pos_args, + Py_ssize_t num_kwargs, + const char* function_name, + int ignore_unknown_kwargs) +{ + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) + return __Pyx_ParseKeywordsTuple(kwds, kwvalues, argnames, kwds2, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); + else if (kwds2) + return __Pyx_ParseKeywordDictToDict(kwds, argnames, kwds2, values, num_pos_args, function_name); + else + return __Pyx_ParseKeywordDict(kwds, argnames, values, num_pos_args, num_kwargs, function_name, ignore_unknown_kwargs); +} + +/* RaiseArgTupleInvalid */ +static void __Pyx_RaiseArgtupleInvalid( + const char* func_name, + int exact, + Py_ssize_t num_min, + Py_ssize_t num_max, + Py_ssize_t num_found) +{ + Py_ssize_t num_expected; + const char *more_or_less; + if (num_found < num_min) { + num_expected = num_min; + more_or_less = "at least"; + } else { + num_expected = num_max; + more_or_less = "at most"; + } + if (exact) { + more_or_less = "exactly"; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", + func_name, more_or_less, num_expected, + (num_expected == 1) ? "" : "s", num_found); +} + +/* Profile */ +#if CYTHON_PROFILE || CYTHON_TRACE +#if CYTHON_TRACE && !CYTHON_USE_SYS_MONITORING +static int __Pyx_call_line_trace_func(PyThreadState *tstate, PyFrameObject *frame, int line) { + int ret; + PyObject *type, *value, *traceback; + __Pyx_ErrFetchInState(tstate, &type, &value, &traceback); + __Pyx_PyFrame_SetLineNumber(frame, line); + __Pyx_EnterTracing(tstate); + ret = tstate->c_tracefunc(tstate->c_traceobj, frame, PyTrace_LINE, NULL); + __Pyx_LeaveTracing(tstate); + if (likely(!ret)) { + __Pyx_ErrRestoreInState(tstate, type, value, traceback); + } else { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + } + return ret; +} +#endif +CYTHON_UNUSED static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) { + PyCodeObject *py_code = PyCode_NewEmpty(srcfile, funcname, firstlineno); + if (likely(py_code)) { + py_code->co_flags |= CO_OPTIMIZED | CO_NEWLOCALS; + } + return py_code; +} +#if CYTHON_USE_SYS_MONITORING +CYTHON_UNUSED static int __Pyx__TraceStartFunc(PyMonitoringState *state_array, PyObject *code_obj, int offset, int skip_event) { + int ret; + __pyx_monitoring_version_type version = 0; + ret = PyMonitoring_EnterScope(state_array, &version, __Pyx_MonitoringEventTypes, __Pyx_MonitoringEventTypes_CyFunc_count); + if (unlikely(ret == -1)) return -1; + return skip_event ? 0 : PyMonitoring_FirePyStartEvent(&state_array[__Pyx_Monitoring_PY_START], code_obj, offset); +} +CYTHON_UNUSED static int __Pyx__TraceStartGen(PyMonitoringState *state_array, __pyx_monitoring_version_type *version, PyObject *code_obj, int offset) { + int ret; + ret = PyMonitoring_EnterScope(state_array, version, __Pyx_MonitoringEventTypes, __Pyx_MonitoringEventTypes_CyGen_count); + if (unlikely(ret == -1)) return -1; + return PyMonitoring_FirePyStartEvent(&state_array[__Pyx_Monitoring_PY_START], code_obj, offset); +} +CYTHON_UNUSED static int __Pyx__TraceResumeGen(PyMonitoringState *state_array, __pyx_monitoring_version_type *version, PyObject *code_obj, int offset) { + int ret; + ret = PyMonitoring_EnterScope(state_array, version, __Pyx_MonitoringEventTypes, __Pyx_MonitoringEventTypes_CyGen_count); + if (unlikely(ret == -1)) return -1; + return PyMonitoring_FirePyResumeEvent(&state_array[__Pyx_Monitoring_PY_RESUME], code_obj, offset); +} +CYTHON_UNUSED static void __Pyx__TraceException(PyMonitoringState *monitoring_state, PyObject *code_obj, int offset, int reraised) { + if (reraised) { + (void) PyMonitoring_FireReraiseEvent(monitoring_state, code_obj, offset); + } else { + (void) PyMonitoring_FireRaiseEvent(monitoring_state, code_obj, offset); + } +} +#if CYTHON_TRACE +CYTHON_UNUSED static int __Pyx__TraceLine(PyMonitoringState *monitoring_state, PyObject *code_obj, int line, int offset) { + int ret; + PyObject *exc = PyErr_GetRaisedException(); + ret = PyMonitoring_FireLineEvent(monitoring_state, code_obj, offset, line); + if (exc) PyErr_SetRaisedException(exc); + return ret; +} +#endif +#else +static int __Pyx_TraceSetupAndCall(PyCodeObject** code, + PyFrameObject** frame, + PyThreadState* tstate, + const char *funcname, + const char *srcfile, + int firstlineno, + int skip_event) { + if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) { + int needs_new_code_obj = (*code == NULL); + if (needs_new_code_obj) { + *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno); + if (*code == NULL) return 0; + } + *frame = PyFrame_New( + tstate, /*PyThreadState *tstate*/ + *code, /*PyCodeObject *code*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals*/ + 0 /*PyObject *locals*/ + ); + if (needs_new_code_obj && !CYTHON_PROFILE_REUSE_CODEOBJ) + Py_CLEAR(*code); // otherwise the reference is owned externally + if (*frame == NULL) return 0; + if (CYTHON_TRACE && (*frame)->f_trace == NULL) { + Py_INCREF(Py_None); + (*frame)->f_trace = Py_None; + } + } + if (!skip_event) { + PyObject *type, *value, *traceback; + int retval = 1; + __Pyx_PyFrame_SetLineNumber(*frame, firstlineno); + __Pyx_EnterTracing(tstate); + __Pyx_ErrFetchInState(tstate, &type, &value, &traceback); + #if CYTHON_TRACE + if (tstate->c_tracefunc) + retval = tstate->c_tracefunc(tstate->c_traceobj, *frame, PyTrace_CALL, NULL) == 0; + if (retval && tstate->c_profilefunc) + #endif + retval = tstate->c_profilefunc(tstate->c_profileobj, *frame, PyTrace_CALL, NULL) == 0; + __Pyx_LeaveTracing(tstate); + if (unlikely(!retval)) { + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + return -1; + } + __Pyx_ErrRestoreInState(tstate, type, value, traceback); + } + return __Pyx_IsTracing(tstate, 0, 0); +} +#endif +#endif + +/* PyObjectFastCallMethod */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_PyObject_FastCallMethod(PyObject *name, PyObject *const *args, size_t nargsf) { + PyObject *result; + PyObject *attr = PyObject_GetAttr(args[0], name); + if (unlikely(!attr)) + return NULL; + result = __Pyx_PyObject_FastCall(attr, args+1, nargsf - 1); + Py_DECREF(attr); + return result; +} +#endif + +/* PyObjectFormatAndDecref */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatSimpleAndDecref(PyObject* s, PyObject* f) { + if (unlikely(!s)) return NULL; + if (likely(PyUnicode_CheckExact(s))) return s; + return __Pyx_PyObject_FormatAndDecref(s, f); +} +static CYTHON_INLINE PyObject* __Pyx_PyObject_FormatAndDecref(PyObject* s, PyObject* f) { + PyObject *result; + if (unlikely(!s)) return NULL; + result = PyObject_Format(s, f); + Py_DECREF(s); + return result; +} + +/* GetItemInt */ +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (unlikely(!j)) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS && !CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif +} +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { + return __Pyx_PyList_GetItemRef(o, n); + } + } + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PyMappingMethods *mm = Py_TYPE(o)->tp_as_mapping; + PySequenceMethods *sm = Py_TYPE(o)->tp_as_sequence; + if (mm && mm->mp_subscript) { + PyObject *r, *key = PyLong_FromSsize_t(i); + if (unlikely(!key)) return NULL; + r = mm->mp_subscript(o, key); + Py_DECREF(key); + return r; + } + if (likely(sm && sm->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(sm->sq_length)) { + Py_ssize_t l = sm->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return sm->sq_item(o, i); + } + } +#else + if (is_list || !PyMapping_Check(o)) { + return PySequence_GetItem(o, i); + } +#endif + return __Pyx_GetItemInt_Generic(o, PyLong_FromSsize_t(i)); +} + +/* PyObjectCallOneArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *args[2] = {NULL, arg}; + return __Pyx_PyObject_FastCall(func, args+1, 1 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* ObjectGetItem */ +#if CYTHON_USE_TYPE_SLOTS +static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject *index) { + PyObject *runerr = NULL; + Py_ssize_t key_value; + key_value = __Pyx_PyIndex_AsSsize_t(index); + if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { + return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); + } + if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { + __Pyx_TypeName index_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(index)); + PyErr_Clear(); + PyErr_Format(PyExc_IndexError, + "cannot fit '" __Pyx_FMT_TYPENAME "' into an index-sized integer", index_type_name); + __Pyx_DECREF_TypeName(index_type_name); + } + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem_Slow(PyObject *obj, PyObject *key) { + __Pyx_TypeName obj_type_name; + if (likely(PyType_Check(obj))) { + PyObject *meth = __Pyx_PyObject_GetAttrStrNoError(obj, __pyx_mstate_global->__pyx_n_u_class_getitem); + if (!meth) { + PyErr_Clear(); + } else { + PyObject *result = __Pyx_PyObject_CallOneArg(meth, key); + Py_DECREF(meth); + return result; + } + } + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "'" __Pyx_FMT_TYPENAME "' object is not subscriptable", obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return NULL; +} +static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject *key) { + PyTypeObject *tp = Py_TYPE(obj); + PyMappingMethods *mm = tp->tp_as_mapping; + PySequenceMethods *sm = tp->tp_as_sequence; + if (likely(mm && mm->mp_subscript)) { + return mm->mp_subscript(obj, key); + } + if (likely(sm && sm->sq_item)) { + return __Pyx_PyObject_GetIndex(obj, key); + } + return __Pyx_PyObject_GetItem_Slow(obj, key); +} +#endif + +/* JoinPyUnicode */ +static PyObject* __Pyx_PyUnicode_Join(PyObject** values, Py_ssize_t value_count, Py_ssize_t result_ulength, + Py_UCS4 max_char) { +#if CYTHON_USE_UNICODE_INTERNALS && CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *result_uval; + int result_ukind, kind_shift; + Py_ssize_t i, char_pos; + void *result_udata; + if (max_char > 1114111) max_char = 1114111; + result_uval = PyUnicode_New(result_ulength, max_char); + if (unlikely(!result_uval)) return NULL; + result_ukind = (max_char <= 255) ? PyUnicode_1BYTE_KIND : (max_char <= 65535) ? PyUnicode_2BYTE_KIND : PyUnicode_4BYTE_KIND; + kind_shift = (result_ukind == PyUnicode_4BYTE_KIND) ? 2 : result_ukind - 1; + result_udata = PyUnicode_DATA(result_uval); + assert(kind_shift == 2 || kind_shift == 1 || kind_shift == 0); + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - result_ulength < 0)) + goto overflow; + char_pos = 0; + for (i=0; i < value_count; i++) { + int ukind; + Py_ssize_t ulength; + void *udata; + PyObject *uval = values[i]; + #if !CYTHON_COMPILING_IN_LIMITED_API + if (__Pyx_PyUnicode_READY(uval) == (-1)) + goto bad; + #endif + ulength = __Pyx_PyUnicode_GET_LENGTH(uval); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(ulength < 0)) goto bad; + #endif + if (unlikely(!ulength)) + continue; + if (unlikely((PY_SSIZE_T_MAX >> kind_shift) - ulength < char_pos)) + goto overflow; + ukind = __Pyx_PyUnicode_KIND(uval); + udata = __Pyx_PyUnicode_DATA(uval); + if (ukind == result_ukind) { + memcpy((char *)result_udata + (char_pos << kind_shift), udata, (size_t) (ulength << kind_shift)); + } else { + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(result_uval, char_pos, uval, 0, ulength) < 0)) goto bad; + #elif CYTHON_COMPILING_IN_CPYTHON || defined(_PyUnicode_FastCopyCharacters) + _PyUnicode_FastCopyCharacters(result_uval, char_pos, uval, 0, ulength); + #else + Py_ssize_t j; + for (j=0; j < ulength; j++) { + Py_UCS4 uchar = __Pyx_PyUnicode_READ(ukind, udata, j); + __Pyx_PyUnicode_WRITE(result_ukind, result_udata, char_pos+j, uchar); + } + #endif + } + char_pos += ulength; + } + return result_uval; +overflow: + PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); +bad: + Py_DECREF(result_uval); + return NULL; +#else + Py_ssize_t i; + PyObject *result = NULL; + PyObject *value_tuple = PyTuple_New(value_count); + if (unlikely(!value_tuple)) return NULL; + CYTHON_UNUSED_VAR(max_char); + CYTHON_UNUSED_VAR(result_ulength); + for (i=0; i__pyx_empty_unicode, value_tuple); +bad: + Py_DECREF(value_tuple); + return result; +#endif +} + +/* PyDictVersioning */ +#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS +static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; +} +static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { + PyObject **dictptr = NULL; + Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; + if (offset) { +#if CYTHON_COMPILING_IN_CPYTHON + dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); +#else + dictptr = _PyObject_GetDictPtr(obj); +#endif + } + return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; +} +static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { + PyObject *dict = Py_TYPE(obj)->tp_dict; + if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) + return 0; + return obj_dict_version == __Pyx_get_object_dict_version(obj); +} +#endif + +/* GetModuleGlobalName */ +#if CYTHON_USE_DICT_VERSIONS +static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) +#else +static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) +#endif +{ + PyObject *result; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(!__pyx_m)) { + if (!PyErr_Occurred()) + PyErr_SetNone(PyExc_NameError); + return NULL; + } + result = PyObject_GetAttr(__pyx_m, name); + if (likely(result)) { + return result; + } + PyErr_Clear(); +#elif CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + if (unlikely(__Pyx_PyDict_GetItemRef(__pyx_mstate_global->__pyx_d, name, &result) == -1)) PyErr_Clear(); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return result; + } +#else + result = _PyDict_GetItem_KnownHash(__pyx_mstate_global->__pyx_d, name, ((PyASCIIObject *) name)->hash); + __PYX_UPDATE_DICT_CACHE(__pyx_mstate_global->__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); + } + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); +} + +/* RaiseException */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { + PyObject* owned_instance = NULL; + if (tb == Py_None) { + tb = 0; + } else if (tb && !PyTraceBack_Check(tb)) { + PyErr_SetString(PyExc_TypeError, + "raise: arg 3 must be a traceback or None"); + goto bad; + } + if (value == Py_None) + value = 0; + if (PyExceptionInstance_Check(type)) { + if (value) { + PyErr_SetString(PyExc_TypeError, + "instance exception may not have a separate value"); + goto bad; + } + value = type; + type = (PyObject*) Py_TYPE(value); + } else if (PyExceptionClass_Check(type)) { + PyObject *instance_class = NULL; + if (value && PyExceptionInstance_Check(value)) { + instance_class = (PyObject*) Py_TYPE(value); + if (instance_class != type) { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { + instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; + } + } + } + if (!instance_class) { + PyObject *args; + if (!value) + args = PyTuple_New(0); + else if (PyTuple_Check(value)) { + Py_INCREF(value); + args = value; + } else + args = PyTuple_Pack(1, value); + if (!args) + goto bad; + owned_instance = PyObject_Call(type, args, NULL); + Py_DECREF(args); + if (!owned_instance) + goto bad; + value = owned_instance; + if (!PyExceptionInstance_Check(value)) { + PyErr_Format(PyExc_TypeError, + "calling %R should have returned an instance of " + "BaseException, not %R", + type, Py_TYPE(value)); + goto bad; + } + } + } else { + PyErr_SetString(PyExc_TypeError, + "raise: exception class must be a subclass of BaseException"); + goto bad; + } + if (cause) { + PyObject *fixed_cause; + if (cause == Py_None) { + fixed_cause = NULL; + } else if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto bad; + } else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + Py_INCREF(fixed_cause); + } else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto bad; + } + PyException_SetCause(value, fixed_cause); + } + PyErr_SetObject(type, value); + if (tb) { +#if PY_VERSION_HEX >= 0x030C00A6 + PyException_SetTraceback(value, tb); +#elif CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* tmp_tb = tstate->curexc_traceback; + if (tb != tmp_tb) { + Py_INCREF(tb); + tstate->curexc_traceback = tb; + Py_XDECREF(tmp_tb); + } +#else + PyObject *tmp_type, *tmp_value, *tmp_tb; + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); + Py_INCREF(tb); + PyErr_Restore(tmp_type, tmp_value, tb); + Py_XDECREF(tmp_tb); +#endif + } +bad: + Py_XDECREF(owned_instance); + return; +} + +/* PyLongCompare */ +static CYTHON_INLINE int __Pyx_PyLong_BoolEqObjC(PyObject *op1, PyObject *op2, long intval, long inplace) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(inplace); + if (op1 == op2) { + return 1; + } + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + int unequal; + unsigned long uintval; + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + if (intval == 0) { + return (__Pyx_PyLong_IsZero(op1) == 1); + } else if (intval < 0) { + if (__Pyx_PyLong_IsNonNeg(op1)) + return 0; + intval = -intval; + } else { + if (__Pyx_PyLong_IsNeg(op1)) + return 0; + } + uintval = (unsigned long) intval; +#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 4)) { + unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 3)) { + unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 2)) { + unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 1)) { + unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif + unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); + return (unequal == 0); + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(op1); + return ((double)a == (double)b); + } + return __Pyx_PyObject_IsTrueAndDecref( + PyObject_RichCompare(op1, op2, Py_EQ)); +} + +/* RejectKeywords */ +static void __Pyx_RejectKeywords(const char* function_name, PyObject *kwds) { + PyObject *key = NULL; + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kwds))) { + key = __Pyx_PySequence_ITEM(kwds, 0); + } else { + Py_ssize_t pos = 0; +#if !CYTHON_COMPILING_IN_PYPY || defined(PyArg_ValidateKeywordArguments) + if (unlikely(!PyArg_ValidateKeywordArguments(kwds))) return; +#endif + PyDict_Next(kwds, &pos, &key, NULL); + Py_INCREF(key); + } + if (likely(key)) { + PyErr_Format(PyExc_TypeError, + "%s() got an unexpected keyword argument '%U'", + function_name, key); + Py_DECREF(key); + } +} + +/* SliceObject */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, + Py_ssize_t cstart, Py_ssize_t cstop, + PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, + int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { + __Pyx_TypeName obj_type_name; +#if CYTHON_USE_TYPE_SLOTS + PyMappingMethods* mp = Py_TYPE(obj)->tp_as_mapping; + if (likely(mp && mp->mp_subscript)) +#endif + { + PyObject* result; + PyObject *py_slice, *py_start, *py_stop; + if (_py_slice) { + py_slice = *_py_slice; + } else { + PyObject* owned_start = NULL; + PyObject* owned_stop = NULL; + if (_py_start) { + py_start = *_py_start; + } else { + if (has_cstart) { + owned_start = py_start = PyLong_FromSsize_t(cstart); + if (unlikely(!py_start)) goto bad; + } else + py_start = Py_None; + } + if (_py_stop) { + py_stop = *_py_stop; + } else { + if (has_cstop) { + owned_stop = py_stop = PyLong_FromSsize_t(cstop); + if (unlikely(!py_stop)) { + Py_XDECREF(owned_start); + goto bad; + } + } else + py_stop = Py_None; + } + py_slice = PySlice_New(py_start, py_stop, Py_None); + Py_XDECREF(owned_start); + Py_XDECREF(owned_stop); + if (unlikely(!py_slice)) goto bad; + } +#if CYTHON_USE_TYPE_SLOTS + result = mp->mp_subscript(obj, py_slice); +#else + result = PyObject_GetItem(obj, py_slice); +#endif + if (!_py_slice) { + Py_DECREF(py_slice); + } + return result; + } + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "'" __Pyx_FMT_TYPENAME "' object is unsliceable", obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); +bad: + return NULL; +} + +/* DictGetItem */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { + PyObject *value; + if (unlikely(__Pyx_PyDict_GetItemRef(d, key, &value) == 0)) { // no value, no error + if (unlikely(PyTuple_Check(key))) { + PyObject* args = PyTuple_Pack(1, key); + if (likely(args)) { + PyErr_SetObject(PyExc_KeyError, args); + Py_DECREF(args); + } + } else { + PyErr_SetObject(PyExc_KeyError, key); + } + } + return value; +} +#endif + +/* GetTopmostException */ +#if CYTHON_USE_EXC_INFO_STACK && CYTHON_FAST_THREAD_STATE +static _PyErr_StackItem * +__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + while ((exc_info->exc_value == NULL || exc_info->exc_value == Py_None) && + exc_info->previous_item != NULL) + { + exc_info = exc_info->previous_item; + } + return exc_info; +} +#endif + +/* SaveResetException */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + PyObject *exc_value = exc_info->exc_value; + if (exc_value == NULL || exc_value == Py_None) { + *value = NULL; + *type = NULL; + *tb = NULL; + } else { + *value = exc_value; + Py_INCREF(*value); + *type = (PyObject*) Py_TYPE(exc_value); + Py_INCREF(*type); + *tb = PyException_GetTraceback(exc_value); + } + #elif CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); + *type = exc_info->exc_type; + *value = exc_info->exc_value; + *tb = exc_info->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); + #endif +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + #if CYTHON_USE_EXC_INFO_STACK && PY_VERSION_HEX >= 0x030B00a4 + _PyErr_StackItem *exc_info = tstate->exc_info; + PyObject *tmp_value = exc_info->exc_value; + exc_info->exc_value = value; + Py_XDECREF(tmp_value); + Py_XDECREF(type); + Py_XDECREF(tb); + #else + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if CYTHON_USE_EXC_INFO_STACK + _PyErr_StackItem *exc_info = tstate->exc_info; + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = type; + exc_info->exc_value = value; + exc_info->exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + #endif +} +#endif + +/* GetException */ +#if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) +#endif +{ + PyObject *local_type = NULL, *local_value, *local_tb = NULL; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030C0000 + local_value = tstate->current_exception; + tstate->current_exception = 0; + #else + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + #endif +#elif __PYX_LIMITED_VERSION_HEX > 0x030C0000 + local_value = PyErr_GetRaisedException(); +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif +#if __PYX_LIMITED_VERSION_HEX > 0x030C0000 + if (likely(local_value)) { + local_type = (PyObject*) Py_TYPE(local_value); + Py_INCREF(local_type); + local_tb = PyException_GetTraceback(local_value); + } +#else + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } +#endif // __PYX_LIMITED_VERSION_HEX > 0x030C0000 + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if CYTHON_USE_EXC_INFO_STACK + { + _PyErr_StackItem *exc_info = tstate->exc_info; + #if PY_VERSION_HEX >= 0x030B00a4 + tmp_value = exc_info->exc_value; + exc_info->exc_value = local_value; + tmp_type = NULL; + tmp_tb = NULL; + Py_XDECREF(local_type); + Py_XDECREF(local_tb); + #else + tmp_type = exc_info->exc_type; + tmp_value = exc_info->exc_value; + tmp_tb = exc_info->exc_traceback; + exc_info->exc_type = local_type; + exc_info->exc_value = local_value; + exc_info->exc_traceback = local_tb; + #endif + } + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +#elif __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + PyErr_SetHandledException(local_value); + Py_XDECREF(local_value); + Py_XDECREF(local_type); + Py_XDECREF(local_tb); +#else + PyErr_SetExcInfo(local_type, local_value, local_tb); +#endif + return 0; +#if __PYX_LIMITED_VERSION_HEX <= 0x030C0000 +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; +#endif +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { + PyObject* exc_type; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + exc_type = __Pyx_PyErr_CurrentExceptionType(); + if (unlikely(exc_type)) { + if (unlikely(!__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) + return -1; + __Pyx_PyErr_Clear(); + return 0; + } + return 0; +} + +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } + return __Pyx_IterFinish(); +} + +/* UnicodeConcatInPlace */ +# if CYTHON_COMPILING_IN_CPYTHON +static int +__Pyx_unicode_modifiable(PyObject *unicode) +{ + if (Py_REFCNT(unicode) != 1) + return 0; + if (!PyUnicode_CheckExact(unicode)) + return 0; + if (PyUnicode_CHECK_INTERNED(unicode)) + return 0; + return 1; +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_ConcatInPlaceImpl(PyObject **p_left, PyObject *right + #if CYTHON_REFNANNY + , void* __pyx_refnanny + #endif + ) { + PyObject *left = *p_left; + Py_ssize_t left_len, right_len, new_len; + if (unlikely(__Pyx_PyUnicode_READY(left) == -1)) + return NULL; + if (unlikely(__Pyx_PyUnicode_READY(right) == -1)) + return NULL; + left_len = PyUnicode_GET_LENGTH(left); + if (left_len == 0) { + Py_INCREF(right); + return right; + } + right_len = PyUnicode_GET_LENGTH(right); + if (right_len == 0) { + Py_INCREF(left); + return left; + } + if (unlikely(left_len > PY_SSIZE_T_MAX - right_len)) { + PyErr_SetString(PyExc_OverflowError, + "strings are too large to concat"); + return NULL; + } + new_len = left_len + right_len; + if (__Pyx_unicode_modifiable(left) + && PyUnicode_CheckExact(right) + && PyUnicode_KIND(right) <= PyUnicode_KIND(left) + && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right))) { + int ret; + __Pyx_GIVEREF(*p_left); + ret = PyUnicode_Resize(p_left, new_len); + __Pyx_GOTREF(*p_left); + if (unlikely(ret != 0)) + return NULL; + #if PY_VERSION_HEX >= 0x030d0000 + if (unlikely(PyUnicode_CopyCharacters(*p_left, left_len, right, 0, right_len) < 0)) return NULL; + #else + _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len); + #endif + __Pyx_INCREF(*p_left); + __Pyx_GIVEREF(*p_left); + return *p_left; + } else { + return __Pyx_PyUnicode_Concat(left, right); + } + } +#endif + +/* WriteUnraisableException */ +static void __Pyx_WriteUnraisable(const char *name, int clineno, + int lineno, const char *filename, + int full_traceback, int nogil) { + PyObject *old_exc, *old_val, *old_tb; + PyObject *ctx; + __Pyx_PyThreadState_declare + PyGILState_STATE state; + if (nogil) + state = PyGILState_Ensure(); + else state = (PyGILState_STATE)0; + CYTHON_UNUSED_VAR(clineno); + CYTHON_UNUSED_VAR(lineno); + CYTHON_UNUSED_VAR(filename); + CYTHON_MAYBE_UNUSED_VAR(nogil); + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); + if (full_traceback) { + Py_XINCREF(old_exc); + Py_XINCREF(old_val); + Py_XINCREF(old_tb); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + PyErr_PrintEx(0); + } + ctx = PyUnicode_FromString(name); + __Pyx_ErrRestore(old_exc, old_val, old_tb); + if (!ctx) { + PyErr_WriteUnraisable(Py_None); + } else { + PyErr_WriteUnraisable(ctx); + Py_DECREF(ctx); + } + if (nogil) + PyGILState_Release(state); +} + +/* PyObjectCall2Args */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { + PyObject *args[3] = {NULL, arg1, arg2}; + return __Pyx_PyObject_FastCall(function, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectGetMethod */ +static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { + PyObject *attr; +#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP + __Pyx_TypeName type_name; + PyTypeObject *tp = Py_TYPE(obj); + PyObject *descr; + descrgetfunc f = NULL; + PyObject **dictptr, *dict; + int meth_found = 0; + assert (*method == NULL); + if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; + } + if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { + return 0; + } + descr = _PyType_Lookup(tp, name); + if (likely(descr != NULL)) { + Py_INCREF(descr); +#if defined(Py_TPFLAGS_METHOD_DESCRIPTOR) && Py_TPFLAGS_METHOD_DESCRIPTOR + if (__Pyx_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) +#else + #ifdef __Pyx_CyFunction_USED + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) + #else + if (likely(PyFunction_Check(descr) || __Pyx_IS_TYPE(descr, &PyMethodDescr_Type))) + #endif +#endif + { + meth_found = 1; + } else { + f = Py_TYPE(descr)->tp_descr_get; + if (f != NULL && PyDescr_IsData(descr)) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + } + } + dictptr = _PyObject_GetDictPtr(obj); + if (dictptr != NULL && (dict = *dictptr) != NULL) { + Py_INCREF(dict); + attr = __Pyx_PyDict_GetItemStr(dict, name); + if (attr != NULL) { + Py_INCREF(attr); + Py_DECREF(dict); + Py_XDECREF(descr); + goto try_unpack; + } + Py_DECREF(dict); + } + if (meth_found) { + *method = descr; + return 1; + } + if (f != NULL) { + attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); + Py_DECREF(descr); + goto try_unpack; + } + if (likely(descr != NULL)) { + *method = descr; + return 0; + } + type_name = __Pyx_PyType_GetFullyQualifiedName(tp); + PyErr_Format(PyExc_AttributeError, + "'" __Pyx_FMT_TYPENAME "' object has no attribute '%U'", + type_name, name); + __Pyx_DECREF_TypeName(type_name); + return 0; +#else + attr = __Pyx_PyObject_GetAttrStr(obj, name); + goto try_unpack; +#endif +try_unpack: +#if CYTHON_UNPACK_METHODS + if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { + PyObject *function = PyMethod_GET_FUNCTION(attr); + Py_INCREF(function); + Py_DECREF(attr); + *method = function; + return 1; + } +#endif + *method = attr; + return 0; +} + +/* PyObjectCallMethod1 */ +#if !(CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C0000) +static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { + PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); + Py_DECREF(method); + return result; +} +#endif +static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { +#if CYTHON_VECTORCALL && __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + PyObject *args[2] = {obj, arg}; + (void) __Pyx_PyObject_GetMethod; + (void) __Pyx_PyObject_CallOneArg; + (void) __Pyx_PyObject_Call2Args; + return PyObject_VectorcallMethod(method_name, args, 2 | PY_VECTORCALL_ARGUMENTS_OFFSET, NULL); +#else + PyObject *method = NULL, *result; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_Call2Args(method, obj, arg); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) return NULL; + return __Pyx__PyObject_CallMethod1(method, arg); +#endif +} + +/* append */ +static CYTHON_INLINE int __Pyx_PyObject_Append(PyObject* L, PyObject* x) { + if (likely(PyList_CheckExact(L))) { + if (unlikely(__Pyx_PyList_Append(L, x) < 0)) return -1; + } else { + PyObject* retval = __Pyx_PyObject_CallMethod1(L, __pyx_mstate_global->__pyx_n_u_append, x); + if (unlikely(!retval)) + return -1; + Py_DECREF(retval); + } + return 0; +} + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op2); + } + if (likely(__Pyx_PyLong_IsCompact(op1))) { + a = __Pyx_PyLong_CompactValue(op1); + } else { + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(op1); + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); + } + } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + return __Pyx_Fallback___Pyx_PyLong_AddObjC(op1, op2, inplace); + + +} +#endif +static PyObject* __Pyx_Float___Pyx_PyLong_AddObjC(PyObject *float_val, long intval, int zerodivision_check) { + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(float_val); + double result; + + result = ((double)a) + (double)b; + return PyFloat_FromDouble(result); +} +static CYTHON_INLINE PyObject* __Pyx_PyLong_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + return __Pyx_Unpacked___Pyx_PyLong_AddObjC(op1, op2, intval, inplace, zerodivision_check); + } + #endif + if (PyFloat_CheckExact(op1)) { + return __Pyx_Float___Pyx_PyLong_AddObjC(op1, intval, zerodivision_check); + } + return __Pyx_Fallback___Pyx_PyLong_AddObjC(op1, op2, inplace); +} +#endif + +/* KeywordStringCheck */ +static int __Pyx_CheckKeywordStrings( + const char* function_name, + PyObject *kw) +{ +#if CYTHON_COMPILING_IN_PYPY && !defined(PyArg_ValidateKeywordArguments) + CYTHON_UNUSED_VAR(function_name); + CYTHON_UNUSED_VAR(kw); + return 0; +#else + if (CYTHON_METH_FASTCALL && likely(PyTuple_Check(kw))) { +#if PY_VERSION_HEX >= 0x03090000 + CYTHON_UNUSED_VAR(function_name); +#else + Py_ssize_t kwsize; + #if CYTHON_ASSUME_SAFE_SIZE + kwsize = PyTuple_GET_SIZE(kw); + #else + kwsize = PyTuple_Size(kw); + if (unlikely(kwsize < 0)) return -1; + #endif + for (Py_ssize_t pos = 0; pos < kwsize; pos++) { + PyObject* key = NULL; + #if CYTHON_ASSUME_SAFE_MACROS + key = PyTuple_GET_ITEM(kw, pos); + #else + key = PyTuple_GetItem(kw, pos); + if (unlikely(!key)) return -1; + #endif + if (unlikely(!PyUnicode_Check(key))) { + PyErr_Format(PyExc_TypeError, + "%.200s() keywords must be strings", function_name); + return -1; + } + } +#endif + } else { + if (unlikely(!PyArg_ValidateKeywordArguments(kw))) return -1; + } + return 0; +#endif +} + +/* ArgTypeTest */ +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + __Pyx_TypeName type_name; + __Pyx_TypeName obj_type_name; + PyObject *extra_info = __pyx_mstate_global->__pyx_empty_unicode; + int from_annotation_subclass = 0; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + else if (!exact) { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; + } else if (exact == 2) { + if (__Pyx_TypeCheck(obj, type)) { + from_annotation_subclass = 1; + extra_info = __pyx_mstate_global->__pyx_kp_u_Note_that_Cython_is_deliberately; + } + } + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, + "Argument '%.200s' has incorrect type (expected " __Pyx_FMT_TYPENAME + ", got " __Pyx_FMT_TYPENAME ")" +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + "%s%U" +#endif + , name, type_name, obj_type_name +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 + , (from_annotation_subclass ? ". " : ""), extra_info +#endif + ); +#if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + if (exact == 2 && from_annotation_subclass) { + PyObject *res; + PyObject *vargs[2]; + vargs[0] = PyErr_GetRaisedException(); + vargs[1] = extra_info; + res = PyObject_VectorcallMethod(__pyx_mstate_global->__pyx_kp_u_add_note, vargs, 2, NULL); + Py_XDECREF(res); + PyErr_SetRaisedException(vargs[0]); + } +#endif + __Pyx_DECREF_TypeName(type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* HasAttr */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!PyUnicode_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (!r) { + return (unlikely(PyErr_Occurred())) ? -1 : 0; + } else { + Py_DECREF(r); + return 1; + } +} +#endif + +/* ExtTypeTest */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + __Pyx_TypeName obj_type_name; + __Pyx_TypeName type_name; + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + type_name = __Pyx_PyType_GetFullyQualifiedName(type); + PyErr_Format(PyExc_TypeError, + "Cannot convert " __Pyx_FMT_TYPENAME " to " __Pyx_FMT_TYPENAME, + obj_type_name, type_name); + __Pyx_DECREF_TypeName(obj_type_name); + __Pyx_DECREF_TypeName(type_name); + return 0; +} + +/* PyObjectVectorCallKwBuilder */ +#if CYTHON_VECTORCALL +static int __Pyx_VectorcallBuilder_AddArg(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_PyObject_FastCallDict; + if (__Pyx_PyTuple_SET_ITEM(builder, n, key) != (0)) return -1; + Py_INCREF(key); + args[n] = value; + return 0; +} +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + (void)__Pyx_VectorcallBuilder_AddArgStr; + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return __Pyx_VectorcallBuilder_AddArg(key, value, builder, args, n); +} +static int __Pyx_VectorcallBuilder_AddArgStr(const char *key, PyObject *value, PyObject *builder, PyObject **args, int n) { + PyObject *pyKey = PyUnicode_FromString(key); + if (!pyKey) return -1; + return __Pyx_VectorcallBuilder_AddArg(pyKey, value, builder, args, n); +} +#else // CYTHON_VECTORCALL +CYTHON_UNUSED static int __Pyx_VectorcallBuilder_AddArg_Check(PyObject *key, PyObject *value, PyObject *builder, CYTHON_UNUSED PyObject **args, CYTHON_UNUSED int n) { + if (unlikely(!PyUnicode_Check(key))) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + return -1; + } + return PyDict_SetItem(builder, key, value); +} +#endif + +/* PyObjectVectorCallMethodKwBuilder */ +#if !CYTHON_VECTORCALL || PY_VERSION_HEX < 0x03090000 +static PyObject *__Pyx_Object_VectorcallMethod_CallFromBuilder(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames) { + PyObject *result; + PyObject *obj = PyObject_GetAttr(args[0], name); + if (unlikely(!obj)) + return NULL; + result = __Pyx_Object_Vectorcall_CallFromBuilder(obj, args+1, nargsf-1, kwnames); + Py_DECREF(obj); + return result; +} +#endif + +/* PyLongCompare */ +static CYTHON_INLINE int __Pyx_PyLong_BoolNeObjC(PyObject *op1, PyObject *op2, long intval, long inplace) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(inplace); + if (op1 == op2) { + return 0; + } + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + int unequal; + unsigned long uintval; + Py_ssize_t size = __Pyx_PyLong_DigitCount(op1); + const digit* digits = __Pyx_PyLong_Digits(op1); + if (intval == 0) { + return (__Pyx_PyLong_IsZero(op1) != 1); + } else if (intval < 0) { + if (__Pyx_PyLong_IsNonNeg(op1)) + return 1; + intval = -intval; + } else { + if (__Pyx_PyLong_IsNeg(op1)) + return 1; + } + uintval = (unsigned long) intval; +#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 4)) { + unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 3)) { + unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 2)) { + unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 1)) { + unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif + unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); + return (unequal != 0); + } + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = __Pyx_PyFloat_AS_DOUBLE(op1); + return ((double)a != (double)b); + } + return __Pyx_PyObject_IsTrueAndDecref( + PyObject_RichCompare(op1, op2, Py_NE)); +} + +/* PyObjectCallNoArg */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { + PyObject *arg[2] = {NULL, NULL}; + return __Pyx_PyObject_FastCall(func, arg + 1, 0 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET); +} + +/* PyObjectCallMethod0 */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { + PyObject *method = NULL, *result = NULL; + int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); + if (likely(is_method)) { + result = __Pyx_PyObject_CallOneArg(method, obj); + Py_DECREF(method); + return result; + } + if (unlikely(!method)) goto bad; + result = __Pyx_PyObject_CallNoArg(method); + Py_DECREF(method); +bad: + return result; +} + +/* RaiseNoneIterError */ +static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); +} + +/* UnpackTupleError */ +static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { + if (t == Py_None) { + __Pyx_RaiseNoneNotIterableError(); + } else { + Py_ssize_t size = __Pyx_PyTuple_GET_SIZE(t); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) return; + #endif + if (size < index) { + __Pyx_RaiseNeedMoreValuesError(size); + } else { + __Pyx_RaiseTooManyValuesError(index); + } + } +} + +/* UnpackTuple2 */ +static CYTHON_INLINE int __Pyx_unpack_tuple2( + PyObject* tuple, PyObject** value1, PyObject** value2, int is_tuple, int has_known_size, int decref_tuple) { + if (likely(is_tuple || PyTuple_Check(tuple))) { + Py_ssize_t size; + if (has_known_size) { + return __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple); + } + size = __Pyx_PyTuple_GET_SIZE(tuple); + if (likely(size == 2)) { + return __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple); + } + if (size >= 0) { + __Pyx_UnpackTupleError(tuple, 2); + } + return -1; + } else { + return __Pyx_unpack_tuple2_generic(tuple, value1, value2, has_known_size, decref_tuple); + } +} +static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int decref_tuple) { + PyObject *value1 = NULL, *value2 = NULL; +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS + value1 = __Pyx_PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; + value2 = __Pyx_PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; +#else + value1 = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(value1); + value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value2); +#endif + if (decref_tuple) { + Py_DECREF(tuple); + } + *pvalue1 = value1; + *pvalue2 = value2; + return 0; +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +bad: + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +#endif +} +static int __Pyx_unpack_tuple2_generic(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, + int has_known_size, int decref_tuple) { + Py_ssize_t index; + PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; + iternextfunc iternext; + iter = PyObject_GetIter(tuple); + if (unlikely(!iter)) goto bad; + if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } + iternext = __Pyx_PyObject_GetIterNextFunc(iter); + value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } + value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } + if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; + Py_DECREF(iter); + *pvalue1 = value1; + *pvalue2 = value2; + return 0; +unpacking_failed: + if (!has_known_size && __Pyx_IterFinish() == 0) + __Pyx_RaiseNeedMoreValuesError(index); +bad: + Py_XDECREF(iter); + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +} + +/* dict_iter */ +#if CYTHON_COMPILING_IN_PYPY +#include +#endif +static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, + Py_ssize_t* p_orig_length, int* p_source_is_dict) { + is_dict = is_dict || likely(PyDict_CheckExact(iterable)); + *p_source_is_dict = is_dict; + if (is_dict) { +#if !CYTHON_COMPILING_IN_PYPY + *p_orig_length = PyDict_Size(iterable); + Py_INCREF(iterable); + return iterable; +#else + static PyObject *py_items = NULL, *py_keys = NULL, *py_values = NULL; + PyObject **pp = NULL; + if (method_name) { + const char *name = PyUnicode_AsUTF8(method_name); + if (strcmp(name, "iteritems") == 0) pp = &py_items; + else if (strcmp(name, "iterkeys") == 0) pp = &py_keys; + else if (strcmp(name, "itervalues") == 0) pp = &py_values; + if (pp) { + if (!*pp) { + *pp = PyUnicode_FromString(name + 4); + if (!*pp) + return NULL; + } + method_name = *pp; + } + } +#endif + } + *p_orig_length = 0; + if (method_name) { + PyObject* iter; + iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); + if (!iterable) + return NULL; +#if !CYTHON_COMPILING_IN_PYPY + if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) + return iterable; +#endif + iter = PyObject_GetIter(iterable); + Py_DECREF(iterable); + return iter; + } + return PyObject_GetIter(iterable); +} +#if !CYTHON_COMPILING_IN_PYPY +static CYTHON_INLINE int __Pyx_dict_iter_next_source_is_dict( + PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem) { + PyObject *key, *value; + if (unlikely(orig_length != PyDict_Size(iter_obj))) { + PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); + return -1; + } + if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { + return 0; + } + if (pitem) { + PyObject* tuple = PyTuple_New(2); + if (unlikely(!tuple)) { + return -1; + } + Py_INCREF(key); + Py_INCREF(value); + #if CYTHON_ASSUME_SAFE_MACROS + PyTuple_SET_ITEM(tuple, 0, key); + PyTuple_SET_ITEM(tuple, 1, value); + #else + if (unlikely(PyTuple_SetItem(tuple, 0, key) < 0)) { + Py_DECREF(value); + Py_DECREF(tuple); + return -1; + } + if (unlikely(PyTuple_SetItem(tuple, 1, value) < 0)) { + Py_DECREF(tuple); + return -1; + } + #endif + *pitem = tuple; + } else { + if (pkey) { + Py_INCREF(key); + *pkey = key; + } + if (pvalue) { + Py_INCREF(value); + *pvalue = value; + } + } + return 1; +} +#endif +static CYTHON_INLINE int __Pyx_dict_iter_next( + PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { + PyObject* next_item; +#if !CYTHON_COMPILING_IN_PYPY + if (source_is_dict) { + int result; +#if PY_VERSION_HEX >= 0x030d0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_BEGIN_CRITICAL_SECTION(iter_obj); +#endif + result = __Pyx_dict_iter_next_source_is_dict(iter_obj, orig_length, ppos, pkey, pvalue, pitem); +#if PY_VERSION_HEX >= 0x030d0000 && !CYTHON_COMPILING_IN_LIMITED_API + Py_END_CRITICAL_SECTION(); +#endif + return result; + } else if (PyTuple_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + Py_ssize_t tuple_size = __Pyx_PyTuple_GET_SIZE(iter_obj); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(tuple_size < 0)) return -1; + #endif + if (unlikely(pos >= tuple_size)) return 0; + *ppos = pos + 1; + #if CYTHON_ASSUME_SAFE_MACROS + next_item = PyTuple_GET_ITEM(iter_obj, pos); + #else + next_item = PyTuple_GetItem(iter_obj, pos); + if (unlikely(!next_item)) return -1; + #endif + Py_INCREF(next_item); + } else if (PyList_CheckExact(iter_obj)) { + Py_ssize_t pos = *ppos; + Py_ssize_t list_size = __Pyx_PyList_GET_SIZE(iter_obj); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(list_size < 0)) return -1; + #endif + if (unlikely(pos >= list_size)) return 0; + *ppos = pos + 1; + #if CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + next_item = PyList_GetItemRef(iter_obj, pos); + if (unlikely(!next_item)) return -1; + #elif CYTHON_ASSUME_SAFE_MACROS + next_item = PyList_GET_ITEM(iter_obj, pos); + Py_INCREF(next_item); + #else + next_item = PyList_GetItem(iter_obj, pos); + if (unlikely(!next_item)) return -1; + Py_INCREF(next_item); + #endif + } else +#endif + { + next_item = PyIter_Next(iter_obj); + if (unlikely(!next_item)) { + return __Pyx_IterFinish(); + } + } + if (pitem) { + *pitem = next_item; + } else if (pkey && pvalue) { + if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) + return -1; + } else if (pkey) { + *pkey = next_item; + } else { + *pvalue = next_item; + } + return 1; +} + +/* MergeKeywords */ +static int __Pyx_MergeKeywords_dict(PyObject *kwdict, PyObject *source_dict) { + Py_ssize_t len1, len2; + len2 = PyDict_Size(source_dict); + if (unlikely(len2 == -1)) return -1; + if (len2 == 0) { + return 0; + } + len1 = PyDict_Size(kwdict); + if (unlikely(len1 == -1)) return -1; + if (len1 > 0) { + PyObject *key, *smaller_dict, *larger_dict; + Py_ssize_t ppos = 0; + int duplicates_found = 0; + if (len1 <= len2) { + smaller_dict = kwdict; + larger_dict = source_dict; + } else { + smaller_dict = source_dict; + larger_dict = kwdict; + } + __Pyx_BEGIN_CRITICAL_SECTION(smaller_dict); + while (PyDict_Next(smaller_dict, &ppos, &key, NULL)) { + #if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + Py_INCREF(key); + #endif + if (unlikely(PyDict_Contains(larger_dict, key))) { + __Pyx_RaiseDoubleKeywordsError("function", key); + #if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + Py_DECREF(key); + #endif + duplicates_found = 1; + break; + }; + #if CYTHON_AVOID_BORROWED_REFS || CYTHON_AVOID_THREAD_UNSAFE_BORROWED_REFS + Py_DECREF(key); + #endif + } + __Pyx_END_CRITICAL_SECTION(); + if (unlikely(duplicates_found)) + return -1; + } + return PyDict_Update(kwdict, source_dict); +} +static int __Pyx_MergeKeywords_any(PyObject *kwdict, PyObject *source_mapping) { + PyObject *iter, *key = NULL, *value = NULL; + int source_is_dict, result; + Py_ssize_t orig_length, ppos = 0; + iter = __Pyx_dict_iterator(source_mapping, 0, __pyx_mstate_global->__pyx_n_u_items, &orig_length, &source_is_dict); + if (unlikely(!iter)) { + PyObject *args; + if (unlikely(!PyErr_ExceptionMatches(PyExc_AttributeError))) goto bad; + PyErr_Clear(); + args = PyTuple_Pack(1, source_mapping); + if (likely(args)) { + PyObject *fallback = PyObject_Call((PyObject*)&PyDict_Type, args, NULL); + Py_DECREF(args); + if (likely(fallback)) { + result = __Pyx_MergeKeywords_dict(kwdict, fallback); + Py_DECREF(fallback); + return result; + } + } + if (unlikely(!iter)) goto bad; + } + while (1) { + result = __Pyx_dict_iter_next(iter, orig_length, &ppos, &key, &value, NULL, source_is_dict); + if (unlikely(result < 0)) goto bad; + if (!result) break; + #if PY_VERSION_HEX >= 0x030d0000 && !CYTHON_COMPILING_IN_LIMITED_API + { + int inserted = PyDict_SetDefaultRef(kwdict, key, value, NULL); + if (unlikely(inserted != 0)) { + if (inserted == 1) __Pyx_RaiseDoubleKeywordsError("function", key); + result = -1; + } + } + #else + if (unlikely(PyDict_Contains(kwdict, key))) { + __Pyx_RaiseDoubleKeywordsError("function", key); + result = -1; + } else { + result = PyDict_SetItem(kwdict, key, value); + } + #endif + Py_DECREF(key); + Py_DECREF(value); + if (unlikely(result < 0)) goto bad; + } + Py_XDECREF(iter); + return 0; +bad: + Py_XDECREF(iter); + return -1; +} +static CYTHON_INLINE int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping) { + assert(PyDict_Check(kwdict)); + if (likely(PyDict_Check(source_mapping))) { + return __Pyx_MergeKeywords_dict(kwdict, source_mapping); + } else { + return __Pyx_MergeKeywords_any(kwdict, source_mapping); + } +} + +/* PyLongBinop */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_Fallback___Pyx_PyLong_AndObjC(PyObject *op1, PyObject *op2, int inplace) { + return (inplace ? PyNumber_InPlaceAnd : PyNumber_And)(op1, op2); +} +#if CYTHON_USE_PYLONG_INTERNALS +static PyObject* __Pyx_Unpacked___Pyx_PyLong_AndObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(inplace); + CYTHON_UNUSED_VAR(zerodivision_check); + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + if (unlikely(__Pyx_PyLong_IsZero(op1))) { + return __Pyx_NewRef(op1); + } + if ((intval & PyLong_MASK) == intval) { + long last_digit = (long) __Pyx_PyLong_Digits(op1)[0]; + long result = intval & (likely(__Pyx_PyLong_IsPos(op1)) ? last_digit : (PyLong_MASK - last_digit + 1)); + return PyLong_FromLong(result); + } + if (likely(__Pyx_PyLong_IsCompact(op1))) { + a = __Pyx_PyLong_CompactValue(op1); + } else { + const digit* digits = __Pyx_PyLong_Digits(op1); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(op1); + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; + #ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; + #endif + } + CYTHON_FALLTHROUGH; + default: return PyLong_Type.tp_as_number->nb_and(op1, op2); + } + } + x = a & b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla & llb; + return PyLong_FromLongLong(llx); +#endif + return __Pyx_Fallback___Pyx_PyLong_AndObjC(op1, op2, inplace); + + +} +#endif +static CYTHON_INLINE PyObject* __Pyx_PyLong_AndObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check) { + CYTHON_MAYBE_UNUSED_VAR(intval); + CYTHON_UNUSED_VAR(zerodivision_check); + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + return __Pyx_Unpacked___Pyx_PyLong_AndObjC(op1, op2, intval, inplace, zerodivision_check); + } + #endif + return __Pyx_Fallback___Pyx_PyLong_AndObjC(op1, op2, inplace); +} +#endif + +/* RaiseUnexpectedTypeError */ +static int +__Pyx_RaiseUnexpectedTypeError(const char *expected, PyObject *obj) +{ + __Pyx_TypeName obj_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(obj)); + PyErr_Format(PyExc_TypeError, "Expected %s, got " __Pyx_FMT_TYPENAME, + expected, obj_type_name); + __Pyx_DECREF_TypeName(obj_type_name); + return 0; +} + +/* SetStringIndexingError */ +static void __Pyx_SetStringIndexingError(const char* message, int has_gil) { + if (!has_gil) { + PyGILState_STATE gil_state = PyGILState_Ensure(); + PyErr_SetString(PyExc_IndexError, message); + PyGILState_Release(gil_state); + } else + PyErr_SetString(PyExc_IndexError, message); +} + +/* GetItemIntUnicode */ +static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i, + int wraparound, int boundscheck, int has_gil) { + Py_ssize_t length; + if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return (Py_UCS4)-1; + if (wraparound | boundscheck) { + length = __Pyx_PyUnicode_GET_LENGTH(ustring); + #if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(length < 0)) return (Py_UCS4)-1; + #endif + if (wraparound & unlikely(i < 0)) i += length; + if ((!boundscheck) || likely(__Pyx_is_valid_index(i, length))) { + return __Pyx_PyUnicode_READ_CHAR(ustring, i); + } else { + __Pyx_SetStringIndexingError("string index out of range", has_gil); + return (Py_UCS4)-1; + } + } else { + return __Pyx_PyUnicode_READ_CHAR(ustring, i); + } +} + +/* RaiseUnboundLocalError */ +static void __Pyx_RaiseUnboundLocalError(const char *varname) { + PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); +} + +/* pyfrozenset_new */ +static CYTHON_INLINE PyObject* __Pyx_PyFrozenSet_New(PyObject* it) { + if (it) { + PyObject* result; +#if CYTHON_COMPILING_IN_PYPY + PyObject* args; + args = PyTuple_Pack(1, it); + if (unlikely(!args)) + return NULL; + result = PyObject_Call((PyObject*)&PyFrozenSet_Type, args, NULL); + Py_DECREF(args); + return result; +#else + if (PyFrozenSet_CheckExact(it)) { + Py_INCREF(it); + return it; + } + result = PyFrozenSet_New(it); + if (unlikely(!result)) + return NULL; + if ((__PYX_LIMITED_VERSION_HEX >= 0x030A0000) +#if CYTHON_COMPILING_IN_LIMITED_API + || __Pyx_get_runtime_version() >= 0x030A0000 +#endif + ) + return result; + { + Py_ssize_t size = __Pyx_PySet_GET_SIZE(result); + if (likely(size > 0)) + return result; +#if !CYTHON_ASSUME_SAFE_SIZE + if (unlikely(size < 0)) { + Py_DECREF(result); + return NULL; + } +#endif + } + Py_DECREF(result); +#endif + } + return __Pyx_PyObject_CallNoArg((PyObject*) &PyFrozenSet_Type); +} + +/* PySetContains */ +static int __Pyx_PySet_ContainsUnhashable(PyObject *set, PyObject *key) { + int result = -1; + if (PySet_Check(key) && PyErr_ExceptionMatches(PyExc_TypeError)) { + PyObject *tmpkey; + PyErr_Clear(); + tmpkey = __Pyx_PyFrozenSet_New(key); + if (tmpkey != NULL) { + result = PySet_Contains(set, tmpkey); + Py_DECREF(tmpkey); + } + } + return result; +} +static CYTHON_INLINE int __Pyx_PySet_ContainsTF(PyObject* key, PyObject* set, int eq) { + int result = PySet_Contains(set, key); + if (unlikely(result < 0)) { + result = __Pyx_PySet_ContainsUnhashable(set, key); + } + return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); +} + +/* CallUnboundCMethod1 */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg) { + int was_initialized = __Pyx_CachedCFunction_GetAndSetInitializing(cfunc); + if (likely(was_initialized == 2 && cfunc->func)) { + int flag = cfunc->flag; + if (flag == METH_O) { + return __Pyx_CallCFunction(cfunc, self, arg); + } else if (flag == METH_FASTCALL) { + return __Pyx_CallCFunctionFast(cfunc, self, &arg, 1); + } else if (flag == (METH_FASTCALL | METH_KEYWORDS)) { + return __Pyx_CallCFunctionFastWithKeywords(cfunc, self, &arg, 1, NULL); + } + } +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + else if (unlikely(was_initialized == 1)) { + __Pyx_CachedCFunction tmp_cfunc = { +#ifndef __cplusplus + 0 +#endif + }; + tmp_cfunc.type = cfunc->type; + tmp_cfunc.method_name = cfunc->method_name; + return __Pyx__CallUnboundCMethod1(&tmp_cfunc, self, arg); + } +#endif + PyObject* result = __Pyx__CallUnboundCMethod1(cfunc, self, arg); + __Pyx_CachedCFunction_SetFinishedInitializing(cfunc); + return result; +} +#endif +static PyObject* __Pyx__CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg){ + PyObject *result = NULL; + if (unlikely(!cfunc->func && !cfunc->method) && unlikely(__Pyx_TryUnpackUnboundCMethod(cfunc) < 0)) return NULL; +#if CYTHON_COMPILING_IN_CPYTHON + if (cfunc->func && (cfunc->flag & METH_VARARGS)) { + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; + Py_INCREF(arg); + PyTuple_SET_ITEM(args, 0, arg); + if (cfunc->flag & METH_KEYWORDS) + result = __Pyx_CallCFunctionWithKeywords(cfunc, self, args, NULL); + else + result = __Pyx_CallCFunction(cfunc, self, args); + Py_DECREF(args); + } else +#endif + { + result = __Pyx_PyObject_Call2Args(cfunc->method, self, arg); + } + return result; +} + +/* dict_getitem_default */ +static PyObject* __Pyx_PyDict_GetItemDefault(PyObject* d, PyObject* key, PyObject* default_value) { + PyObject* value; +#if !CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07020000 + value = PyDict_GetItemWithError(d, key); + if (unlikely(!value)) { + if (unlikely(PyErr_Occurred())) + return NULL; + value = default_value; + } + Py_INCREF(value); + if ((1)); +#else + if (PyBytes_CheckExact(key) || PyUnicode_CheckExact(key) || PyLong_CheckExact(key)) { + value = PyDict_GetItem(d, key); + if (unlikely(!value)) { + value = default_value; + } + Py_INCREF(value); + } +#endif + else { + if (default_value == Py_None) + value = __Pyx_CallUnboundCMethod1(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_get, d, key); + else + value = __Pyx_CallUnboundCMethod2(&__pyx_mstate_global->__pyx_umethod_PyDict_Type_get, d, key, default_value); + } + return value; +} + +/* GetAttr3 */ +#if __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +#endif +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r; +#if __PYX_LIMITED_VERSION_HEX >= 0x030d0000 + int res = PyObject_GetOptionalAttr(o, n, &r); + return (res != 0) ? r : __Pyx_NewRef(d); +#else + #if CYTHON_USE_TYPE_SLOTS + if (likely(PyUnicode_Check(n))) { + r = __Pyx_PyObject_GetAttrStrNoError(o, n); + if (unlikely(!r) && likely(!PyErr_Occurred())) { + r = __Pyx_NewRef(d); + } + return r; + } + #endif + r = PyObject_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +#endif +} + +/* Import */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *module = 0; + PyObject *empty_dict = 0; + PyObject *empty_list = 0; + empty_dict = PyDict_New(); + if (unlikely(!empty_dict)) + goto bad; + if (level == -1) { + const char* package_sep = strchr(__Pyx_MODULE_NAME, '.'); + if (package_sep != (0)) { + module = PyImport_ImportModuleLevelObject( + name, __pyx_mstate_global->__pyx_d, empty_dict, from_list, 1); + if (unlikely(!module)) { + if (unlikely(!PyErr_ExceptionMatches(PyExc_ImportError))) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + if (!module) { + module = PyImport_ImportModuleLevelObject( + name, __pyx_mstate_global->__pyx_d, empty_dict, from_list, level); + } +bad: + Py_XDECREF(empty_dict); + Py_XDECREF(empty_list); + return module; +} + +/* ImportFrom */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + const char* module_name_str = 0; + PyObject* module_name = 0; + PyObject* module_dot = 0; + PyObject* full_name = 0; + PyErr_Clear(); + module_name_str = PyModule_GetName(module); + if (unlikely(!module_name_str)) { goto modbad; } + module_name = PyUnicode_FromString(module_name_str); + if (unlikely(!module_name)) { goto modbad; } + module_dot = PyUnicode_Concat(module_name, __pyx_mstate_global->__pyx_kp_u__11); + if (unlikely(!module_dot)) { goto modbad; } + full_name = PyUnicode_Concat(module_dot, name); + if (unlikely(!full_name)) { goto modbad; } + #if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + { + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + goto modbad; + value = PyObject_GetItem(modules, full_name); + } + #else + value = PyImport_GetModule(full_name); + #endif + modbad: + Py_XDECREF(full_name); + Py_XDECREF(module_dot); + Py_XDECREF(module_name); + } + if (unlikely(!value)) { + PyErr_Format(PyExc_ImportError, "cannot import name %S", name); + } + return value; +} + +/* CallNextTpDealloc */ +static void __Pyx_call_next_tp_dealloc(PyObject* obj, destructor current_tp_dealloc) { + PyTypeObject* type = Py_TYPE(obj); + destructor tp_dealloc = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_dealloc, destructor) != current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_dealloc = __Pyx_PyType_GetSlot(type, tp_dealloc, destructor)) == current_tp_dealloc) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type) + tp_dealloc(obj); +} + +/* CallNextTpTraverse */ +static int __Pyx_call_next_tp_traverse(PyObject* obj, visitproc v, void *a, traverseproc current_tp_traverse) { + PyTypeObject* type = Py_TYPE(obj); + traverseproc tp_traverse = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc) != current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_traverse = __Pyx_PyType_GetSlot(type, tp_traverse, traverseproc)) == current_tp_traverse) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_traverse) + return tp_traverse(obj, v, a); + return 0; +} + +/* CallTypeTraverse */ +#if !CYTHON_USE_TYPE_SPECS || (!CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x03090000) +#else +static int __Pyx_call_type_traverse(PyObject *o, int always_call, visitproc visit, void *arg) { + #if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x03090000 + if (__Pyx_get_runtime_version() < 0x03090000) return 0; + #endif + if (!always_call) { + PyTypeObject *base = __Pyx_PyObject_GetSlot(o, tp_base, PyTypeObject*); + unsigned long flags = PyType_GetFlags(base); + if (flags & Py_TPFLAGS_HEAPTYPE) { + return 0; + } + } + Py_VISIT((PyObject*)Py_TYPE(o)); + return 0; +} +#endif + +/* CallNextTpClear */ +static void __Pyx_call_next_tp_clear(PyObject* obj, inquiry current_tp_clear) { + PyTypeObject* type = Py_TYPE(obj); + inquiry tp_clear = NULL; + while (type && __Pyx_PyType_GetSlot(type, tp_clear, inquiry) != current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (type && (tp_clear = __Pyx_PyType_GetSlot(type, tp_clear, inquiry)) == current_tp_clear) + type = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + if (type && tp_clear) + tp_clear(obj); +} + +/* LimitedApiGetTypeDict */ +#if CYTHON_COMPILING_IN_LIMITED_API +static Py_ssize_t __Pyx_GetTypeDictOffset(void) { + PyObject *tp_dictoffset_o; + Py_ssize_t tp_dictoffset; + tp_dictoffset_o = PyObject_GetAttrString((PyObject*)(&PyType_Type), "__dictoffset__"); + if (unlikely(!tp_dictoffset_o)) return -1; + tp_dictoffset = PyLong_AsSsize_t(tp_dictoffset_o); + Py_DECREF(tp_dictoffset_o); + if (unlikely(tp_dictoffset == 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' doesn't have a dictoffset"); + return -1; + } else if (unlikely(tp_dictoffset < 0)) { + PyErr_SetString( + PyExc_TypeError, + "'type' has an unexpected negative dictoffset. " + "Please report this as Cython bug"); + return -1; + } + return tp_dictoffset; +} +static PyObject *__Pyx_GetTypeDict(PyTypeObject *tp) { + static Py_ssize_t tp_dictoffset = 0; + if (unlikely(tp_dictoffset == 0)) { + tp_dictoffset = __Pyx_GetTypeDictOffset(); + if (unlikely(tp_dictoffset == -1 && PyErr_Occurred())) { + tp_dictoffset = 0; // try again next time? + return NULL; + } + } + return *(PyObject**)((char*)tp + tp_dictoffset); +} +#endif + +/* SetItemOnTypeDict */ +static int __Pyx__SetItemOnTypeDict(PyTypeObject *tp, PyObject *k, PyObject *v) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_SetItem(tp_dict, k, v); + if (likely(!result)) { + PyType_Modified(tp); + if (unlikely(PyObject_HasAttr(v, __pyx_mstate_global->__pyx_n_u_set_name))) { + PyObject *setNameResult = PyObject_CallMethodObjArgs(v, __pyx_mstate_global->__pyx_n_u_set_name, (PyObject *) tp, k, NULL); + if (!setNameResult) return -1; + Py_DECREF(setNameResult); + } + } + return result; +} + +/* FixUpExtensionType */ +static int __Pyx_fix_up_extension_type_from_spec(PyType_Spec *spec, PyTypeObject *type) { +#if __PYX_LIMITED_VERSION_HEX > 0x030900B1 + CYTHON_UNUSED_VAR(spec); + CYTHON_UNUSED_VAR(type); + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); +#else + const PyType_Slot *slot = spec->slots; + int changed = 0; +#if !CYTHON_COMPILING_IN_LIMITED_API + while (slot && slot->slot && slot->slot != Py_tp_members) + slot++; + if (slot && slot->slot == Py_tp_members) { +#if !CYTHON_COMPILING_IN_CPYTHON + const +#endif // !CYTHON_COMPILING_IN_CPYTHON) + PyMemberDef *memb = (PyMemberDef*) slot->pfunc; + while (memb && memb->name) { + if (memb->name[0] == '_' && memb->name[1] == '_') { + if (strcmp(memb->name, "__weaklistoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_weaklistoffset = memb->offset; + changed = 1; + } + else if (strcmp(memb->name, "__dictoffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); + type->tp_dictoffset = memb->offset; + changed = 1; + } +#if CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__vectorcalloffset__") == 0) { + assert(memb->type == T_PYSSIZET); + assert(memb->flags == READONLY); +#if PY_VERSION_HEX >= 0x030800b4 + type->tp_vectorcall_offset = memb->offset; +#else + type->tp_print = (printfunc) memb->offset; +#endif + changed = 1; + } +#endif // CYTHON_METH_FASTCALL + else if (strcmp(memb->name, "__module__") == 0) { + PyObject *descr; + assert(memb->type == T_OBJECT); + assert(memb->flags == 0 || memb->flags == READONLY); + descr = PyDescr_NewMember(type, memb); + if (unlikely(!descr)) + return -1; + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + } + memb++; + } + } +#endif // !CYTHON_COMPILING_IN_LIMITED_API + slot = spec->slots; + while (slot && slot->slot && slot->slot != Py_tp_getset) + slot++; + if (slot && slot->slot == Py_tp_getset) { + PyGetSetDef *getset = (PyGetSetDef*) slot->pfunc; + while (getset && getset->name) { + if (getset->name[0] == '_' && getset->name[1] == '_' && strcmp(getset->name, "__module__") == 0) { + PyObject *descr = PyDescr_NewGetSet(type, getset); + if (unlikely(!descr)) + return -1; + #if CYTHON_COMPILING_IN_LIMITED_API + PyObject *pyname = PyUnicode_FromString(getset->name); + if (unlikely(!pyname)) { + Py_DECREF(descr); + return -1; + } + int set_item_result = __Pyx_SetItemOnTypeDict(type, pyname, descr); + Py_DECREF(pyname); + #else + CYTHON_UNUSED_VAR(__Pyx__SetItemOnTypeDict); + int set_item_result = PyDict_SetItem(type->tp_dict, PyDescr_NAME(descr), descr); + #endif + Py_DECREF(descr); + if (unlikely(set_item_result < 0)) { + return -1; + } + changed = 1; + } + ++getset; + } + } + if (changed) + PyType_Modified(type); +#endif // PY_VERSION_HEX > 0x030900B1 + return 0; +} + +/* ValidateBasesTuple */ +#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_LIMITED_API || CYTHON_USE_TYPE_SPECS +static int __Pyx_validate_bases_tuple(const char *type_name, Py_ssize_t dictoffset, PyObject *bases) { + Py_ssize_t i, n; +#if CYTHON_ASSUME_SAFE_SIZE + n = PyTuple_GET_SIZE(bases); +#else + n = PyTuple_Size(bases); + if (unlikely(n < 0)) return -1; +#endif + for (i = 1; i < n; i++) + { + PyTypeObject *b; +#if CYTHON_AVOID_BORROWED_REFS + PyObject *b0 = PySequence_GetItem(bases, i); + if (!b0) return -1; +#elif CYTHON_ASSUME_SAFE_MACROS + PyObject *b0 = PyTuple_GET_ITEM(bases, i); +#else + PyObject *b0 = PyTuple_GetItem(bases, i); + if (!b0) return -1; +#endif + b = (PyTypeObject*) b0; + if (!__Pyx_PyType_HasFeature(b, Py_TPFLAGS_HEAPTYPE)) + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "base class '" __Pyx_FMT_TYPENAME "' is not a heap type", b_name); + __Pyx_DECREF_TypeName(b_name); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + if (dictoffset == 0) + { + Py_ssize_t b_dictoffset = 0; +#if CYTHON_USE_TYPE_SLOTS + b_dictoffset = b->tp_dictoffset; +#else + PyObject *py_b_dictoffset = PyObject_GetAttrString((PyObject*)b, "__dictoffset__"); + if (!py_b_dictoffset) goto dictoffset_return; + b_dictoffset = PyLong_AsSsize_t(py_b_dictoffset); + Py_DECREF(py_b_dictoffset); + if (b_dictoffset == -1 && PyErr_Occurred()) goto dictoffset_return; +#endif + if (b_dictoffset) { + { + __Pyx_TypeName b_name = __Pyx_PyType_GetFullyQualifiedName(b); + PyErr_Format(PyExc_TypeError, + "extension type '%.200s' has no __dict__ slot, " + "but base type '" __Pyx_FMT_TYPENAME "' has: " + "either add 'cdef dict __dict__' to the extension type " + "or add '__slots__ = [...]' to the base type", + type_name, b_name); + __Pyx_DECREF_TypeName(b_name); + } +#if !CYTHON_USE_TYPE_SLOTS + dictoffset_return: +#endif +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + return -1; + } + } +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(b0); +#endif + } + return 0; +} +#endif + +/* PyType_Ready */ +CYTHON_UNUSED static int __Pyx_PyType_HasMultipleInheritance(PyTypeObject *t) { + while (t) { + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases) { + return 1; + } + t = __Pyx_PyType_GetSlot(t, tp_base, PyTypeObject*); + } + return 0; +} +static int __Pyx_PyType_Ready(PyTypeObject *t) { +#if CYTHON_USE_TYPE_SPECS || !CYTHON_COMPILING_IN_CPYTHON || defined(PYSTON_MAJOR_VERSION) + (void)__Pyx_PyObject_CallMethod0; +#if CYTHON_USE_TYPE_SPECS + (void)__Pyx_validate_bases_tuple; +#endif + return PyType_Ready(t); +#else + int r; + if (!__Pyx_PyType_HasMultipleInheritance(t)) { + return PyType_Ready(t); + } + PyObject *bases = __Pyx_PyType_GetSlot(t, tp_bases, PyObject*); + if (bases && unlikely(__Pyx_validate_bases_tuple(t->tp_name, t->tp_dictoffset, bases) == -1)) + return -1; +#if !defined(PYSTON_MAJOR_VERSION) + { + int gc_was_enabled; + #if PY_VERSION_HEX >= 0x030A00b1 + gc_was_enabled = PyGC_Disable(); + (void)__Pyx_PyObject_CallMethod0; + #else + PyObject *ret, *py_status; + PyObject *gc = NULL; + #if (!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM+0 >= 0x07030400) &&\ + !CYTHON_COMPILING_IN_GRAAL + gc = PyImport_GetModule(__pyx_mstate_global->__pyx_kp_u_gc); + #endif + if (unlikely(!gc)) gc = PyImport_Import(__pyx_mstate_global->__pyx_kp_u_gc); + if (unlikely(!gc)) return -1; + py_status = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_isenabled); + if (unlikely(!py_status)) { + Py_DECREF(gc); + return -1; + } + gc_was_enabled = __Pyx_PyObject_IsTrue(py_status); + Py_DECREF(py_status); + if (gc_was_enabled > 0) { + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_disable); + if (unlikely(!ret)) { + Py_DECREF(gc); + return -1; + } + Py_DECREF(ret); + } else if (unlikely(gc_was_enabled == -1)) { + Py_DECREF(gc); + return -1; + } + #endif + t->tp_flags |= Py_TPFLAGS_HEAPTYPE; +#if PY_VERSION_HEX >= 0x030A0000 + t->tp_flags |= Py_TPFLAGS_IMMUTABLETYPE; +#endif +#else + (void)__Pyx_PyObject_CallMethod0; +#endif + r = PyType_Ready(t); +#if !defined(PYSTON_MAJOR_VERSION) + t->tp_flags &= ~Py_TPFLAGS_HEAPTYPE; + #if PY_VERSION_HEX >= 0x030A00b1 + if (gc_was_enabled) + PyGC_Enable(); + #else + if (gc_was_enabled) { + PyObject *tp, *v, *tb; + PyErr_Fetch(&tp, &v, &tb); + ret = __Pyx_PyObject_CallMethod0(gc, __pyx_mstate_global->__pyx_kp_u_enable); + if (likely(ret || r == -1)) { + Py_XDECREF(ret); + PyErr_Restore(tp, v, tb); + } else { + Py_XDECREF(tp); + Py_XDECREF(v); + Py_XDECREF(tb); + r = -1; + } + } + Py_DECREF(gc); + #endif + } +#endif + return r; +#endif +} + +/* DelItemOnTypeDict */ +static int __Pyx__DelItemOnTypeDict(PyTypeObject *tp, PyObject *k) { + int result; + PyObject *tp_dict; +#if CYTHON_COMPILING_IN_LIMITED_API + tp_dict = __Pyx_GetTypeDict(tp); + if (unlikely(!tp_dict)) return -1; +#else + tp_dict = tp->tp_dict; +#endif + result = PyDict_DelItem(tp_dict, k); + if (likely(!result)) PyType_Modified(tp); + return result; +} + +/* SetupReduce */ +static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStrNoError(meth, __pyx_mstate_global->__pyx_n_u_name_2); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_getstate = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; + PyObject *getstate = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + getstate = _PyType_Lookup((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_getstate); +#else + getstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_getstate); + if (!getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (getstate) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_getstate = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); +#else + object_getstate = __Pyx_PyObject_GetAttrStrNoError((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_getstate); + if (!object_getstate && PyErr_Occurred()) { + goto __PYX_BAD; + } +#endif + if (object_getstate != getstate) { + goto __PYX_GOOD; + } + } +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_mstate_global->__pyx_n_u_reduce); if (!object_reduce) goto __PYX_BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_mstate_global->__pyx_n_u_reduce); if (unlikely(!reduce)) goto __PYX_BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_mstate_global->__pyx_n_u_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); + if (likely(reduce_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (reduce == object_reduce || PyErr_Occurred()) { + goto __PYX_BAD; + } + setstate = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_mstate_global->__pyx_n_u_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); + if (likely(setstate_cython)) { + ret = __Pyx_SetItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + ret = __Pyx_DelItemOnTypeDict((PyTypeObject*)type_obj, __pyx_mstate_global->__pyx_n_u_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; + } else if (!setstate || PyErr_Occurred()) { + goto __PYX_BAD; + } + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto __PYX_GOOD; +__PYX_BAD: + if (!PyErr_Occurred()) { + __Pyx_TypeName type_obj_name = + __Pyx_PyType_GetFullyQualifiedName((PyTypeObject*)type_obj); + PyErr_Format(PyExc_RuntimeError, + "Unable to initialize pickling for " __Pyx_FMT_TYPENAME, type_obj_name); + __Pyx_DECREF_TypeName(type_obj_name); + } + ret = -1; +__PYX_GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); + Py_XDECREF(object_getstate); + Py_XDECREF(getstate); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; +} + +/* TypeImport */ +#ifndef __PYX_HAVE_RT_ImportType_3_1_2 +#define __PYX_HAVE_RT_ImportType_3_1_2 +static PyTypeObject *__Pyx_ImportType_3_1_2(PyObject *module, const char *module_name, const char *class_name, + size_t size, size_t alignment, enum __Pyx_ImportType_CheckSize_3_1_2 check_size) +{ + PyObject *result = 0; + Py_ssize_t basicsize; + Py_ssize_t itemsize; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + PyObject *py_itemsize; +#endif + result = PyObject_GetAttrString(module, class_name); + if (!result) + goto bad; + if (!PyType_Check(result)) { + PyErr_Format(PyExc_TypeError, + "%.200s.%.200s is not a type object", + module_name, class_name); + goto bad; + } +#if !CYTHON_COMPILING_IN_LIMITED_API + basicsize = ((PyTypeObject *)result)->tp_basicsize; + itemsize = ((PyTypeObject *)result)->tp_itemsize; +#else + if (size == 0) { + return (PyTypeObject *)result; + } + py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); + if (!py_basicsize) + goto bad; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = 0; + if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; + py_itemsize = PyObject_GetAttrString(result, "__itemsize__"); + if (!py_itemsize) + goto bad; + itemsize = PyLong_AsSsize_t(py_itemsize); + Py_DECREF(py_itemsize); + py_itemsize = 0; + if (itemsize == (Py_ssize_t)-1 && PyErr_Occurred()) + goto bad; +#endif + if (itemsize) { + if (size % alignment) { + alignment = size % alignment; + } + if (itemsize < (Py_ssize_t)alignment) + itemsize = (Py_ssize_t)alignment; + } + if ((size_t)(basicsize + itemsize) < size) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize+itemsize); + goto bad; + } + if (check_size == __Pyx_ImportType_CheckSize_Error_3_1_2 && + ((size_t)basicsize > size || (size_t)(basicsize + itemsize) < size)) { + PyErr_Format(PyExc_ValueError, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd-%zd from PyObject", + module_name, class_name, size, basicsize, basicsize+itemsize); + goto bad; + } + else if (check_size == __Pyx_ImportType_CheckSize_Warn_3_1_2 && (size_t)basicsize > size) { + if (PyErr_WarnFormat(NULL, 0, + "%.200s.%.200s size changed, may indicate binary incompatibility. " + "Expected %zd from C header, got %zd from PyObject", + module_name, class_name, size, basicsize) < 0) { + goto bad; + } + } + return (PyTypeObject *)result; +bad: + Py_XDECREF(result); + return NULL; +} +#endif + +/* GetVTable */ +static void* __Pyx_GetVtable(PyTypeObject *type) { + void* ptr; +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *ob = PyObject_GetAttr((PyObject *)type, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#else + PyObject *ob = PyObject_GetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable); +#endif + if (!ob) + goto bad; + ptr = PyCapsule_GetPointer(ob, 0); + if (!ptr && !PyErr_Occurred()) + PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type"); + Py_DECREF(ob); + return ptr; +bad: + Py_XDECREF(ob); + return NULL; +} + +/* SetVTable */ +static int __Pyx_SetVtable(PyTypeObject *type, void *vtable) { + PyObject *ob = PyCapsule_New(vtable, 0, 0); + if (unlikely(!ob)) + goto bad; +#if CYTHON_COMPILING_IN_LIMITED_API + if (unlikely(PyObject_SetAttr((PyObject *) type, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#else + if (unlikely(PyDict_SetItem(type->tp_dict, __pyx_mstate_global->__pyx_n_u_pyx_vtable, ob) < 0)) +#endif + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* MergeVTables */ +static int __Pyx_MergeVtables(PyTypeObject *type) { + int i=0; + Py_ssize_t size; + void** base_vtables; + __Pyx_TypeName tp_base_name = NULL; + __Pyx_TypeName base_name = NULL; + void* unknown = (void*)-1; + PyObject* bases = __Pyx_PyType_GetSlot(type, tp_bases, PyObject*); + int base_depth = 0; + { + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + while (base) { + base_depth += 1; + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + base_vtables = (void**) PyMem_Malloc(sizeof(void*) * (size_t)(base_depth + 1)); + base_vtables[0] = unknown; +#if CYTHON_COMPILING_IN_LIMITED_API + size = PyTuple_Size(bases); + if (size < 0) goto other_failure; +#else + size = PyTuple_GET_SIZE(bases); +#endif + for (i = 1; i < size; i++) { + PyObject *basei; + void* base_vtable; +#if CYTHON_AVOID_BORROWED_REFS + basei = PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto other_failure; +#else + basei = PyTuple_GET_ITEM(bases, i); +#endif + base_vtable = __Pyx_GetVtable((PyTypeObject*)basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + if (base_vtable != NULL) { + int j; + PyTypeObject* base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + for (j = 0; j < base_depth; j++) { + if (base_vtables[j] == unknown) { + base_vtables[j] = __Pyx_GetVtable(base); + base_vtables[j + 1] = unknown; + } + if (base_vtables[j] == base_vtable) { + break; + } else if (base_vtables[j] == NULL) { + goto bad; + } + base = __Pyx_PyType_GetSlot(base, tp_base, PyTypeObject*); + } + } + } + PyErr_Clear(); + PyMem_Free(base_vtables); + return 0; +bad: + { + PyTypeObject* basei = NULL; + PyTypeObject* tp_base = __Pyx_PyType_GetSlot(type, tp_base, PyTypeObject*); + tp_base_name = __Pyx_PyType_GetFullyQualifiedName(tp_base); +#if CYTHON_AVOID_BORROWED_REFS + basei = (PyTypeObject*)PySequence_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#elif !CYTHON_ASSUME_SAFE_MACROS + basei = (PyTypeObject*)PyTuple_GetItem(bases, i); + if (unlikely(!basei)) goto really_bad; +#else + basei = (PyTypeObject*)PyTuple_GET_ITEM(bases, i); +#endif + base_name = __Pyx_PyType_GetFullyQualifiedName(basei); +#if CYTHON_AVOID_BORROWED_REFS + Py_DECREF(basei); +#endif + } + PyErr_Format(PyExc_TypeError, + "multiple bases have vtable conflict: '" __Pyx_FMT_TYPENAME "' and '" __Pyx_FMT_TYPENAME "'", tp_base_name, base_name); +#if CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +really_bad: // bad has failed! +#endif + __Pyx_DECREF_TypeName(tp_base_name); + __Pyx_DECREF_TypeName(base_name); +#if CYTHON_COMPILING_IN_LIMITED_API || CYTHON_AVOID_BORROWED_REFS || !CYTHON_ASSUME_SAFE_MACROS +other_failure: +#endif + PyMem_Free(base_vtables); + return -1; +} + +/* ImportDottedModule */ +static PyObject *__Pyx__ImportDottedModule_Error(PyObject *name, PyObject *parts_tuple, Py_ssize_t count) { + PyObject *partial_name = NULL, *slice = NULL, *sep = NULL; + Py_ssize_t size; + if (unlikely(PyErr_Occurred())) { + PyErr_Clear(); + } +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(parts_tuple); +#else + size = PyTuple_Size(parts_tuple); + if (size < 0) goto bad; +#endif + if (likely(size == count)) { + partial_name = name; + } else { + slice = PySequence_GetSlice(parts_tuple, 0, count); + if (unlikely(!slice)) + goto bad; + sep = PyUnicode_FromStringAndSize(".", 1); + if (unlikely(!sep)) + goto bad; + partial_name = PyUnicode_Join(sep, slice); + } + PyErr_Format( + PyExc_ModuleNotFoundError, + "No module named '%U'", partial_name); +bad: + Py_XDECREF(sep); + Py_XDECREF(slice); + Py_XDECREF(partial_name); + return NULL; +} +static PyObject *__Pyx__ImportDottedModule_Lookup(PyObject *name) { + PyObject *imported_module; +#if (CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM < 0x07030400) ||\ + CYTHON_COMPILING_IN_GRAAL + PyObject *modules = PyImport_GetModuleDict(); + if (unlikely(!modules)) + return NULL; + imported_module = __Pyx_PyDict_GetItemStr(modules, name); + Py_XINCREF(imported_module); +#else + imported_module = PyImport_GetModule(name); +#endif + return imported_module; +} +static PyObject *__Pyx_ImportDottedModule_WalkParts(PyObject *module, PyObject *name, PyObject *parts_tuple) { + Py_ssize_t i, nparts; +#if CYTHON_ASSUME_SAFE_SIZE + nparts = PyTuple_GET_SIZE(parts_tuple); +#else + nparts = PyTuple_Size(parts_tuple); + if (nparts < 0) return NULL; +#endif + for (i=1; i < nparts && module; i++) { + PyObject *part, *submodule; +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + part = PyTuple_GET_ITEM(parts_tuple, i); +#else + part = __Pyx_PySequence_ITEM(parts_tuple, i); + if (!part) return NULL; +#endif + submodule = __Pyx_PyObject_GetAttrStrNoError(module, part); +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(part); +#endif + Py_DECREF(module); + module = submodule; + } + if (unlikely(!module)) { + return __Pyx__ImportDottedModule_Error(name, parts_tuple, i); + } + return module; +} +static PyObject *__Pyx__ImportDottedModule(PyObject *name, PyObject *parts_tuple) { + PyObject *imported_module; + PyObject *module = __Pyx_Import(name, NULL, 0); + if (!parts_tuple || unlikely(!module)) + return module; + imported_module = __Pyx__ImportDottedModule_Lookup(name); + if (likely(imported_module)) { + Py_DECREF(module); + return imported_module; + } + PyErr_Clear(); + return __Pyx_ImportDottedModule_WalkParts(module, name, parts_tuple); +} +static PyObject *__Pyx_ImportDottedModule(PyObject *name, PyObject *parts_tuple) { +#if CYTHON_COMPILING_IN_CPYTHON + PyObject *module = __Pyx__ImportDottedModule_Lookup(name); + if (likely(module)) { + PyObject *spec = __Pyx_PyObject_GetAttrStrNoError(module, __pyx_mstate_global->__pyx_n_u_spec); + if (likely(spec)) { + PyObject *unsafe = __Pyx_PyObject_GetAttrStrNoError(spec, __pyx_mstate_global->__pyx_n_u_initializing); + if (likely(!unsafe || !__Pyx_PyObject_IsTrue(unsafe))) { + Py_DECREF(spec); + spec = NULL; + } + Py_XDECREF(unsafe); + } + if (likely(!spec)) { + PyErr_Clear(); + return module; + } + Py_DECREF(spec); + Py_DECREF(module); + } else if (PyErr_Occurred()) { + PyErr_Clear(); + } +#endif + return __Pyx__ImportDottedModule(name, parts_tuple); +} + +/* ListPack */ +static PyObject *__Pyx_PyList_Pack(Py_ssize_t n, ...) { + va_list va; + PyObject *l = PyList_New(n); + va_start(va, n); + if (unlikely(!l)) goto end; + for (Py_ssize_t i=0; i= 0x030d0000 + PyDict_SetDefaultRef(d, key, default_value, &value); +#else + value = PyDict_SetDefault(d, key, default_value); + if (unlikely(!value)) return NULL; + Py_INCREF(value); +#endif + return value; +} + +/* FetchCommonType */ +#if __PYX_LIMITED_VERSION_HEX < 0x030C0000 +static PyObject* __Pyx_PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *result = __Pyx_PyType_FromModuleAndSpec(module, spec, bases); + if (result && metaclass) { + PyObject *old_tp = (PyObject*)Py_TYPE(result); + Py_INCREF((PyObject*)metaclass); +#if __PYX_LIMITED_VERSION_HEX >= 0x03090000 + Py_SET_TYPE(result, metaclass); +#else + result->ob_type = metaclass; +#endif + Py_DECREF(old_tp); + } + return result; +} +#else +#define __Pyx_PyType_FromMetaclass(me, mo, s, b) PyType_FromMetaclass(me, mo, s, b) +#endif +static int __Pyx_VerifyCachedType(PyObject *cached_type, + const char *name, + Py_ssize_t expected_basicsize) { + Py_ssize_t basicsize; + if (!PyType_Check(cached_type)) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s is not a type object", name); + return -1; + } + if (expected_basicsize == 0) { + return 0; // size is inherited, nothing useful to check + } +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_basicsize; + py_basicsize = PyObject_GetAttrString(cached_type, "__basicsize__"); + if (unlikely(!py_basicsize)) return -1; + basicsize = PyLong_AsSsize_t(py_basicsize); + Py_DECREF(py_basicsize); + py_basicsize = NULL; + if (unlikely(basicsize == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; +#else + basicsize = ((PyTypeObject*) cached_type)->tp_basicsize; +#endif + if (basicsize != expected_basicsize) { + PyErr_Format(PyExc_TypeError, + "Shared Cython type %.200s has the wrong size, try recompiling", + name); + return -1; + } + return 0; +} +static PyTypeObject *__Pyx_FetchCommonTypeFromSpec(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases) { + PyObject *abi_module = NULL, *cached_type = NULL, *abi_module_dict, *new_cached_type, *py_object_name; + int get_item_ref_result; + const char* object_name = strrchr(spec->name, '.'); + object_name = object_name ? object_name+1 : spec->name; + py_object_name = PyUnicode_FromString(object_name); + if (!py_object_name) return NULL; + abi_module = __Pyx_FetchSharedCythonABIModule(); + if (!abi_module) goto done; + abi_module_dict = PyModule_GetDict(abi_module); + if (!abi_module_dict) goto done; + get_item_ref_result = __Pyx_PyDict_GetItemRef(abi_module_dict, py_object_name, &cached_type); + if (get_item_ref_result == 1) { + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else if (unlikely(get_item_ref_result == -1)) { + goto bad; + } + CYTHON_UNUSED_VAR(module); + cached_type = __Pyx_PyType_FromMetaclass(metaclass, abi_module, spec, bases); + if (unlikely(!cached_type)) goto bad; + if (unlikely(__Pyx_fix_up_extension_type_from_spec(spec, (PyTypeObject *) cached_type) < 0)) goto bad; + new_cached_type = __Pyx_PyDict_SetDefault(abi_module_dict, py_object_name, cached_type, 1); + if (unlikely(new_cached_type != cached_type)) { + if (unlikely(!new_cached_type)) goto bad; + Py_DECREF(cached_type); + cached_type = new_cached_type; + if (__Pyx_VerifyCachedType( + cached_type, + object_name, + spec->basicsize) < 0) { + goto bad; + } + goto done; + } else { + Py_DECREF(new_cached_type); + } +done: + Py_XDECREF(abi_module); + Py_DECREF(py_object_name); + assert(cached_type == NULL || PyType_Check(cached_type)); + return (PyTypeObject *) cached_type; +bad: + Py_XDECREF(cached_type); + cached_type = NULL; + goto done; +} + +/* CommonTypesMetaclass */ +PyObject* __pyx_CommonTypesMetaclass_get_module(CYTHON_UNUSED PyObject *self, CYTHON_UNUSED void* context) { + return PyUnicode_FromString(__PYX_ABI_MODULE_NAME); +} +static PyGetSetDef __pyx_CommonTypesMetaclass_getset[] = { + {"__module__", __pyx_CommonTypesMetaclass_get_module, NULL, NULL, NULL}, + {0, 0, 0, 0, 0} +}; +static PyType_Slot __pyx_CommonTypesMetaclass_slots[] = { + {Py_tp_getset, (void *)__pyx_CommonTypesMetaclass_getset}, + {0, 0} +}; +static PyType_Spec __pyx_CommonTypesMetaclass_spec = { + __PYX_TYPE_MODULE_PREFIX "_common_types_metatype", + 0, + 0, +#if PY_VERSION_HEX >= 0x030A0000 + Py_TPFLAGS_IMMUTABLETYPE | + Py_TPFLAGS_DISALLOW_INSTANTIATION | +#endif + Py_TPFLAGS_DEFAULT, + __pyx_CommonTypesMetaclass_slots +}; +static int __pyx_CommonTypesMetaclass_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + PyObject *bases = PyTuple_Pack(1, &PyType_Type); + if (unlikely(!bases)) { + return -1; + } + mstate->__pyx_CommonTypesMetaclassType = __Pyx_FetchCommonTypeFromSpec(NULL, module, &__pyx_CommonTypesMetaclass_spec, bases); + if (unlikely(mstate->__pyx_CommonTypesMetaclassType == NULL)) { + return -1; + } + return 0; +} + +/* PyMethodNew */ +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + PyObject *result; + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + #if __PYX_LIMITED_VERSION_HEX >= 0x030C0000 + { + PyObject *args[] = {func, self}; + result = PyObject_Vectorcall(__pyx_mstate_global->__Pyx_CachedMethodType, args, 2, NULL); + } + #else + result = PyObject_CallFunctionObjArgs(__pyx_mstate_global->__Pyx_CachedMethodType, func, self, NULL); + #endif + return result; +} +#else +static PyObject *__Pyx_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) { + CYTHON_UNUSED_VAR(typ); + if (!self) + return __Pyx_NewRef(func); + return PyMethod_New(func, self); +} +#endif + +/* PyVectorcallFastCallDict */ +#if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) +static PyObject *__Pyx_PyVectorcall_FastCallDict_kw(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + PyObject *res = NULL; + PyObject *kwnames; + PyObject **newargs; + PyObject **kwvalues; + Py_ssize_t i, pos; + size_t j; + PyObject *key, *value; + unsigned long keys_are_strings; + #if !CYTHON_ASSUME_SAFE_SIZE + Py_ssize_t nkw = PyDict_Size(kw); + if (unlikely(nkw == -1)) return NULL; + #else + Py_ssize_t nkw = PyDict_GET_SIZE(kw); + #endif + newargs = (PyObject **)PyMem_Malloc((nargs + (size_t)nkw) * sizeof(args[0])); + if (unlikely(newargs == NULL)) { + PyErr_NoMemory(); + return NULL; + } + for (j = 0; j < nargs; j++) newargs[j] = args[j]; + kwnames = PyTuple_New(nkw); + if (unlikely(kwnames == NULL)) { + PyMem_Free(newargs); + return NULL; + } + kwvalues = newargs + nargs; + pos = i = 0; + keys_are_strings = Py_TPFLAGS_UNICODE_SUBCLASS; + while (PyDict_Next(kw, &pos, &key, &value)) { + keys_are_strings &= + #if CYTHON_COMPILING_IN_LIMITED_API + PyType_GetFlags(Py_TYPE(key)); + #else + Py_TYPE(key)->tp_flags; + #endif + Py_INCREF(key); + Py_INCREF(value); + #if !CYTHON_ASSUME_SAFE_MACROS + if (unlikely(PyTuple_SetItem(kwnames, i, key) < 0)) goto cleanup; + #else + PyTuple_SET_ITEM(kwnames, i, key); + #endif + kwvalues[i] = value; + i++; + } + if (unlikely(!keys_are_strings)) { + PyErr_SetString(PyExc_TypeError, "keywords must be strings"); + goto cleanup; + } + res = vc(func, newargs, nargs, kwnames); +cleanup: + Py_DECREF(kwnames); + for (i = 0; i < nkw; i++) + Py_DECREF(kwvalues[i]); + PyMem_Free(newargs); + return res; +} +static CYTHON_INLINE PyObject *__Pyx_PyVectorcall_FastCallDict(PyObject *func, __pyx_vectorcallfunc vc, PyObject *const *args, size_t nargs, PyObject *kw) +{ + Py_ssize_t kw_size = + likely(kw == NULL) ? + 0 : +#if !CYTHON_ASSUME_SAFE_SIZE + PyDict_Size(kw); +#else + PyDict_GET_SIZE(kw); +#endif + if (kw_size == 0) { + return vc(func, args, nargs, NULL); + } +#if !CYTHON_ASSUME_SAFE_SIZE + else if (unlikely(kw_size == -1)) { + return NULL; + } +#endif + return __Pyx_PyVectorcall_FastCallDict_kw(func, vc, args, nargs, kw); +} +#endif + +/* CythonFunctionShared */ +#if CYTHON_COMPILING_IN_LIMITED_API +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunctionNoMethod(PyObject *func, void (*cfunc)(void)) { + if (__Pyx_CyFunction_Check(func)) { + return PyCFunction_GetFunction(((__pyx_CyFunctionObject*)func)->func) == (PyCFunction) cfunc; + } else if (PyCFunction_Check(func)) { + return PyCFunction_GetFunction(func) == (PyCFunction) cfunc; + } + return 0; +} +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if ((PyObject*)Py_TYPE(func) == __pyx_mstate_global->__Pyx_CachedMethodType) { + int result; + PyObject *newFunc = PyObject_GetAttr(func, __pyx_mstate_global->__pyx_n_u_func); + if (unlikely(!newFunc)) { + PyErr_Clear(); // It's only an optimization, so don't throw an error + return 0; + } + result = __Pyx__IsSameCyOrCFunctionNoMethod(newFunc, cfunc); + Py_DECREF(newFunc); + return result; + } + return __Pyx__IsSameCyOrCFunctionNoMethod(func, cfunc); +} +#else +static CYTHON_INLINE int __Pyx__IsSameCyOrCFunction(PyObject *func, void (*cfunc)(void)) { + if (PyMethod_Check(func)) { + func = PyMethod_GET_FUNCTION(func); + } + return __Pyx_CyOrPyCFunction_Check(func) && __Pyx_CyOrPyCFunction_GET_FUNCTION(func) == (PyCFunction) cfunc; +} +#endif +static CYTHON_INLINE void __Pyx__CyFunction_SetClassObj(__pyx_CyFunctionObject* f, PyObject* classobj) { +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + __Pyx_Py_XDECREF_SET( + __Pyx_CyFunction_GetClassObj(f), + ((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#else + __Pyx_Py_XDECREF_SET( + ((PyCMethodObject *) (f))->mm_class, + (PyTypeObject*)((classobj) ? __Pyx_NewRef(classobj) : NULL)); +#endif +} +static PyObject * +__Pyx_CyFunction_get_doc_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_doc == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_doc = PyObject_GetAttrString(op->func, "__doc__"); + if (unlikely(!op->func_doc)) return NULL; +#else + if (((PyCFunctionObject*)op)->m_ml->ml_doc) { + op->func_doc = PyUnicode_FromString(((PyCFunctionObject*)op)->m_ml->ml_doc); + if (unlikely(op->func_doc == NULL)) + return NULL; + } else { + Py_INCREF(Py_None); + return Py_None; + } +#endif + } + Py_INCREF(op->func_doc); + return op->func_doc; +} +static PyObject * +__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, void *closure) { + PyObject *result; + CYTHON_UNUSED_VAR(closure); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_doc_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (value == NULL) { + value = Py_None; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_doc, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_name_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_name == NULL)) { +#if CYTHON_COMPILING_IN_LIMITED_API + op->func_name = PyObject_GetAttrString(op->func, "__name__"); +#else + op->func_name = PyUnicode_InternFromString(((PyCFunctionObject*)op)->m_ml->ml_name); +#endif + if (unlikely(op->func_name == NULL)) + return NULL; + } + Py_INCREF(op->func_name); + return op->func_name; +} +static PyObject * +__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op, void *context) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_name_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_name, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + Py_INCREF(op->func_qualname); + result = op->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL || !PyUnicode_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_qualname, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_dict_locked(__pyx_CyFunctionObject *op) +{ + if (unlikely(op->func_dict == NULL)) { + op->func_dict = PyDict_New(); + if (unlikely(op->func_dict == NULL)) + return NULL; + } + Py_INCREF(op->func_dict); + return op->func_dict; +} +static PyObject * +__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + PyObject *result; + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_dict_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value, void *context) +{ + CYTHON_UNUSED_VAR(context); + if (unlikely(value == NULL)) { + PyErr_SetString(PyExc_TypeError, + "function's dictionary may not be deleted"); + return -1; + } + if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "setting function's dictionary to a non-dict"); + return -1; + } + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_dict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(context); + Py_INCREF(op->func_globals); + return op->func_globals; +} +static PyObject * +__Pyx_CyFunction_get_closure(__pyx_CyFunctionObject *op, void *context) +{ + CYTHON_UNUSED_VAR(op); + CYTHON_UNUSED_VAR(context); + Py_INCREF(Py_None); + return Py_None; +} +static PyObject * +__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op, void *context) +{ + PyObject* result = (op->func_code) ? op->func_code : Py_None; + CYTHON_UNUSED_VAR(context); + Py_INCREF(result); + return result; +} +static int +__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; + PyObject *res = op->defaults_getter((PyObject *) op); + if (unlikely(!res)) + return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + op->defaults_tuple = PyTuple_GET_ITEM(res, 0); + Py_INCREF(op->defaults_tuple); + op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); + Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = __Pyx_PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = __Pyx_PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif + Py_DECREF(res); + return result; +} +static int +__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyTuple_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__defaults__ must be set to a tuple object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__defaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_tuple, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_defaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_tuple; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_tuple; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result = NULL; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_defaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value) { + value = Py_None; + } else if (unlikely(value != Py_None && !PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__kwdefaults__ must be set to a dict object"); + return -1; + } + PyErr_WarnEx(PyExc_RuntimeWarning, "changes to cyfunction.__kwdefaults__ will not " + "currently affect the values used in function calls", 1); + Py_INCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->defaults_kwdict, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->defaults_kwdict; + if (unlikely(!result)) { + if (op->defaults_getter) { + if (unlikely(__Pyx_CyFunction_init_defaults(op) < 0)) return NULL; + result = op->defaults_kwdict; + } else { + result = Py_None; + } + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op, void *context) { + PyObject* result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_kwdefaults_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static int +__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + if (!value || value == Py_None) { + value = NULL; + } else if (unlikely(!PyDict_Check(value))) { + PyErr_SetString(PyExc_TypeError, + "__annotations__ must be set to a dict object"); + return -1; + } + Py_XINCREF(value); + __Pyx_BEGIN_CRITICAL_SECTION(op); + __Pyx_Py_XDECREF_SET(op->func_annotations, value); + __Pyx_END_CRITICAL_SECTION(); + return 0; +} +static PyObject * +__Pyx_CyFunction_get_annotations_locked(__pyx_CyFunctionObject *op) { + PyObject* result = op->func_annotations; + if (unlikely(!result)) { + result = PyDict_New(); + if (unlikely(!result)) return NULL; + op->func_annotations = result; + } + Py_INCREF(result); + return result; +} +static PyObject * +__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + __Pyx_BEGIN_CRITICAL_SECTION(op); + result = __Pyx_CyFunction_get_annotations_locked(op); + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine_value(__pyx_CyFunctionObject *op) { + int is_coroutine = op->flags & __Pyx_CYFUNCTION_COROUTINE; + if (is_coroutine) { + PyObject *is_coroutine_value, *module, *fromlist, *marker = __pyx_mstate_global->__pyx_n_u_is_coroutine; + fromlist = PyList_New(1); + if (unlikely(!fromlist)) return NULL; + Py_INCREF(marker); +#if CYTHON_ASSUME_SAFE_MACROS + PyList_SET_ITEM(fromlist, 0, marker); +#else + if (unlikely(PyList_SetItem(fromlist, 0, marker) < 0)) { + Py_DECREF(marker); + Py_DECREF(fromlist); + return NULL; + } +#endif + module = PyImport_ImportModuleLevelObject(__pyx_mstate_global->__pyx_n_u_asyncio_coroutines, NULL, NULL, fromlist, 0); + Py_DECREF(fromlist); + if (unlikely(!module)) goto ignore; + is_coroutine_value = __Pyx_PyObject_GetAttrStr(module, marker); + Py_DECREF(module); + if (likely(is_coroutine_value)) { + return is_coroutine_value; + } +ignore: + PyErr_Clear(); + } + return __Pyx_PyBool_FromLong(is_coroutine); +} +static PyObject * +__Pyx_CyFunction_get_is_coroutine(__pyx_CyFunctionObject *op, void *context) { + PyObject *result; + CYTHON_UNUSED_VAR(context); + if (op->func_is_coroutine) { + return __Pyx_NewRef(op->func_is_coroutine); + } + result = __Pyx_CyFunction_get_is_coroutine_value(op); + if (unlikely(!result)) + return NULL; + __Pyx_BEGIN_CRITICAL_SECTION(op); + if (op->func_is_coroutine) { + Py_DECREF(result); + result = __Pyx_NewRef(op->func_is_coroutine); + } else { + op->func_is_coroutine = __Pyx_NewRef(result); + } + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static void __Pyx_CyFunction_raise_argument_count_error(__pyx_CyFunctionObject *func, const char* message, Py_ssize_t size) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + py_name, message, size); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s (%" CYTHON_FORMAT_SSIZE_T "d given)", + name, message, size); +#endif +} +static void __Pyx_CyFunction_raise_type_error(__pyx_CyFunctionObject *func, const char* message) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *py_name = __Pyx_CyFunction_get_name(func, NULL); + if (!py_name) return; + PyErr_Format(PyExc_TypeError, + "%.200S() %s", + py_name, message); + Py_DECREF(py_name); +#else + const char* name = ((PyCFunctionObject*)func)->m_ml->ml_name; + PyErr_Format(PyExc_TypeError, + "%.200s() %s", + name, message); +#endif +} +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject * +__Pyx_CyFunction_get_module(__pyx_CyFunctionObject *op, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_GetAttrString(op->func, "__module__"); +} +static int +__Pyx_CyFunction_set_module(__pyx_CyFunctionObject *op, PyObject* value, void *context) { + CYTHON_UNUSED_VAR(context); + return PyObject_SetAttrString(op->func, "__module__", value); +} +#endif +static PyGetSetDef __pyx_CyFunction_getsets[] = { + {"func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, + {"func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, + {"__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, + {"func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {"__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, + {"func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, + {"func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, + {"func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, + {"func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, + {"__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, + {"__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, + {"_is_coroutine", (getter)__Pyx_CyFunction_get_is_coroutine, 0, 0, 0}, +#if CYTHON_COMPILING_IN_LIMITED_API + {"__module__", (getter)__Pyx_CyFunction_get_module, (setter)__Pyx_CyFunction_set_module, 0, 0}, +#endif + {0, 0, 0, 0, 0} +}; +static PyMemberDef __pyx_CyFunction_members[] = { +#if !CYTHON_COMPILING_IN_LIMITED_API + {"__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0}, +#endif + {"__dictoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_dict), READONLY, 0}, +#if CYTHON_METH_FASTCALL +#if CYTHON_BACKPORT_VECTORCALL || CYTHON_COMPILING_IN_LIMITED_API + {"__vectorcalloffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_vectorcall), READONLY, 0}, +#else + {"__vectorcalloffset__", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0}, +#endif +#if CYTHON_COMPILING_IN_LIMITED_API + {"__weaklistoffset__", T_PYSSIZET, offsetof(__pyx_CyFunctionObject, func_weakreflist), READONLY, 0}, +#else + {"__weaklistoffset__", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0}, +#endif +#endif + {0, 0, 0, 0, 0} +}; +static PyObject * +__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, PyObject *args) +{ + PyObject *result = NULL; + CYTHON_UNUSED_VAR(args); + __Pyx_BEGIN_CRITICAL_SECTION(m); + Py_INCREF(m->func_qualname); + result = m->func_qualname; + __Pyx_END_CRITICAL_SECTION(); + return result; +} +static PyMethodDef __pyx_CyFunction_methods[] = { + {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, + {0, 0, 0, 0} +}; +#if CYTHON_COMPILING_IN_LIMITED_API +#define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) +#else +#define __Pyx_CyFunction_weakreflist(cyfunc) (((PyCFunctionObject*)cyfunc)->m_weakreflist) +#endif +static PyObject *__Pyx_CyFunction_Init(__pyx_CyFunctionObject *op, PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { +#if !CYTHON_COMPILING_IN_LIMITED_API + PyCFunctionObject *cf = (PyCFunctionObject*) op; +#endif + if (unlikely(op == NULL)) + return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + op->func = PyCFunction_NewEx(ml, (PyObject*)op, module); + if (unlikely(!op->func)) return NULL; +#endif + op->flags = flags; + __Pyx_CyFunction_weakreflist(op) = NULL; +#if !CYTHON_COMPILING_IN_LIMITED_API + cf->m_ml = ml; + cf->m_self = (PyObject *) op; +#endif + Py_XINCREF(closure); + op->func_closure = closure; +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_XINCREF(module); + cf->m_module = module; +#endif + op->func_dict = NULL; + op->func_name = NULL; + Py_INCREF(qualname); + op->func_qualname = qualname; + op->func_doc = NULL; +#if PY_VERSION_HEX < 0x030900B1 || CYTHON_COMPILING_IN_LIMITED_API + op->func_classobj = NULL; +#else + ((PyCMethodObject*)op)->mm_class = NULL; +#endif + op->func_globals = globals; + Py_INCREF(op->func_globals); + Py_XINCREF(code); + op->func_code = code; + op->defaults = NULL; + op->defaults_tuple = NULL; + op->defaults_kwdict = NULL; + op->defaults_getter = NULL; + op->func_annotations = NULL; + op->func_is_coroutine = NULL; +#if CYTHON_METH_FASTCALL + switch (ml->ml_flags & (METH_VARARGS | METH_FASTCALL | METH_NOARGS | METH_O | METH_KEYWORDS | METH_METHOD)) { + case METH_NOARGS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_NOARGS; + break; + case METH_O: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_O; + break; + case METH_METHOD | METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD; + break; + case METH_FASTCALL | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS; + break; + case METH_VARARGS | METH_KEYWORDS: + __Pyx_CyFunction_func_vectorcall(op) = NULL; + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + Py_DECREF(op); + return NULL; + } +#endif + return (PyObject *) op; +} +static int +__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) +{ + Py_CLEAR(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_CLEAR(m->func); +#else + Py_CLEAR(((PyCFunctionObject*)m)->m_module); +#endif + Py_CLEAR(m->func_dict); + Py_CLEAR(m->func_name); + Py_CLEAR(m->func_qualname); + Py_CLEAR(m->func_doc); + Py_CLEAR(m->func_globals); + Py_CLEAR(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API +#if PY_VERSION_HEX < 0x030900B1 + Py_CLEAR(__Pyx_CyFunction_GetClassObj(m)); +#else + { + PyObject *cls = (PyObject*) ((PyCMethodObject *) (m))->mm_class; + ((PyCMethodObject *) (m))->mm_class = NULL; + Py_XDECREF(cls); + } +#endif +#endif + Py_CLEAR(m->defaults_tuple); + Py_CLEAR(m->defaults_kwdict); + Py_CLEAR(m->func_annotations); + Py_CLEAR(m->func_is_coroutine); + Py_CLEAR(m->defaults); + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + __Pyx_PyHeapTypeObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + { + int e = __Pyx_call_type_traverse((PyObject*)m, 1, visit, arg); + if (e) return e; + } + Py_VISIT(m->func_closure); +#if CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(m->func); +#else + Py_VISIT(((PyCFunctionObject*)m)->m_module); +#endif + Py_VISIT(m->func_dict); + __Pyx_VISIT_CONST(m->func_name); + __Pyx_VISIT_CONST(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + __Pyx_VISIT_CONST(m->func_code); +#if !CYTHON_COMPILING_IN_LIMITED_API + Py_VISIT(__Pyx_CyFunction_GetClassObj(m)); +#endif + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + Py_VISIT(m->func_is_coroutine); + Py_VISIT(m->defaults); + return 0; +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ + PyObject *repr; + __Pyx_BEGIN_CRITICAL_SECTION(op); + repr = PyUnicode_FromFormat("", + op->func_qualname, (void *)op); + __Pyx_END_CRITICAL_SECTION(); + return repr; +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { +#if CYTHON_COMPILING_IN_LIMITED_API + PyObject *f = ((__pyx_CyFunctionObject*)func)->func; + PyCFunction meth; + int flags; + meth = PyCFunction_GetFunction(f); + if (unlikely(!meth)) return NULL; + flags = PyCFunction_GetFlags(f); + if (unlikely(flags < 0)) return NULL; +#else + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + int flags = f->m_ml->ml_flags; +#endif + Py_ssize_t size; + switch (flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)(void(*)(void))meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 0)) + return (*meth)(self, NULL); + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes no arguments", size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { +#if CYTHON_ASSUME_SAFE_SIZE + size = PyTuple_GET_SIZE(arg); +#else + size = PyTuple_Size(arg); + if (unlikely(size < 0)) return NULL; +#endif + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = __Pyx_PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + __Pyx_CyFunction_raise_argument_count_error( + (__pyx_CyFunctionObject*)func, + "takes exactly one argument", size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags for CyFunction"); + return NULL; + } + __Pyx_CyFunction_raise_type_error( + (__pyx_CyFunctionObject*)func, "takes no keyword arguments"); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + PyObject *self, *result; +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)func)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)func)->m_self; +#endif + result = __Pyx_CyFunction_CallMethod(func, self, arg, kw); + return result; +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; +#if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) + __pyx_vectorcallfunc vc = __Pyx_CyFunction_func_vectorcall(cyfunc); + if (vc) { +#if CYTHON_ASSUME_SAFE_MACROS && CYTHON_ASSUME_SAFE_SIZE + return __Pyx_PyVectorcall_FastCallDict(func, vc, &PyTuple_GET_ITEM(args, 0), (size_t)PyTuple_GET_SIZE(args), kw); +#else + (void) &__Pyx_PyVectorcall_FastCallDict; + return PyVectorcall_Call(func, args, kw); +#endif + } +#endif + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; +#if CYTHON_ASSUME_SAFE_SIZE + argc = PyTuple_GET_SIZE(args); +#else + argc = PyTuple_Size(args); + if (unlikely(argc < 0)) return NULL; +#endif + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + PyErr_Format(PyExc_TypeError, + "unbound method %.200S() needs an argument", + cyfunc->func_qualname); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +#if CYTHON_METH_FASTCALL && (CYTHON_VECTORCALL || CYTHON_BACKPORT_VECTORCALL) +static CYTHON_INLINE int __Pyx_CyFunction_Vectorcall_CheckArgs(__pyx_CyFunctionObject *cyfunc, Py_ssize_t nargs, PyObject *kwnames) +{ + int ret = 0; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + if (unlikely(nargs < 1)) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "needs an argument"); + return -1; + } + ret = 1; + } + if (unlikely(kwnames) && unlikely(__Pyx_PyTuple_GET_SIZE(kwnames))) { + __Pyx_CyFunction_raise_type_error( + cyfunc, "takes no keyword arguments"); + return -1; + } + return ret; +} +static PyObject * __Pyx_CyFunction_Vectorcall_NOARGS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 0)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes no arguments", nargs); + return NULL; + } + return meth(self, NULL); +} +static PyObject * __Pyx_CyFunction_Vectorcall_O(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, kwnames)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + if (unlikely(nargs != 1)) { + __Pyx_CyFunction_raise_argument_count_error( + cyfunc, "takes exactly one argument", nargs); + return NULL; + } + return meth(self, args[0]); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames); +} +static PyObject * __Pyx_CyFunction_Vectorcall_FASTCALL_KEYWORDS_METHOD(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) +{ + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *)func; + PyTypeObject *cls = (PyTypeObject *) __Pyx_CyFunction_GetClassObj(cyfunc); +#if CYTHON_BACKPORT_VECTORCALL + Py_ssize_t nargs = (Py_ssize_t)nargsf; +#else + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); +#endif + PyObject *self; +#if CYTHON_COMPILING_IN_LIMITED_API + PyCFunction meth = PyCFunction_GetFunction(cyfunc->func); + if (unlikely(!meth)) return NULL; +#else + PyCFunction meth = ((PyCFunctionObject*)cyfunc)->m_ml->ml_meth; +#endif + switch (__Pyx_CyFunction_Vectorcall_CheckArgs(cyfunc, nargs, NULL)) { + case 1: + self = args[0]; + args += 1; + nargs -= 1; + break; + case 0: +#if CYTHON_COMPILING_IN_LIMITED_API + self = PyCFunction_GetSelf(((__pyx_CyFunctionObject*)cyfunc)->func); + if (unlikely(!self) && PyErr_Occurred()) return NULL; +#else + self = ((PyCFunctionObject*)cyfunc)->m_self; +#endif + break; + default: + return NULL; + } + return ((__Pyx_PyCMethod)(void(*)(void))meth)(self, cls, args, (size_t)nargs, kwnames); +} +#endif +static PyType_Slot __pyx_CyFunctionType_slots[] = { + {Py_tp_dealloc, (void *)__Pyx_CyFunction_dealloc}, + {Py_tp_repr, (void *)__Pyx_CyFunction_repr}, + {Py_tp_call, (void *)__Pyx_CyFunction_CallAsMethod}, + {Py_tp_traverse, (void *)__Pyx_CyFunction_traverse}, + {Py_tp_clear, (void *)__Pyx_CyFunction_clear}, + {Py_tp_methods, (void *)__pyx_CyFunction_methods}, + {Py_tp_members, (void *)__pyx_CyFunction_members}, + {Py_tp_getset, (void *)__pyx_CyFunction_getsets}, + {Py_tp_descr_get, (void *)__Pyx_PyMethod_New}, + {0, 0}, +}; +static PyType_Spec __pyx_CyFunctionType_spec = { + __PYX_TYPE_MODULE_PREFIX "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, +#ifdef Py_TPFLAGS_METHOD_DESCRIPTOR + Py_TPFLAGS_METHOD_DESCRIPTOR | +#endif +#if CYTHON_METH_FASTCALL +#if defined(Py_TPFLAGS_HAVE_VECTORCALL) + Py_TPFLAGS_HAVE_VECTORCALL | +#elif defined(_Py_TPFLAGS_HAVE_VECTORCALL) + _Py_TPFLAGS_HAVE_VECTORCALL | +#endif +#endif // CYTHON_METH_FASTCALL +#if PY_VERSION_HEX >= 0x030A0000 + Py_TPFLAGS_IMMUTABLETYPE | +#endif + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, + __pyx_CyFunctionType_slots +}; +static int __pyx_CyFunction_init(PyObject *module) { + __pyx_mstatetype *mstate = __Pyx_PyModule_GetState(module); + mstate->__pyx_CyFunctionType = __Pyx_FetchCommonTypeFromSpec( + mstate->__pyx_CommonTypesMetaclassType, module, &__pyx_CyFunctionType_spec, NULL); + if (unlikely(mstate->__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_InitDefaults(PyObject *func, PyTypeObject *defaults_type) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_CallObject((PyObject*)defaults_type, NULL); // _PyObject_New(defaults_type); + if (unlikely(!m->defaults)) + return NULL; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* CythonFunction */ +static PyObject *__Pyx_CyFunction_New(PyMethodDef *ml, int flags, PyObject* qualname, + PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { + PyObject *op = __Pyx_CyFunction_Init( + PyObject_GC_New(__pyx_CyFunctionObject, __pyx_mstate_global->__pyx_CyFunctionType), + ml, flags, qualname, closure, module, globals, code + ); + if (likely(op)) { + PyObject_GC_Track(op); + } + return op; +} + +/* ClassMethod */ +static PyObject* __Pyx_Method_ClassMethod(PyObject *method) { +#if CYTHON_COMPILING_IN_PYPY && PYPY_VERSION_NUM <= 0x05080000 + if (PyObject_TypeCheck(method, &PyWrapperDescr_Type)) { + return PyClassMethod_New(method); + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (PyMethodDescr_Check(method)) +#else + if (__Pyx_TypeCheck(method, &PyMethodDescr_Type)) +#endif + { +#if CYTHON_COMPILING_IN_LIMITED_API + return PyErr_Format( + PyExc_SystemError, + "Cython cannot yet handle classmethod on a MethodDescriptorType (%S) in limited API mode. " + "This is most likely a classmethod in a cdef class method with binding=False. " + "Try setting 'binding' to True.", + method); +#elif CYTHON_COMPILING_IN_GRAAL + PyTypeObject *d_type = PyDescrObject_GetType(method); + return PyDescr_NewClassMethod(d_type, PyMethodDescrObject_GetMethod(method)); +#else + PyMethodDescrObject *descr = (PyMethodDescrObject *)method; + PyTypeObject *d_type = descr->d_common.d_type; + return PyDescr_NewClassMethod(d_type, descr->d_method); +#endif + } +#endif +#if !CYTHON_COMPILING_IN_LIMITED_API + else if (PyMethod_Check(method)) { + return PyClassMethod_New(PyMethod_GET_FUNCTION(method)); + } + else { + return PyClassMethod_New(method); + } +#else + { + PyObject *func=NULL; + PyObject *builtins, *classmethod, *classmethod_str, *result=NULL; + if (__Pyx_TypeCheck(method, __pyx_mstate_global->__Pyx_CachedMethodType)) { + func = PyObject_GetAttrString(method, "__func__"); + if (!func) goto bad; + } else { + func = method; + Py_INCREF(func); + } + builtins = PyEval_GetBuiltins(); // borrowed + if (unlikely(!builtins)) goto bad; + classmethod_str = PyUnicode_FromString("classmethod"); + if (unlikely(!classmethod_str)) goto bad; + classmethod = PyObject_GetItem(builtins, classmethod_str); + Py_DECREF(classmethod_str); + if (unlikely(!classmethod)) goto bad; + result = PyObject_CallFunctionObjArgs(classmethod, func, NULL); + Py_DECREF(classmethod); + bad: + Py_XDECREF(func); + return result; + } +#endif +} + +/* GetNameInClass */ +static PyObject *__Pyx__GetNameInClass(PyObject *nmspace, PyObject *name) { + PyObject *result; + PyObject *dict; + assert(PyType_Check(nmspace)); +#if CYTHON_USE_TYPE_SLOTS + dict = ((PyTypeObject*)nmspace)->tp_dict; + Py_XINCREF(dict); +#else + dict = PyObject_GetAttr(nmspace, __pyx_mstate_global->__pyx_n_u_dict); +#endif + if (likely(dict)) { + result = PyObject_GetItem(dict, name); + Py_DECREF(dict); + if (result) { + return result; + } + } + PyErr_Clear(); + __Pyx_GetModuleGlobalNameUncached(result, name); + return result; +} + +/* CLineInTraceback */ +#if CYTHON_CLINE_IN_TRACEBACK && CYTHON_CLINE_IN_TRACEBACK_RUNTIME +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + CYTHON_MAYBE_UNUSED_VAR(tstate); + if (unlikely(!__pyx_mstate_global->__pyx_cython_runtime)) { + return c_line; + } + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_mstate_global->__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + __Pyx_BEGIN_CRITICAL_SECTION(*cython_runtime_dict); + __PYX_PY_DICT_LOOKUP_IF_MODIFIED( + use_cline, *cython_runtime_dict, + __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_mstate_global->__pyx_n_u_cline_in_traceback)) + Py_XINCREF(use_cline); + __Pyx_END_CRITICAL_SECTION(); + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStrNoError(__pyx_mstate_global->__pyx_cython_runtime, __pyx_mstate_global->__pyx_n_u_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_INCREF(use_cline); + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + (void) PyObject_SetAttr(__pyx_mstate_global->__pyx_cython_runtime, __pyx_mstate_global->__pyx_n_u_cline_in_traceback, Py_False); + } + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { + c_line = 0; + } + Py_XDECREF(use_cline); + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; +} +#endif + +/* CodeObjectCache */ +static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } +} +static __Pyx_CachedCodeObjectType *__pyx__find_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line) { + __Pyx_CachedCodeObjectType* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!code_cache->entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if (unlikely(pos >= code_cache->count) || unlikely(code_cache->entries[pos].code_line != code_line)) { + return NULL; + } + code_object = code_cache->entries[pos].code_object; + Py_INCREF(code_object); + return code_object; +} +static __Pyx_CachedCodeObjectType *__pyx_find_code_object(int code_line) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__find_code_object; + return NULL; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just miss. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type old_count = __pyx_atomic_incr_acq_rel(&code_cache->accessor_count); + if (old_count < 0) { + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); + return NULL; + } +#endif + __Pyx_CachedCodeObjectType *result = __pyx__find_code_object(code_cache, code_line); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_decr_acq_rel(&code_cache->accessor_count); +#endif + return result; +#endif +} +static void __pyx__insert_code_object(struct __Pyx_CodeObjectCache *code_cache, int code_line, __Pyx_CachedCodeObjectType* code_object) +{ + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = code_cache->entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + code_cache->entries = entries; + code_cache->max_count = 64; + code_cache->count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(code_cache->entries, code_cache->count, code_line); + if ((pos < code_cache->count) && unlikely(code_cache->entries[pos].code_line == code_line)) { + __Pyx_CachedCodeObjectType* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_INCREF(code_object); + Py_DECREF(tmp); + return; + } + if (code_cache->count == code_cache->max_count) { + int new_max = code_cache->max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + code_cache->entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + code_cache->entries = entries; + code_cache->max_count = new_max; + } + for (i=code_cache->count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + code_cache->count++; + Py_INCREF(code_object); +} +static void __pyx_insert_code_object(int code_line, __Pyx_CachedCodeObjectType* code_object) { +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING && !CYTHON_ATOMICS + (void)__pyx__insert_code_object; + return; // Most implementation should have atomics. But otherwise, don't make it thread-safe, just fail. +#else + struct __Pyx_CodeObjectCache *code_cache = &__pyx_mstate_global->__pyx_code_cache; +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_nonatomic_int_type expected = 0; + if (!__pyx_atomic_int_cmp_exchange(&code_cache->accessor_count, &expected, INT_MIN)) { + return; + } +#endif + __pyx__insert_code_object(code_cache, code_line, code_object); +#if CYTHON_COMPILING_IN_CPYTHON_FREETHREADING + __pyx_atomic_sub(&code_cache->accessor_count, INT_MIN); +#endif +#endif +} + +/* AddTraceback */ +#include "compile.h" +#include "frameobject.h" +#include "traceback.h" +#if PY_VERSION_HEX >= 0x030b00a6 && !CYTHON_COMPILING_IN_LIMITED_API && !defined(PYPY_VERSION) + #ifndef Py_BUILD_CORE + #define Py_BUILD_CORE 1 + #endif + #include "internal/pycore_frame.h" +#endif +#if CYTHON_COMPILING_IN_LIMITED_API +static PyObject *__Pyx_PyCode_Replace_For_AddTraceback(PyObject *code, PyObject *scratch_dict, + PyObject *firstlineno, PyObject *name) { + PyObject *replace = NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_firstlineno", firstlineno))) return NULL; + if (unlikely(PyDict_SetItemString(scratch_dict, "co_name", name))) return NULL; + replace = PyObject_GetAttrString(code, "replace"); + if (likely(replace)) { + PyObject *result = PyObject_Call(replace, __pyx_mstate_global->__pyx_empty_tuple, scratch_dict); + Py_DECREF(replace); + return result; + } + PyErr_Clear(); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyObject *code_object = NULL, *py_py_line = NULL, *py_funcname = NULL, *dict = NULL; + PyObject *replace = NULL, *getframe = NULL, *frame = NULL; + PyObject *exc_type, *exc_value, *exc_traceback; + int success = 0; + if (c_line) { + (void) __pyx_cfilenm; + (void) __Pyx_CLineForTraceback(__Pyx_PyThreadState_Current, c_line); + } + PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); + code_object = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!code_object) { + code_object = Py_CompileString("_getframe()", filename, Py_eval_input); + if (unlikely(!code_object)) goto bad; + py_py_line = PyLong_FromLong(py_line); + if (unlikely(!py_py_line)) goto bad; + py_funcname = PyUnicode_FromString(funcname); + if (unlikely(!py_funcname)) goto bad; + dict = PyDict_New(); + if (unlikely(!dict)) goto bad; + { + PyObject *old_code_object = code_object; + code_object = __Pyx_PyCode_Replace_For_AddTraceback(code_object, dict, py_py_line, py_funcname); + Py_DECREF(old_code_object); + } + if (unlikely(!code_object)) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, code_object); + } else { + dict = PyDict_New(); + } + getframe = PySys_GetObject("_getframe"); + if (unlikely(!getframe)) goto bad; + if (unlikely(PyDict_SetItemString(dict, "_getframe", getframe))) goto bad; + frame = PyEval_EvalCode(code_object, dict, dict); + if (unlikely(!frame) || frame == Py_None) goto bad; + success = 1; + bad: + PyErr_Restore(exc_type, exc_value, exc_traceback); + Py_XDECREF(code_object); + Py_XDECREF(py_py_line); + Py_XDECREF(py_funcname); + Py_XDECREF(dict); + Py_XDECREF(replace); + if (success) { + PyTraceBack_Here( + (struct _frame*)frame); + } + Py_XDECREF(frame); +} +#else +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = NULL; + PyObject *py_funcname = NULL; + if (c_line) { + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + if (!py_funcname) goto bad; + funcname = PyUnicode_AsUTF8(py_funcname); + if (!funcname) goto bad; + } + py_code = PyCode_NewEmpty(filename, funcname, py_line); + Py_XDECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject *ptype, *pvalue, *ptraceback; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) { + /* If the code object creation fails, then we should clear the + fetched exception references and propagate the new exception */ + Py_XDECREF(ptype); + Py_XDECREF(pvalue); + Py_XDECREF(ptraceback); + goto bad; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_mstate_global->__pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} +#endif + +/* CIntFromPyVerify */ +#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int(int value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyLong_As_int(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int neg_one = (int) -1, const_zero = (int) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int) -1; + val = __Pyx_PyLong_As_int(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 2 * PyLong_SHIFT)) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 3 * PyLong_SHIFT)) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) >= 4 * PyLong_SHIFT)) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int) - 1 > 4 * PyLong_SHIFT)) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int) -1; + } else { + stepval = v; + } + v = NULL; + val = (int) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int) 1) << (sizeof(int) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int"); + return (int) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_char(char value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const char neg_one = (char) -1, const_zero = (char) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(char) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(char) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(char) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(char), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(char)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE char __Pyx_PyLong_As_char(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const char neg_one = (char) -1, const_zero = (char) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + char val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (char) -1; + val = __Pyx_PyLong_As_char(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(char, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(char) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 2 * PyLong_SHIFT)) { + return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(char) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 3 * PyLong_SHIFT)) { + return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(char) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) >= 4 * PyLong_SHIFT)) { + return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (char) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(char) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(char) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(char, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(char) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(char) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(char) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(char) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(char) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 4 * PyLong_SHIFT)) { + return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(char) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(char) - 1 > 4 * PyLong_SHIFT)) { + return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(char) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(char) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + char val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (char) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (char) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (char) -1; + } else { + stepval = v; + } + v = NULL; + val = (char) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(char) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((char) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(char) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((char) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((char) 1) << (sizeof(char) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (char) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE long __Pyx_PyLong_As_long(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + long val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (long) -1; + val = __Pyx_PyLong_As_long(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 2 * PyLong_SHIFT)) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 3 * PyLong_SHIFT)) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) >= 4 * PyLong_SHIFT)) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(long) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(long, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(long) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(long) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(long) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(long) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(long) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(long) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(long) - 1 > 4 * PyLong_SHIFT)) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(long) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(long) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + long val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (long) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (long) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (long) -1; + } else { + stepval = v; + } + v = NULL; + val = (long) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(long) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((long) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(long) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((long) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((long) 1) << (sizeof(long) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (long) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to long"); + return (long) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to long"); + return (long) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_long(long value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const long neg_one = (long) -1, const_zero = (long) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(long) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(long) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(long) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(long)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE uint32_t __Pyx_PyLong_As_uint32_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + uint32_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (uint32_t) -1; + val = __Pyx_PyLong_As_uint32_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(uint32_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(uint32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) >= 2 * PyLong_SHIFT)) { + return (uint32_t) (((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(uint32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) >= 3 * PyLong_SHIFT)) { + return (uint32_t) (((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(uint32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) >= 4 * PyLong_SHIFT)) { + return (uint32_t) (((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (uint32_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(uint32_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(uint32_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(uint32_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(uint32_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT)) { + return (uint32_t) (((uint32_t)-1)*(((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(uint32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT)) { + return (uint32_t) ((((((uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(uint32_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT)) { + return (uint32_t) (((uint32_t)-1)*(((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(uint32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT)) { + return (uint32_t) ((((((((uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(uint32_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT)) { + return (uint32_t) (((uint32_t)-1)*(((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(uint32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint32_t) - 1 > 4 * PyLong_SHIFT)) { + return (uint32_t) ((((((((((uint32_t)digits[3]) << PyLong_SHIFT) | (uint32_t)digits[2]) << PyLong_SHIFT) | (uint32_t)digits[1]) << PyLong_SHIFT) | (uint32_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(uint32_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(uint32_t, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(uint32_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(uint32_t, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + uint32_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (uint32_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (uint32_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (uint32_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (uint32_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(uint32_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((uint32_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(uint32_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((uint32_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((uint32_t) 1) << (sizeof(uint32_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (uint32_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to uint32_t"); + return (uint32_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to uint32_t"); + return (uint32_t) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_int32_t(int32_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int32_t neg_one = (int32_t) -1, const_zero = (int32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int32_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(int32_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(int32_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int32_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int32_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(int32_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(int32_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_uint32_t(uint32_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const uint32_t neg_one = (uint32_t) -1, const_zero = (uint32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(uint32_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(uint32_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(uint32_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(uint32_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint32_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(uint32_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(uint32_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int64_t __Pyx_PyLong_As_int64_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int64_t neg_one = (int64_t) -1, const_zero = (int64_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int64_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int64_t) -1; + val = __Pyx_PyLong_As_int64_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int64_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 2 * PyLong_SHIFT)) { + return (int64_t) (((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 3 * PyLong_SHIFT)) { + return (int64_t) (((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) >= 4 * PyLong_SHIFT)) { + return (int64_t) (((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int64_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int64_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int64_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int64_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int64_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + return (int64_t) ((((((int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int64_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + return (int64_t) ((((((((int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int64_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 4 * PyLong_SHIFT)) { + return (int64_t) (((int64_t)-1)*(((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int64_t) - 1 > 4 * PyLong_SHIFT)) { + return (int64_t) ((((((((((int64_t)digits[3]) << PyLong_SHIFT) | (int64_t)digits[2]) << PyLong_SHIFT) | (int64_t)digits[1]) << PyLong_SHIFT) | (int64_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int64_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int64_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int64_t, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int64_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int64_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int64_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int64_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (int64_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int64_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int64_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int64_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int64_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int64_t) 1) << (sizeof(int64_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int64_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int64_t"); + return (int64_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int64_t"); + return (int64_t) -1; +} + +/* CIntFromPy */ +static CYTHON_INLINE int32_t __Pyx_PyLong_As_int32_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const int32_t neg_one = (int32_t) -1, const_zero = (int32_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + int32_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (int32_t) -1; + val = __Pyx_PyLong_As_int32_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int32_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(int32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 2 * PyLong_SHIFT)) { + return (int32_t) (((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(int32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 3 * PyLong_SHIFT)) { + return (int32_t) (((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(int32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) >= 4 * PyLong_SHIFT)) { + return (int32_t) (((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int32_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(int32_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int32_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(int32_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(int32_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(int32_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + return (int32_t) ((((((int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(int32_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(int32_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + return (int32_t) ((((((((int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(int32_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 4 * PyLong_SHIFT)) { + return (int32_t) (((int32_t)-1)*(((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(int32_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(int32_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(int32_t) - 1 > 4 * PyLong_SHIFT)) { + return (int32_t) ((((((((((int32_t)digits[3]) << PyLong_SHIFT) | (int32_t)digits[2]) << PyLong_SHIFT) | (int32_t)digits[1]) << PyLong_SHIFT) | (int32_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(int32_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(int32_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(int32_t, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + int32_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (int32_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (int32_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (int32_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (int32_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(int32_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((int32_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(int32_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((int32_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((int32_t) 1) << (sizeof(int32_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (int32_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to int32_t"); + return (int32_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int32_t"); + return (int32_t) -1; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyLong_From_uint64_t(uint64_t value) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const uint64_t neg_one = (uint64_t) -1, const_zero = (uint64_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(uint64_t) < sizeof(long)) { + return PyLong_FromLong((long) value); + } else if (sizeof(uint64_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#if defined(HAVE_LONG_LONG) && !CYTHON_COMPILING_IN_PYPY + } else if (sizeof(uint64_t) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(uint64_t) <= sizeof(long)) { + return PyLong_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint64_t) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + unsigned char *bytes = (unsigned char *)&value; +#if !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d00A4 + if (is_unsigned) { + return PyLong_FromUnsignedNativeBytes(bytes, sizeof(value), -1); + } else { + return PyLong_FromNativeBytes(bytes, sizeof(value), -1); + } +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX < 0x030d0000 + int one = 1; int little = (int)*(unsigned char *)&one; + return _PyLong_FromByteArray(bytes, sizeof(uint64_t), + little, !is_unsigned); +#else + int one = 1; int little = (int)*(unsigned char *)&one; + PyObject *from_bytes, *result = NULL, *kwds = NULL; + PyObject *py_bytes = NULL, *order_str = NULL; + from_bytes = PyObject_GetAttrString((PyObject*)&PyLong_Type, "from_bytes"); + if (!from_bytes) return NULL; + py_bytes = PyBytes_FromStringAndSize((char*)bytes, sizeof(uint64_t)); + if (!py_bytes) goto limited_bad; + order_str = PyUnicode_FromString(little ? "little" : "big"); + if (!order_str) goto limited_bad; + { + PyObject *args[3+(CYTHON_VECTORCALL ? 1 : 0)] = { NULL, py_bytes, order_str }; + if (!is_unsigned) { + kwds = __Pyx_MakeVectorcallBuilderKwds(1); + if (!kwds) goto limited_bad; + if (__Pyx_VectorcallBuilder_AddArgStr("signed", __Pyx_NewRef(Py_True), kwds, args+3, 0) < 0) goto limited_bad; + } + result = __Pyx_Object_Vectorcall_CallFromBuilder(from_bytes, args+1, 2 | __Pyx_PY_VECTORCALL_ARGUMENTS_OFFSET, kwds); + } + limited_bad: + Py_XDECREF(kwds); + Py_XDECREF(order_str); + Py_XDECREF(py_bytes); + Py_XDECREF(from_bytes); + return result; +#endif + } +} + +/* CIntFromPy */ +static CYTHON_INLINE uint64_t __Pyx_PyLong_As_uint64_t(PyObject *x) { +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wconversion" +#endif + const uint64_t neg_one = (uint64_t) -1, const_zero = (uint64_t) 0; +#ifdef __Pyx_HAS_GCC_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + const int is_unsigned = neg_one > const_zero; + if (unlikely(!PyLong_Check(x))) { + uint64_t val; + PyObject *tmp = __Pyx_PyNumber_Long(x); + if (!tmp) return (uint64_t) -1; + val = __Pyx_PyLong_As_uint64_t(tmp); + Py_DECREF(tmp); + return val; + } + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + if (unlikely(__Pyx_PyLong_IsNeg(x))) { + goto raise_neg_overflow; + } else if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(uint64_t, __Pyx_compact_upylong, __Pyx_PyLong_CompactValueUnsigned(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_DigitCount(x)) { + case 2: + if ((8 * sizeof(uint64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) >= 2 * PyLong_SHIFT)) { + return (uint64_t) (((((uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0])); + } + } + break; + case 3: + if ((8 * sizeof(uint64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) >= 3 * PyLong_SHIFT)) { + return (uint64_t) (((((((uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0])); + } + } + break; + case 4: + if ((8 * sizeof(uint64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) >= 4 * PyLong_SHIFT)) { + return (uint64_t) (((((((((uint64_t)digits[3]) << PyLong_SHIFT) | (uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0])); + } + } + break; + } + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030C00A7 + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (uint64_t) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if ((sizeof(uint64_t) <= sizeof(unsigned long))) { + __PYX_VERIFY_RETURN_INT_EXC(uint64_t, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(uint64_t) <= sizeof(unsigned PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(uint64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + if (__Pyx_PyLong_IsCompact(x)) { + __PYX_VERIFY_RETURN_INT(uint64_t, __Pyx_compact_pylong, __Pyx_PyLong_CompactValue(x)) + } else { + const digit* digits = __Pyx_PyLong_Digits(x); + assert(__Pyx_PyLong_DigitCount(x) > 1); + switch (__Pyx_PyLong_SignedDigitCount(x)) { + case -2: + if ((8 * sizeof(uint64_t) - 1 > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 2 * PyLong_SHIFT)) { + return (uint64_t) (((uint64_t)-1)*(((((uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + case 2: + if ((8 * sizeof(uint64_t) > 1 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 2 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 2 * PyLong_SHIFT)) { + return (uint64_t) ((((((uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + case -3: + if ((8 * sizeof(uint64_t) - 1 > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 3 * PyLong_SHIFT)) { + return (uint64_t) (((uint64_t)-1)*(((((((uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + case 3: + if ((8 * sizeof(uint64_t) > 2 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 3 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 3 * PyLong_SHIFT)) { + return (uint64_t) ((((((((uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + case -4: + if ((8 * sizeof(uint64_t) - 1 > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 4 * PyLong_SHIFT)) { + return (uint64_t) (((uint64_t)-1)*(((((((((uint64_t)digits[3]) << PyLong_SHIFT) | (uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + case 4: + if ((8 * sizeof(uint64_t) > 3 * PyLong_SHIFT)) { + if ((8 * sizeof(unsigned long) > 4 * PyLong_SHIFT)) { + __PYX_VERIFY_RETURN_INT(uint64_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if ((8 * sizeof(uint64_t) - 1 > 4 * PyLong_SHIFT)) { + return (uint64_t) ((((((((((uint64_t)digits[3]) << PyLong_SHIFT) | (uint64_t)digits[2]) << PyLong_SHIFT) | (uint64_t)digits[1]) << PyLong_SHIFT) | (uint64_t)digits[0]))); + } + } + break; + } + } +#endif + if ((sizeof(uint64_t) <= sizeof(long))) { + __PYX_VERIFY_RETURN_INT_EXC(uint64_t, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if ((sizeof(uint64_t) <= sizeof(PY_LONG_LONG))) { + __PYX_VERIFY_RETURN_INT_EXC(uint64_t, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { + uint64_t val; + int ret = -1; +#if PY_VERSION_HEX >= 0x030d00A6 && !CYTHON_COMPILING_IN_LIMITED_API + Py_ssize_t bytes_copied = PyLong_AsNativeBytes( + x, &val, sizeof(val), Py_ASNATIVEBYTES_NATIVE_ENDIAN | (is_unsigned ? Py_ASNATIVEBYTES_UNSIGNED_BUFFER | Py_ASNATIVEBYTES_REJECT_NEGATIVE : 0)); + if (unlikely(bytes_copied == -1)) { + } else if (unlikely(bytes_copied > (Py_ssize_t) sizeof(val))) { + goto raise_overflow; + } else { + ret = 0; + } +#elif PY_VERSION_HEX < 0x030d0000 && !(CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_LIMITED_API) || defined(_PyLong_AsByteArray) + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + ret = _PyLong_AsByteArray((PyLongObject *)x, + bytes, sizeof(val), + is_little, !is_unsigned); +#else + PyObject *v; + PyObject *stepval = NULL, *mask = NULL, *shift = NULL; + int bits, remaining_bits, is_negative = 0; + int chunk_size = (sizeof(long) < 8) ? 30 : 62; + if (likely(PyLong_CheckExact(x))) { + v = __Pyx_NewRef(x); + } else { + v = PyNumber_Long(x); + if (unlikely(!v)) return (uint64_t) -1; + assert(PyLong_CheckExact(v)); + } + { + int result = PyObject_RichCompareBool(v, Py_False, Py_LT); + if (unlikely(result < 0)) { + Py_DECREF(v); + return (uint64_t) -1; + } + is_negative = result == 1; + } + if (is_unsigned && unlikely(is_negative)) { + Py_DECREF(v); + goto raise_neg_overflow; + } else if (is_negative) { + stepval = PyNumber_Invert(v); + Py_DECREF(v); + if (unlikely(!stepval)) + return (uint64_t) -1; + } else { + stepval = v; + } + v = NULL; + val = (uint64_t) 0; + mask = PyLong_FromLong((1L << chunk_size) - 1); if (unlikely(!mask)) goto done; + shift = PyLong_FromLong(chunk_size); if (unlikely(!shift)) goto done; + for (bits = 0; bits < (int) sizeof(uint64_t) * 8 - chunk_size; bits += chunk_size) { + PyObject *tmp, *digit; + long idigit; + digit = PyNumber_And(stepval, mask); + if (unlikely(!digit)) goto done; + idigit = PyLong_AsLong(digit); + Py_DECREF(digit); + if (unlikely(idigit < 0)) goto done; + val |= ((uint64_t) idigit) << bits; + tmp = PyNumber_Rshift(stepval, shift); + if (unlikely(!tmp)) goto done; + Py_DECREF(stepval); stepval = tmp; + } + Py_DECREF(shift); shift = NULL; + Py_DECREF(mask); mask = NULL; + { + long idigit = PyLong_AsLong(stepval); + if (unlikely(idigit < 0)) goto done; + remaining_bits = ((int) sizeof(uint64_t) * 8) - bits - (is_unsigned ? 0 : 1); + if (unlikely(idigit >= (1L << remaining_bits))) + goto raise_overflow; + val |= ((uint64_t) idigit) << bits; + } + if (!is_unsigned) { + if (unlikely(val & (((uint64_t) 1) << (sizeof(uint64_t) * 8 - 1)))) + goto raise_overflow; + if (is_negative) + val = ~val; + } + ret = 0; + done: + Py_XDECREF(shift); + Py_XDECREF(mask); + Py_XDECREF(stepval); +#endif + if (unlikely(ret)) + return (uint64_t) -1; + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to uint64_t"); + return (uint64_t) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to uint64_t"); + return (uint64_t) -1; +} + +/* FormatTypeName */ +#if CYTHON_COMPILING_IN_LIMITED_API && __PYX_LIMITED_VERSION_HEX < 0x030d0000 +static __Pyx_TypeName +__Pyx_PyType_GetFullyQualifiedName(PyTypeObject* tp) +{ + PyObject *module = NULL, *name = NULL, *result = NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + name = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_qualname); + #else + name = PyType_GetQualName(tp); + #endif + if (unlikely(name == NULL) || unlikely(!PyUnicode_Check(name))) goto bad; + module = __Pyx_PyObject_GetAttrStr((PyObject *)tp, + __pyx_mstate_global->__pyx_n_u_module); + if (unlikely(module == NULL) || unlikely(!PyUnicode_Check(module))) goto bad; + if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) { + result = name; + name = NULL; + goto done; + } + result = PyUnicode_FromFormat("%U.%U", module, name); + if (unlikely(result == NULL)) goto bad; + done: + Py_XDECREF(name); + Py_XDECREF(module); + return result; + bad: + PyErr_Clear(); + if (name) { + result = name; + name = NULL; + } else { + result = __Pyx_NewRef(__pyx_mstate_global->__pyx_kp_u__12); + } + goto done; +} +#endif + +/* FastTypeChecks */ +#if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = __Pyx_PyType_GetSlot(a, tp_base, PyTypeObject*); + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +static CYTHON_INLINE int __Pyx_IsAnySubtype2(PyTypeObject *cls, PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (cls == a || cls == b) return 1; + mro = cls->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + PyObject *base = PyTuple_GET_ITEM(mro, i); + if (base == (PyObject *)a || base == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(cls, a) || __Pyx_InBases(cls, b); +} +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + if (exc_type1) { + return __Pyx_IsAnySubtype2((PyTypeObject*)err, (PyTypeObject*)exc_type1, (PyTypeObject*)exc_type2); + } else { + return __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } +} +static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + assert(PyExceptionClass_Check(exc_type)); + n = PyTuple_GET_SIZE(tuple); + for (i=0; i= 0x030b0000 + return Py_Version & ~0xFFUL; +#else + static unsigned long __Pyx_cached_runtime_version = 0; + if (__Pyx_cached_runtime_version == 0) { + const char* rt_version = Py_GetVersion(); + unsigned long version = 0; + unsigned long factor = 0x01000000UL; + unsigned int digit = 0; + int i = 0; + while (factor) { + while ('0' <= rt_version[i] && rt_version[i] <= '9') { + digit = digit * 10 + (unsigned int) (rt_version[i] - '0'); + ++i; + } + version += factor * digit; + if (rt_version[i] != '.') + break; + digit = 0; + factor >>= 8; + ++i; + } + __Pyx_cached_runtime_version = version; + } + return __Pyx_cached_runtime_version; +#endif +} + +/* CheckBinaryVersion */ +static int __Pyx_check_binary_version(unsigned long ct_version, unsigned long rt_version, int allow_newer) { + const unsigned long MAJOR_MINOR = 0xFFFF0000UL; + if ((rt_version & MAJOR_MINOR) == (ct_version & MAJOR_MINOR)) + return 0; + if (likely(allow_newer && (rt_version & MAJOR_MINOR) > (ct_version & MAJOR_MINOR))) + return 1; + { + char message[200]; + PyOS_snprintf(message, sizeof(message), + "compile time Python version %d.%d " + "of module '%.100s' " + "%s " + "runtime version %d.%d", + (int) (ct_version >> 24), (int) ((ct_version >> 16) & 0xFF), + __Pyx_MODULE_NAME, + (allow_newer) ? "was newer than" : "does not match", + (int) (rt_version >> 24), (int) ((rt_version >> 16) & 0xFF) + ); + return PyErr_WarnEx(NULL, message, 1); + } +} + +/* FunctionImport */ +#ifndef __PYX_HAVE_RT_ImportFunction_3_1_2 +#define __PYX_HAVE_RT_ImportFunction_3_1_2 +static int __Pyx_ImportFunction_3_1_2(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, "__pyx_capi__"); + if (!d) + goto bad; +#if (defined(Py_LIMITED_API) && Py_LIMITED_API >= 0x030d0000) || (!defined(Py_LIMITED_API) && PY_VERSION_HEX >= 0x030d0000) + PyDict_GetItemStringRef(d, funcname, &cobj); +#else + cobj = PyDict_GetItemString(d, funcname); + Py_XINCREF(cobj); +#endif + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + Py_DECREF(cobj); + return 0; +bad: + Py_XDECREF(d); + Py_XDECREF(cobj); + return -1; +} +#endif + +/* NewCodeObj */ +#if CYTHON_COMPILING_IN_LIMITED_API + static PyObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyObject *exception_table = NULL; + PyObject *types_module=NULL, *code_type=NULL, *result=NULL; + #if __PYX_LIMITED_VERSION_HEX < 0x030b0000 + PyObject *version_info; + PyObject *py_minor_version = NULL; + #endif + long minor_version = 0; + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + #if __PYX_LIMITED_VERSION_HEX >= 0x030b0000 + minor_version = 11; + #else + if (!(version_info = PySys_GetObject("version_info"))) goto end; + if (!(py_minor_version = PySequence_GetItem(version_info, 1))) goto end; + minor_version = PyLong_AsLong(py_minor_version); + Py_DECREF(py_minor_version); + if (minor_version == -1 && PyErr_Occurred()) goto end; + #endif + if (!(types_module = PyImport_ImportModule("types"))) goto end; + if (!(code_type = PyObject_GetAttrString(types_module, "CodeType"))) goto end; + if (minor_version <= 7) { + (void)p; + result = PyObject_CallFunction(code_type, "iiiiiOOOOOOiOOO", a, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else if (minor_version <= 10) { + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOiOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, fline, lnos, fv, cell); + } else { + if (!(exception_table = PyBytes_FromStringAndSize(NULL, 0))) goto end; + result = PyObject_CallFunction(code_type, "iiiiiiOOOOOOOiOOOO", a,p, k, l, s, f, code, + c, n, v, fn, name, name, fline, lnos, exception_table, fv, cell); + } + end: + Py_XDECREF(code_type); + Py_XDECREF(exception_table); + Py_XDECREF(types_module); + if (type) { + PyErr_Restore(type, value, traceback); + } + return result; + } +#elif PY_VERSION_HEX >= 0x030B0000 + static PyCodeObject* __Pyx__PyCode_New(int a, int p, int k, int l, int s, int f, + PyObject *code, PyObject *c, PyObject* n, PyObject *v, + PyObject *fv, PyObject *cell, PyObject* fn, + PyObject *name, int fline, PyObject *lnos) { + PyCodeObject *result; + result = + #if PY_VERSION_HEX >= 0x030C0000 + PyUnstable_Code_NewWithPosOnlyArgs + #else + PyCode_NewWithPosOnlyArgs + #endif + (a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, name, fline, lnos, __pyx_mstate_global->__pyx_empty_bytes); + return result; + } +#elif PY_VERSION_HEX >= 0x030800B2 && !CYTHON_COMPILING_IN_PYPY + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_NewWithPosOnlyArgs(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#else + #define __Pyx__PyCode_New(a, p, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ + PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) +#endif +static PyObject* __Pyx_PyCode_New( + const __Pyx_PyCode_New_function_description descr, + PyObject * const *varnames, + PyObject *filename, + PyObject *funcname, + const char *line_table, + PyObject *tuple_dedup_map +) { + PyObject *code_obj = NULL, *varnames_tuple_dedup = NULL, *code_bytes = NULL, *line_table_bytes = NULL; + Py_ssize_t var_count = (Py_ssize_t) descr.nlocals; + PyObject *varnames_tuple = PyTuple_New(var_count); + if (unlikely(!varnames_tuple)) return NULL; + for (Py_ssize_t i=0; i < var_count; i++) { + Py_INCREF(varnames[i]); + if (__Pyx_PyTuple_SET_ITEM(varnames_tuple, i, varnames[i]) != (0)) goto done; + } + #if CYTHON_COMPILING_IN_LIMITED_API + varnames_tuple_dedup = PyDict_GetItem(tuple_dedup_map, varnames_tuple); + if (!varnames_tuple_dedup) { + if (unlikely(PyDict_SetItem(tuple_dedup_map, varnames_tuple, varnames_tuple) < 0)) goto done; + varnames_tuple_dedup = varnames_tuple; + } + #else + varnames_tuple_dedup = PyDict_SetDefault(tuple_dedup_map, varnames_tuple, varnames_tuple); + if (unlikely(!varnames_tuple_dedup)) goto done; + #endif + #if CYTHON_AVOID_BORROWED_REFS + Py_INCREF(varnames_tuple_dedup); + #endif + if (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table != NULL + && !CYTHON_COMPILING_IN_GRAAL) { + line_table_bytes = PyBytes_FromStringAndSize(line_table, descr.line_table_length); + if (unlikely(!line_table_bytes)) goto done; + Py_ssize_t code_len = (descr.line_table_length * 2 + 4) & ~3; + code_bytes = PyBytes_FromStringAndSize(NULL, code_len); + if (unlikely(!code_bytes)) goto done; + char* c_code_bytes = PyBytes_AsString(code_bytes); + if (unlikely(!c_code_bytes)) goto done; + memset(c_code_bytes, 0, (size_t) code_len); + } + code_obj = (PyObject*) __Pyx__PyCode_New( + (int) descr.argcount, + (int) descr.num_posonly_args, + (int) descr.num_kwonly_args, + (int) descr.nlocals, + 0, + (int) descr.flags, + code_bytes ? code_bytes : __pyx_mstate_global->__pyx_empty_bytes, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + varnames_tuple_dedup, + __pyx_mstate_global->__pyx_empty_tuple, + __pyx_mstate_global->__pyx_empty_tuple, + filename, + funcname, + (int) descr.first_line, + (__PYX_LIMITED_VERSION_HEX >= (0x030b0000) && line_table_bytes) ? line_table_bytes : __pyx_mstate_global->__pyx_empty_bytes + ); +done: + Py_XDECREF(code_bytes); + Py_XDECREF(line_table_bytes); + #if CYTHON_AVOID_BORROWED_REFS + Py_XDECREF(varnames_tuple_dedup); + #endif + Py_DECREF(varnames_tuple); + return code_obj; +} + +/* InitStrings */ +static int __Pyx_InitStrings(__Pyx_StringTabEntry const *t, PyObject **target, const char* const* encoding_names) { + while (t->s) { + PyObject *str; + if (t->is_unicode) { + if (t->intern) { + str = PyUnicode_InternFromString(t->s); + } else if (t->encoding) { + str = PyUnicode_Decode(t->s, t->n - 1, encoding_names[t->encoding], NULL); + } else { + str = PyUnicode_FromStringAndSize(t->s, t->n - 1); + } + } else { + str = PyBytes_FromStringAndSize(t->s, t->n - 1); + } + if (!str) + return -1; + *target = str; + if (PyObject_Hash(str) == -1) + return -1; + ++t; + ++target; + } + return 0; +} + +#include +static CYTHON_INLINE Py_ssize_t __Pyx_ssize_strlen(const char *s) { + size_t len = strlen(s); + if (unlikely(len > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, "byte string is too long"); + return -1; + } + return (Py_ssize_t) len; +} +static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return __Pyx_PyUnicode_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE PyObject* __Pyx_PyByteArray_FromString(const char* c_str) { + Py_ssize_t len = __Pyx_ssize_strlen(c_str); + if (unlikely(len < 0)) return NULL; + return PyByteArray_FromStringAndSize(c_str, len); +} +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { + Py_ssize_t ignore; + return __Pyx_PyObject_AsStringAndSize(o, &ignore); +} +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; +#if CYTHON_COMPILING_IN_LIMITED_API + { + const char* result; + Py_ssize_t unicode_length; + CYTHON_MAYBE_UNUSED_VAR(unicode_length); // only for __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + #if __PYX_LIMITED_VERSION_HEX < 0x030A0000 + if (unlikely(PyArg_Parse(o, "s#", &result, length) < 0)) return NULL; + #else + result = PyUnicode_AsUTF8AndSize(o, length); + #endif + #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + unicode_length = PyUnicode_GetLength(o); + if (unlikely(unicode_length < 0)) return NULL; + if (unlikely(unicode_length != *length)) { + PyUnicode_AsASCIIString(o); + return NULL; + } + #endif + return result; + } +#else +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } +#else + return PyUnicode_AsUTF8AndSize(o, length); +#endif +#endif +} +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 + if (PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); + } else +#endif + if (PyByteArray_Check(o)) { +#if (CYTHON_ASSUME_SAFE_SIZE && CYTHON_ASSUME_SAFE_MACROS) || (CYTHON_COMPILING_IN_PYPY && (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE))) + *length = PyByteArray_GET_SIZE(o); + return PyByteArray_AS_STRING(o); +#else + *length = PyByteArray_Size(o); + if (*length == -1) return NULL; + return PyByteArray_AsString(o); +#endif + } else + { + char* result; + int r = PyBytes_AsStringAndSize(o, &result, length); + if (unlikely(r < 0)) { + return NULL; + } else { + return result; + } + } +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { + int is_true = x == Py_True; + if (is_true | (x == Py_False) | (x == Py_None)) return is_true; + else return PyObject_IsTrue(x); +} +static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { + int retval; + if (unlikely(!x)) return -1; + retval = __Pyx_PyObject_IsTrue(x); + Py_DECREF(x); + return retval; +} +static PyObject* __Pyx_PyNumber_LongWrongResultType(PyObject* result) { + __Pyx_TypeName result_type_name = __Pyx_PyType_GetFullyQualifiedName(Py_TYPE(result)); + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME "). " + "The ability to return an instance of a strict subclass of int is deprecated, " + "and may be removed in a future version of Python.", + result_type_name)) { + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; + } + __Pyx_DECREF_TypeName(result_type_name); + return result; + } + PyErr_Format(PyExc_TypeError, + "__int__ returned non-int (type " __Pyx_FMT_TYPENAME ")", + result_type_name); + __Pyx_DECREF_TypeName(result_type_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_Long(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS + PyNumberMethods *m; +#endif + PyObject *res = NULL; + if (likely(PyLong_Check(x))) + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS + m = Py_TYPE(x)->tp_as_number; + if (likely(m && m->nb_int)) { + res = m->nb_int(x); + } +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Long(x); + } +#endif + if (likely(res)) { + if (unlikely(!PyLong_CheckExact(res))) { + return __Pyx_PyNumber_LongWrongResultType(res); + } + } + else if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_TypeError, + "an integer is required"); + } + return res; +} +static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { + Py_ssize_t ival; + PyObject *x; + if (likely(PyLong_CheckExact(b))) { + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(__Pyx_PyLong_IsCompact(b))) { + return __Pyx_PyLong_CompactValue(b); + } else { + const digit* digits = __Pyx_PyLong_Digits(b); + const Py_ssize_t size = __Pyx_PyLong_SignedDigitCount(b); + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } + #endif + return PyLong_AsSsize_t(b); + } + x = PyNumber_Index(b); + if (!x) return -1; + ival = PyLong_AsSsize_t(x); + Py_DECREF(x); + return ival; +} +static CYTHON_INLINE Py_hash_t __Pyx_PyIndex_AsHash_t(PyObject* o) { + if (sizeof(Py_hash_t) == sizeof(Py_ssize_t)) { + return (Py_hash_t) __Pyx_PyIndex_AsSsize_t(o); + } else { + Py_ssize_t ival; + PyObject *x; + x = PyNumber_Index(o); + if (!x) return -1; + ival = PyLong_AsLong(x); + Py_DECREF(x); + return ival; + } +} +static CYTHON_INLINE PyObject *__Pyx_Owned_Py_None(int b) { + CYTHON_UNUSED_VAR(b); + return __Pyx_NewRef(Py_None); +} +static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { + return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); +} +static CYTHON_INLINE PyObject * __Pyx_PyLong_FromSize_t(size_t ival) { + return PyLong_FromSize_t(ival); +} + + +/* MultiPhaseInitModuleState */ +#if CYTHON_PEP489_MULTI_PHASE_INIT && CYTHON_USE_MODULE_STATE +#ifndef CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#if (CYTHON_COMPILING_IN_LIMITED_API || PY_VERSION_HEX >= 0x030C0000) + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 1 +#else + #define CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE 0 +#endif +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE && !CYTHON_ATOMICS +#error "Module state with PEP489 requires atomics. Currently that's one of\ + C11, C++11, gcc atomic intrinsics or MSVC atomic intrinsics" +#endif +#if !CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +#define __Pyx_ModuleStateLookup_Lock() +#define __Pyx_ModuleStateLookup_Unlock() +#elif !CYTHON_COMPILING_IN_LIMITED_API && PY_VERSION_HEX >= 0x030d0000 +static PyMutex __Pyx_ModuleStateLookup_mutex = {0}; +#define __Pyx_ModuleStateLookup_Lock() PyMutex_Lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() PyMutex_Unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#include +static std::mutex __Pyx_ModuleStateLookup_mutex; +#define __Pyx_ModuleStateLookup_Lock() __Pyx_ModuleStateLookup_mutex.lock() +#define __Pyx_ModuleStateLookup_Unlock() __Pyx_ModuleStateLookup_mutex.unlock() +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201112L) && !defined(__STDC_NO_THREADS__) +#include +static mtx_t __Pyx_ModuleStateLookup_mutex; +static once_flag __Pyx_ModuleStateLookup_mutex_once_flag = ONCE_FLAG_INIT; +static void __Pyx_ModuleStateLookup_initialize_mutex(void) { + mtx_init(&__Pyx_ModuleStateLookup_mutex, mtx_plain); +} +#define __Pyx_ModuleStateLookup_Lock()\ + call_once(&__Pyx_ModuleStateLookup_mutex_once_flag, __Pyx_ModuleStateLookup_initialize_mutex);\ + mtx_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() mtx_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(HAVE_PTHREAD_H) +#include +static pthread_mutex_t __Pyx_ModuleStateLookup_mutex = PTHREAD_MUTEX_INITIALIZER; +#define __Pyx_ModuleStateLookup_Lock() pthread_mutex_lock(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() pthread_mutex_unlock(&__Pyx_ModuleStateLookup_mutex) +#elif defined(_WIN32) +#include // synchapi.h on its own doesn't work +static SRWLOCK __Pyx_ModuleStateLookup_mutex = SRWLOCK_INIT; +#define __Pyx_ModuleStateLookup_Lock() AcquireSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#define __Pyx_ModuleStateLookup_Unlock() ReleaseSRWLockExclusive(&__Pyx_ModuleStateLookup_mutex) +#else +#error "No suitable lock available for CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE.\ + Requires C standard >= C11, or C++ standard >= C++11,\ + or pthreads, or the Windows 32 API, or Python >= 3.13." +#endif +typedef struct { + int64_t id; + PyObject *module; +} __Pyx_InterpreterIdAndModule; +typedef struct { + char interpreter_id_as_index; + Py_ssize_t count; + Py_ssize_t allocated; + __Pyx_InterpreterIdAndModule table[1]; +} __Pyx_ModuleStateLookupData; +#define __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE 32 +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_int_type __Pyx_ModuleStateLookup_read_counter = 0; +#endif +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static __pyx_atomic_ptr_type __Pyx_ModuleStateLookup_data = 0; +#else +static __Pyx_ModuleStateLookupData* __Pyx_ModuleStateLookup_data = NULL; +#endif +static __Pyx_InterpreterIdAndModule* __Pyx_State_FindModuleStateLookupTableLowerBound( + __Pyx_InterpreterIdAndModule* table, + Py_ssize_t count, + int64_t interpreterId) { + __Pyx_InterpreterIdAndModule* begin = table; + __Pyx_InterpreterIdAndModule* end = begin + count; + if (begin->id == interpreterId) { + return begin; + } + while ((end - begin) > __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + __Pyx_InterpreterIdAndModule* halfway = begin + (end - begin)/2; + if (halfway->id == interpreterId) { + return halfway; + } + if (halfway->id < interpreterId) { + begin = halfway; + } else { + end = halfway; + } + } + for (; begin < end; ++begin) { + if (begin->id >= interpreterId) return begin; + } + return begin; +} +static PyObject *__Pyx_State_FindModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return NULL; +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData* data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + { + __pyx_atomic_incr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + if (likely(data)) { + __Pyx_ModuleStateLookupData* new_data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_acquire(&__Pyx_ModuleStateLookup_data); + if (likely(data == new_data)) { + goto read_finished; + } + } + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); + __Pyx_ModuleStateLookup_Lock(); + __pyx_atomic_incr_relaxed(&__Pyx_ModuleStateLookup_read_counter); + data = (__Pyx_ModuleStateLookupData*)__pyx_atomic_pointer_load_relaxed(&__Pyx_ModuleStateLookup_data); + __Pyx_ModuleStateLookup_Unlock(); + } + read_finished:; +#else + __Pyx_ModuleStateLookupData* data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_InterpreterIdAndModule* found = NULL; + if (unlikely(!data)) goto end; + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + found = data->table+interpreter_id; + } + } else { + found = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + } + end: + { + PyObject *result=NULL; + if (found && found->id == interpreter_id) { + result = found->module; + } +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_decr_acq_rel(&__Pyx_ModuleStateLookup_read_counter); +#endif + return result; + } +} +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE +static void __Pyx_ModuleStateLookup_wait_until_no_readers(void) { + while (__pyx_atomic_load(&__Pyx_ModuleStateLookup_read_counter) != 0); +} +#else +#define __Pyx_ModuleStateLookup_wait_until_no_readers() +#endif +static int __Pyx_State_AddModuleInterpIdAsIndex(__Pyx_ModuleStateLookupData **old_data, PyObject* module, int64_t interpreter_id) { + Py_ssize_t to_allocate = (*old_data)->allocated; + while (to_allocate <= interpreter_id) { + if (to_allocate == 0) to_allocate = 1; + else to_allocate *= 2; + } + __Pyx_ModuleStateLookupData *new_data = *old_data; + if (to_allocate != (*old_data)->allocated) { + new_data = (__Pyx_ModuleStateLookupData *)realloc( + *old_data, + sizeof(__Pyx_ModuleStateLookupData)+(to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + PyErr_NoMemory(); + return -1; + } + for (Py_ssize_t i = new_data->allocated; i < to_allocate; ++i) { + new_data->table[i].id = i; + new_data->table[i].module = NULL; + } + new_data->allocated = to_allocate; + } + new_data->table[interpreter_id].module = module; + if (new_data->count < interpreter_id+1) { + new_data->count = interpreter_id+1; + } + *old_data = new_data; + return 0; +} +static void __Pyx_State_ConvertFromInterpIdAsIndex(__Pyx_ModuleStateLookupData *data) { + __Pyx_InterpreterIdAndModule *read = data->table; + __Pyx_InterpreterIdAndModule *write = data->table; + __Pyx_InterpreterIdAndModule *end = read + data->count; + for (; readmodule) { + write->id = read->id; + write->module = read->module; + ++write; + } + } + data->count = write - data->table; + for (; writeid = 0; + write->module = NULL; + } + data->interpreter_id_as_index = 0; +} +static int __Pyx_State_AddModule(PyObject* module, CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + int result = 0; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *old_data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *old_data = __Pyx_ModuleStateLookup_data; +#endif + __Pyx_ModuleStateLookupData *new_data = old_data; + if (!new_data) { + new_data = (__Pyx_ModuleStateLookupData *)calloc(1, sizeof(__Pyx_ModuleStateLookupData)); + if (!new_data) { + result = -1; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = 1; + new_data->interpreter_id_as_index = 1; + } + __Pyx_ModuleStateLookup_wait_until_no_readers(); + if (new_data->interpreter_id_as_index) { + if (interpreter_id < __PYX_MODULE_STATE_LOOKUP_SMALL_SIZE) { + result = __Pyx_State_AddModuleInterpIdAsIndex(&new_data, module, interpreter_id); + goto end; + } + __Pyx_State_ConvertFromInterpIdAsIndex(new_data); + } + { + Py_ssize_t insert_at = 0; + { + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + new_data->table, new_data->count, interpreter_id); + assert(lower_bound); + insert_at = lower_bound - new_data->table; + if (unlikely(insert_at < new_data->count && lower_bound->id == interpreter_id)) { + lower_bound->module = module; + goto end; // already in table, nothing more to do + } + } + if (new_data->count+1 >= new_data->allocated) { + Py_ssize_t to_allocate = (new_data->count+1)*2; + new_data = + (__Pyx_ModuleStateLookupData*)realloc( + new_data, + sizeof(__Pyx_ModuleStateLookupData) + + (to_allocate-1)*sizeof(__Pyx_InterpreterIdAndModule)); + if (!new_data) { + result = -1; + new_data = old_data; + PyErr_NoMemory(); + goto end; + } + new_data->allocated = to_allocate; + } + ++new_data->count; + int64_t last_id = interpreter_id; + PyObject *last_module = module; + for (Py_ssize_t i=insert_at; icount; ++i) { + int64_t current_id = new_data->table[i].id; + new_data->table[i].id = last_id; + last_id = current_id; + PyObject *current_module = new_data->table[i].module; + new_data->table[i].module = last_module; + last_module = current_module; + } + } + end: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, new_data); +#else + __Pyx_ModuleStateLookup_data = new_data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return result; +} +static int __Pyx_State_RemoveModule(CYTHON_UNUSED void* dummy) { + int64_t interpreter_id = PyInterpreterState_GetID(__Pyx_PyInterpreterState_Get()); + if (interpreter_id == -1) return -1; + __Pyx_ModuleStateLookup_Lock(); +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __Pyx_ModuleStateLookupData *data = (__Pyx_ModuleStateLookupData *) + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, 0); +#else + __Pyx_ModuleStateLookupData *data = __Pyx_ModuleStateLookup_data; +#endif + if (data->interpreter_id_as_index) { + if (interpreter_id < data->count) { + data->table[interpreter_id].module = NULL; + } + goto done; + } + { + __Pyx_ModuleStateLookup_wait_until_no_readers(); + __Pyx_InterpreterIdAndModule* lower_bound = __Pyx_State_FindModuleStateLookupTableLowerBound( + data->table, data->count, interpreter_id); + if (!lower_bound) goto done; + if (lower_bound->id != interpreter_id) goto done; + __Pyx_InterpreterIdAndModule *end = data->table+data->count; + for (;lower_boundid = (lower_bound+1)->id; + lower_bound->module = (lower_bound+1)->module; + } + } + --data->count; + if (data->count == 0) { + free(data); + data = NULL; + } + done: +#if CYTHON_MODULE_STATE_LOOKUP_THREAD_SAFE + __pyx_atomic_pointer_exchange(&__Pyx_ModuleStateLookup_data, data); +#else + __Pyx_ModuleStateLookup_data = data; +#endif + __Pyx_ModuleStateLookup_Unlock(); + return 0; +} +#endif + +/* #### Code section: utility_code_pragmas_end ### */ +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + + + +/* #### Code section: end ### */ +#endif /* Py_PYTHON_H */ diff --git a/shared/package-files/4a/4a1ab3f3bb39a9f6d775bf63c0cffe2e19976617d057c5c06d62497c369be371/config.c b/shared/package-files/4a/4a1ab3f3bb39a9f6d775bf63c0cffe2e19976617d057c5c06d62497c369be371/config.c new file mode 100644 index 0000000000000000000000000000000000000000..dd542ba8d392353d7ede0835f64e46627be5a8dd --- /dev/null +++ b/shared/package-files/4a/4a1ab3f3bb39a9f6d775bf63c0cffe2e19976617d057c5c06d62497c369be371/config.c @@ -0,0 +1,118 @@ +/* Generated automatically from /home/conda/feedstock_root/build_artifacts/python-split_1749047345446/work/Modules/config.c.in by makesetup. */ +/* -*- C -*- *********************************************** +Copyright (c) 2000, BeOpen.com. +Copyright (c) 1995-2000, Corporation for National Research Initiatives. +Copyright (c) 1990-1995, Stichting Mathematisch Centrum. +All rights reserved. + +See the file "Misc/COPYRIGHT" for information on usage and +redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. +******************************************************************/ + +/* Module configuration */ + +/* !!! !!! !!! This file is edited by the makesetup script !!! !!! !!! */ + +/* This file contains the table of built-in modules. + See create_builtin() in import.c. */ + +#include "Python.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +extern PyObject* PyInit_atexit(void); +extern PyObject* PyInit_faulthandler(void); +extern PyObject* PyInit_posix(void); +extern PyObject* PyInit__signal(void); +extern PyObject* PyInit__tracemalloc(void); +extern PyObject* PyInit__codecs(void); +extern PyObject* PyInit__collections(void); +extern PyObject* PyInit_errno(void); +extern PyObject* PyInit__io(void); +extern PyObject* PyInit_itertools(void); +extern PyObject* PyInit__sre(void); +extern PyObject* PyInit__thread(void); +extern PyObject* PyInit_time(void); +extern PyObject* PyInit__weakref(void); +extern PyObject* PyInit__abc(void); +extern PyObject* PyInit__functools(void); +extern PyObject* PyInit__locale(void); +extern PyObject* PyInit__operator(void); +extern PyObject* PyInit__stat(void); +extern PyObject* PyInit__symtable(void); +extern PyObject* PyInit_pwd(void); +extern PyObject* PyInit_xxsubtype(void); + +/* -- ADDMODULE MARKER 1 -- */ + +extern PyObject* PyMarshal_Init(void); +extern PyObject* PyInit__imp(void); +extern PyObject* PyInit_gc(void); +extern PyObject* PyInit__ast(void); +extern PyObject* PyInit__tokenize(void); +extern PyObject* _PyWarnings_Init(void); +extern PyObject* PyInit__string(void); + +struct _inittab _PyImport_Inittab[] = { + + {"atexit", PyInit_atexit}, + {"faulthandler", PyInit_faulthandler}, + {"posix", PyInit_posix}, + {"_signal", PyInit__signal}, + {"_tracemalloc", PyInit__tracemalloc}, + {"_codecs", PyInit__codecs}, + {"_collections", PyInit__collections}, + {"errno", PyInit_errno}, + {"_io", PyInit__io}, + {"itertools", PyInit_itertools}, + {"_sre", PyInit__sre}, + {"_thread", PyInit__thread}, + {"time", PyInit_time}, + {"_weakref", PyInit__weakref}, + {"_abc", PyInit__abc}, + {"_functools", PyInit__functools}, + {"_locale", PyInit__locale}, + {"_operator", PyInit__operator}, + {"_stat", PyInit__stat}, + {"_symtable", PyInit__symtable}, + {"pwd", PyInit_pwd}, + {"xxsubtype", PyInit_xxsubtype}, + +/* -- ADDMODULE MARKER 2 -- */ + + /* This module lives in marshal.c */ + {"marshal", PyMarshal_Init}, + + /* This lives in import.c */ + {"_imp", PyInit__imp}, + + /* This lives in Python/Python-ast.c */ + {"_ast", PyInit__ast}, + + /* This lives in Python/Python-tokenizer.c */ + {"_tokenize", PyInit__tokenize}, + + /* These entries are here for sys.builtin_module_names */ + {"builtins", NULL}, + {"sys", NULL}, + + /* This lives in gcmodule.c */ + {"gc", PyInit_gc}, + + /* This lives in _warnings.c */ + {"_warnings", _PyWarnings_Init}, + + /* This lives in Objects/unicodeobject.c */ + {"_string", PyInit__string}, + + /* Sentinel */ + {0, 0} +}; + + +#ifdef __cplusplus +} +#endif diff --git a/shared/package-files/4a/4a1dcb213c621d85df513785625029839ebc4246e709823edc1dc6457a67c043/special_gammaln.h b/shared/package-files/4a/4a1dcb213c621d85df513785625029839ebc4246e709823edc1dc6457a67c043/special_gammaln.h new file mode 100644 index 0000000000000000000000000000000000000000..fec342a6e1afaf6add394e5c7ddc6821a5187f11 --- /dev/null +++ b/shared/package-files/4a/4a1dcb213c621d85df513785625029839ebc4246e709823edc1dc6457a67c043/special_gammaln.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_gammaln(Tensor self) -> Tensor +inline at::Tensor special_gammaln(const at::Tensor & self) { + return at::_ops::special_gammaln::call(self); +} + +// aten::special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_gammaln_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_gammaln_out::call(self, out); +} +// aten::special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_gammaln_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_gammaln_out::call(self, out); +} + +} diff --git a/shared/package-files/4a/4a1f86f8e77d0d7717487c161dd897b595c13ccc7a96ab1975873a9116f0770e/fbgemm_pack_gemm_matrix_fp16_ops.h b/shared/package-files/4a/4a1f86f8e77d0d7717487c161dd897b595c13ccc7a96ab1975873a9116f0770e/fbgemm_pack_gemm_matrix_fp16_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0f77841d677e8d691c5601c514481fcb1879f086 --- /dev/null +++ b/shared/package-files/4a/4a1f86f8e77d0d7717487c161dd897b595c13ccc7a96ab1975873a9116f0770e/fbgemm_pack_gemm_matrix_fp16_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API fbgemm_pack_gemm_matrix_fp16 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::fbgemm_pack_gemm_matrix_fp16"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor"; + static at::Tensor call(const at::Tensor & input); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4a/4a2b3d6d9bf0722536fc1673af7182bd72e405c5d55213fdc9ca86203bbdf715/meijerint_doc.py b/shared/package-files/4a/4a2b3d6d9bf0722536fc1673af7182bd72e405c5d55213fdc9ca86203bbdf715/meijerint_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..1df385db6b6fe6d46d4a14217aa53d1fdd9670b5 --- /dev/null +++ b/shared/package-files/4a/4a2b3d6d9bf0722536fc1673af7182bd72e405c5d55213fdc9ca86203bbdf715/meijerint_doc.py @@ -0,0 +1,38 @@ +""" This module cooks up a docstring when imported. Its only purpose is to + be displayed in the sphinx documentation. """ + +from __future__ import annotations +from typing import Any + +from sympy.integrals.meijerint import _create_lookup_table +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.relational import Eq +from sympy.core.symbol import Symbol +from sympy.printing.latex import latex + +t: dict[tuple[type[Basic], ...], list[Any]] = {} +_create_lookup_table(t) + + +doc = "" +for about, category in t.items(): + if about == (): + doc += 'Elementary functions:\n\n' + else: + doc += 'Functions involving ' + ', '.join('`%s`' % latex( + list(category[0][0].atoms(func))[0]) for func in about) + ':\n\n' + for formula, gs, cond, hint in category: + if not isinstance(gs, list): + g: Expr = Symbol('\\text{generated}') + else: + g = Add(*[fac*f for (fac, f) in gs]) + obj = Eq(formula, g) + if cond is True: + cond = "" + else: + cond = ',\\text{ if } %s' % latex(cond) + doc += ".. math::\n %s%s\n\n" % (latex(obj), cond) + +__doc__ = doc diff --git a/shared/package-files/4a/4a2e911473e7d10b4ca5205ba0a1727e4adc38c6214e2a26e685270c4a919cfd/hip_ostream_ops.h b/shared/package-files/4a/4a2e911473e7d10b4ca5205ba0a1727e4adc38c6214e2a26e685270c4a919cfd/hip_ostream_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..eba2592fa30584cdb0a50f5badb61c81c3f9ede2 --- /dev/null +++ b/shared/package-files/4a/4a2e911473e7d10b4ca5205ba0a1727e4adc38c6214e2a26e685270c4a919cfd/hip_ostream_ops.h @@ -0,0 +1,4515 @@ +// automatically generated +/* +Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. + +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. +*/ + +#ifndef INC_HIP_OSTREAM_OPS_H_ +#define INC_HIP_OSTREAM_OPS_H_ + +#include +#include +#include "roctracer.h" + +#ifdef __cplusplus +#include +#include +#include +#include + +namespace roctracer { +namespace hip_support { +static int HIP_depth_max = 1; +static int HIP_depth_max_cnt = 0; +static std::string HIP_structs_regex = ""; +// begin ostream ops for HIP +// basic ostream ops +namespace detail { + inline static void print_escaped_string(std::ostream& out, const char *v, size_t len) { + out << '"'; + for (size_t i = 0; i < len && v[i]; ++i) { + switch (v[i]) { + case '\"': out << "\\\""; break; + case '\\': out << "\\\\"; break; + case '\b': out << "\\\b"; break; + case '\f': out << "\\\f"; break; + case '\n': out << "\\\n"; break; + case '\r': out << "\\\r"; break; + case '\t': out << "\\\t"; break; + default: + if (std::isprint((unsigned char)v[i])) std::operator<<(out, v[i]); + else { + std::ios_base::fmtflags flags(out.flags()); + out << "\\x" << std::setfill('0') << std::setw(2) << std::hex << (unsigned int)(unsigned char)v[i]; + out.flags(flags); + } + break; + } + } + out << '"'; + } + + template + inline static std::ostream& operator<<(std::ostream& out, const T& v) { + using std::operator<<; + static bool recursion = false; + if (recursion == false) { recursion = true; out << v; recursion = false; } + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const unsigned char &v) { + out << (unsigned int)v; + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const char &v) { + out << (unsigned char)v; + return out; + } + + template + inline static std::ostream &operator<<(std::ostream &out, const char (&v)[N]) { + print_escaped_string(out, v, N); + return out; + } + + inline static std::ostream &operator<<(std::ostream &out, const char *v) { + print_escaped_string(out, v, strlen(v)); + return out; + } +// End of basic ostream ops + +inline static std::ostream& operator<<(std::ostream& out, const __locale_struct& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("__locale_struct::__names").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__names="); + roctracer::hip_support::detail::operator<<(out, v.__names); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_toupper").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_toupper="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_toupper); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_tolower").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_tolower="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_tolower); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__ctype_b").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__ctype_b="); + roctracer::hip_support::detail::operator<<(out, v.__ctype_b); + std::operator<<(out, ", "); + } + if (std::string("__locale_struct::__locales").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "__locales="); + roctracer::hip_support::detail::operator<<(out, v.__locales); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceArch_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceArch_t::hasDynamicParallelism").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasDynamicParallelism="); + roctracer::hip_support::detail::operator<<(out, v.hasDynamicParallelism); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::has3dGrid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "has3dGrid="); + roctracer::hip_support::detail::operator<<(out, v.has3dGrid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSurfaceFuncs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSurfaceFuncs="); + roctracer::hip_support::detail::operator<<(out, v.hasSurfaceFuncs); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSyncThreadsExt").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSyncThreadsExt="); + roctracer::hip_support::detail::operator<<(out, v.hasSyncThreadsExt); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasThreadFenceSystem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasThreadFenceSystem="); + roctracer::hip_support::detail::operator<<(out, v.hasThreadFenceSystem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasFunnelShift").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasFunnelShift="); + roctracer::hip_support::detail::operator<<(out, v.hasFunnelShift); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpShuffle").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpShuffle="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpShuffle); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpBallot").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpBallot="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpBallot); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasWarpVote").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasWarpVote="); + roctracer::hip_support::detail::operator<<(out, v.hasWarpVote); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasDoubles").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasDoubles="); + roctracer::hip_support::detail::operator<<(out, v.hasDoubles); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedInt64Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedInt64Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedInt64Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalInt64Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalInt64Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalInt64Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasFloatAtomicAdd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasFloatAtomicAdd="); + roctracer::hip_support::detail::operator<<(out, v.hasFloatAtomicAdd); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedFloatAtomicExch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedFloatAtomicExch="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedFloatAtomicExch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasSharedInt32Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasSharedInt32Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasSharedInt32Atomics); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalFloatAtomicExch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalFloatAtomicExch="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalFloatAtomicExch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceArch_t::hasGlobalInt32Atomics").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hasGlobalInt32Atomics="); + roctracer::hip_support::detail::operator<<(out, v.hasGlobalInt32Atomics); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipUUID& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipUUID::bytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "bytes="); + roctracer::hip_support::detail::operator<<(out, v.bytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0600& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceProp_tR0600::asicRevision").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asicRevision="); + roctracer::hip_support::detail::operator<<(out, v.asicRevision); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::isLargeBar").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isLargeBar="); + roctracer::hip_support::detail::operator<<(out, v.isLargeBar); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedSharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedSharedMem="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedSharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedBlockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedBlockDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedBlockDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedGridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedGridDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedGridDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceUnmatchedFunc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedFunc="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedFunc); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hdpRegFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpRegFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpRegFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hdpMemFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpMemFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpMemFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::arch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "arch="); + roctracer::hip_support::detail::operator<<(out, v.arch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clockInstructionRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockInstructionRate="); + roctracer::hip_support::detail::operator<<(out, v.clockInstructionRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSharedMemoryPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSharedMemoryPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxSharedMemoryPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gcnArchName").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArchName="); + roctracer::hip_support::detail::operator<<(out, v.gcnArchName); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hipReserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hipReserved="); + roctracer::hip_support::detail::operator<<(out, v.hipReserved); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::unifiedFunctionPointers").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "unifiedFunctionPointers="); + roctracer::hip_support::detail::operator<<(out, v.unifiedFunctionPointers); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clusterLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clusterLaunch="); + roctracer::hip_support::detail::operator<<(out, v.clusterLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::ipcEventSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ipcEventSupported="); + roctracer::hip_support::detail::operator<<(out, v.ipcEventSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::deferredMappingHipArraySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deferredMappingHipArraySupported="); + roctracer::hip_support::detail::operator<<(out, v.deferredMappingHipArraySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryPoolSupportedHandleTypes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryPoolSupportedHandleTypes="); + roctracer::hip_support::detail::operator<<(out, v.memoryPoolSupportedHandleTypes); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMAWritesOrdering").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMAWritesOrdering="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMAWritesOrdering); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMAFlushWritesOptions").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMAFlushWritesOptions="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMAFlushWritesOptions); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::gpuDirectRDMASupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gpuDirectRDMASupported="); + roctracer::hip_support::detail::operator<<(out, v.gpuDirectRDMASupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryPoolsSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryPoolsSupported="); + roctracer::hip_support::detail::operator<<(out, v.memoryPoolsSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::timelineSemaphoreInteropSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "timelineSemaphoreInteropSupported="); + roctracer::hip_support::detail::operator<<(out, v.timelineSemaphoreInteropSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostRegisterReadOnlySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostRegisterReadOnlySupported="); + roctracer::hip_support::detail::operator<<(out, v.hostRegisterReadOnlySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sparseHipArraySupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sparseHipArraySupported="); + roctracer::hip_support::detail::operator<<(out, v.sparseHipArraySupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostRegisterSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostRegisterSupported="); + roctracer::hip_support::detail::operator<<(out, v.hostRegisterSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::reservedSharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reservedSharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.reservedSharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::accessPolicyMaxWindowSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessPolicyMaxWindowSize="); + roctracer::hip_support::detail::operator<<(out, v.accessPolicyMaxWindowSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxBlocksPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxBlocksPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxBlocksPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::directManagedMemAccessFromHost").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "directManagedMemAccessFromHost="); + roctracer::hip_support::detail::operator<<(out, v.directManagedMemAccessFromHost); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pageableMemoryAccessUsesHostPageTables").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccessUsesHostPageTables="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccessUsesHostPageTables); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerBlockOptin").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlockOptin="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlockOptin); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeMultiDeviceLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::cooperativeLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::canUseHostPointerForRegisteredMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canUseHostPointerForRegisteredMem="); + roctracer::hip_support::detail::operator<<(out, v.canUseHostPointerForRegisteredMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::computePreemptionSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computePreemptionSupported="); + roctracer::hip_support::detail::operator<<(out, v.computePreemptionSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::concurrentManagedAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentManagedAccess="); + roctracer::hip_support::detail::operator<<(out, v.concurrentManagedAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pageableMemoryAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccess="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::singleToDoublePrecisionPerfRatio").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "singleToDoublePrecisionPerfRatio="); + roctracer::hip_support::detail::operator<<(out, v.singleToDoublePrecisionPerfRatio); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::hostNativeAtomicSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hostNativeAtomicSupported="); + roctracer::hip_support::detail::operator<<(out, v.hostNativeAtomicSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::multiGpuBoardGroupID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiGpuBoardGroupID="); + roctracer::hip_support::detail::operator<<(out, v.multiGpuBoardGroupID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::isMultiGpuBoard").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isMultiGpuBoard="); + roctracer::hip_support::detail::operator<<(out, v.isMultiGpuBoard); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::managedMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "managedMemory="); + roctracer::hip_support::detail::operator<<(out, v.managedMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::regsPerMultiprocessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerMultiprocessor="); + roctracer::hip_support::detail::operator<<(out, v.regsPerMultiprocessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerMultiprocessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerMultiprocessor="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerMultiprocessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::localL1CacheSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "localL1CacheSupported="); + roctracer::hip_support::detail::operator<<(out, v.localL1CacheSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::globalL1CacheSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "globalL1CacheSupported="); + roctracer::hip_support::detail::operator<<(out, v.globalL1CacheSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::streamPrioritiesSupported").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "streamPrioritiesSupported="); + roctracer::hip_support::detail::operator<<(out, v.streamPrioritiesSupported); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::persistingL2CacheMaxSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "persistingL2CacheMaxSize="); + roctracer::hip_support::detail::operator<<(out, v.persistingL2CacheMaxSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::l2CacheSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "l2CacheSize="); + roctracer::hip_support::detail::operator<<(out, v.l2CacheSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryBusWidth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryBusWidth="); + roctracer::hip_support::detail::operator<<(out, v.memoryBusWidth); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memoryClockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryClockRate="); + roctracer::hip_support::detail::operator<<(out, v.memoryClockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::unifiedAddressing").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "unifiedAddressing="); + roctracer::hip_support::detail::operator<<(out, v.unifiedAddressing); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::asyncEngineCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asyncEngineCount="); + roctracer::hip_support::detail::operator<<(out, v.asyncEngineCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::tccDriver").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "tccDriver="); + roctracer::hip_support::detail::operator<<(out, v.tccDriver); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciDomainID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDomainID="); + roctracer::hip_support::detail::operator<<(out, v.pciDomainID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciDeviceID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDeviceID="); + roctracer::hip_support::detail::operator<<(out, v.pciDeviceID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::pciBusID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciBusID="); + roctracer::hip_support::detail::operator<<(out, v.pciBusID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::ECCEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ECCEnabled="); + roctracer::hip_support::detail::operator<<(out, v.ECCEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::concurrentKernels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentKernels="); + roctracer::hip_support::detail::operator<<(out, v.concurrentKernels); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::surfaceAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "surfaceAlignment="); + roctracer::hip_support::detail::operator<<(out, v.surfaceAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurfaceCubemapLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurfaceCubemapLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurfaceCubemapLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurfaceCubemap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurfaceCubemap="); + roctracer::hip_support::detail::operator<<(out, v.maxSurfaceCubemap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface2DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface2DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface2DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface1DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface1DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface1DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface3D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface2D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxSurface1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSurface1D="); + roctracer::hip_support::detail::operator<<(out, v.maxSurface1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTextureCubemapLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTextureCubemapLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTextureCubemapLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DLayered").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLayered="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLayered); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTextureCubemap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTextureCubemap="); + roctracer::hip_support::detail::operator<<(out, v.maxTextureCubemap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture3DAlt").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3DAlt="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3DAlt); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DGather").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DGather="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DGather); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2DMipmap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2DMipmap="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2DMipmap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1DMipmap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DMipmap="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DMipmap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxTexture1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::computeMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computeMode="); + roctracer::hip_support::detail::operator<<(out, v.computeMode); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::canMapHostMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canMapHostMemory="); + roctracer::hip_support::detail::operator<<(out, v.canMapHostMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::integrated").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "integrated="); + roctracer::hip_support::detail::operator<<(out, v.integrated); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::kernelExecTimeoutEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kernelExecTimeoutEnabled="); + roctracer::hip_support::detail::operator<<(out, v.kernelExecTimeoutEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::multiProcessorCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiProcessorCount="); + roctracer::hip_support::detail::operator<<(out, v.multiProcessorCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::deviceOverlap").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deviceOverlap="); + roctracer::hip_support::detail::operator<<(out, v.deviceOverlap); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::texturePitchAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "texturePitchAlignment="); + roctracer::hip_support::detail::operator<<(out, v.texturePitchAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::textureAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureAlignment="); + roctracer::hip_support::detail::operator<<(out, v.textureAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::minor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minor="); + roctracer::hip_support::detail::operator<<(out, v.minor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::major").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "major="); + roctracer::hip_support::detail::operator<<(out, v.major); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::totalConstMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalConstMem="); + roctracer::hip_support::detail::operator<<(out, v.totalConstMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::clockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockRate="); + roctracer::hip_support::detail::operator<<(out, v.clockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxGridSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxGridSize="); + roctracer::hip_support::detail::operator<<(out, v.maxGridSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsDim="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::memPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memPitch="); + roctracer::hip_support::detail::operator<<(out, v.memPitch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::warpSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "warpSize="); + roctracer::hip_support::detail::operator<<(out, v.warpSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::regsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.regsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::sharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::totalGlobalMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalGlobalMem="); + roctracer::hip_support::detail::operator<<(out, v.totalGlobalMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::luidDeviceNodeMask").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "luidDeviceNodeMask="); + roctracer::hip_support::detail::operator<<(out, v.luidDeviceNodeMask); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::luid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "luid="); + roctracer::hip_support::detail::operator<<(out, v.luid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::uuid").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "uuid="); + roctracer::hip_support::detail::operator<<(out, v.uuid); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0600::name").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "name="); + roctracer::hip_support::detail::operator<<(out, v.name); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPointerAttribute_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPointerAttribute_t::allocationFlags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "allocationFlags="); + roctracer::hip_support::detail::operator<<(out, v.allocationFlags); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::isManaged").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isManaged="); + roctracer::hip_support::detail::operator<<(out, v.isManaged); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::device").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "device="); + roctracer::hip_support::detail::operator<<(out, v.device); + std::operator<<(out, ", "); + } + if (std::string("hipPointerAttribute_t::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipChannelFormatDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipChannelFormatDesc::f").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "f="); + roctracer::hip_support::detail::operator<<(out, v.f); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("hipChannelFormatDesc::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY_DESCRIPTOR& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_ARRAY_DESCRIPTOR::NumChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "NumChannels="); + roctracer::hip_support::detail::operator<<(out, v.NumChannels); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Format="); + roctracer::hip_support::detail::operator<<(out, v.Format); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY_DESCRIPTOR::Width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Width="); + roctracer::hip_support::detail::operator<<(out, v.Width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY3D_DESCRIPTOR& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Flags="); + roctracer::hip_support::detail::operator<<(out, v.Flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::NumChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "NumChannels="); + roctracer::hip_support::detail::operator<<(out, v.NumChannels); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Format="); + roctracer::hip_support::detail::operator<<(out, v.Format); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Depth="); + roctracer::hip_support::detail::operator<<(out, v.Depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_ARRAY3D_DESCRIPTOR::Width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Width="); + roctracer::hip_support::detail::operator<<(out, v.Width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hip_Memcpy2D& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hip_Memcpy2D::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::WidthInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "WidthInBytes="); + roctracer::hip_support::detail::operator<<(out, v.WidthInBytes); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPitch="); + roctracer::hip_support::detail::operator<<(out, v.dstPitch); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstDevice="); + roctracer::hip_support::detail::operator<<(out, v.dstDevice); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.dstMemoryType); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstY="); + roctracer::hip_support::detail::operator<<(out, v.dstY); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::dstXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.dstXInBytes); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPitch="); + roctracer::hip_support::detail::operator<<(out, v.srcPitch); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcDevice="); + roctracer::hip_support::detail::operator<<(out, v.srcDevice); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.srcMemoryType); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcY="); + roctracer::hip_support::detail::operator<<(out, v.srcY); + std::operator<<(out, ", "); + } + if (std::string("hip_Memcpy2D::srcXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.srcXInBytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMipmappedArray& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMipmappedArray::num_channels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "num_channels="); + roctracer::hip_support::detail::operator<<(out, v.num_channels); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::max_mipmap_level").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "max_mipmap_level="); + roctracer::hip_support::detail::operator<<(out, v.max_mipmap_level); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::min_mipmap_level").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "min_mipmap_level="); + roctracer::hip_support::detail::operator<<(out, v.min_mipmap_level); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + std::operator<<(out, ", "); + } + if (std::string("hipMipmappedArray::desc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "desc="); + roctracer::hip_support::detail::operator<<(out, v.desc); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_TEXTURE_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_TEXTURE_DESC::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::borderColor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "borderColor="); + roctracer::hip_support::detail::operator<<(out, v.borderColor); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + std::operator<<(out, ", "); + } + if (std::string("HIP_TEXTURE_DESC::addressMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "addressMode="); + roctracer::hip_support::detail::operator<<(out, v.addressMode); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipResourceDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipResourceDesc::resType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resType="); + roctracer::hip_support::detail::operator<<(out, v.resType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_RESOURCE_DESC::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_DESC::resType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resType="); + roctracer::hip_support::detail::operator<<(out, v.resType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipResourceViewDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipResourceViewDesc::lastLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastLayer="); + roctracer::hip_support::detail::operator<<(out, v.lastLayer); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::firstLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstLayer="); + roctracer::hip_support::detail::operator<<(out, v.firstLayer); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::lastMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.lastMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::firstMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.firstMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipResourceViewDesc::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_VIEW_DESC& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_RESOURCE_VIEW_DESC::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::lastLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastLayer="); + roctracer::hip_support::detail::operator<<(out, v.lastLayer); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::firstLayer").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstLayer="); + roctracer::hip_support::detail::operator<<(out, v.firstLayer); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::lastMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "lastMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.lastMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::firstMipmapLevel").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "firstMipmapLevel="); + roctracer::hip_support::detail::operator<<(out, v.firstMipmapLevel); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("HIP_RESOURCE_VIEW_DESC::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPitchedPtr& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPitchedPtr::ysize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ysize="); + roctracer::hip_support::detail::operator<<(out, v.ysize); + std::operator<<(out, ", "); + } + if (std::string("hipPitchedPtr::xsize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "xsize="); + roctracer::hip_support::detail::operator<<(out, v.xsize); + std::operator<<(out, ", "); + } + if (std::string("hipPitchedPtr::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExtent& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExtent::depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "depth="); + roctracer::hip_support::detail::operator<<(out, v.depth); + std::operator<<(out, ", "); + } + if (std::string("hipExtent::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipExtent::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipPos& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipPos::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("hipPos::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("hipPos::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpy3DParms& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemcpy3DParms::kind").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kind="); + roctracer::hip_support::detail::operator<<(out, v.kind); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::extent").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extent="); + roctracer::hip_support::detail::operator<<(out, v.extent); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstPtr").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPtr="); + roctracer::hip_support::detail::operator<<(out, v.dstPtr); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstPos").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPos="); + roctracer::hip_support::detail::operator<<(out, v.dstPos); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcPtr").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPtr="); + roctracer::hip_support::detail::operator<<(out, v.srcPtr); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcPos").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPos="); + roctracer::hip_support::detail::operator<<(out, v.srcPos); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpy3DParms::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMCPY3D& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_MEMCPY3D::Depth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Depth="); + roctracer::hip_support::detail::operator<<(out, v.Depth); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::Height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "Height="); + roctracer::hip_support::detail::operator<<(out, v.Height); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::WidthInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "WidthInBytes="); + roctracer::hip_support::detail::operator<<(out, v.WidthInBytes); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstHeight").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstHeight="); + roctracer::hip_support::detail::operator<<(out, v.dstHeight); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstPitch="); + roctracer::hip_support::detail::operator<<(out, v.dstPitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstArray="); + roctracer::hip_support::detail::operator<<(out, v.dstArray); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstDevice="); + roctracer::hip_support::detail::operator<<(out, v.dstDevice); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.dstMemoryType); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstLOD").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstLOD="); + roctracer::hip_support::detail::operator<<(out, v.dstLOD); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstZ="); + roctracer::hip_support::detail::operator<<(out, v.dstZ); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstY="); + roctracer::hip_support::detail::operator<<(out, v.dstY); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::dstXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dstXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.dstXInBytes); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcHeight").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcHeight="); + roctracer::hip_support::detail::operator<<(out, v.srcHeight); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcPitch="); + roctracer::hip_support::detail::operator<<(out, v.srcPitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcArray="); + roctracer::hip_support::detail::operator<<(out, v.srcArray); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcDevice").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcDevice="); + roctracer::hip_support::detail::operator<<(out, v.srcDevice); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcMemoryType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcMemoryType="); + roctracer::hip_support::detail::operator<<(out, v.srcMemoryType); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcLOD").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcLOD="); + roctracer::hip_support::detail::operator<<(out, v.srcLOD); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcZ="); + roctracer::hip_support::detail::operator<<(out, v.srcZ); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcY="); + roctracer::hip_support::detail::operator<<(out, v.srcY); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMCPY3D::srcXInBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "srcXInBytes="); + roctracer::hip_support::detail::operator<<(out, v.srcXInBytes); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uchar3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uchar4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uchar4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("uchar4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uchar4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uchar4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("char3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const char4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("char4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("char4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("char4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("char4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ushort3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ushort4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ushort4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ushort4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ushort4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ushort4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("short3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const short4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("short4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("short4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("short4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("short4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uint3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const uint4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("uint4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("uint4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("uint4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("uint4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("int3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const int4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("int4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("int4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("int4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("int4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ulong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("long3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const long4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("long4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("long4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("long4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("long4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulonglong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const ulonglong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("ulonglong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("ulonglong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("longlong3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const longlong4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("longlong4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("longlong4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("longlong4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("longlong4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("float3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const float4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("float4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("float4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("float4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("float4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double1& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double1::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double2& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double2::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double2::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("double3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const double4& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("double4::w").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "w="); + roctracer::hip_support::detail::operator<<(out, v.w); + std::operator<<(out, ", "); + } + if (std::string("double4::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("double4::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("double4::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const textureReference& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("textureReference::format").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "format="); + roctracer::hip_support::detail::operator<<(out, v.format); + std::operator<<(out, ", "); + } + if (std::string("textureReference::numChannels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numChannels="); + roctracer::hip_support::detail::operator<<(out, v.numChannels); + std::operator<<(out, ", "); + } + if (std::string("textureReference::textureObject").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureObject="); + roctracer::hip_support::detail::operator<<(out, v.textureObject); + std::operator<<(out, ", "); + } + if (std::string("textureReference::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("textureReference::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("textureReference::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("textureReference::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("textureReference::sRGB").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sRGB="); + roctracer::hip_support::detail::operator<<(out, v.sRGB); + std::operator<<(out, ", "); + } + if (std::string("textureReference::channelDesc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "channelDesc="); + roctracer::hip_support::detail::operator<<(out, v.channelDesc); + std::operator<<(out, ", "); + } + if (std::string("textureReference::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::readMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "readMode="); + roctracer::hip_support::detail::operator<<(out, v.readMode); + std::operator<<(out, ", "); + } + if (std::string("textureReference::normalized").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "normalized="); + roctracer::hip_support::detail::operator<<(out, v.normalized); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipTextureDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipTextureDesc::maxMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.maxMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::minMipmapLevelClamp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minMipmapLevelClamp="); + roctracer::hip_support::detail::operator<<(out, v.minMipmapLevelClamp); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::mipmapLevelBias").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapLevelBias="); + roctracer::hip_support::detail::operator<<(out, v.mipmapLevelBias); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::mipmapFilterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "mipmapFilterMode="); + roctracer::hip_support::detail::operator<<(out, v.mipmapFilterMode); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::maxAnisotropy").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxAnisotropy="); + roctracer::hip_support::detail::operator<<(out, v.maxAnisotropy); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::normalizedCoords").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "normalizedCoords="); + roctracer::hip_support::detail::operator<<(out, v.normalizedCoords); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::borderColor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "borderColor="); + roctracer::hip_support::detail::operator<<(out, v.borderColor); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::sRGB").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sRGB="); + roctracer::hip_support::detail::operator<<(out, v.sRGB); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::readMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "readMode="); + roctracer::hip_support::detail::operator<<(out, v.readMode); + std::operator<<(out, ", "); + } + if (std::string("hipTextureDesc::filterMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "filterMode="); + roctracer::hip_support::detail::operator<<(out, v.filterMode); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const surfaceReference& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("surfaceReference::surfaceObject").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "surfaceObject="); + roctracer::hip_support::detail::operator<<(out, v.surfaceObject); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipIpcMemHandle_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipIpcMemHandle_t::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipIpcEventHandle_t& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipIpcEventHandle_t::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipFuncAttributes& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipFuncAttributes::sharedSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::ptxVersion").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ptxVersion="); + roctracer::hip_support::detail::operator<<(out, v.ptxVersion); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::preferredShmemCarveout").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "preferredShmemCarveout="); + roctracer::hip_support::detail::operator<<(out, v.preferredShmemCarveout); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::numRegs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numRegs="); + roctracer::hip_support::detail::operator<<(out, v.numRegs); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::maxDynamicSharedSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxDynamicSharedSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.maxDynamicSharedSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::localSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "localSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.localSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::constSizeBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "constSizeBytes="); + roctracer::hip_support::detail::operator<<(out, v.constSizeBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::cacheModeCA").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cacheModeCA="); + roctracer::hip_support::detail::operator<<(out, v.cacheModeCA); + std::operator<<(out, ", "); + } + if (std::string("hipFuncAttributes::binaryVersion").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "binaryVersion="); + roctracer::hip_support::detail::operator<<(out, v.binaryVersion); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemLocation& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemLocation::id").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "id="); + roctracer::hip_support::detail::operator<<(out, v.id); + std::operator<<(out, ", "); + } + if (std::string("hipMemLocation::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAccessDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAccessDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipMemAccessDesc::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolProps& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemPoolProps::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::maxSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSize="); + roctracer::hip_support::detail::operator<<(out, v.maxSize); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::handleTypes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handleTypes="); + roctracer::hip_support::detail::operator<<(out, v.handleTypes); + std::operator<<(out, ", "); + } + if (std::string("hipMemPoolProps::allocType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "allocType="); + roctracer::hip_support::detail::operator<<(out, v.allocType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolPtrExportData& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemPoolPtrExportData::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const dim3& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("dim3::z").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "z="); + roctracer::hip_support::detail::operator<<(out, v.z); + std::operator<<(out, ", "); + } + if (std::string("dim3::y").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "y="); + roctracer::hip_support::detail::operator<<(out, v.y); + std::operator<<(out, ", "); + } + if (std::string("dim3::x").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "x="); + roctracer::hip_support::detail::operator<<(out, v.x); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipLaunchParams::stream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "stream="); + roctracer::hip_support::detail::operator<<(out, v.stream); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::sharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMem="); + roctracer::hip_support::detail::operator<<(out, v.sharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::blockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDim="); + roctracer::hip_support::detail::operator<<(out, v.blockDim); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchParams::gridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDim="); + roctracer::hip_support::detail::operator<<(out, v.gridDim); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipFunctionLaunchParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipFunctionLaunchParams::hStream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hStream="); + roctracer::hip_support::detail::operator<<(out, v.hStream); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::sharedMemBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemBytes); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimZ="); + roctracer::hip_support::detail::operator<<(out, v.blockDimZ); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimY="); + roctracer::hip_support::detail::operator<<(out, v.blockDimY); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::blockDimX").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDimX="); + roctracer::hip_support::detail::operator<<(out, v.blockDimX); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimZ").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimZ="); + roctracer::hip_support::detail::operator<<(out, v.gridDimZ); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimY").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimY="); + roctracer::hip_support::detail::operator<<(out, v.gridDimY); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::gridDimX").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDimX="); + roctracer::hip_support::detail::operator<<(out, v.gridDimX); + std::operator<<(out, ", "); + } + if (std::string("hipFunctionLaunchParams::function").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "function="); + roctracer::hip_support::detail::operator<<(out, v.function); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryHandleDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryHandleDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::size").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "size="); + roctracer::hip_support::detail::operator<<(out, v.size); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc_st::union ::handle.fd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handle.fd="); + roctracer::hip_support::detail::operator<<(out, v.handle.fd); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryHandleDesc::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryBufferDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryBufferDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::size").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "size="); + roctracer::hip_support::detail::operator<<(out, v.size); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryBufferDesc::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryMipmappedArrayDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalMemoryMipmappedArrayDesc::numLevels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numLevels="); + roctracer::hip_support::detail::operator<<(out, v.numLevels); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::extent").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extent="); + roctracer::hip_support::detail::operator<<(out, v.extent); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::formatDesc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "formatDesc="); + roctracer::hip_support::detail::operator<<(out, v.formatDesc); + std::operator<<(out, ", "); + } + if (std::string("hipExternalMemoryMipmappedArrayDesc::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreHandleDesc& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreHandleDesc::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc_st::union ::handle.fd").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "handle.fd="); + roctracer::hip_support::detail::operator<<(out, v.handle.fd); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreHandleDesc::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreSignalParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreWaitParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipHostNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipHostNodeParams::fn").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "fn="); + roctracer::hip_support::detail::operator<<(out, v.fn); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipKernelNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipKernelNodeParams::sharedMemBytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemBytes="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemBytes); + std::operator<<(out, ", "); + } + if (std::string("hipKernelNodeParams::gridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gridDim="); + roctracer::hip_support::detail::operator<<(out, v.gridDim); + std::operator<<(out, ", "); + } + if (std::string("hipKernelNodeParams::blockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "blockDim="); + roctracer::hip_support::detail::operator<<(out, v.blockDim); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemsetParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemsetParams::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::value").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "value="); + roctracer::hip_support::detail::operator<<(out, v.value); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("hipMemsetParams::elementSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "elementSize="); + roctracer::hip_support::detail::operator<<(out, v.elementSize); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAllocNodeParams::bytesize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "bytesize="); + roctracer::hip_support::detail::operator<<(out, v.bytesize); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::accessDescCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessDescCount="); + roctracer::hip_support::detail::operator<<(out, v.accessDescCount); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::accessDescs").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessDescs="); + roctracer::hip_support::detail::operator<<(out, v.accessDescs); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocNodeParams::poolProps").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "poolProps="); + roctracer::hip_support::detail::operator<<(out, v.poolProps); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipAccessPolicyWindow& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipAccessPolicyWindow::num_bytes").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "num_bytes="); + roctracer::hip_support::detail::operator<<(out, v.num_bytes); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::missProp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "missProp="); + roctracer::hip_support::detail::operator<<(out, v.missProp); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::hitRatio").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hitRatio="); + roctracer::hip_support::detail::operator<<(out, v.hitRatio); + std::operator<<(out, ", "); + } + if (std::string("hipAccessPolicyWindow::hitProp").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hitProp="); + roctracer::hip_support::detail::operator<<(out, v.hitProp); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchAttributeValue& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipLaunchAttributeValue::priority").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "priority="); + roctracer::hip_support::detail::operator<<(out, v.priority); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchAttributeValue::cooperative").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperative="); + roctracer::hip_support::detail::operator<<(out, v.cooperative); + std::operator<<(out, ", "); + } + if (std::string("hipLaunchAttributeValue::accessPolicyWindow").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "accessPolicyWindow="); + roctracer::hip_support::detail::operator<<(out, v.accessPolicyWindow); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMSET_NODE_PARAMS& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("HIP_MEMSET_NODE_PARAMS::height").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "height="); + roctracer::hip_support::detail::operator<<(out, v.height); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::width").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "width="); + roctracer::hip_support::detail::operator<<(out, v.width); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::elementSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "elementSize="); + roctracer::hip_support::detail::operator<<(out, v.elementSize); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::value").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "value="); + roctracer::hip_support::detail::operator<<(out, v.value); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::pitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pitch="); + roctracer::hip_support::detail::operator<<(out, v.pitch); + std::operator<<(out, ", "); + } + if (std::string("HIP_MEMSET_NODE_PARAMS::dst").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "dst="); + roctracer::hip_support::detail::operator<<(out, v.dst); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphInstantiateParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphInstantiateParams::uploadStream").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "uploadStream="); + roctracer::hip_support::detail::operator<<(out, v.uploadStream); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::result_out").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "result_out="); + roctracer::hip_support::detail::operator<<(out, v.result_out); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipGraphInstantiateParams::errNode_out").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "errNode_out="); + roctracer::hip_support::detail::operator<<(out, v.errNode_out); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocationProp& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemAllocationProp::location").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "location="); + roctracer::hip_support::detail::operator<<(out, v.location); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocationProp::requestedHandleType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "requestedHandleType="); + roctracer::hip_support::detail::operator<<(out, v.requestedHandleType); + std::operator<<(out, ", "); + } + if (std::string("hipMemAllocationProp::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreSignalNodeParams::numExtSems").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numExtSems="); + roctracer::hip_support::detail::operator<<(out, v.numExtSems); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalNodeParams::paramsArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "paramsArray="); + roctracer::hip_support::detail::operator<<(out, v.paramsArray); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreSignalNodeParams::extSemArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extSemArray="); + roctracer::hip_support::detail::operator<<(out, v.extSemArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipExternalSemaphoreWaitNodeParams::numExtSems").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "numExtSems="); + roctracer::hip_support::detail::operator<<(out, v.numExtSems); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitNodeParams::paramsArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "paramsArray="); + roctracer::hip_support::detail::operator<<(out, v.paramsArray); + std::operator<<(out, ", "); + } + if (std::string("hipExternalSemaphoreWaitNodeParams::extSemArray").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "extSemArray="); + roctracer::hip_support::detail::operator<<(out, v.extSemArray); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipArrayMapInfo& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipArrayMapInfo::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::deviceBitMask").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "deviceBitMask="); + roctracer::hip_support::detail::operator<<(out, v.deviceBitMask); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::offset").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "offset="); + roctracer::hip_support::detail::operator<<(out, v.offset); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::union ::memHandle.memHandle").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memHandle.memHandle="); + roctracer::hip_support::detail::operator<<(out, v.memHandle.memHandle); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::memHandleType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memHandleType="); + roctracer::hip_support::detail::operator<<(out, v.memHandleType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::memOperationType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memOperationType="); + roctracer::hip_support::detail::operator<<(out, v.memOperationType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::subresourceType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "subresourceType="); + roctracer::hip_support::detail::operator<<(out, v.subresourceType); + std::operator<<(out, ", "); + } + if (std::string("hipArrayMapInfo::resourceType").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "resourceType="); + roctracer::hip_support::detail::operator<<(out, v.resourceType); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpyNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipMemcpyNodeParams::copyParams").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "copyParams="); + roctracer::hip_support::detail::operator<<(out, v.copyParams); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpyNodeParams::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipMemcpyNodeParams::flags").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "flags="); + roctracer::hip_support::detail::operator<<(out, v.flags); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipChildGraphNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipChildGraphNodeParams::graph").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "graph="); + roctracer::hip_support::detail::operator<<(out, v.graph); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipEventWaitNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipEventWaitNodeParams::event").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "event="); + roctracer::hip_support::detail::operator<<(out, v.event); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipEventRecordNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipEventRecordNodeParams::event").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "event="); + roctracer::hip_support::detail::operator<<(out, v.event); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipMemFreeNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphNodeParams& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphNodeParams::reserved2").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved2="); + roctracer::hip_support::detail::operator<<(out, v.reserved2); + std::operator<<(out, ", "); + } + if (std::string("hipGraphNodeParams::reserved0").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved0="); + roctracer::hip_support::detail::operator<<(out, v.reserved0); + std::operator<<(out, ", "); + } + if (std::string("hipGraphNodeParams::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipGraphEdgeData& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipGraphEdgeData::type").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "type="); + roctracer::hip_support::detail::operator<<(out, v.type); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::to_port").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "to_port="); + roctracer::hip_support::detail::operator<<(out, v.to_port); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::reserved").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "reserved="); + roctracer::hip_support::detail::operator<<(out, 0); + std::operator<<(out, ", "); + } + if (std::string("hipGraphEdgeData::from_port").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "from_port="); + roctracer::hip_support::detail::operator<<(out, v.from_port); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0000& v) +{ + std::operator<<(out, '{'); + HIP_depth_max_cnt++; + if (HIP_depth_max == -1 || HIP_depth_max_cnt <= HIP_depth_max) { + if (std::string("hipDeviceProp_tR0000::pageableMemoryAccessUsesHostPageTables").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccessUsesHostPageTables="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccessUsesHostPageTables); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pageableMemoryAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pageableMemoryAccess="); + roctracer::hip_support::detail::operator<<(out, v.pageableMemoryAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::concurrentManagedAccess").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentManagedAccess="); + roctracer::hip_support::detail::operator<<(out, v.concurrentManagedAccess); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::directManagedMemAccessFromHost").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "directManagedMemAccessFromHost="); + roctracer::hip_support::detail::operator<<(out, v.directManagedMemAccessFromHost); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::managedMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "managedMemory="); + roctracer::hip_support::detail::operator<<(out, v.managedMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::asicRevision").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "asicRevision="); + roctracer::hip_support::detail::operator<<(out, v.asicRevision); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::isLargeBar").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isLargeBar="); + roctracer::hip_support::detail::operator<<(out, v.isLargeBar); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedSharedMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedSharedMem="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedSharedMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedBlockDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedBlockDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedBlockDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedGridDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedGridDim="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedGridDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceUnmatchedFunc").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceUnmatchedFunc="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceUnmatchedFunc); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::tccDriver").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "tccDriver="); + roctracer::hip_support::detail::operator<<(out, v.tccDriver); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::ECCEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "ECCEnabled="); + roctracer::hip_support::detail::operator<<(out, v.ECCEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::kernelExecTimeoutEnabled").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "kernelExecTimeoutEnabled="); + roctracer::hip_support::detail::operator<<(out, v.kernelExecTimeoutEnabled); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::texturePitchAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "texturePitchAlignment="); + roctracer::hip_support::detail::operator<<(out, v.texturePitchAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::textureAlignment").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "textureAlignment="); + roctracer::hip_support::detail::operator<<(out, v.textureAlignment); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memPitch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memPitch="); + roctracer::hip_support::detail::operator<<(out, v.memPitch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::hdpRegFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpRegFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpRegFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::hdpMemFlushCntl").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "hdpMemFlushCntl="); + roctracer::hip_support::detail::operator<<(out, v.hdpMemFlushCntl); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture3D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture3D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture3D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture2D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture2D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture2D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture1D").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1D="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1D); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxTexture1DLinear").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxTexture1DLinear="); + roctracer::hip_support::detail::operator<<(out, v.maxTexture1DLinear); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeMultiDeviceLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeMultiDeviceLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeMultiDeviceLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::cooperativeLaunch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "cooperativeLaunch="); + roctracer::hip_support::detail::operator<<(out, v.cooperativeLaunch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::integrated").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "integrated="); + roctracer::hip_support::detail::operator<<(out, v.integrated); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::gcnArchName").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArchName="); + roctracer::hip_support::detail::operator<<(out, v.gcnArchName); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::gcnArch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "gcnArch="); + roctracer::hip_support::detail::operator<<(out, v.gcnArch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::canMapHostMemory").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "canMapHostMemory="); + roctracer::hip_support::detail::operator<<(out, v.canMapHostMemory); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::isMultiGpuBoard").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "isMultiGpuBoard="); + roctracer::hip_support::detail::operator<<(out, v.isMultiGpuBoard); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxSharedMemoryPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxSharedMemoryPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxSharedMemoryPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciDeviceID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDeviceID="); + roctracer::hip_support::detail::operator<<(out, v.pciDeviceID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciBusID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciBusID="); + roctracer::hip_support::detail::operator<<(out, v.pciBusID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::pciDomainID").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "pciDomainID="); + roctracer::hip_support::detail::operator<<(out, v.pciDomainID); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::concurrentKernels").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "concurrentKernels="); + roctracer::hip_support::detail::operator<<(out, v.concurrentKernels); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::arch").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "arch="); + roctracer::hip_support::detail::operator<<(out, v.arch); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::clockInstructionRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockInstructionRate="); + roctracer::hip_support::detail::operator<<(out, v.clockInstructionRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::computeMode").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "computeMode="); + roctracer::hip_support::detail::operator<<(out, v.computeMode); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsPerMultiProcessor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerMultiProcessor="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerMultiProcessor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::l2CacheSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "l2CacheSize="); + roctracer::hip_support::detail::operator<<(out, v.l2CacheSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::multiProcessorCount").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "multiProcessorCount="); + roctracer::hip_support::detail::operator<<(out, v.multiProcessorCount); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::minor").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "minor="); + roctracer::hip_support::detail::operator<<(out, v.minor); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::major").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "major="); + roctracer::hip_support::detail::operator<<(out, v.major); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::totalConstMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalConstMem="); + roctracer::hip_support::detail::operator<<(out, v.totalConstMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memoryBusWidth").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryBusWidth="); + roctracer::hip_support::detail::operator<<(out, v.memoryBusWidth); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::memoryClockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "memoryClockRate="); + roctracer::hip_support::detail::operator<<(out, v.memoryClockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::clockRate").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "clockRate="); + roctracer::hip_support::detail::operator<<(out, v.clockRate); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxGridSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxGridSize="); + roctracer::hip_support::detail::operator<<(out, v.maxGridSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsDim").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsDim="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsDim); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::maxThreadsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "maxThreadsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.maxThreadsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::warpSize").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "warpSize="); + roctracer::hip_support::detail::operator<<(out, v.warpSize); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::regsPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "regsPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.regsPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::sharedMemPerBlock").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "sharedMemPerBlock="); + roctracer::hip_support::detail::operator<<(out, v.sharedMemPerBlock); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::totalGlobalMem").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "totalGlobalMem="); + roctracer::hip_support::detail::operator<<(out, v.totalGlobalMem); + std::operator<<(out, ", "); + } + if (std::string("hipDeviceProp_tR0000::name").find(HIP_structs_regex) != std::string::npos) { + std::operator<<(out, "name="); + roctracer::hip_support::detail::operator<<(out, v.name); + } + }; + HIP_depth_max_cnt--; + std::operator<<(out, '}'); + return out; +} +// end ostream ops for HIP +};};}; + +inline static std::ostream& operator<<(std::ostream& out, const __locale_struct& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceArch_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipUUID& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0600& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPointerAttribute_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipChannelFormatDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY_DESCRIPTOR& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_ARRAY3D_DESCRIPTOR& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hip_Memcpy2D& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMipmappedArray& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_TEXTURE_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipResourceDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipResourceViewDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_RESOURCE_VIEW_DESC& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPitchedPtr& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExtent& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipPos& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpy3DParms& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMCPY3D& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uchar4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const char4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ushort4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const short4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const uint4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const int4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const long4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const ulonglong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const longlong4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const float4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double1& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double2& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const double4& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const textureReference& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipTextureDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const surfaceReference& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipIpcMemHandle_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipIpcEventHandle_t& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipFuncAttributes& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemLocation& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAccessDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolProps& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemPoolPtrExportData& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const dim3& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipFunctionLaunchParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryHandleDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryBufferDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalMemoryMipmappedArrayDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreHandleDesc& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipHostNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipKernelNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemsetParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipAccessPolicyWindow& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipLaunchAttributeValue& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const HIP_MEMSET_NODE_PARAMS& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphInstantiateParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemAllocationProp& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreSignalNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipExternalSemaphoreWaitNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipArrayMapInfo& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemcpyNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipChildGraphNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipEventWaitNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipEventRecordNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipMemFreeNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphNodeParams& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipGraphEdgeData& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +inline static std::ostream& operator<<(std::ostream& out, const hipDeviceProp_tR0000& v) +{ + roctracer::hip_support::detail::operator<<(out, v); + return out; +} + +#endif //__cplusplus +#endif // INC_HIP_OSTREAM_OPS_H_ + diff --git a/shared/package-files/4a/4a308253d6927c387e03e318700480b007bf41ab0e6d1d83f496429a5a107a96/misc.cpython-311.pyc b/shared/package-files/4a/4a308253d6927c387e03e318700480b007bf41ab0e6d1d83f496429a5a107a96/misc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bf45fac6f409be0e26626e9efbd0276647f254d Binary files /dev/null and b/shared/package-files/4a/4a308253d6927c387e03e318700480b007bf41ab0e6d1d83f496429a5a107a96/misc.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a327fda7dcdc0cf112a1f8972a0f0a6f733c877b6c4a925e06634305e29d9d0/_sparse_semi_structured_linear_ops.h b/shared/package-files/4a/4a327fda7dcdc0cf112a1f8972a0f0a6f733c877b6c4a925e06634305e29d9d0/_sparse_semi_structured_linear_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e51b7821910f7bb2f09d940c6d02fca4fbddef95 --- /dev/null +++ b/shared/package-files/4a/4a327fda7dcdc0cf112a1f8972a0f0a6f733c877b6c4a925e06634305e29d9d0/_sparse_semi_structured_linear_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_semi_structured_linear { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const ::std::optional &, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_semi_structured_linear"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_sparse_semi_structured_linear(Tensor input, Tensor weight, Tensor meta, *, Tensor? bias=None, str? activation=None, ScalarType? out_dtype=None) -> Tensor"; + static at::Tensor call(const at::Tensor & input, const at::Tensor & weight, const at::Tensor & meta, const ::std::optional & bias, ::std::optional activation, ::std::optional out_dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & weight, const at::Tensor & meta, const ::std::optional & bias, ::std::optional activation, ::std::optional out_dtype); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4a/4a33ed5b3d6dc7a2e8b6bd9678e282088c3d350739d198decf7cb381fafb483c/memory_pool.h b/shared/package-files/4a/4a33ed5b3d6dc7a2e8b6bd9678e282088c3d350739d198decf7cb381fafb483c/memory_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..98c6dc3e211b8231586283a2bf54b823eb5cc1ae --- /dev/null +++ b/shared/package-files/4a/4a33ed5b3d6dc7a2e8b6bd9678e282088c3d350739d198decf7cb381fafb483c/memory_pool.h @@ -0,0 +1,296 @@ +// 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. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type_fwd.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +namespace internal { + +/////////////////////////////////////////////////////////////////////// +// Helper tracking memory statistics + +/// \brief Memory pool statistics +/// +/// 64-byte aligned so that all atomic values are on the same cache line. +class alignas(64) MemoryPoolStats { + private: + // All atomics are updated according to Acquire-Release ordering. + // https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering + // + // max_memory_, total_allocated_bytes_, and num_allocs_ only go up (they are + // monotonically increasing) which can allow some optimizations. + std::atomic max_memory_{0}; + std::atomic bytes_allocated_{0}; + std::atomic total_allocated_bytes_{0}; + std::atomic num_allocs_{0}; + + public: + int64_t max_memory() const { return max_memory_.load(std::memory_order_acquire); } + + int64_t bytes_allocated() const { + return bytes_allocated_.load(std::memory_order_acquire); + } + + int64_t total_bytes_allocated() const { + return total_allocated_bytes_.load(std::memory_order_acquire); + } + + int64_t num_allocations() const { return num_allocs_.load(std::memory_order_acquire); } + + inline void DidAllocateBytes(int64_t size) { + // Issue the load before everything else. max_memory_ is monotonically increasing, + // so we can use a relaxed load before the read-modify-write. + auto max_memory = max_memory_.load(std::memory_order_relaxed); + const auto old_bytes_allocated = + bytes_allocated_.fetch_add(size, std::memory_order_acq_rel); + // Issue store operations on values that we don't depend on to proceed + // with execution. When done, max_memory and old_bytes_allocated have + // a higher chance of being available on CPU registers. This also has the + // nice side-effect of putting 3 atomic stores close to each other in the + // instruction stream. + total_allocated_bytes_.fetch_add(size, std::memory_order_acq_rel); + num_allocs_.fetch_add(1, std::memory_order_acq_rel); + + // If other threads are updating max_memory_ concurrently we leave the loop without + // updating knowing that it already reached a value even higher than ours. + const auto allocated = old_bytes_allocated + size; + while (max_memory < allocated && !max_memory_.compare_exchange_weak( + /*expected=*/max_memory, /*desired=*/allocated, + std::memory_order_acq_rel)) { + } + } + + inline void DidReallocateBytes(int64_t old_size, int64_t new_size) { + if (new_size > old_size) { + DidAllocateBytes(new_size - old_size); + } else { + DidFreeBytes(old_size - new_size); + } + } + + inline void DidFreeBytes(int64_t size) { + bytes_allocated_.fetch_sub(size, std::memory_order_acq_rel); + } +}; + +} // namespace internal + +/// Base class for memory allocation on the CPU. +/// +/// Besides tracking the number of allocated bytes, the allocator also should +/// take care of the required 64-byte alignment. +class ARROW_EXPORT MemoryPool { + public: + virtual ~MemoryPool() = default; + + /// \brief EXPERIMENTAL. Create a new instance of the default MemoryPool + static std::unique_ptr CreateDefault(); + + /// Allocate a new memory region of at least size bytes. + /// + /// The allocated region shall be 64-byte aligned. + Status Allocate(int64_t size, uint8_t** out) { + return Allocate(size, kDefaultBufferAlignment, out); + } + + /// Allocate a new memory region of at least size bytes aligned to alignment. + virtual Status Allocate(int64_t size, int64_t alignment, uint8_t** out) = 0; + + /// Resize an already allocated memory section. + /// + /// As by default most default allocators on a platform don't support aligned + /// reallocation, this function can involve a copy of the underlying data. + virtual Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment, + uint8_t** ptr) = 0; + Status Reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) { + return Reallocate(old_size, new_size, kDefaultBufferAlignment, ptr); + } + + /// Free an allocated region. + /// + /// @param buffer Pointer to the start of the allocated memory region + /// @param size Allocated size located at buffer. An allocator implementation + /// may use this for tracking the amount of allocated bytes as well as for + /// faster deallocation if supported by its backend. + /// @param alignment The alignment of the allocation. Defaults to 64 bytes. + virtual void Free(uint8_t* buffer, int64_t size, int64_t alignment) = 0; + void Free(uint8_t* buffer, int64_t size) { + Free(buffer, size, kDefaultBufferAlignment); + } + + /// Return unused memory to the OS + /// + /// Only applies to allocators that hold onto unused memory. This will be + /// best effort, a memory pool may not implement this feature or may be + /// unable to fulfill the request due to fragmentation. + virtual void ReleaseUnused() {} + + /// The number of bytes that were allocated and not yet free'd through + /// this allocator. + virtual int64_t bytes_allocated() const = 0; + + /// Return peak memory allocation in this memory pool + /// + /// \return Maximum bytes allocated. If not known (or not implemented), + /// returns -1 + virtual int64_t max_memory() const; + + /// The number of bytes that were allocated. + virtual int64_t total_bytes_allocated() const = 0; + + /// The number of allocations or reallocations that were requested. + virtual int64_t num_allocations() const = 0; + + /// The name of the backend used by this MemoryPool (e.g. "system" or "jemalloc"). + virtual std::string backend_name() const = 0; + + protected: + MemoryPool() = default; +}; + +class ARROW_EXPORT LoggingMemoryPool : public MemoryPool { + public: + explicit LoggingMemoryPool(MemoryPool* pool); + ~LoggingMemoryPool() override = default; + + using MemoryPool::Allocate; + using MemoryPool::Free; + using MemoryPool::Reallocate; + + Status Allocate(int64_t size, int64_t alignment, uint8_t** out) override; + Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment, + uint8_t** ptr) override; + void Free(uint8_t* buffer, int64_t size, int64_t alignment) override; + + int64_t bytes_allocated() const override; + + int64_t max_memory() const override; + + int64_t total_bytes_allocated() const override; + + int64_t num_allocations() const override; + + std::string backend_name() const override; + + private: + MemoryPool* pool_; +}; + +/// Derived class for memory allocation. +/// +/// Tracks the number of bytes and maximum memory allocated through its direct +/// calls. Actual allocation is delegated to MemoryPool class. +class ARROW_EXPORT ProxyMemoryPool : public MemoryPool { + public: + explicit ProxyMemoryPool(MemoryPool* pool); + ~ProxyMemoryPool() override; + + using MemoryPool::Allocate; + using MemoryPool::Free; + using MemoryPool::Reallocate; + + Status Allocate(int64_t size, int64_t alignment, uint8_t** out) override; + Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment, + uint8_t** ptr) override; + void Free(uint8_t* buffer, int64_t size, int64_t alignment) override; + + int64_t bytes_allocated() const override; + + int64_t max_memory() const override; + + int64_t total_bytes_allocated() const override; + + int64_t num_allocations() const override; + + std::string backend_name() const override; + + private: + class ProxyMemoryPoolImpl; + std::unique_ptr impl_; +}; + +/// \brief Return a process-wide memory pool based on the system allocator. +ARROW_EXPORT MemoryPool* system_memory_pool(); + +/// \brief Return a process-wide memory pool based on jemalloc. +/// +/// May return NotImplemented if jemalloc is not available. +ARROW_EXPORT Status jemalloc_memory_pool(MemoryPool** out); + +/// \brief Set jemalloc memory page purging behavior for future-created arenas +/// to the indicated number of milliseconds. See dirty_decay_ms and +/// muzzy_decay_ms options in jemalloc for a description of what these do. The +/// default is configured to 1000 (1 second) which releases memory more +/// aggressively to the operating system than the jemalloc default of 10 +/// seconds. If you set the value to 0, dirty / muzzy pages will be released +/// immediately rather than with a time decay, but this may reduce application +/// performance. +ARROW_EXPORT +Status jemalloc_set_decay_ms(int ms); + +/// \brief Get basic statistics from jemalloc's mallctl. +/// See the MALLCTL NAMESPACE section in jemalloc project documentation for +/// available stats. +ARROW_EXPORT +Result jemalloc_get_stat(const char* name); + +/// \brief Reset the counter for peak bytes allocated in the calling thread to zero. +/// This affects subsequent calls to thread.peak.read, but not the values returned by +/// thread.allocated or thread.deallocated. +ARROW_EXPORT +Status jemalloc_peak_reset(); + +/// \brief Print summary statistics in human-readable form to stderr. +/// See malloc_stats_print documentation in jemalloc project documentation for +/// available opt flags. +ARROW_EXPORT +Status jemalloc_stats_print(const char* opts = ""); + +/// \brief Print summary statistics in human-readable form using a callback +/// See malloc_stats_print documentation in jemalloc project documentation for +/// available opt flags. +ARROW_EXPORT +Status jemalloc_stats_print(std::function write_cb, + const char* opts = ""); + +/// \brief Get summary statistics in human-readable form. +/// See malloc_stats_print documentation in jemalloc project documentation for +/// available opt flags. +ARROW_EXPORT +Result jemalloc_stats_string(const char* opts = ""); + +/// \brief Return a process-wide memory pool based on mimalloc. +/// +/// May return NotImplemented if mimalloc is not available. +ARROW_EXPORT Status mimalloc_memory_pool(MemoryPool** out); + +/// \brief Return the names of the backends supported by this Arrow build. +ARROW_EXPORT std::vector SupportedMemoryBackendNames(); + +} // namespace arrow diff --git a/shared/package-files/4a/4a37c07a1d77c9b5c8c627a4720733cee6b4da4200a844e8a49291858bc26adf/curand_kernel.h b/shared/package-files/4a/4a37c07a1d77c9b5c8c627a4720733cee6b4da4200a844e8a49291858bc26adf/curand_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..c9d27c5f271cae931091c85ecfe37b5e7d427bf3 --- /dev/null +++ b/shared/package-files/4a/4a37c07a1d77c9b5c8c627a4720733cee6b4da4200a844e8a49291858bc26adf/curand_kernel.h @@ -0,0 +1,1677 @@ + + /* Copyright 2010-2014 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * The source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * The Licensed Deliverables contained herein are PROPRIETARY and + * CONFIDENTIAL to NVIDIA and are being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + + +#if !defined(CURAND_KERNEL_H_) +#define CURAND_KERNEL_H_ + +/** + * \defgroup DEVICE Device API + * + * @{ + */ + +#if !defined(QUALIFIERS) +#define QUALIFIERS static __forceinline__ __device__ +#endif + +/* To prevent unused parameter warnings */ +#if !defined(GCC_UNUSED_PARAMETER) +#if defined(__GNUC__) +#define GCC_UNUSED_PARAMETER __attribute__((unused)) +#else +#define GCC_UNUSED_PARAMETER +#endif /* defined(__GNUC__) */ +#endif /* !defined(GCC_UNUSED_PARAMETER) */ + +#include + +#ifdef __CUDACC_RTC__ +#define CURAND_DETAIL_USE_CUDA_STL +#endif + +#if __cplusplus >= 201103L +# ifdef CURAND_DETAIL_USE_CUDA_STL +# define CURAND_STD cuda::std +# include +# else +# define CURAND_STD std +# include +# endif // CURAND_DETAIL_USE_CUDA_STL +#else +// To support C++03 compilation +# define CURAND_STD curand_detail +namespace curand_detail { + template + struct enable_if {}; + + template + struct enable_if { typedef T type; }; + + template + struct is_same { static const bool value = false; }; + + template + struct is_same { static const bool value = true; }; +} // namespace curand_detail +#endif // __cplusplus >= 201103L + +#ifndef __CUDACC_RTC__ +#include +#endif // __CUDACC_RTC__ + +#include "curand.h" +#include "curand_discrete.h" +#include "curand_precalc.h" +#include "curand_mrg32k3a.h" +#include "curand_mtgp32_kernel.h" +#include "curand_philox4x32_x.h" +#include "curand_globals.h" + +/* Test RNG */ +/* This generator uses the formula: + x_n = x_(n-1) + 1 mod 2^32 + x_0 = (unsigned int)seed * 3 + Subsequences are spaced 31337 steps apart. +*/ +struct curandStateTest { + unsigned int v; +}; + +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateTest curandStateTest_t; +/** \endcond */ + +/* XORSHIFT FAMILY RNGs */ +/* These generators are a family proposed by Marsaglia. They keep state + in 32 bit chunks, then use repeated shift and xor operations to scramble + the bits. The following generators are a combination of a simple Weyl + generator with an N variable XORSHIFT generator. +*/ + +/* XORSHIFT RNG */ +/* This generator uses the xorwow formula of +www.jstatsoft.org/v08/i14/paper page 5 +Has period 2^192 - 2^32. +*/ +/** + * CURAND XORWOW state + */ +struct curandStateXORWOW; + +/* + * Implementation details not in reference documentation */ +struct curandStateXORWOW { + unsigned int d, v[5]; + int boxmuller_flag; + int boxmuller_flag_double; + float boxmuller_extra; + double boxmuller_extra_double; +}; + +/* + * CURAND XORWOW state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateXORWOW curandStateXORWOW_t; + +#define EXTRA_FLAG_NORMAL 0x00000001 +#define EXTRA_FLAG_LOG_NORMAL 0x00000002 +/** \endcond */ + +/* Combined Multiple Recursive Generators */ +/* These generators are a family proposed by L'Ecuyer. They keep state + in sets of doubles, then use repeated modular arithmetic multiply operations + to scramble the bits in each set, and combine the result. +*/ + +/* MRG32k3a RNG */ +/* This generator uses the MRG32k3A formula of +http://www.iro.umontreal.ca/~lecuyer/myftp/streams00/c++/streams4.pdf +Has period 2^191. +*/ + +/* moduli for the recursions */ +/** \cond UNHIDE_DEFINES */ +#define MRG32K3A_MOD1 4294967087. +#define MRG32K3A_MOD2 4294944443. + +/* Constants used in generation */ + +#define MRG32K3A_A12 1403580. +#define MRG32K3A_A13N 810728. +#define MRG32K3A_A21 527612. +#define MRG32K3A_A23N 1370589. +#define MRG32K3A_NORM (2.3283065498378288e-10) +// +// #define MRG32K3A_BITS_NORM ((double)((POW32_DOUBLE-1.0)/MOD1)) +// above constant, used verbatim, rounds differently on some host systems. +#define MRG32K3A_BITS_NORM 1.000000048662 + +/** \endcond */ + + + + +/** + * CURAND MRG32K3A state + */ +struct curandStateMRG32k3a; + +/* Implementation details not in reference documentation */ +struct curandStateMRG32k3a { + unsigned int s1[3]; + unsigned int s2[3]; + int boxmuller_flag; + int boxmuller_flag_double; + float boxmuller_extra; + double boxmuller_extra_double; +}; + +/* + * CURAND MRG32K3A state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateMRG32k3a curandStateMRG32k3a_t; +/** \endcond */ + +/* SOBOL QRNG */ +/** + * CURAND Sobol32 state + */ +struct curandStateSobol32; + +/* Implementation details not in reference documentation */ +struct curandStateSobol32 { + unsigned int i, x, c; + unsigned int direction_vectors[32]; +}; + +/* + * CURAND Sobol32 state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateSobol32 curandStateSobol32_t; +/** \endcond */ + +/** + * CURAND Scrambled Sobol32 state + */ +struct curandStateScrambledSobol32; + +/* Implementation details not in reference documentation */ +struct curandStateScrambledSobol32 { + unsigned int i, x, c; + unsigned int direction_vectors[32]; +}; + +/* + * CURAND Scrambled Sobol32 state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateScrambledSobol32 curandStateScrambledSobol32_t; +/** \endcond */ + +/** + * CURAND Sobol64 state + */ +struct curandStateSobol64; + +/* Implementation details not in reference documentation */ +struct curandStateSobol64 { + unsigned long long i, x, c; + unsigned long long direction_vectors[64]; +}; + +/* + * CURAND Sobol64 state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateSobol64 curandStateSobol64_t; +/** \endcond */ + +/** + * CURAND Scrambled Sobol64 state + */ +struct curandStateScrambledSobol64; + +/* Implementation details not in reference documentation */ +struct curandStateScrambledSobol64 { + unsigned long long i, x, c; + unsigned long long direction_vectors[64]; +}; + +/* + * CURAND Scrambled Sobol64 state + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateScrambledSobol64 curandStateScrambledSobol64_t; +/** \endcond */ + +/* + * Default RNG + */ +/** \cond UNHIDE_TYPEDEFS */ +typedef struct curandStateXORWOW curandState_t; +typedef struct curandStateXORWOW curandState; +/** \endcond */ + +/****************************************************************************/ +/* Utility functions needed by RNGs */ +/****************************************************************************/ +/** \cond UNHIDE_UTILITIES */ +/* + multiply vector by matrix, store in result + matrix is n x n, measured in 32 bit units + matrix is stored in row major order + vector and result cannot be same pointer +*/ +template +QUALIFIERS void __curand_matvec_inplace(unsigned int *vector, unsigned int *matrix) +{ + unsigned int result[N] = { 0 }; + for(int i = 0; i < N; i++) { + #ifdef __CUDA_ARCH__ + #pragma unroll 16 + #endif + for(int j = 0; j < 32; j++) { + if(vector[i] & (1 << j)) { + for(int k = 0; k < N; k++) { + result[k] ^= matrix[N * (i * 32 + j) + k]; + } + } + } + } + for(int i = 0; i < N; i++) { + vector[i] = result[i]; + } +} + +QUALIFIERS void __curand_matvec(unsigned int *vector, unsigned int *matrix, + unsigned int *result, int n) +{ + for(int i = 0; i < n; i++) { + result[i] = 0; + } + for(int i = 0; i < n; i++) { + for(int j = 0; j < 32; j++) { + if(vector[i] & (1 << j)) { + for(int k = 0; k < n; k++) { + result[k] ^= matrix[n * (i * 32 + j) + k]; + } + } + } + } +} + +/* generate identity matrix */ +QUALIFIERS void __curand_matidentity(unsigned int *matrix, int n) +{ + int r; + for(int i = 0; i < n * 32; i++) { + for(int j = 0; j < n; j++) { + r = i & 31; + if(i / 32 == j) { + matrix[i * n + j] = (1 << r); + } else { + matrix[i * n + j] = 0; + } + } + } +} + +/* multiply matrixA by matrixB, store back in matrixA + matrixA and matrixB must not be same matrix */ +QUALIFIERS void __curand_matmat(unsigned int *matrixA, unsigned int *matrixB, int n) +{ + unsigned int result[MAX_XOR_N]; + for(int i = 0; i < n * 32; i++) { + __curand_matvec(matrixA + i * n, matrixB, result, n); + for(int j = 0; j < n; j++) { + matrixA[i * n + j] = result[j]; + } + } +} + +/* copy vectorA to vector */ +QUALIFIERS void __curand_veccopy(unsigned int *vector, unsigned int *vectorA, int n) +{ + for(int i = 0; i < n; i++) { + vector[i] = vectorA[i]; + } +} + +/* copy matrixA to matrix */ +QUALIFIERS void __curand_matcopy(unsigned int *matrix, unsigned int *matrixA, int n) +{ + for(int i = 0; i < n * n * 32; i++) { + matrix[i] = matrixA[i]; + } +} + +/* compute matrixA to power p, store result in matrix */ +QUALIFIERS void __curand_matpow(unsigned int *matrix, unsigned int *matrixA, + unsigned long long p, int n) +{ + unsigned int matrixR[MAX_XOR_N * MAX_XOR_N * 32]; + unsigned int matrixS[MAX_XOR_N * MAX_XOR_N * 32]; + __curand_matidentity(matrix, n); + __curand_matcopy(matrixR, matrixA, n); + while(p) { + if(p & 1) { + __curand_matmat(matrix, matrixR, n); + } + __curand_matcopy(matrixS, matrixR, n); + __curand_matmat(matrixR, matrixS, n); + p >>= 1; + } +} + +/****************************************************************************/ +/* Utility functions needed by MRG32k3a RNG */ +/* Matrix operations modulo some integer less than 2**32, done in */ +/* double precision floating point, with care not to overflow 53 bits */ +/****************************************************************************/ + +/* return i mod m. */ +/* assumes i and m are integers represented accurately in doubles */ + +QUALIFIERS double curand_MRGmod(double i, double m) +{ + double quo; + double rem; + quo = floor(i/m); + rem = i - (quo*m); + if (rem < 0.0) rem += m; + return rem; +} + +/* Multiplication modulo m. Inputs i and j less than 2**32 */ +/* Ensure intermediate results do not exceed 2**53 */ + +QUALIFIERS double curand_MRGmodMul(double i, double j, double m) +{ + double tempHi; + double tempLo; + + tempHi = floor(i/131072.0); + tempLo = i - (tempHi*131072.0); + tempLo = curand_MRGmod( curand_MRGmod( (tempHi * j), m) * 131072.0 + curand_MRGmod(tempLo * j, m),m); + + if (tempLo < 0.0) tempLo += m; + return tempLo; +} + +/* multiply 3 by 3 matrices of doubles, modulo m */ + +QUALIFIERS void curand_MRGmatMul3x3(unsigned int i1[][3],unsigned int i2[][3],unsigned int o[][3],double m) +{ + int i,j; + double temp[3][3]; + for (i=0; i<3; i++){ + for (j=0; j<3; j++){ + temp[i][j] = ( curand_MRGmodMul(i1[i][0], i2[0][j], m) + + curand_MRGmodMul(i1[i][1], i2[1][j], m) + + curand_MRGmodMul(i1[i][2], i2[2][j], m)); + temp[i][j] = curand_MRGmod( temp[i][j], m ); + } + } + for (i=0; i<3; i++){ + for (j=0; j<3; j++){ + o[i][j] = (unsigned int)temp[i][j]; + } + } +} + +/* multiply 3 by 3 matrix times 3 by 1 vector of doubles, modulo m */ + +QUALIFIERS void curand_MRGmatVecMul3x3( unsigned int i[][3], unsigned int v[], double m) +{ + int k; + double t[3]; + for (k = 0; k < 3; k++) { + t[k] = ( curand_MRGmodMul(i[k][0], v[0], m) + + curand_MRGmodMul(i[k][1], v[1], m) + + curand_MRGmodMul(i[k][2], v[2], m) ); + t[k] = curand_MRGmod( t[k], m ); + } + for (k = 0; k < 3; k++) { + v[k] = (unsigned int)t[k]; + } + +} + +/* raise a 3 by 3 matrix of doubles to a 64 bit integer power pow, modulo m */ +/* input is index zero of an array of 3 by 3 matrices m, */ +/* each m = m[0]**(2**index) */ + +QUALIFIERS void curand_MRGmatPow3x3( unsigned int in[][3][3], unsigned int o[][3], double m, unsigned long long pow ) +{ + int i,j; + for ( i = 0; i < 3; i++ ) { + for ( j = 0; j < 3; j++ ) { + o[i][j] = 0; + if ( i == j ) o[i][j] = 1; + } + } + i = 0; + curand_MRGmatVecMul3x3(o,o[0],m); + while (pow) { + if ( pow & 1ll ) { + curand_MRGmatMul3x3(in[i], o, o, m); + } + i++; + pow >>= 1; + } +} + +/* raise a 3 by 3 matrix of doubles to the power */ +/* 2 to the power (pow modulo 191), modulo m */ + +QUALIFIERS void curnand_MRGmatPow2Pow3x3( double in[][3], double o[][3], double m, unsigned long pow ) +{ + unsigned int temp[3][3]; + int i,j; + pow = pow % 191; + for ( i = 0; i < 3; i++ ) { + for ( j = 0; j < 3; j++ ) { + temp[i][j] = (unsigned int)in[i][j]; + } + } + while (pow) { + curand_MRGmatMul3x3(temp, temp, temp, m); + pow--; + } + for ( i = 0; i < 3; i++ ) { + for ( j = 0; j < 3; j++ ) { + o[i][j] = temp[i][j]; + } + } +} + +/** \endcond */ + +/****************************************************************************/ +/* Kernel implementations of RNGs */ +/****************************************************************************/ + +/* Test RNG */ + +QUALIFIERS void curand_init(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStateTest_t *state) +{ + state->v = (unsigned int)(seed * 3) + (unsigned int)(subsequence * 31337) + \ + (unsigned int)offset; +} + + +QUALIFIERS unsigned int curand(curandStateTest_t *state) +{ + unsigned int r = state->v++; + return r; +} + +QUALIFIERS void skipahead(unsigned long long n, curandStateTest_t *state) +{ + state->v += (unsigned int)n; +} + +/* XORWOW RNG */ + +template +QUALIFIERS void __curand_generate_skipahead_matrix_xor(unsigned int matrix[]) +{ + T state; + // Generate matrix that advances one step + // matrix has n * n * 32 32-bit elements + // solve for matrix by stepping single bit states + for(int i = 0; i < 32 * n; i++) { + state.d = 0; + for(int j = 0; j < n; j++) { + state.v[j] = 0; + } + state.v[i / 32] = (1 << (i & 31)); + curand(&state); + for(int j = 0; j < n; j++) { + matrix[i * n + j] = state.v[j]; + } + } +} + +template +QUALIFIERS void _skipahead_scratch(unsigned long long x, T *state, unsigned int *scratch) +{ + // unsigned int matrix[n * n * 32]; + unsigned int *matrix = scratch; + // unsigned int matrixA[n * n * 32]; + unsigned int *matrixA = scratch + (n * n * 32); + // unsigned int vector[n]; + unsigned int *vector = scratch + (n * n * 32) + (n * n * 32); + // unsigned int result[n]; + unsigned int *result = scratch + (n * n * 32) + (n * n * 32) + n; + unsigned long long p = x; + for(int i = 0; i < n; i++) { + vector[i] = state->v[i]; + } + int matrix_num = 0; + while(p && (matrix_num < PRECALC_NUM_MATRICES - 1)) { + for(unsigned int t = 0; t < (p & PRECALC_BLOCK_MASK); t++) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matvec(vector, precalc_xorwow_offset_matrix[matrix_num], result, n); +, + __curand_matvec(vector, precalc_xorwow_offset_matrix_host[matrix_num], result, n); +) + __curand_veccopy(vector, result, n); + } + p >>= PRECALC_BLOCK_SIZE; + matrix_num++; + } + if(p) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matcopy(matrix, precalc_xorwow_offset_matrix[PRECALC_NUM_MATRICES - 1], n); + __curand_matcopy(matrixA, precalc_xorwow_offset_matrix[PRECALC_NUM_MATRICES - 1], n); +, + __curand_matcopy(matrix, precalc_xorwow_offset_matrix_host[PRECALC_NUM_MATRICES - 1], n); + __curand_matcopy(matrixA, precalc_xorwow_offset_matrix_host[PRECALC_NUM_MATRICES - 1], n); +) + } + while(p) { + for(unsigned int t = 0; t < (p & SKIPAHEAD_MASK); t++) { + __curand_matvec(vector, matrixA, result, n); + __curand_veccopy(vector, result, n); + } + p >>= SKIPAHEAD_BLOCKSIZE; + if(p) { + for(int i = 0; i < SKIPAHEAD_BLOCKSIZE; i++) { + __curand_matmat(matrix, matrixA, n); + __curand_matcopy(matrixA, matrix, n); + } + } + } + for(int i = 0; i < n; i++) { + state->v[i] = vector[i]; + } + state->d += 362437 * (unsigned int)x; +} + +template +QUALIFIERS void _skipahead_sequence_scratch(unsigned long long x, T *state, unsigned int *scratch) +{ + // unsigned int matrix[n * n * 32]; + unsigned int *matrix = scratch; + // unsigned int matrixA[n * n * 32]; + unsigned int *matrixA = scratch + (n * n * 32); + // unsigned int vector[n]; + unsigned int *vector = scratch + (n * n * 32) + (n * n * 32); + // unsigned int result[n]; + unsigned int *result = scratch + (n * n * 32) + (n * n * 32) + n; + unsigned long long p = x; + for(int i = 0; i < n; i++) { + vector[i] = state->v[i]; + } + int matrix_num = 0; + while(p && matrix_num < PRECALC_NUM_MATRICES - 1) { + for(unsigned int t = 0; t < (p & PRECALC_BLOCK_MASK); t++) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matvec(vector, precalc_xorwow_matrix[matrix_num], result, n); +, + __curand_matvec(vector, precalc_xorwow_matrix_host[matrix_num], result, n); +) + __curand_veccopy(vector, result, n); + } + p >>= PRECALC_BLOCK_SIZE; + matrix_num++; + } + if(p) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matcopy(matrix, precalc_xorwow_matrix[PRECALC_NUM_MATRICES - 1], n); + __curand_matcopy(matrixA, precalc_xorwow_matrix[PRECALC_NUM_MATRICES - 1], n); +, + __curand_matcopy(matrix, precalc_xorwow_matrix_host[PRECALC_NUM_MATRICES - 1], n); + __curand_matcopy(matrixA, precalc_xorwow_matrix_host[PRECALC_NUM_MATRICES - 1], n); +) + } + while(p) { + for(unsigned int t = 0; t < (p & SKIPAHEAD_MASK); t++) { + __curand_matvec(vector, matrixA, result, n); + __curand_veccopy(vector, result, n); + } + p >>= SKIPAHEAD_BLOCKSIZE; + if(p) { + for(int i = 0; i < SKIPAHEAD_BLOCKSIZE; i++) { + __curand_matmat(matrix, matrixA, n); + __curand_matcopy(matrixA, matrix, n); + } + } + } + for(int i = 0; i < n; i++) { + state->v[i] = vector[i]; + } + /* No update of state->d needed, guaranteed to be a multiple of 2^32 */ +} + +template +QUALIFIERS void _skipahead_inplace(const unsigned long long x, T *state) +{ + unsigned long long p = x; + int matrix_num = 0; + while(p) { + for(unsigned int t = 0; t < (p & PRECALC_BLOCK_MASK); t++) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matvec_inplace(state->v, precalc_xorwow_offset_matrix[matrix_num]); +, + __curand_matvec_inplace(state->v, precalc_xorwow_offset_matrix_host[matrix_num]); +) + } + p >>= PRECALC_BLOCK_SIZE; + matrix_num++; + } + state->d += 362437 * (unsigned int)x; +} + +template +QUALIFIERS void _skipahead_sequence_inplace(unsigned long long x, T *state) +{ + int matrix_num = 0; + while(x) { + for(unsigned int t = 0; t < (x & PRECALC_BLOCK_MASK); t++) { +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + __curand_matvec_inplace(state->v, precalc_xorwow_matrix[matrix_num]); +, + __curand_matvec_inplace(state->v, precalc_xorwow_matrix_host[matrix_num]); +) + } + x >>= PRECALC_BLOCK_SIZE; + matrix_num++; + } + /* No update of state->d needed, guaranteed to be a multiple of 2^32 */ +} + +/** + * \brief Update XORWOW state to skip \p n elements. + * + * Update the XORWOW state in \p state to skip ahead \p n elements. + * + * All values of \p n are valid. Large values require more computation and so + * will take more time to complete. + * + * \param n - Number of elements to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead(unsigned long long n, curandStateXORWOW_t *state) +{ + _skipahead_inplace(n, state); +} + +/** + * \brief Update XORWOW state to skip ahead \p n subsequences. + * + * Update the XORWOW state in \p state to skip ahead \p n subsequences. Each + * subsequence is \xmlonly267\endxmlonly elements long, so this means the function will skip ahead + * \xmlonly267\endxmlonly * n elements. + * + * All values of \p n are valid. Large values require more computation and so + * will take more time to complete. + * + * \param n - Number of subsequences to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead_sequence(unsigned long long n, curandStateXORWOW_t *state) +{ + _skipahead_sequence_inplace(n, state); +} + +QUALIFIERS void _curand_init_scratch(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStateXORWOW_t *state, + unsigned int *scratch) +{ + // Break up seed, apply salt + // Constants are arbitrary nonzero values + unsigned int s0 = ((unsigned int)seed) ^ 0xaad26b49UL; + unsigned int s1 = (unsigned int)(seed >> 32) ^ 0xf7dcefddUL; + // Simple multiplication to mix up bits + // Constants are arbitrary odd values + unsigned int t0 = 1099087573UL * s0; + unsigned int t1 = 2591861531UL * s1; + state->d = 6615241 + t1 + t0; + state->v[0] = 123456789UL + t0; + state->v[1] = 362436069UL ^ t0; + state->v[2] = 521288629UL + t1; + state->v[3] = 88675123UL ^ t1; + state->v[4] = 5783321UL + t0; + _skipahead_sequence_scratch(subsequence, state, scratch); + _skipahead_scratch(offset, state, scratch); + state->boxmuller_flag = 0; + state->boxmuller_flag_double = 0; + state->boxmuller_extra = 0.f; + state->boxmuller_extra_double = 0.; +} + +QUALIFIERS void _curand_init_inplace(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStateXORWOW_t *state) +{ + // Break up seed, apply salt + // Constants are arbitrary nonzero values + unsigned int s0 = ((unsigned int)seed) ^ 0xaad26b49UL; + unsigned int s1 = (unsigned int)(seed >> 32) ^ 0xf7dcefddUL; + // Simple multiplication to mix up bits + // Constants are arbitrary odd values + unsigned int t0 = 1099087573UL * s0; + unsigned int t1 = 2591861531UL * s1; + state->d = 6615241 + t1 + t0; + state->v[0] = 123456789UL + t0; + state->v[1] = 362436069UL ^ t0; + state->v[2] = 521288629UL + t1; + state->v[3] = 88675123UL ^ t1; + state->v[4] = 5783321UL + t0; + _skipahead_sequence_inplace(subsequence, state); + _skipahead_inplace(offset, state); + state->boxmuller_flag = 0; + state->boxmuller_flag_double = 0; + state->boxmuller_extra = 0.f; + state->boxmuller_extra_double = 0.; +} + +/** + * \brief Initialize XORWOW state. + * + * Initialize XORWOW state in \p state with the given \p seed, \p subsequence, + * and \p offset. + * + * All input values of \p seed, \p subsequence, and \p offset are legal. Large + * values for \p subsequence and \p offset require more computation and so will + * take more time to complete. + * + * A value of 0 for \p seed sets the state to the values of the original + * published version of the \p xorwow algorithm. + * + * \param seed - Arbitrary bits to use as a seed + * \param subsequence - Subsequence to start at + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStateXORWOW_t *state) +{ + _curand_init_inplace(seed, subsequence, offset, state); +} + +/** + * \brief Return 32-bits of pseudorandomness from an XORWOW generator. + * + * Return 32-bits of pseudorandomness from the XORWOW generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 32-bits of pseudorandomness as an unsigned int, all bits valid to use. + */ +QUALIFIERS unsigned int curand(curandStateXORWOW_t *state) +{ + unsigned int t; + t = (state->v[0] ^ (state->v[0] >> 2)); + state->v[0] = state->v[1]; + state->v[1] = state->v[2]; + state->v[2] = state->v[3]; + state->v[3] = state->v[4]; + state->v[4] = (state->v[4] ^ (state->v[4] <<4)) ^ (t ^ (t << 1)); + state->d += 362437; + return state->v[4] + state->d; +} + + +/** + * \brief Return 32-bits of pseudorandomness from an Philox4_32_10 generator. + * + * Return 32-bits of pseudorandomness from the Philox4_32_10 generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 32-bits of pseudorandomness as an unsigned int, all bits valid to use. + */ + +QUALIFIERS unsigned int curand(curandStatePhilox4_32_10_t *state) +{ + // Maintain the invariant: output[STATE] is always "good" and + // is the next value to be returned by curand. + unsigned int ret; + switch(state->STATE++){ + default: + ret = state->output.x; + break; + case 1: + ret = state->output.y; + break; + case 2: + ret = state->output.z; + break; + case 3: + ret = state->output.w; + break; + } + if(state->STATE == 4){ + Philox_State_Incr(state); + state->output = curand_Philox4x32_10(state->ctr,state->key); + state->STATE = 0; + } + return ret; +} + +/** + * \brief Return tuple of 4 32-bit pseudorandoms from a Philox4_32_10 generator. + * + * Return 128 bits of pseudorandomness from the Philox4_32_10 generator in \p state, + * increment position of generator by four. + * + * \param state - Pointer to state to update + * + * \return 128-bits of pseudorandomness as a uint4, all bits valid to use. + */ + +QUALIFIERS uint4 curand4(curandStatePhilox4_32_10_t *state) +{ + uint4 r; + + uint4 tmp = state->output; + Philox_State_Incr(state); + state->output= curand_Philox4x32_10(state->ctr,state->key); + switch(state->STATE){ + case 0: + return tmp; + case 1: + r.x = tmp.y; + r.y = tmp.z; + r.z = tmp.w; + r.w = state->output.x; + break; + case 2: + r.x = tmp.z; + r.y = tmp.w; + r.z = state->output.x; + r.w = state->output.y; + break; + case 3: + r.x = tmp.w; + r.y = state->output.x; + r.z = state->output.y; + r.w = state->output.z; + break; + default: + // NOT possible but needed to avoid compiler warnings + return tmp; + } + return r; +} + +/** + * \brief Update Philox4_32_10 state to skip \p n elements. + * + * Update the Philox4_32_10 state in \p state to skip ahead \p n elements. + * + * All values of \p n are valid. + * + * \param n - Number of elements to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead(unsigned long long n, curandStatePhilox4_32_10_t *state) +{ + state->STATE += (n & 3); + n /= 4; + if( state->STATE > 3 ){ + n += 1; + state->STATE -= 4; + } + Philox_State_Incr(state, n); + state->output = curand_Philox4x32_10(state->ctr,state->key); +} + +/** + * \brief Update Philox4_32_10 state to skip ahead \p n subsequences. + * + * Update the Philox4_32_10 state in \p state to skip ahead \p n subsequences. Each + * subsequence is \xmlonly266\endxmlonly elements long, so this means the function will skip ahead + * \xmlonly266\endxmlonly * n elements. + * + * All values of \p n are valid. + * + * \param n - Number of subsequences to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead_sequence(unsigned long long n, curandStatePhilox4_32_10_t *state) +{ + Philox_State_Incr_hi(state, n); + state->output = curand_Philox4x32_10(state->ctr,state->key); +} + +/** + * \brief Initialize Philox4_32_10 state. + * + * Initialize Philox4_32_10 state in \p state with the given \p seed, p\ subsequence, + * and \p offset. + * + * All input values for \p seed, \p subseqence and \p offset are legal. Each of the + * \xmlonly264\endxmlonly possible + * values of seed selects an independent sequence of length + * \xmlonly2130\endxmlonly. + * The first + * \xmlonly266 * subsequence + offset\endxmlonly. + * values of the sequence are skipped. + * I.e., subsequences are of length + * \xmlonly266\endxmlonly. + * + * \param seed - Arbitrary bits to use as a seed + * \param subsequence - Subsequence to start at + * \param offset - Absolute offset into subsequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStatePhilox4_32_10_t *state) +{ + state->ctr = make_uint4(0, 0, 0, 0); + state->key.x = (unsigned int)seed; + state->key.y = (unsigned int)(seed>>32); + state->STATE = 0; + state->boxmuller_flag = 0; + state->boxmuller_flag_double = 0; + state->boxmuller_extra = 0.f; + state->boxmuller_extra_double = 0.; + skipahead_sequence(subsequence, state); + skipahead(offset, state); +} + + +/* MRG32k3a RNG */ + +/* Base generator for MRG32k3a */ +QUALIFIERS unsigned long long __curand_umad(GCC_UNUSED_PARAMETER unsigned int a, GCC_UNUSED_PARAMETER unsigned int b, GCC_UNUSED_PARAMETER unsigned long long c) +{ + unsigned long long r = 0; +NV_IF_TARGET(NV_PROVIDES_SM_61, + asm("mad.wide.u32 %0, %1, %2, %3;" + : "=l"(r) : "r"(a), "r"(b), "l"(c)); +) + return r; +} +QUALIFIERS unsigned long long __curand_umul(GCC_UNUSED_PARAMETER unsigned int a, GCC_UNUSED_PARAMETER unsigned int b) +{ + unsigned long long r = 0; +NV_IF_TARGET(NV_PROVIDES_SM_61, + asm("mul.wide.u32 %0, %1, %2;" + : "=l"(r) : "r"(a), "r"(b)); +) + return r; +} +QUALIFIERS double curand_MRG32k3a (curandStateMRG32k3a_t *state) +{ +NV_IF_TARGET(NV_PROVIDES_SM_61, + const unsigned int m1 = 4294967087u; + const unsigned int m2 = 4294944443u; + const unsigned int m1c = 209u; + const unsigned int m2c = 22853u; + const unsigned int a12 = 1403580u; + const unsigned int a13n = 810728u; + const unsigned int a21 = 527612u; + const unsigned int a23n = 1370589u; + + unsigned long long p1; + unsigned long long p2; + const unsigned long long p3 = __curand_umul(a13n, m1 - state->s1[0]); + p1 = __curand_umad(a12, state->s1[1], p3); + + // Putting addition inside and changing umul to umad + // slowed this function down on GV100 + p1 = __curand_umul(p1 >> 32, m1c) + (p1 & 0xffffffff); + if (p1 >= m1) p1 -= m1; + + state->s1[0] = state->s1[1]; state->s1[1] = state->s1[2]; state->s1[2] = p1; + const unsigned long long p4 = __curand_umul(a23n, m2 - state->s2[0]); + p2 = __curand_umad(a21, state->s2[2], p4); + + // Putting addition inside and changing umul to umad + // slowed this function down on GV100 + p2 = __curand_umul(p2 >> 32, m2c) + (p2 & 0xffffffff); + p2 = __curand_umul(p2 >> 32, m2c) + (p2 & 0xffffffff); + if (p2 >= m2) p2 -= m2; + + state->s2[0] = state->s2[1]; state->s2[1] = state->s2[2]; state->s2[2] = p2; + + const unsigned int p5 = (unsigned int)p1 - (unsigned int)p2; + if(p1 <= p2) return p5 + m1; + return p5; +) +NV_IF_TARGET(NV_IS_DEVICE, +/* nj's implementation */ + const double m1 = 4294967087.; + const double m2 = 4294944443.; + const double a12 = 1403580.; + const double a13n = 810728.; + const double a21 = 527612.; + const double a23n = 1370589.; + + const double rh1 = 2.3283065498378290e-010; /* (1.0 / m1)__hi */ + const double rl1 = -1.7354913086174288e-026; /* (1.0 / m1)__lo */ + const double rh2 = 2.3283188252407387e-010; /* (1.0 / m2)__hi */ + const double rl2 = 2.4081018096503646e-026; /* (1.0 / m2)__lo */ + + double q; + double p1; + double p2; + p1 = a12 * state->s1[1] - a13n * state->s1[0]; + q = trunc (fma (p1, rh1, p1 * rl1)); + p1 -= q * m1; + if (p1 < 0.0) p1 += m1; + state->s1[0] = state->s1[1]; state->s1[1] = state->s1[2]; state->s1[2] = (unsigned int)p1; + p2 = a21 * state->s2[2] - a23n * state->s2[0]; + q = trunc (fma (p2, rh2, p2 * rl2)); + p2 -= q * m2; + if (p2 < 0.0) p2 += m2; + state->s2[0] = state->s2[1]; state->s2[1] = state->s2[2]; state->s2[2] = (unsigned int)p2; + if (p1 <= p2) return (p1 - p2 + m1); + else return (p1 - p2); +) +/* end nj's implementation */ + double p1; + double p2; + double r; + p1 = (MRG32K3A_A12 * state->s1[1]) - (MRG32K3A_A13N * state->s1[0]); + p1 = curand_MRGmod(p1, MRG32K3A_MOD1); + if (p1 < 0.0) p1 += MRG32K3A_MOD1; + state->s1[0] = state->s1[1]; + state->s1[1] = state->s1[2]; + state->s1[2] = (unsigned int)p1; + p2 = (MRG32K3A_A21 * state->s2[2]) - (MRG32K3A_A23N * state->s2[0]); + p2 = curand_MRGmod(p2, MRG32K3A_MOD2); + if (p2 < 0) p2 += MRG32K3A_MOD2; + state->s2[0] = state->s2[1]; + state->s2[1] = state->s2[2]; + state->s2[2] = (unsigned int)p2; + r = p1 - p2; + if (r <= 0) r += MRG32K3A_MOD1; + return r; +} + + +/** + * \brief Return 32-bits of pseudorandomness from an MRG32k3a generator. + * + * Return 32-bits of pseudorandomness from the MRG32k3a generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 32-bits of pseudorandomness as an unsigned int, all bits valid to use. + */ +QUALIFIERS unsigned int curand(curandStateMRG32k3a_t *state) +{ + double dRet; + dRet = (double)curand_MRG32k3a(state)*(double)MRG32K3A_BITS_NORM; + return (unsigned int)dRet; +} + + + +/** + * \brief Update MRG32k3a state to skip \p n elements. + * + * Update the MRG32k3a state in \p state to skip ahead \p n elements. + * + * All values of \p n are valid. Large values require more computation and so + * will take more time to complete. + * + * \param n - Number of elements to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead(unsigned long long n, curandStateMRG32k3a_t *state) +{ + unsigned int t[3][3]; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + curand_MRGmatPow3x3( mrg32k3aM1, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3(mrg32k3aM2, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +, + curand_MRGmatPow3x3( mrg32k3aM1Host, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3(mrg32k3aM2Host, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +) +} + +/** + * \brief Update MRG32k3a state to skip ahead \p n subsequences. + * + * Update the MRG32k3a state in \p state to skip ahead \p n subsequences. Each + * subsequence is \xmlonly2127\endxmlonly + * + * \xmlonly276\endxmlonly elements long, so this means the function will skip ahead + * \xmlonly267\endxmlonly * n elements. + * + * Valid values of \p n are 0 to \xmlonly251\endxmlonly. Note \p n will be masked to 51 bits + * + * \param n - Number of subsequences to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead_subsequence(unsigned long long n, curandStateMRG32k3a_t *state) +{ + unsigned int t[3][3]; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + curand_MRGmatPow3x3( mrg32k3aM1SubSeq, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3( mrg32k3aM2SubSeq, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +, + curand_MRGmatPow3x3( mrg32k3aM1SubSeqHost, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3( mrg32k3aM2SubSeqHost, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +) +} + +/** + * \brief Update MRG32k3a state to skip ahead \p n sequences. + * + * Update the MRG32k3a state in \p state to skip ahead \p n sequences. Each + * sequence is \xmlonly2127\endxmlonly elements long, so this means the function will skip ahead + * \xmlonly2127\endxmlonly * n elements. + * + * All values of \p n are valid. Large values require more computation and so + * will take more time to complete. + * + * \param n - Number of sequences to skip + * \param state - Pointer to state to update + */ +QUALIFIERS void skipahead_sequence(unsigned long long n, curandStateMRG32k3a_t *state) +{ + unsigned int t[3][3]; +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + curand_MRGmatPow3x3( mrg32k3aM1Seq, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3( mrg32k3aM2Seq, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +, + curand_MRGmatPow3x3( mrg32k3aM1SeqHost, t, MRG32K3A_MOD1, n); + curand_MRGmatVecMul3x3( t, state->s1, MRG32K3A_MOD1); + curand_MRGmatPow3x3( mrg32k3aM2SeqHost, t, MRG32K3A_MOD2, n); + curand_MRGmatVecMul3x3( t, state->s2, MRG32K3A_MOD2); +) +} + + +/** + * \brief Initialize MRG32k3a state. + * + * Initialize MRG32k3a state in \p state with the given \p seed, \p subsequence, + * and \p offset. + * + * All input values of \p seed, \p subsequence, and \p offset are legal. + * \p subsequence will be truncated to 51 bits to avoid running into the next sequence + * + * A value of 0 for \p seed sets the state to the values of the original + * published version of the \p MRG32k3a algorithm. + * + * \param seed - Arbitrary bits to use as a seed + * \param subsequence - Subsequence to start at + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(unsigned long long seed, + unsigned long long subsequence, + unsigned long long offset, + curandStateMRG32k3a_t *state) +{ + int i; + for ( i=0; i<3; i++ ) { + state->s1[i] = 12345u; + state->s2[i] = 12345u; + } + if (seed != 0ull) { + unsigned int x1 = ((unsigned int)seed) ^ 0x55555555UL; + unsigned int x2 = (unsigned int)((seed >> 32) ^ 0xAAAAAAAAUL); + state->s1[0] = (unsigned int)curand_MRGmodMul(x1, state->s1[0], MRG32K3A_MOD1); + state->s1[1] = (unsigned int)curand_MRGmodMul(x2, state->s1[1], MRG32K3A_MOD1); + state->s1[2] = (unsigned int)curand_MRGmodMul(x1, state->s1[2], MRG32K3A_MOD1); + state->s2[0] = (unsigned int)curand_MRGmodMul(x2, state->s2[0], MRG32K3A_MOD2); + state->s2[1] = (unsigned int)curand_MRGmodMul(x1, state->s2[1], MRG32K3A_MOD2); + state->s2[2] = (unsigned int)curand_MRGmodMul(x2, state->s2[2], MRG32K3A_MOD2); + } + skipahead_subsequence( subsequence, state ); + skipahead( offset, state ); + state->boxmuller_flag = 0; + state->boxmuller_flag_double = 0; + state->boxmuller_extra = 0.f; + state->boxmuller_extra_double = 0.; +} + +/** + * \brief Update Sobol32 state to skip \p n elements. + * + * Update the Sobol32 state in \p state to skip ahead \p n elements. + * + * All values of \p n are valid. + * + * \param n - Number of elements to skip + * \param state - Pointer to state to update + */ +template +QUALIFIERS +typename CURAND_STD::enable_if::value || CURAND_STD::is_same::value>::type +skipahead(unsigned int n, T state) +{ + unsigned int i_gray; + state->x = state->c; + state->i += n; + /* Convert state->i to gray code */ + i_gray = state->i ^ (state->i >> 1); + for(unsigned int k = 0; k < 32; k++) { + if(i_gray & (1 << k)) { + state->x ^= state->direction_vectors[k]; + } + } + return; +} + +/** + * \brief Update Sobol64 state to skip \p n elements. + * + * Update the Sobol64 state in \p state to skip ahead \p n elements. + * + * All values of \p n are valid. + * + * \param n - Number of elements to skip + * \param state - Pointer to state to update + */ +template +QUALIFIERS +typename CURAND_STD::enable_if::value || CURAND_STD::is_same::value>::type +skipahead(unsigned long long n, T state) +{ + unsigned long long i_gray; + state->x = state->c; + state->i += n; + /* Convert state->i to gray code */ + i_gray = state->i ^ (state->i >> 1); + for(unsigned k = 0; k < 64; k++) { + if(i_gray & (1ULL << k)) { + state->x ^= state->direction_vectors[k]; + } + } + return; +} + +/** + * \brief Initialize Sobol32 state. + * + * Initialize Sobol32 state in \p state with the given \p direction \p vectors and + * \p offset. + * + * The direction vector is a device pointer to an array of 32 unsigned ints. + * All input values of \p offset are legal. + * + * \param direction_vectors - Pointer to array of 32 unsigned ints representing the + * direction vectors for the desired dimension + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(curandDirectionVectors32_t direction_vectors, + unsigned int offset, + curandStateSobol32_t *state) +{ + state->i = 0; + state->c = 0; + for(int i = 0; i < 32; i++) { + state->direction_vectors[i] = direction_vectors[i]; + } + state->x = 0; + skipahead(offset, state); +} +/** + * \brief Initialize Scrambled Sobol32 state. + * + * Initialize Sobol32 state in \p state with the given \p direction \p vectors and + * \p offset. + * + * The direction vector is a device pointer to an array of 32 unsigned ints. + * All input values of \p offset are legal. + * + * \param direction_vectors - Pointer to array of 32 unsigned ints representing the + direction vectors for the desired dimension + * \param scramble_c Scramble constant + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(curandDirectionVectors32_t direction_vectors, + unsigned int scramble_c, + unsigned int offset, + curandStateScrambledSobol32_t *state) +{ + state->i = 0; + state->c = scramble_c; + for(int i = 0; i < 32; i++) { + state->direction_vectors[i] = direction_vectors[i]; + } + state->x = state->c; + skipahead(offset, state); +} + +QUALIFIERS int __curand_find_trailing_zero(unsigned int x) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + int y = __ffs(~x); + if(y) + return y - 1; + return 31; +, + int i = 1; + while(x & 1) { + i++; + x >>= 1; + } + i = i - 1; + return i == 32 ? 31 : i; +) +} + +QUALIFIERS int __curand_find_trailing_zero(unsigned long long x) +{ +NV_IF_ELSE_TARGET(NV_IS_DEVICE, + int y = __ffsll(~x); + if(y) + return y - 1; + return 63; +, + int i = 1; + while(x & 1) { + i++; + x >>= 1; + } + i = i - 1; + return i == 64 ? 63 : i; +) +} + +/** + * \brief Initialize Sobol64 state. + * + * Initialize Sobol64 state in \p state with the given \p direction \p vectors and + * \p offset. + * + * The direction vector is a device pointer to an array of 64 unsigned long longs. + * All input values of \p offset are legal. + * + * \param direction_vectors - Pointer to array of 64 unsigned long longs representing the + direction vectors for the desired dimension + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(curandDirectionVectors64_t direction_vectors, + unsigned long long offset, + curandStateSobol64_t *state) +{ + state->i = 0; + state->c = 0; + for(int i = 0; i < 64; i++) { + state->direction_vectors[i] = direction_vectors[i]; + } + state->x = 0; + skipahead(offset, state); +} + +/** + * \brief Initialize Scrambled Sobol64 state. + * + * Initialize Sobol64 state in \p state with the given \p direction \p vectors and + * \p offset. + * + * The direction vector is a device pointer to an array of 64 unsigned long longs. + * All input values of \p offset are legal. + * + * \param direction_vectors - Pointer to array of 64 unsigned long longs representing the + direction vectors for the desired dimension + * \param scramble_c Scramble constant + * \param offset - Absolute offset into sequence + * \param state - Pointer to state to initialize + */ +QUALIFIERS void curand_init(curandDirectionVectors64_t direction_vectors, + unsigned long long scramble_c, + unsigned long long offset, + curandStateScrambledSobol64_t *state) +{ + state->i = 0; + state->c = scramble_c; + for(int i = 0; i < 64; i++) { + state->direction_vectors[i] = direction_vectors[i]; + } + state->x = state->c; + skipahead(offset, state); +} + +/** + * \brief Return 32-bits of quasirandomness from a Sobol32 generator. + * + * Return 32-bits of quasirandomness from the Sobol32 generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 32-bits of quasirandomness as an unsigned int, all bits valid to use. + */ + +QUALIFIERS unsigned int curand(curandStateSobol32_t * state) +{ + /* Moving from i to i+1 element in gray code is flipping one bit, + the trailing zero bit of i + */ + unsigned int res = state->x; + state->x ^= state->direction_vectors[__curand_find_trailing_zero(state->i)]; + state->i ++; + return res; +} + +/** + * \brief Return 32-bits of quasirandomness from a scrambled Sobol32 generator. + * + * Return 32-bits of quasirandomness from the scrambled Sobol32 generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 32-bits of quasirandomness as an unsigned int, all bits valid to use. + */ + +QUALIFIERS unsigned int curand(curandStateScrambledSobol32_t * state) +{ + /* Moving from i to i+1 element in gray code is flipping one bit, + the trailing zero bit of i + */ + unsigned int res = state->x; + state->x ^= state->direction_vectors[__curand_find_trailing_zero(state->i)]; + state->i ++; + return res; +} + +/** + * \brief Return 64-bits of quasirandomness from a Sobol64 generator. + * + * Return 64-bits of quasirandomness from the Sobol64 generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 64-bits of quasirandomness as an unsigned long long, all bits valid to use. + */ + +QUALIFIERS unsigned long long curand(curandStateSobol64_t * state) +{ + /* Moving from i to i+1 element in gray code is flipping one bit, + the trailing zero bit of i + */ + unsigned long long res = state->x; + state->x ^= state->direction_vectors[__curand_find_trailing_zero(state->i)]; + state->i ++; + return res; +} + +/** + * \brief Return 64-bits of quasirandomness from a scrambled Sobol64 generator. + * + * Return 64-bits of quasirandomness from the scrambled Sobol32 generator in \p state, + * increment position of generator by one. + * + * \param state - Pointer to state to update + * + * \return 64-bits of quasirandomness as an unsigned long long, all bits valid to use. + */ + +QUALIFIERS unsigned long long curand(curandStateScrambledSobol64_t * state) +{ + /* Moving from i to i+1 element in gray code is flipping one bit, + the trailing zero bit of i + */ + unsigned long long res = state->x; + state->x ^= state->direction_vectors[__curand_find_trailing_zero(state->i)]; + state->i ++; + return res; +} + +#include "curand_uniform.h" +#include "curand_normal.h" +#include "curand_lognormal.h" +#include "curand_poisson.h" +#include "curand_discrete2.h" + +__device__ static inline unsigned int *__get_precalculated_matrix(int n) +{ + if(n == 0) { + return precalc_xorwow_matrix[n]; + } + if(n == 2) { + return precalc_xorwow_offset_matrix[n]; + } + return precalc_xorwow_matrix[n]; +} + +#ifndef __CUDACC_RTC__ +__host__ static inline unsigned int *__get_precalculated_matrix_host(int n) +{ + if(n == 1) { + return precalc_xorwow_matrix_host[n]; + } + if(n == 3) { + return precalc_xorwow_offset_matrix_host[n]; + } + return precalc_xorwow_matrix_host[n]; +} +#endif // #ifndef __CUDACC_RTC__ + +__device__ static inline unsigned int *__get_mrg32k3a_matrix(int n) +{ + if(n == 0) { + return mrg32k3aM1[n][0]; + } + if(n == 2) { + return mrg32k3aM2[n][0]; + } + if(n == 4) { + return mrg32k3aM1SubSeq[n][0]; + } + if(n == 6) { + return mrg32k3aM2SubSeq[n][0]; + } + if(n == 8) { + return mrg32k3aM1Seq[n][0]; + } + if(n == 10) { + return mrg32k3aM2Seq[n][0]; + } + return mrg32k3aM1[n][0]; +} + +#ifndef __CUDACC_RTC__ +__host__ static inline unsigned int *__get_mrg32k3a_matrix_host(int n) +{ + if(n == 1) { + return mrg32k3aM1Host[n][0]; + } + if(n == 3) { + return mrg32k3aM2Host[n][0]; + } + if(n == 5) { + return mrg32k3aM1SubSeqHost[n][0]; + } + if(n == 7) { + return mrg32k3aM2SubSeqHost[n][0]; + } + if(n == 9) { + return mrg32k3aM1SeqHost[n][0]; + } + if(n == 11) { + return mrg32k3aM2SeqHost[n][0]; + } + return mrg32k3aM1Host[n][0]; +} + +__host__ static inline double *__get__cr_lgamma_table_host(void) { + return __cr_lgamma_table; +} +#endif // #ifndef __CUDACC_RTC__ + +/** @} */ + +#endif // !defined(CURAND_KERNEL_H_) diff --git a/shared/package-files/4a/4a3f2bbba14216b21474d52464f27b07b3e8c813fed15b79b66b061087c552d1/timer.py b/shared/package-files/4a/4a3f2bbba14216b21474d52464f27b07b3e8c813fed15b79b66b061087c552d1/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..731ac21359a47a224bb944199bf53f81488dba88 --- /dev/null +++ b/shared/package-files/4a/4a3f2bbba14216b21474d52464f27b07b3e8c813fed15b79b66b061087c552d1/timer.py @@ -0,0 +1,541 @@ +"""Timer class based on the timeit.Timer class, but torch aware.""" +import enum +import timeit +import textwrap +from typing import overload, Any, Callable, NoReturn, Optional, Union + +import torch +from torch.utils.benchmark.utils import common, cpp_jit +from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType +from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface + + +__all__ = ["Timer", "timer", "Language"] + + +if torch.backends.cuda.is_built() and torch.cuda.is_available(): # type: ignore[no-untyped-call] + def timer() -> float: + torch.cuda.synchronize() + return timeit.default_timer() +elif torch.xpu.is_available(): + def timer() -> float: + torch.xpu.synchronize() + return timeit.default_timer() +elif torch._C._get_privateuse1_backend_name() != "privateuseone": + privateuse1_device_handler = getattr(torch, torch._C._get_privateuse1_backend_name(), None) \ + if torch._C._get_privateuse1_backend_name() != "cpu" else None + + def timer() -> float: + if privateuse1_device_handler: + privateuse1_device_handler.synchronize() + return timeit.default_timer() +else: + timer = timeit.default_timer + + +class Language(enum.Enum): + PYTHON = 0 + CPP = 1 + + +class CPPTimer: + def __init__( + self, + stmt: str, + setup: str, + global_setup: str, + timer: Callable[[], float], + globals: dict[str, Any], + ) -> None: + if timer is not timeit.default_timer: + raise NotImplementedError( + "PyTorch was built with CUDA and a GPU is present; however " + "Timer does not yet support GPU measurements. If your " + "code is CPU only, pass `timer=timeit.default_timer` to the " + "Timer's constructor to indicate this. (Note that this will " + "produce incorrect results if the GPU is in fact used, as " + "Timer will not synchronize CUDA.)" + ) + + if globals: + raise ValueError("C++ timing does not support globals.") + + self._stmt: str = textwrap.dedent(stmt) + self._setup: str = textwrap.dedent(setup) + self._global_setup: str = textwrap.dedent(global_setup) + self._timeit_module: Optional[TimeitModuleType] = None + + def timeit(self, number: int) -> float: + if self._timeit_module is None: + self._timeit_module = cpp_jit.compile_timeit_template( + stmt=self._stmt, + setup=self._setup, + global_setup=self._global_setup, + ) + + return self._timeit_module.timeit(number) + + +class Timer: + """Helper class for measuring execution time of PyTorch statements. + + For a full tutorial on how to use this class, see: + https://pytorch.org/tutorials/recipes/recipes/benchmark.html + + The PyTorch Timer is based on `timeit.Timer` (and in fact uses + `timeit.Timer` internally), but with several key differences: + + 1) Runtime aware: + Timer will perform warmups (important as some elements of PyTorch are + lazily initialized), set threadpool size so that comparisons are + apples-to-apples, and synchronize asynchronous CUDA functions when + necessary. + + 2) Focus on replicates: + When measuring code, and particularly complex kernels / models, + run-to-run variation is a significant confounding factor. It is + expected that all measurements should include replicates to quantify + noise and allow median computation, which is more robust than mean. + To that effect, this class deviates from the `timeit` API by + conceptually merging `timeit.Timer.repeat` and `timeit.Timer.autorange`. + (Exact algorithms are discussed in method docstrings.) The `timeit` + method is replicated for cases where an adaptive strategy is not + desired. + + 3) Optional metadata: + When defining a Timer, one can optionally specify `label`, `sub_label`, + `description`, and `env`. (Defined later) These fields are included in + the representation of result object and by the `Compare` class to group + and display results for comparison. + + 4) Instruction counts + In addition to wall times, Timer can run a statement under Callgrind + and report instructions executed. + + Directly analogous to `timeit.Timer` constructor arguments: + + `stmt`, `setup`, `timer`, `globals` + + PyTorch Timer specific constructor arguments: + + `label`, `sub_label`, `description`, `env`, `num_threads` + + Args: + stmt: Code snippet to be run in a loop and timed. + + setup: Optional setup code. Used to define variables used in `stmt` + + global_setup: (C++ only) + Code which is placed at the top level of the file for things like + `#include` statements. + + timer: + Callable which returns the current time. If PyTorch was built + without CUDA or there is no GPU present, this defaults to + `timeit.default_timer`; otherwise it will synchronize CUDA before + measuring the time. + + globals: + A dict which defines the global variables when `stmt` is being + executed. This is the other method for providing variables which + `stmt` needs. + + label: + String which summarizes `stmt`. For instance, if `stmt` is + "torch.nn.functional.relu(torch.add(x, 1, out=out))" + one might set label to "ReLU(x + 1)" to improve readability. + + sub_label: + Provide supplemental information to disambiguate measurements + with identical stmt or label. For instance, in our example + above sub_label might be "float" or "int", so that it is easy + to differentiate: + "ReLU(x + 1): (float)" + + "ReLU(x + 1): (int)" + when printing Measurements or summarizing using `Compare`. + + description: + String to distinguish measurements with identical label and + sub_label. The principal use of `description` is to signal to + `Compare` the columns of data. For instance one might set it + based on the input size to create a table of the form: :: + + | n=1 | n=4 | ... + ------------- ... + ReLU(x + 1): (float) | ... | ... | ... + ReLU(x + 1): (int) | ... | ... | ... + + + using `Compare`. It is also included when printing a Measurement. + + env: + This tag indicates that otherwise identical tasks were run in + different environments, and are therefore not equivalent, for + instance when A/B testing a change to a kernel. `Compare` will + treat Measurements with different `env` specification as distinct + when merging replicate runs. + + num_threads: + The size of the PyTorch threadpool when executing `stmt`. Single + threaded performance is important as both a key inference workload + and a good indicator of intrinsic algorithmic efficiency, so the + default is set to one. This is in contrast to the default PyTorch + threadpool size which tries to utilize all cores. + """ + + _timer_cls: type[TimerClass] = timeit.Timer + + def __init__( + self, + stmt: str = "pass", + setup: str = "pass", + global_setup: str = "", + timer: Callable[[], float] = timer, + globals: Optional[dict[str, Any]] = None, + label: Optional[str] = None, + sub_label: Optional[str] = None, + description: Optional[str] = None, + env: Optional[str] = None, + num_threads: int = 1, + language: Union[Language, str] = Language.PYTHON, + ): + if not isinstance(stmt, str): + raise ValueError("Currently only a `str` stmt is supported.") + + # We copy `globals` to prevent mutations from leaking. + # (For instance, `eval` adds the `__builtins__` key) + self._globals = dict(globals or {}) + + timer_kwargs = {} + if language in (Language.PYTHON, "py", "python"): + # Include `torch` if not specified as a convenience feature. + self._globals.setdefault("torch", torch) + self._language: Language = Language.PYTHON + if global_setup: + raise ValueError( + f"global_setup is C++ only, got `{global_setup}`. Most " + "likely this code can simply be moved to `setup`." + ) + + elif language in (Language.CPP, "cpp", "c++"): + assert self._timer_cls is timeit.Timer, "_timer_cls has already been swapped." + self._timer_cls = CPPTimer + setup = ("" if setup == "pass" else setup) + self._language = Language.CPP + timer_kwargs["global_setup"] = global_setup + + else: + raise ValueError(f"Invalid language `{language}`.") + + # Convenience adjustment so that multi-line code snippets defined in + # functions do not IndentationError (Python) or look odd (C++). The + # leading newline removal is for the initial newline that appears when + # defining block strings. For instance: + # textwrap.dedent(""" + # print("This is a stmt") + # """) + # produces '\nprint("This is a stmt")\n'. + # + # Stripping this down to 'print("This is a stmt")' doesn't change + # what gets executed, but it makes __repr__'s nicer. + stmt = textwrap.dedent(stmt) + stmt = (stmt[1:] if stmt and stmt[0] == "\n" else stmt).rstrip() + setup = textwrap.dedent(setup) + setup = (setup[1:] if setup and setup[0] == "\n" else setup).rstrip() + + self._timer = self._timer_cls( + stmt=stmt, + setup=setup, + timer=timer, + globals=valgrind_timer_interface.CopyIfCallgrind.unwrap_all(self._globals), + **timer_kwargs, + ) + self._task_spec = common.TaskSpec( + stmt=stmt, + setup=setup, + global_setup=global_setup, + label=label, + sub_label=sub_label, + description=description, + env=env, + num_threads=num_threads, + ) + + def _timeit(self, number: int) -> float: + # Even calling a timer in C++ takes ~50 ns, so no real operation should + # take less than 1 ns. (And this prevents divide by zero errors.) + return max(self._timer.timeit(number), 1e-9) + + def timeit(self, number: int = 1000000) -> common.Measurement: + """Mirrors the semantics of timeit.Timer.timeit(). + + Execute the main statement (`stmt`) `number` times. + https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit + """ + with common.set_torch_threads(self._task_spec.num_threads): + # Warmup + self._timeit(number=max(int(number // 100), 2)) + + return common.Measurement( + number_per_run=number, + raw_times=[self._timeit(number=number)], + task_spec=self._task_spec + ) + + def repeat(self, repeat: int = -1, number: int = -1) -> None: + raise NotImplementedError("See `Timer.blocked_autorange.`") + + def autorange(self, callback: Optional[Callable[[int, float], NoReturn]] = None) -> None: + raise NotImplementedError("See `Timer.blocked_autorange.`") + + def _threaded_measurement_loop( + self, + number: int, + time_hook: Callable[[], float], + stop_hook: Callable[[list[float]], bool], + min_run_time: float, + max_run_time: Optional[float] = None, + callback: Optional[Callable[[int, float], NoReturn]] = None + ) -> list[float]: + total_time = 0.0 + can_stop = False + times: list[float] = [] + with common.set_torch_threads(self._task_spec.num_threads): + while (total_time < min_run_time) or (not can_stop): + time_spent = time_hook() + times.append(time_spent) + total_time += time_spent + if callback: + callback(number, time_spent) + can_stop = stop_hook(times) + if max_run_time and total_time > max_run_time: + break + return times + + def _estimate_block_size(self, min_run_time: float) -> int: + with common.set_torch_threads(self._task_spec.num_threads): + # Estimate the block size needed for measurement to be negligible + # compared to the inner loop. This also serves as a warmup. + overhead = torch.tensor([self._timeit(0) for _ in range(5)]).median().item() + number = 1 + while True: + time_taken = self._timeit(number) + relative_overhead = overhead / time_taken + if relative_overhead <= 1e-4 and time_taken >= min_run_time / 1000: + break + if time_taken > min_run_time: + break + # Avoid overflow in C++ pybind11 interface + if number * 10 > 2147483647: + break + number *= 10 + return number + + def blocked_autorange( + self, + callback: Optional[Callable[[int, float], NoReturn]] = None, + min_run_time: float = 0.2, + ) -> common.Measurement: + """Measure many replicates while keeping timer overhead to a minimum. + + At a high level, blocked_autorange executes the following pseudo-code:: + + `setup` + + total_time = 0 + while total_time < min_run_time + start = timer() + for _ in range(block_size): + `stmt` + total_time += (timer() - start) + + Note the variable `block_size` in the inner loop. The choice of block + size is important to measurement quality, and must balance two + competing objectives: + + 1) A small block size results in more replicates and generally + better statistics. + + 2) A large block size better amortizes the cost of `timer` + invocation, and results in a less biased measurement. This is + important because CUDA synchronization time is non-trivial + (order single to low double digit microseconds) and would + otherwise bias the measurement. + + blocked_autorange sets block_size by running a warmup period, + increasing block size until timer overhead is less than 0.1% of + the overall computation. This value is then used for the main + measurement loop. + + Returns: + A `Measurement` object that contains measured runtimes and + repetition counts, and can be used to compute statistics. + (mean, median, etc.) + """ + number = self._estimate_block_size(min_run_time) + + def time_hook() -> float: + return self._timeit(number) + + def stop_hook(times: list[float]) -> bool: + return True + + times = self._threaded_measurement_loop( + number, time_hook, stop_hook, + min_run_time=min_run_time, + callback=callback) + + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ) + + def adaptive_autorange( + self, + threshold: float = 0.1, + *, + min_run_time: float = 0.01, + max_run_time: float = 10.0, + callback: Optional[Callable[[int, float], NoReturn]] = None, + ) -> common.Measurement: + """Similar to `blocked_autorange` but also checks for variablility in measurements + and repeats until iqr/median is smaller than `threshold` or `max_run_time` is reached. + + + At a high level, adaptive_autorange executes the following pseudo-code:: + + `setup` + + times = [] + while times.sum < max_run_time + start = timer() + for _ in range(block_size): + `stmt` + times.append(timer() - start) + + enough_data = len(times)>3 and times.sum > min_run_time + small_iqr=times.iqr/times.mean float: + return self._timeit(number) + + def stop_hook(times: list[float]) -> bool: + if len(times) > 3: + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ).meets_confidence(threshold=threshold) + return False + times = self._threaded_measurement_loop( + number, time_hook, stop_hook, min_run_time, max_run_time, callback=callback) + + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ) + + @overload + def collect_callgrind( + self, + number: int, + *, + repeats: None, + collect_baseline: bool, + retain_out_file: bool, + ) -> valgrind_timer_interface.CallgrindStats: + ... + + @overload + def collect_callgrind( + self, + number: int, + *, + repeats: int, + collect_baseline: bool, + retain_out_file: bool, + ) -> tuple[valgrind_timer_interface.CallgrindStats, ...]: + ... + + def collect_callgrind( + self, + number: int = 100, + *, + repeats: Optional[int] = None, + collect_baseline: bool = True, + retain_out_file: bool = False, + ) -> Any: + """Collect instruction counts using Callgrind. + + Unlike wall times, instruction counts are deterministic + (modulo non-determinism in the program itself and small amounts of + jitter from the Python interpreter.) This makes them ideal for detailed + performance analysis. This method runs `stmt` in a separate process + so that Valgrind can instrument the program. Performance is severely + degraded due to the instrumentation, however this is ameliorated by + the fact that a small number of iterations is generally sufficient to + obtain good measurements. + + In order to to use this method `valgrind`, `callgrind_control`, and + `callgrind_annotate` must be installed. + + Because there is a process boundary between the caller (this process) + and the `stmt` execution, `globals` cannot contain arbitrary in-memory + data structures. (Unlike timing methods) Instead, globals are + restricted to builtins, `nn.Modules`'s, and TorchScripted functions/modules + to reduce the surprise factor from serialization and subsequent + deserialization. The `GlobalsBridge` class provides more detail on this + subject. Take particular care with nn.Modules: they rely on pickle and + you may need to add an import to `setup` for them to transfer properly. + + By default, a profile for an empty statement will be collected and + cached to indicate how many instructions are from the Python loop which + drives `stmt`. + + Returns: + A `CallgrindStats` object which provides instruction counts and + some basic facilities for analyzing and manipulating results. + """ + if not isinstance(self._task_spec.stmt, str): + raise ValueError("`collect_callgrind` currently only supports string `stmt`") + + if repeats is not None and repeats < 1: + raise ValueError("If specified, `repeats` must be >= 1") + + # Check that the statement is valid. It doesn't guarantee success, but it's much + # simpler and quicker to raise an exception for a faulty `stmt` or `setup` in + # the parent process rather than the valgrind subprocess. + self._timeit(1) + is_python = (self._language == Language.PYTHON) + assert is_python or not self._globals + result = valgrind_timer_interface.wrapper_singleton().collect_callgrind( + task_spec=self._task_spec, + globals=self._globals, + number=number, + repeats=repeats or 1, + collect_baseline=collect_baseline and is_python, + is_python=is_python, + retain_out_file=retain_out_file, + ) + + return (result[0] if repeats is None else result) diff --git a/shared/package-files/4a/4a40c35e4c59becba08e4b438170d02d086077dced8c998f57de4f07462bd3da/Types.h b/shared/package-files/4a/4a40c35e4c59becba08e4b438170d02d086077dced8c998f57de4f07462bd3da/Types.h new file mode 100644 index 0000000000000000000000000000000000000000..202a72e4761aecb485780c9d6b1e2129b9ac31cb --- /dev/null +++ b/shared/package-files/4a/4a40c35e4c59becba08e4b438170d02d086077dced8c998f57de4f07462bd3da/Types.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace at::native { + +TORCH_CUDA_CPP_API cudnnDataType_t +getCudnnDataTypeFromScalarType(const at::ScalarType dtype); +cudnnDataType_t getCudnnDataType(const at::Tensor& tensor); + +int64_t cudnn_version(); + +} // namespace at::native diff --git a/shared/package-files/4a/4a4c2e8b0cfd062cce87a44f3cdba84f46fcb17649f54bf9598da698ce723d90/__init__.cpython-311.pyc b/shared/package-files/4a/4a4c2e8b0cfd062cce87a44f3cdba84f46fcb17649f54bf9598da698ce723d90/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..376f04c239bdd6350bcca56ffa13099bacdb3063 Binary files /dev/null and b/shared/package-files/4a/4a4c2e8b0cfd062cce87a44f3cdba84f46fcb17649f54bf9598da698ce723d90/__init__.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a4d0a719d04fda86baa0c5eb5cb724136305f812e4eb5a986a718f895e9e3a7/torchbind_impls.cpython-311.pyc b/shared/package-files/4a/4a4d0a719d04fda86baa0c5eb5cb724136305f812e4eb5a986a718f895e9e3a7/torchbind_impls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b58e8ed0663fa70c34b2c2cdab39aa78696205ab Binary files /dev/null and b/shared/package-files/4a/4a4d0a719d04fda86baa0c5eb5cb724136305f812e4eb5a986a718f895e9e3a7/torchbind_impls.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a5041e5d2da1020a8d005278493326ab40ee370b5cb265ee5a9e43c628feb18/build.cpython-311.pyc b/shared/package-files/4a/4a5041e5d2da1020a8d005278493326ab40ee370b5cb265ee5a9e43c628feb18/build.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ef10d2563286d25a7fa9f6452a2b8308ce9b4da Binary files /dev/null and b/shared/package-files/4a/4a5041e5d2da1020a8d005278493326ab40ee370b5cb265ee5a9e43c628feb18/build.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a53fa2017d10bc512c7930e83f1da5ef8556aa8a213bbceb6ef4ad2d117d2c7/cross_native.h b/shared/package-files/4a/4a53fa2017d10bc512c7930e83f1da5ef8556aa8a213bbceb6ef4ad2d117d2c7/cross_native.h new file mode 100644 index 0000000000000000000000000000000000000000..3ed9e02c9d589d7a0de636e7ddbabfc0c073ba53 --- /dev/null +++ b/shared/package-files/4a/4a53fa2017d10bc512c7930e83f1da5ef8556aa8a213bbceb6ef4ad2d117d2c7/cross_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor cross(const at::Tensor & self, const at::Tensor & other, ::std::optional dim=::std::nullopt); +TORCH_API at::Tensor & cross_out(const at::Tensor & self, const at::Tensor & other, ::std::optional dim, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/4a/4a555778c8c18d37a63be6c3c5dd6ec1f1db315a8bca1401881796dd69c39de9/reshape_ops.h b/shared/package-files/4a/4a555778c8c18d37a63be6c3c5dd6ec1f1db315a8bca1401881796dd69c39de9/reshape_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d7396f5373f6f71816b961e38b3f2cdebb9473d1 --- /dev/null +++ b/shared/package-files/4a/4a555778c8c18d37a63be6c3c5dd6ec1f1db315a8bca1401881796dd69c39de9/reshape_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API reshape { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::reshape"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef shape); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef shape); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4a/4a5fd41eec82d0d2d774ea61d780b2a2da5f99c12021f73da05403c31c00f1af/binary_cross_entropy_backward_cuda_dispatch.h b/shared/package-files/4a/4a5fd41eec82d0d2d774ea61d780b2a2da5f99c12021f73da05403c31c00f1af/binary_cross_entropy_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9ab4bf562101a392da831bf18113de8f585d3ac4 --- /dev/null +++ b/shared/package-files/4a/4a5fd41eec82d0d2d774ea61d780b2a2da5f99c12021f73da05403c31c00f1af/binary_cross_entropy_backward_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor binary_cross_entropy_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/4a/4a63996e76ee3a1a33bee7d9e63fa21c1a6d43d5d6fdd6bc992b870c2de1e689/prune_functions.cpython-311.pyc b/shared/package-files/4a/4a63996e76ee3a1a33bee7d9e63fa21c1a6d43d5d6fdd6bc992b870c2de1e689/prune_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce4c3c07609481822e8085a9dee2671f5f269b6c Binary files /dev/null and b/shared/package-files/4a/4a63996e76ee3a1a33bee7d9e63fa21c1a6d43d5d6fdd6bc992b870c2de1e689/prune_functions.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a63b1614ee9ccd281a804af409ec38d7dd719417dda5ac684c6f747afe28aa2/WHEEL b/shared/package-files/4a/4a63b1614ee9ccd281a804af409ec38d7dd719417dda5ac684c6f747afe28aa2/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098 --- /dev/null +++ b/shared/package-files/4a/4a63b1614ee9ccd281a804af409ec38d7dd719417dda5ac684c6f747afe28aa2/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/shared/package-files/4a/4a689f46f82c3060e0a00856810b6042c71e81ec61e5d5a6d291bf33faef27ee/loopnest.h b/shared/package-files/4a/4a689f46f82c3060e0a00856810b6042c71e81ec61e5d5a6d291bf33faef27ee/loopnest.h new file mode 100644 index 0000000000000000000000000000000000000000..20614fea0bad9dafaf9190b1a931a8e24ed2b030 --- /dev/null +++ b/shared/package-files/4a/4a689f46f82c3060e0a00856810b6042c71e81ec61e5d5a6d291bf33faef27ee/loopnest.h @@ -0,0 +1,616 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace torch::jit::tensorexpr { + +class Expr; +class Var; +class Buf; +class Tensor; +class Function; +class Stmt; +class For; +class Block; +class Store; +class Dtype; + +class TORCH_API LoopNest { + public: + // A constructor for building a LoopNest from a list of Tensors + LoopNest( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + // A convenience constructor for the case when all tensors are output tensors + LoopNest(const std::vector& output_tensors); + + // A constructor for building a LoopNest from an Stmt and a list of output + // buffers. + LoopNest(StmtPtr stmt, std::unordered_set output_bufs); + + // A constructor for building a LoopNest from another loopnest. It clones the + // other loopnest's stmt. + LoopNest(const LoopNest& other); + + StmtPtr root_stmt() const { + return root_stmt_; + } + + std::vector getLoopStmtsFor(const Tensor&) const; + std::vector getLoopStmtsFor(const BufPtr&) const; + std::vector getLoopStmtsFor(StmtPtr) const; + StmtPtr getLoopBodyFor(const Tensor&) const; + StmtPtr getLoopBodyFor(BufPtr) const; + + // Returns the For stmt indexed by 'indices' in the 'root' For stmt. + //'indices' indicates the path to the returned loop from 'root' in AST, e.g., + // + // root: for(int i...){ + // j_loop: for (int j...){ + // k1_loop: for (int k1...){ + // A[i, j, k1] = .... + // } + // B[i, j] = ... + // k2_loop: for (int k2...){ + // A[i, j, k2] = ... + // } + // } + // } + // + // the path from 'root' to 'j_loop' is [0] + // the path from 'root' to 'k1_loop' is [0, 0] + // the path from 'root' to 'k2_loop' is [0, 2] + ForPtr getLoopAt(ForPtr root, const std::vector& indices) const; + + // Returns the For stmt that is immediately enclosing the given stmt. + static ForPtr getParentLoop(const StmtPtr& st); + + // Returns the list of For stmts corresponding to the loopnest that is + // enclosing the given stmt. + static std::vector getEnclosingLoopNest(const StmtPtr& st); + + // Returns a list of all Stmts that write to the given buf. + std::vector getAllWritesToBuf(BufPtr) const; + + // The following methods return the For loops that contain writes to + // the given buf. + // + // For example, consider the following code: + // for i1 + // for j1 + // a[i1,j1] = + // for i2 + // for j2 + // for k2 + // a[i2,j2] = + // for j3 + // a[i2,j3] = + + // Returns a list of For loops which directly contain a Stmt that writes + // to buf. + // For the above example: + // getAllInnermostLoopsWritingToBuf(a) => {j1, k2, j3} + std::vector getAllInnermostLoopsWritingToBuf(BufPtr) const; + + // Returns a list of For loopnests which contain a Stmt that writes to + // the given buf. Each loopnest here is a vector For loops. + // For the above example: + // getAllLoopNestsWritingToBuf(a) => {{i1,j1}, {i2,j2,k2}, {i2,j3}} + std::vector> getAllLoopNestsWritingToBuf(BufPtr) const; + + StmtPtr simplify(); + + // Sanitize variables and buffer names. + // The pass assigns predefined names for loop index variables + // (i,j,k,l,m,n,o,p,i1,j1,k1,...) and ensures these names are not conflicting + // anywhere. It also removes duplicates from other Buf nad Var names as well + // as replaces illegal characters in them with underscores. + // + // Note: since it's currently technically possible to use the same variable + // as index in two different loops, this transformation finds such cases and + // introduces new variables to avoid duplication. + static StmtPtr sanitizeNames(StmtPtr s); + + bool computeInline(const StmtPtr& s); + bool computeInline(const BufPtr& b); + void inlineIntermediateBufs(bool allow_duplicated_work); + + // Optimizes conditionals. + // + // Currently, only the following pattern of conditionals is optimized. + // This corresponds to the conditional format that is generated to handle + // `aten::cat` op. + // + // for (int i = 0; i < 20; i++) { + // A[i] = IfThenElse(i<5 ? 1 : 0, B[i], C[i-5]) + // } + // + // Constraints that must be satisfied for this optimization: + // * All conditions should be of the form "var < expr". + // * All conditions should have the same variable, say v. + // * The condition variable found should be the same as the inner-most + // loop variable. TODO: Remove this constraint. + // * If there are multiple stores that contain conditionals using the same + // loop variable, only the first conditional will be optimized. + // TODO: Remove this constraint. + bool optimizeConditionals(); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then the remaining iterations are extracted into a tail loop that is + // added after the given loop. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithTail(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 12; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // A[i_outer * 8 + i_inner] = + // } + // } + // for (int i_tail = 0; i_tail < 4; ++i_tail) { + // A[i_tail + 96] = + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` and `tail` parameters will be + // set to point to the inner and tail loops that are generated. + static void splitWithTail( + const ForPtr& f, + int factor, + ForPtr* inner, + ForPtr* tail); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithTail(const ForPtr& f, int factor); + + // Splits the given loop into 2 nested loops with the given factor as the + // inner loop bound. If the factor does not evenly divide the loop bound, + // then a conditional is inserted into the body to handle the remaining + // iterations appropriately. + // + // For example, consider the following code: + // for (int i = 0; i < 100; ++i) { + // A[i] = + // } + // + // splitWithMask(i, 8, ...) will result in: + // for (int i_outer = 0; i_outer < 13; ++i_outer) { + // for (int i_inner = 0; i_inner < 8; ++i_inner) { + // if (i_outer * 8 + i_inner < 100) { + // A[i_outer * 8 + i_inner] = + // } + // } + // } + // + // The given loop will be transformed to the outer loop after splitting. + // So, the pointer to the input loop should be valid after splitting and + // will point to the outer loop. The `inner` parameter will be set to point + // to the inner loop that is generated. + static void splitWithMask(const ForPtr& f, int factor, ForPtr* inner); + // A convenience wrapper when the caller does not need to access the + // split loops. + static void splitWithMask(const ForPtr& f, int factor); + + // The following methods support loop distribution. + // For example, consider the following code. This will be used to + // demonstrate the methods below. + // + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + + // This method distributes the given loop over its body by splitting + // after every given pivot stmt. + // + // NOTE: Pivot stmts that are not in the given loop's body will be ignored. + // + // For the above example: + // distributeLoop(S1, {S3, S5}) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop( + const ForPtr& loop, + const std::unordered_set& pivots); + + // This method distributes the given loop over every stmt in its body. + // + // For the above example: + // distributeLoop(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoop(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParents(S1) will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // : for m + // : for i + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // : for m + // : for i + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParents(const ForPtr& loop); + + // This method distributes the given loop over its body by splitting + // after every For stmt in its body. + // + // For the above example: + // distributeLoopOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopOverInnerLoops(const ForPtr& loop); + // Same as above, but also distribute parent loops. + // Returns the result of distributing the outermost loop. + // + // For the above example: + // distributeLoopAndParentsOverInnerLoops(S1) + // will result in: + // S0: for m + // S1: for i + // S2: A[i] = 0 + // S3: for j + // S4: A[i] = A[i] + + // : for m + // : for i + // S5: B[i] = A[i] + // S6: for k + // S7: B[i] = B[i] + + static std::vector distributeLoopAndParentsOverInnerLoops( + const ForPtr& loop); + + // This method performs loop fusion. + // For example, consider the following code. + // + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: for n + // S5: B[n] = A[n] + // S6: for k + // S7: B[n] = B[n] + + // + // fuseLoops({S1, S5}), will return the following loop: + // S1: for m + // S2: A[m] = 0 + // S3: for j + // S4: A[m] = A[m] + + // S5: B[m] = A[m] + // S6: for k + // S7: B[m] = B[m] + + // + // This transformation is unsafe as it simply add all loops into the body of + // the first loop for fusion without correctness checks. + // + // Below are the two requirements to apply unsafeFuseLoops: + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + static bool unsafeFuseLoops(const std::vector& loops, ForPtr* fused); + + // Loop fusion is done only when all the conditions below are satisfied. + // * All the loops have the same parent. + // * There are no statements between these loops in their parent body. + // * The start bounds are the same for all loops. + // * The stop bounds are the same for all loops. + // * Fusing the loops does not violate or add any dependencies. + static bool fuseLoops(const std::vector& loops, ForPtr* fused); + + static void reorderAxis(const ForPtr& a, const ForPtr& b); + + // Reorder the given list of loops according to the permutation specified. + // Here `permutation[i]` represents the position of the loop in the input + // which will end up at position `i` after the reorder. + // + // For example, consider the following code: + // for p + // for q + // for r + // for s + // A[p,q,r,s] = + // + // reorder({p, q, r, s}, {2, 3, 0, 1}) will return the list of loops in the + // following form: + // for r + // for s + // for p + // for q + // A[p,q,r,s] = + static std::vector reorder( + const std::vector& loops, + const std::vector& permutation); + + // Tile takes a 2d domain (x, y) and splits it into small rectangular blocks + // each with shape (x_factor, y_factor). The traversal over the domain turns + // into an outer iteration over the blocks and an inner traversal over all + // points in the block. + // Note that if x dim % x_factor or y dim % y_factor does not equal to 0, the + // loop body will generate corresponding tailing loops. + // The transformation is in-place and returns 'xtail'. + // + // For example, consider the following code: + // for i: [0, 64) + // for j: [0, 64) + // for k: [0, 32) + // A[i, j] = B[i, k] + C[j, k] + // + // tile(i, j, 4, 8) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 8) + // for i_inner: [0, 4) + // for j_inner: [0, 8) + // for k: [0, 32) + // A[i_outer * 4 + i_inner, j_outer * 8 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 8 + j_inner, k] + // + // tile(i, j, 4, 9) will transform "i" for-stmt into the following nested + // loop: + // for i_outer: [0, 16) + // for j_outer: [0, 7) + // for i_inner: [0, 4) + // for j_inner: [0, 9) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, j_outer * 9 + j_inner] = + // B[i_outer * 4 + i_inner, k] + C[j_outer * 9 + j_inner, k] + // for j_tail: [0, 1) + // for i_inner: [0, 4) + // for k: (0, 32) + // A[i_outer * 4 + i_inner, 7 * 9 + j_tail] = + // B[i_outer * 4 + i_inner, k] + C[7 * 9 + j_tail, k] + ForPtr tile(const ForPtr& x, const ForPtr& y, int x_factor, int y_factor); + + // Returns true if the given loops are perfectly nested, i.e., every loop + // (except the innermost) should have exactly one statement in its body + // and that statement must be the next inner loop. + static bool areLoopsPerfectlyNested(const std::vector& loops); + + // Returns true if the given loop has a loop-carried dependence. + static bool hasLoopCarriedDependence(const ForPtr& loop); + + // Unrolls all the iterations of the given loop. + // Requires that the loop bounds are constant. + static void fullUnroll(const ForPtr& f, StmtPtr* unrolled); + static void fullUnroll(const ForPtr& f); + + // Unrolls the given loop for the specified factor. + // This does not require constant bounds for the loop being unrolled. + static void unroll(const ForPtr& f, int factor, ForPtr* tail); + static void unroll(const ForPtr& f, int factor); + + static bool normalize(const ForPtr& f); + static bool isNormalized(const ForPtr& f); + + static bool flatten(const std::vector& f, ForPtr* flattened); + static bool flatten(const std::vector& f); + + // Compresses the given buffer based on its use in the given Stmts. + // + // NOTE: This API assumes that there are no accesses to the given buffer + // outside the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // For example, given the input: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[i,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[i,j] + A[i, j+1] + // } + // } + // + // compressBuffer(A, ...) will compress buffer A from + // [100, 200] to [1, 200] and modify the code as follows: + // + // for (int i = 0; i < 100; ++i) { + // for (int j = 0; j < 200; ++j) { + // A[0,j] = sin(i*j) + // } + // for (int j = 0; j < 199; ++j) { + // B[i,j] = A[0,j] + A[0, j+1] + // } + // } + static void compressBuffer(const BufPtr& buf, const StmtPtr& stmt); + + // Compresses all buffers in the given statement. + // + // NOTE: This API assumes that there are no accesses to buffers outside + // the given statement. So, this should be called with the entire + // kernel statement to avoid incorrect buffer compressions. + // + // TODO: Add an IR verifier check to detect invalidly compressed buffers. + static void compressAllBuffers(const StmtPtr& stmt); + + // Get 'num' loops from the loopnest starting at 'f'. + static std::vector getLoopStmtsInLoopNest( + const ForPtr& f, + size_t num); + + // LoopOptions are propagated to tail. + static void sliceHead( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceHead(const ForPtr& f, int factor); + // LoopOptions are propagated to head. + static void sliceTail( + const ForPtr& f, + int factor, + ForPtr* head, + ForPtr* tail); + static void sliceTail(const ForPtr& f, int factor); + + using AccessResult = std::pair; + // Insert a cache for the consumer's usages of the buffer produced in + // consumer, and redirect reads and writes in the consumer to that cache. + // Returns a pair of the new cache buffer, and the new rewritten consumer. + static AccessResult cacheAccesses( + const BufPtr& producer, + const std::string& name, + const StmtPtr& consumer); + + // Insert a temporary computation of statement S in the scope of loop AT. + // S is assumed to be a Store or a Block containing a Store. Along with the + // computation itself, this transformation inserts Alloc/Free statements for + // the temporary buffer used in the computation. + static void computeAt(const StmtPtr& s, const ForPtr& at); + + // Rfactor a reduction axis into a normal axis. + // + // Requirements: + // * S is the reduction store + // * S is the only statement in the innermost loop + // * There is at least two reduction arguments in S + // * OUTER_REDUCTION_FOR loop corresponds to the outermost reduction variable + // used in the store and all other reduction variables are index variables of + // children loops of OUTER_REDUCTION_FOR + // * OUTER_REDUCTION_FOR is a perfect loop nest, i.e. it has only loops + // corresponding to the other reduction variables and the store, nested into + // each other + // + // What it does: + // * Introduce a new buffer with an extra dimension of a size equal to the + // span of the loop OUTER_REDUCTION_FOR (the new buffer is returned via + // RFAC_BUF_PTR) + // * Insert an initialization store for the new buffer in + // OUTER_REDUCTION_FOR before its nested loop + // * Replace the reduction store to the original buffer with the reduction + // store to the temp buffer, removing the index var of OUTER_REDUCTION_FOR + // from reduction arguments + // * Insert a final reduction store over the extra dimension of the new + // buffer to the original buffer + // * Returns TRUE if the transformation succeeded and FALSE otherwise + // + // Example: + // Original IR: + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis + // S4: for k # reduction axis + // S5: X[i] = ReduceOp(X[i] + Y[i,j,k], reduce_axis={j,k}) + // + // After RFACTOR(S5, S3) + // S1: for i # normal axis + // S2: X[i] = 0 + // S3: for j # reduction axis for X, normal axis for X_rfac + // X_rfac[i,j] = 0 + // S4: for k # reduction axis + // X_rfac[i,j] = ReduceOp(X_rfac[i,j] + Y[i,j,k], reduce_axis={k}) + // X[i] = ReduceOp(X[i] + X_rfac[i,j], reduce_axis={j}) + static bool rfactor(const StmtPtr& s, const ForPtr& outer_reduction_for); + static bool rfactor( + const StmtPtr& s, + const ForPtr& outer_reduction_for, + BufPtr* rfac_buf_ptr); + + // Vectorize the given loop. This method requires that the given loop + // does not perform a reduction. + // It returns true if vectorization is successful and false otherwise. + static bool vectorize(const ForPtr&); + + // Find the inner-most loops and vectorize them. Currently, this only works + // for the LLVM backend, when no reductions are involved. + void vectorizeInnerLoops(); + + void eliminateDeadStores(); + + void prepareForCodegen(); + + const std::unordered_set getInputBufs() const; + const std::unordered_set getOutputBufs() const { + return output_bufs_; + } + std::vector getIntermediateBufs() const; + + // Finds which is the outer For between a and b for loops. If neither of the 2 + // Fors is an ancestor of the other, it returns nullptr. + static ForPtr findOuterFor(ForPtr a, ForPtr b); + + private: + void initialize( + const std::vector& output_tensors, + const std::vector& tensors_to_compute); + + StmtPtr root_stmt_; + + std::unordered_set output_bufs_; +}; + +TORCH_API StmtPtr FlattenIndexes(const StmtPtr& s); + +// TODO: Revisit this once we decide on how dependencies analysis should look +// like. Maybe we would choose to use a different API and BufUse would be +// removed, or if we decide to keep it we need to properly document its API. +struct BufLoadOrStoreUse { + StmtPtr s; + bool isStore; +}; + +/* + * Returns a map ( Buf -> uses of this Buf), uses are represented as vectors of + * BufUse elements, which are StmtPtr and a bool isStore flag. The order of uses + * in the vectors reflects the order in which the uses appear in the given + * statement. + */ +std::unordered_map> findLoadOrStoreUses( + const StmtPtr& s); + +// replaces all invalid characters with underscore +TORCH_API std::string sanitizeName(const std::string& input_name); + +} // namespace torch::jit::tensorexpr diff --git a/shared/package-files/4a/4a70e1deb5ae24590feeec413bee750e0c7fabe2d1bf0c7d32cf8c6b607b29e0/dataframe_protocol.cpython-311.pyc b/shared/package-files/4a/4a70e1deb5ae24590feeec413bee750e0c7fabe2d1bf0c7d32cf8c6b607b29e0/dataframe_protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e84e456429cffbacafba9320ab544734df4a1633 Binary files /dev/null and b/shared/package-files/4a/4a70e1deb5ae24590feeec413bee750e0c7fabe2d1bf0c7d32cf8c6b607b29e0/dataframe_protocol.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a7653a9281aacf8c70054a7c8b09265ebce04cc9735bd77400008faacf46757/test_rank.py b/shared/package-files/4a/4a7653a9281aacf8c70054a7c8b09265ebce04cc9735bd77400008faacf46757/test_rank.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7a0b373f5f8ad16b8e35167a1c9b71f0d21753 --- /dev/null +++ b/shared/package-files/4a/4a7653a9281aacf8c70054a7c8b09265ebce04cc9735bd77400008faacf46757/test_rank.py @@ -0,0 +1,510 @@ +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest + +from pandas._libs.algos import ( + Infinity, + NegInfinity, +) + +from pandas import ( + DataFrame, + Index, + Series, +) +import pandas._testing as tm + + +class TestRank: + s = Series([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]) + df = DataFrame({"A": s, "B": s}) + + results = { + "average": np.array([1.5, 5.5, 7.0, 3.5, np.nan, 3.5, 1.5, 8.0, np.nan, 5.5]), + "min": np.array([1, 5, 7, 3, np.nan, 3, 1, 8, np.nan, 5]), + "max": np.array([2, 6, 7, 4, np.nan, 4, 2, 8, np.nan, 6]), + "first": np.array([1, 5, 7, 3, np.nan, 4, 2, 8, np.nan, 6]), + "dense": np.array([1, 3, 4, 2, np.nan, 2, 1, 5, np.nan, 3]), + } + + @pytest.fixture(params=["average", "min", "max", "first", "dense"]) + def method(self, request): + """ + Fixture for trying all rank methods + """ + return request.param + + def test_rank(self, float_frame): + sp_stats = pytest.importorskip("scipy.stats") + + float_frame.loc[::2, "A"] = np.nan + float_frame.loc[::3, "B"] = np.nan + float_frame.loc[::4, "C"] = np.nan + float_frame.loc[::5, "D"] = np.nan + + ranks0 = float_frame.rank() + ranks1 = float_frame.rank(1) + mask = np.isnan(float_frame.values) + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals) + exp0[mask] = np.nan + + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals) + exp1[mask] = np.nan + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # integers + df = DataFrame( + np.random.default_rng(2).integers(0, 5, size=40).reshape((10, 4)) + ) + + result = df.rank() + exp = df.astype(float).rank() + tm.assert_frame_equal(result, exp) + + result = df.rank(1) + exp = df.astype(float).rank(1) + tm.assert_frame_equal(result, exp) + + def test_rank2(self): + df = DataFrame([[1, 3, 2], [1, 2, 3]]) + expected = DataFrame([[1.0, 3.0, 2.0], [1, 2, 3]]) / 3.0 + result = df.rank(1, pct=True) + tm.assert_frame_equal(result, expected) + + df = DataFrame([[1, 3, 2], [1, 2, 3]]) + expected = df.rank(0) / 2.0 + result = df.rank(0, pct=True) + tm.assert_frame_equal(result, expected) + + df = DataFrame([["b", "c", "a"], ["a", "c", "b"]]) + expected = DataFrame([[2.0, 3.0, 1.0], [1, 3, 2]]) + result = df.rank(1, numeric_only=False) + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[2.0, 1.5, 1.0], [1, 1.5, 2]]) + result = df.rank(0, numeric_only=False) + tm.assert_frame_equal(result, expected) + + df = DataFrame([["b", np.nan, "a"], ["a", "c", "b"]]) + expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 3.0, 2.0]]) + result = df.rank(1, numeric_only=False) + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[2.0, np.nan, 1.0], [1.0, 1.0, 2.0]]) + result = df.rank(0, numeric_only=False) + tm.assert_frame_equal(result, expected) + + # f7u12, this does not work without extensive workaround + data = [ + [datetime(2001, 1, 5), np.nan, datetime(2001, 1, 2)], + [datetime(2000, 1, 2), datetime(2000, 1, 3), datetime(2000, 1, 1)], + ] + df = DataFrame(data) + + # check the rank + expected = DataFrame([[2.0, np.nan, 1.0], [2.0, 3.0, 1.0]]) + result = df.rank(1, numeric_only=False, ascending=True) + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[1.0, np.nan, 2.0], [2.0, 1.0, 3.0]]) + result = df.rank(1, numeric_only=False, ascending=False) + tm.assert_frame_equal(result, expected) + + df = DataFrame({"a": [1e-20, -5, 1e-20 + 1e-40, 10, 1e60, 1e80, 1e-30]}) + exp = DataFrame({"a": [3.5, 1.0, 3.5, 5.0, 6.0, 7.0, 2.0]}) + tm.assert_frame_equal(df.rank(), exp) + + def test_rank_does_not_mutate(self): + # GH#18521 + # Check rank does not mutate DataFrame + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 3)), dtype="float64" + ) + expected = df.copy() + df.rank() + result = df + tm.assert_frame_equal(result, expected) + + def test_rank_mixed_frame(self, float_string_frame): + float_string_frame["datetime"] = datetime.now() + float_string_frame["timedelta"] = timedelta(days=1, seconds=1) + + float_string_frame.rank(numeric_only=False) + with pytest.raises(TypeError, match="not supported between instances of"): + float_string_frame.rank(axis=1) + + def test_rank_na_option(self, float_frame): + sp_stats = pytest.importorskip("scipy.stats") + + float_frame.loc[::2, "A"] = np.nan + float_frame.loc[::3, "B"] = np.nan + float_frame.loc[::4, "C"] = np.nan + float_frame.loc[::5, "D"] = np.nan + + # bottom + ranks0 = float_frame.rank(na_option="bottom") + ranks1 = float_frame.rank(1, na_option="bottom") + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fvals) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fvals) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # top + ranks0 = float_frame.rank(na_option="top") + ranks1 = float_frame.rank(1, na_option="top") + + fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values + fval1 = float_frame.T + fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T + fval1 = fval1.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, fval0) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, fval1) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # descending + + # bottom + ranks0 = float_frame.rank(na_option="top", ascending=False) + ranks1 = float_frame.rank(1, na_option="top", ascending=False) + + fvals = float_frame.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fvals) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fvals) + + tm.assert_almost_equal(ranks0.values, exp0) + tm.assert_almost_equal(ranks1.values, exp1) + + # descending + + # top + ranks0 = float_frame.rank(na_option="bottom", ascending=False) + ranks1 = float_frame.rank(1, na_option="bottom", ascending=False) + + fval0 = float_frame.fillna((float_frame.min() - 1).to_dict()).values + fval1 = float_frame.T + fval1 = fval1.fillna((fval1.min() - 1).to_dict()).T + fval1 = fval1.fillna(np.inf).values + + exp0 = np.apply_along_axis(sp_stats.rankdata, 0, -fval0) + exp1 = np.apply_along_axis(sp_stats.rankdata, 1, -fval1) + + tm.assert_numpy_array_equal(ranks0.values, exp0) + tm.assert_numpy_array_equal(ranks1.values, exp1) + + # bad values throw error + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + + with pytest.raises(ValueError, match=msg): + float_frame.rank(na_option="bad", ascending=False) + + # invalid type + with pytest.raises(ValueError, match=msg): + float_frame.rank(na_option=True, ascending=False) + + def test_rank_axis(self): + # check if using axes' names gives the same result + df = DataFrame([[2, 1], [4, 3]]) + tm.assert_frame_equal(df.rank(axis=0), df.rank(axis="index")) + tm.assert_frame_equal(df.rank(axis=1), df.rank(axis="columns")) + + @pytest.mark.parametrize("ax", [0, 1]) + @pytest.mark.parametrize("m", ["average", "min", "max", "first", "dense"]) + def test_rank_methods_frame(self, ax, m): + sp_stats = pytest.importorskip("scipy.stats") + + xs = np.random.default_rng(2).integers(0, 21, (100, 26)) + xs = (xs - 10.0) / 10.0 + cols = [chr(ord("z") - i) for i in range(xs.shape[1])] + + for vals in [xs, xs + 1e6, xs * 1e-6]: + df = DataFrame(vals, columns=cols) + + result = df.rank(axis=ax, method=m) + sprank = np.apply_along_axis( + sp_stats.rankdata, ax, vals, m if m != "first" else "ordinal" + ) + sprank = sprank.astype(np.float64) + expected = DataFrame(sprank, columns=cols).astype("float64") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) + def test_rank_descending(self, method, dtype): + if "i" in dtype: + df = self.df.dropna().astype(dtype) + else: + df = self.df.astype(dtype) + + res = df.rank(ascending=False) + expected = (df.max() - df).rank() + tm.assert_frame_equal(res, expected) + + expected = (df.max() - df).rank(method=method) + + if dtype != "O": + res2 = df.rank(method=method, ascending=False, numeric_only=True) + tm.assert_frame_equal(res2, expected) + + res3 = df.rank(method=method, ascending=False, numeric_only=False) + tm.assert_frame_equal(res3, expected) + + @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.parametrize("dtype", [None, object]) + def test_rank_2d_tie_methods(self, method, axis, dtype): + df = self.df + + def _check2d(df, expected, method="average", axis=0): + exp_df = DataFrame({"A": expected, "B": expected}) + + if axis == 1: + df = df.T + exp_df = exp_df.T + + result = df.rank(method=method, axis=axis) + tm.assert_frame_equal(result, exp_df) + + frame = df if dtype is None else df.astype(dtype) + _check2d(frame, self.results[method], method=method, axis=axis) + + @pytest.mark.parametrize( + "method,exp", + [ + ("dense", [[1.0, 1.0, 1.0], [1.0, 0.5, 2.0 / 3], [1.0, 0.5, 1.0 / 3]]), + ( + "min", + [ + [1.0 / 3, 1.0, 1.0], + [1.0 / 3, 1.0 / 3, 2.0 / 3], + [1.0 / 3, 1.0 / 3, 1.0 / 3], + ], + ), + ( + "max", + [[1.0, 1.0, 1.0], [1.0, 2.0 / 3, 2.0 / 3], [1.0, 2.0 / 3, 1.0 / 3]], + ), + ( + "average", + [[2.0 / 3, 1.0, 1.0], [2.0 / 3, 0.5, 2.0 / 3], [2.0 / 3, 0.5, 1.0 / 3]], + ), + ( + "first", + [ + [1.0 / 3, 1.0, 1.0], + [2.0 / 3, 1.0 / 3, 2.0 / 3], + [3.0 / 3, 2.0 / 3, 1.0 / 3], + ], + ), + ], + ) + def test_rank_pct_true(self, method, exp): + # see gh-15630. + + df = DataFrame([[2012, 66, 3], [2012, 65, 2], [2012, 65, 1]]) + result = df.rank(method=method, pct=True) + + expected = DataFrame(exp) + tm.assert_frame_equal(result, expected) + + @pytest.mark.single_cpu + def test_pct_max_many_rows(self): + # GH 18271 + df = DataFrame( + {"A": np.arange(2**24 + 1), "B": np.arange(2**24 + 1, 0, -1)} + ) + result = df.rank(pct=True).max() + assert (result == 1).all() + + @pytest.mark.parametrize( + "contents,dtype", + [ + ( + [ + -np.inf, + -50, + -1, + -1e-20, + -1e-25, + -1e-50, + 0, + 1e-40, + 1e-20, + 1e-10, + 2, + 40, + np.inf, + ], + "float64", + ), + ( + [ + -np.inf, + -50, + -1, + -1e-20, + -1e-25, + -1e-45, + 0, + 1e-40, + 1e-20, + 1e-10, + 2, + 40, + np.inf, + ], + "float32", + ), + ([np.iinfo(np.uint8).min, 1, 2, 100, np.iinfo(np.uint8).max], "uint8"), + ( + [ + np.iinfo(np.int64).min, + -100, + 0, + 1, + 9999, + 100000, + 1e10, + np.iinfo(np.int64).max, + ], + "int64", + ), + ([NegInfinity(), "1", "A", "BA", "Ba", "C", Infinity()], "object"), + ( + [datetime(2001, 1, 1), datetime(2001, 1, 2), datetime(2001, 1, 5)], + "datetime64", + ), + ], + ) + def test_rank_inf_and_nan(self, contents, dtype, frame_or_series): + dtype_na_map = { + "float64": np.nan, + "float32": np.nan, + "object": None, + "datetime64": np.datetime64("nat"), + } + # Insert nans at random positions if underlying dtype has missing + # value. Then adjust the expected order by adding nans accordingly + # This is for testing whether rank calculation is affected + # when values are interwined with nan values. + values = np.array(contents, dtype=dtype) + exp_order = np.array(range(len(values)), dtype="float64") + 1.0 + if dtype in dtype_na_map: + na_value = dtype_na_map[dtype] + nan_indices = np.random.default_rng(2).choice(range(len(values)), 5) + values = np.insert(values, nan_indices, na_value) + exp_order = np.insert(exp_order, nan_indices, np.nan) + + # Shuffle the testing array and expected results in the same way + random_order = np.random.default_rng(2).permutation(len(values)) + obj = frame_or_series(values[random_order]) + expected = frame_or_series(exp_order[random_order], dtype="float64") + result = obj.rank() + tm.assert_equal(result, expected) + + def test_df_series_inf_nan_consistency(self): + # GH#32593 + index = [5, 4, 3, 2, 1, 6, 7, 8, 9, 10] + col1 = [5, 4, 3, 5, 8, 5, 2, 1, 6, 6] + col2 = [5, 4, np.nan, 5, 8, 5, np.inf, np.nan, 6, -np.inf] + df = DataFrame( + data={ + "col1": col1, + "col2": col2, + }, + index=index, + dtype="f8", + ) + df_result = df.rank() + + series_result = df.copy() + series_result["col1"] = df["col1"].rank() + series_result["col2"] = df["col2"].rank() + + tm.assert_frame_equal(df_result, series_result) + + def test_rank_both_inf(self): + # GH#32593 + df = DataFrame({"a": [-np.inf, 0, np.inf]}) + expected = DataFrame({"a": [1.0, 2.0, 3.0]}) + result = df.rank() + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "na_option,ascending,expected", + [ + ("top", True, [3.0, 1.0, 2.0]), + ("top", False, [2.0, 1.0, 3.0]), + ("bottom", True, [2.0, 3.0, 1.0]), + ("bottom", False, [1.0, 3.0, 2.0]), + ], + ) + def test_rank_inf_nans_na_option( + self, frame_or_series, method, na_option, ascending, expected + ): + obj = frame_or_series([np.inf, np.nan, -np.inf]) + result = obj.rank(method=method, na_option=na_option, ascending=ascending) + expected = frame_or_series(expected) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "na_option,ascending,expected", + [ + ("bottom", True, [1.0, 2.0, 4.0, 3.0]), + ("bottom", False, [1.0, 2.0, 4.0, 3.0]), + ("top", True, [2.0, 3.0, 1.0, 4.0]), + ("top", False, [2.0, 3.0, 1.0, 4.0]), + ], + ) + def test_rank_object_first( + self, frame_or_series, na_option, ascending, expected, using_infer_string + ): + obj = frame_or_series(["foo", "foo", None, "foo"]) + result = obj.rank(method="first", na_option=na_option, ascending=ascending) + expected = frame_or_series(expected) + if using_infer_string and isinstance(obj, Series): + expected = expected.astype("uint64") + tm.assert_equal(result, expected) + + @pytest.mark.parametrize( + "data,expected", + [ + ( + {"a": [1, 2, "a"], "b": [4, 5, 6]}, + DataFrame({"b": [1.0, 2.0, 3.0]}, columns=Index(["b"], dtype=object)), + ), + ({"a": [1, 2, "a"]}, DataFrame(index=range(3), columns=[])), + ], + ) + def test_rank_mixed_axis_zero(self, data, expected): + df = DataFrame(data, columns=Index(list(data.keys()), dtype=object)) + with pytest.raises(TypeError, match="'<' not supported between instances of"): + df.rank() + result = df.rank(numeric_only=True) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "dtype, exp_dtype", + [("string[pyarrow]", "Int64"), ("string[pyarrow_numpy]", "float64")], + ) + def test_rank_string_dtype(self, dtype, exp_dtype): + # GH#55362 + pytest.importorskip("pyarrow") + obj = Series(["foo", "foo", None, "foo"], dtype=dtype) + result = obj.rank(method="first") + expected = Series([1, 2, None, 3], dtype=exp_dtype) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/4a/4a7bc713c9ba4dae79c96845636a318ebbd966066008594544977f99904a6c33/test_searchbase.cpython-311.pyc b/shared/package-files/4a/4a7bc713c9ba4dae79c96845636a318ebbd966066008594544977f99904a6c33/test_searchbase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..add7da0b2da9aa167ed0a40eadeee40237931682 Binary files /dev/null and b/shared/package-files/4a/4a7bc713c9ba4dae79c96845636a318ebbd966066008594544977f99904a6c33/test_searchbase.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a7c46c23142a81db16cb009be53b6f0a6a1598e2cd7b993b7075044755ae134/__init__.cpython-311.pyc b/shared/package-files/4a/4a7c46c23142a81db16cb009be53b6f0a6a1598e2cd7b993b7075044755ae134/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27652d53c72bccf9eb681b20730d6138a68c5a3b Binary files /dev/null and b/shared/package-files/4a/4a7c46c23142a81db16cb009be53b6f0a6a1598e2cd7b993b7075044755ae134/__init__.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a7dc00a3dbd8d5e54f4d11c18ec0f667541f6ca841575f25f0717f7859ce589/async_case.cpython-311.pyc b/shared/package-files/4a/4a7dc00a3dbd8d5e54f4d11c18ec0f667541f6ca841575f25f0717f7859ce589/async_case.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7949a2e17155d92699ab7e7d9aa6abfa7ecced6 Binary files /dev/null and b/shared/package-files/4a/4a7dc00a3dbd8d5e54f4d11c18ec0f667541f6ca841575f25f0717f7859ce589/async_case.cpython-311.pyc differ diff --git a/shared/package-files/4a/4a827535f5bedca717e617dcdc97ae0adf5fe3d4eb6bc1ff1fd268cd0627bf8c/record_stream.h b/shared/package-files/4a/4a827535f5bedca717e617dcdc97ae0adf5fe3d4eb6bc1ff1fd268cd0627bf8c/record_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..ab868ef5a71e9c2bef32209266bc494254100ff6 --- /dev/null +++ b/shared/package-files/4a/4a827535f5bedca717e617dcdc97ae0adf5fe3d4eb6bc1ff1fd268cd0627bf8c/record_stream.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/shared/package-files/4a/4a86a2a6bbec23cd322e61009e5157d2216e7efe91b4a8e330cad5c106638d02/nvtxImplCudaRt_v3.h b/shared/package-files/4a/4a86a2a6bbec23cd322e61009e5157d2216e7efe91b4a8e330cad5c106638d02/nvtxImplCudaRt_v3.h new file mode 100644 index 0000000000000000000000000000000000000000..24be8bd4722506d4ca318b07519884fc407847cd --- /dev/null +++ b/shared/package-files/4a/4a86a2a6bbec23cd322e61009e5157d2216e7efe91b4a8e330cad5c106638d02/nvtxImplCudaRt_v3.h @@ -0,0 +1,112 @@ +/* This file was procedurally generated! Do not modify this file by hand. */ + +/* +* Copyright 2009-2016 NVIDIA Corporation. All rights reserved. +* +* NOTICE TO USER: +* +* This source code is subject to NVIDIA ownership rights under U.S. and +* international Copyright laws. +* +* This software and the information contained herein is PROPRIETARY and +* CONFIDENTIAL to NVIDIA and is being provided under the terms and conditions +* of a form of NVIDIA software license agreement. +* +* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE +* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR +* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH +* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF +* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. +* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, +* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +* OR PERFORMANCE OF THIS SOURCE CODE. +* +* U.S. Government End Users. This source code is a "commercial item" as +* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of +* "commercial computer software" and "commercial computer software +* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) +* and is provided to the U.S. Government only as a commercial end item. +* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through +* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the +* source code with only those rights set forth herein. +* +* Any use of this source code in individual and commercial software must +* include, in the user documentation and internal comments to the code, +* the above Disclaimer and U.S. Government End Users Notice. +*/ + +#ifndef NVTX_IMPL_GUARD_CUDART +#error Never include this file directly -- it is automatically included by nvToolsExtCudaRt.h (except when NVTX_NO_IMPL is defined). +#endif + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +//typedef void (NVTX_API * nvtxNameCudaDeviceA_impl_fntype)(int device, const char* name); +//typedef void (NVTX_API * nvtxNameCudaDeviceW_impl_fntype)(int device, const wchar_t* name); +typedef void (NVTX_API * nvtxNameCudaStreamA_impl_fntype)(cudaStream_t stream, const char* name); +typedef void (NVTX_API * nvtxNameCudaStreamW_impl_fntype)(cudaStream_t stream, const wchar_t* name); +typedef void (NVTX_API * nvtxNameCudaEventA_impl_fntype)(cudaEvent_t event, const char* name); +typedef void (NVTX_API * nvtxNameCudaEventW_impl_fntype)(cudaEvent_t event, const wchar_t* name); + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaDeviceA(int device, const char* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaDeviceA_impl_fntype local = (nvtxNameCudaDeviceA_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaDeviceA_impl_fnptr; + if(local!=0) + (*local)(device, name); +#endif /*NVTX_DISABLE*/ +} + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaDeviceW(int device, const wchar_t* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaDeviceW_impl_fntype local = (nvtxNameCudaDeviceW_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaDeviceW_impl_fnptr; + if(local!=0) + (*local)(device, name); +#endif /*NVTX_DISABLE*/ +} + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaStreamA(cudaStream_t stream, const char* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaStreamA_impl_fntype local = (nvtxNameCudaStreamA_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaStreamA_impl_fnptr; + if(local!=0) + (*local)(stream, name); +#endif /*NVTX_DISABLE*/ +} + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaStreamW(cudaStream_t stream, const wchar_t* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaStreamW_impl_fntype local = (nvtxNameCudaStreamW_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaStreamW_impl_fnptr; + if(local!=0) + (*local)(stream, name); +#endif /*NVTX_DISABLE*/ +} + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaEventA(cudaEvent_t event, const char* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaEventA_impl_fntype local = (nvtxNameCudaEventA_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaEventA_impl_fnptr; + if(local!=0) + (*local)(event, name); +#endif /*NVTX_DISABLE*/ +} + +NVTX_DECLSPEC void NVTX_API nvtxNameCudaEventW(cudaEvent_t event, const wchar_t* name) +{ +#ifndef NVTX_DISABLE + nvtxNameCudaEventW_impl_fntype local = (nvtxNameCudaEventW_impl_fntype)NVTX_VERSIONED_IDENTIFIER(nvtxGlobals).nvtxNameCudaEventW_impl_fnptr; + if(local!=0) + (*local)(event, name); +#endif /*NVTX_DISABLE*/ +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + diff --git a/shared/package-files/4a/4a8972aa04cc00d67ced248da601859e7b23e6b6868dacb4c2345cc1b9c26c1d/accumulation_queue.h b/shared/package-files/4a/4a8972aa04cc00d67ced248da601859e7b23e6b6868dacb4c2345cc1b9c26c1d/accumulation_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..a173f9840388fd955530ea5561cb4953b871fd57 --- /dev/null +++ b/shared/package-files/4a/4a8972aa04cc00d67ced248da601859e7b23e6b6868dacb4c2345cc1b9c26c1d/accumulation_queue.h @@ -0,0 +1,161 @@ +// 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. + +#pragma once + +#include +#include +#include +#include + +#include "arrow/compute/exec.h" +#include "arrow/result.h" + +namespace arrow { +namespace acero { +namespace util { + +using arrow::compute::ExecBatch; + +/// \brief A container that accumulates batches until they are ready to +/// be processed. +class AccumulationQueue { + public: + AccumulationQueue() : row_count_(0) {} + ~AccumulationQueue() = default; + + // We should never be copying ExecBatch around + AccumulationQueue(const AccumulationQueue&) = delete; + AccumulationQueue& operator=(const AccumulationQueue&) = delete; + + AccumulationQueue(AccumulationQueue&& that); + AccumulationQueue& operator=(AccumulationQueue&& that); + + void Concatenate(AccumulationQueue&& that); + void InsertBatch(ExecBatch batch); + int64_t row_count() { return row_count_; } + size_t batch_count() { return batches_.size(); } + bool empty() const { return batches_.empty(); } + void Clear(); + ExecBatch& operator[](size_t i); + + private: + int64_t row_count_; + std::vector batches_; +}; + +/// A queue that sequences incoming batches +/// +/// This can be used when a node needs to do some kind of ordered processing on +/// the stream. +/// +/// Batches can be inserted in any order. The process_callback will be called on +/// the batches, in order, without reentrant calls. For this reason the callback +/// should be quick. +/// +/// For example, in a top-n node, the process callback should determine how many +/// rows need to be delivered for the given batch, and then return a task to actually +/// deliver those rows. +class SequencingQueue { + public: + using Task = std::function; + + /// Strategy that describes how to handle items + class Processor { + public: + /// Process the batch, potentially generating a task + /// + /// This method will be called on each batch in order. Calls to this method + /// will be serialized and it will not be called reentrantly. This makes it + /// safe to do things that rely on order but minimal time should be spent here + /// to avoid becoming a bottleneck. + /// + /// \return a follow-up task that will be scheduled. The follow-up task(s) are + /// is not guaranteed to run in any particular order. If nullopt is + /// returned then nothing will be scheduled. + virtual Result> Process(ExecBatch batch) = 0; + /// Schedule a task + virtual void Schedule(Task task) = 0; + }; + + virtual ~SequencingQueue() = default; + + /// Insert a batch into the queue + /// + /// This will insert the batch into the queue. If this batch was the next batch + /// to deliver then this will trigger 1+ calls to the process callback to generate + /// 1+ tasks. + /// + /// The task generated by this call will be executed immediately. The remaining + /// tasks will be scheduled using the schedule callback. + /// + /// From a data pipeline perspective the sequencing queue is a "sometimes" breaker. If + /// a task arrives in order then this call will usually execute the downstream pipeline. + /// If this task arrives early then this call will only queue the data. + virtual Status InsertBatch(ExecBatch batch) = 0; + + /// Create a queue + /// \param processor describes how to process the batches, must outlive the queue + static std::unique_ptr Make(Processor* processor); +}; + +/// A queue that sequences incoming batches +/// +/// Unlike SequencingQueue the Process method is not expected to schedule new tasks. +/// +/// If a batch arrives and another thread is currently processing then the batch +/// will be queued and control will return. In other words, delivery of batches will +/// not block on the Process method. +/// +/// It can be helpful to think of this as if a dedicated thread is running Process as +/// batches arrive +class SerialSequencingQueue { + public: + /// Strategy that describes how to handle items + class Processor { + public: + virtual ~Processor() = default; + /// Process the batch + /// + /// This method will be called on each batch in order. Calls to this method + /// will be serialized and it will not be called reentrantly. This makes it + /// safe to do things that rely on order. + /// + /// If this falls behind then data may accumulate + /// + /// TODO: Could add backpressure if needed but right now all uses of this should + /// be pretty fast and so are unlikely to block. + virtual Status Process(ExecBatch batch) = 0; + }; + + virtual ~SerialSequencingQueue() = default; + + /// Insert a batch into the queue + /// + /// This will insert the batch into the queue. If this batch was the next batch + /// to deliver then this may trigger calls to the processor which will be run + /// as part of this call. + virtual Status InsertBatch(ExecBatch batch) = 0; + + /// Create a queue + /// \param processor describes how to process the batches, must outlive the queue + static std::unique_ptr Make(Processor* processor); +}; + +} // namespace util +} // namespace acero +} // namespace arrow diff --git a/shared/package-files/4a/4a8d201fd7bed4e8771c6ceb5e82ea00dc8fe254d305f1871d5a39bc275b7dd9/ellipse.py b/shared/package-files/4a/4a8d201fd7bed4e8771c6ceb5e82ea00dc8fe254d305f1871d5a39bc275b7dd9/ellipse.py new file mode 100644 index 0000000000000000000000000000000000000000..199db25fde9b019893a275d69959154990e8a4a7 --- /dev/null +++ b/shared/package-files/4a/4a8d201fd7bed4e8771c6ceb5e82ea00dc8fe254d305f1871d5a39bc275b7dd9/ellipse.py @@ -0,0 +1,1768 @@ +"""Elliptical geometrical entities. + +Contains +* Ellipse +* Circle + +""" + +from sympy.core.expr import Expr +from sympy.core.relational import Eq +from sympy.core import S, pi, sympify +from sympy.core.evalf import N +from sympy.core.parameters import global_parameters +from sympy.core.logic import fuzzy_bool +from sympy.core.numbers import Rational, oo +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol +from sympy.simplify.simplify import simplify +from sympy.simplify.trigsimp import trigsimp +from sympy.functions.elementary.miscellaneous import sqrt, Max +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.functions.special.elliptic_integrals import elliptic_e +from .entity import GeometryEntity, GeometrySet +from .exceptions import GeometryError +from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D +from .point import Point, Point2D, Point3D +from .util import idiff, find +from sympy.polys import DomainError, Poly, PolynomialError +from sympy.polys.polyutils import _not_a_coeff, _nsort +from sympy.solvers import solve +from sympy.solvers.solveset import linear_coeffs +from sympy.utilities.misc import filldedent, func_name + +from mpmath.libmp.libmpf import prec_to_dps + +import random + +x, y = [Dummy('ellipse_dummy', real=True) for i in range(2)] + + +class Ellipse(GeometrySet): + """An elliptical GeometryEntity. + + Parameters + ========== + + center : Point, optional + Default value is Point(0, 0) + hradius : number or SymPy expression, optional + vradius : number or SymPy expression, optional + eccentricity : number or SymPy expression, optional + Two of `hradius`, `vradius` and `eccentricity` must be supplied to + create an Ellipse. The third is derived from the two supplied. + + Attributes + ========== + + center + hradius + vradius + area + circumference + eccentricity + periapsis + apoapsis + focus_distance + foci + + Raises + ====== + + GeometryError + When `hradius`, `vradius` and `eccentricity` are incorrectly supplied + as parameters. + TypeError + When `center` is not a Point. + + See Also + ======== + + Circle + + Notes + ----- + Constructed from a center and two radii, the first being the horizontal + radius (along the x-axis) and the second being the vertical radius (along + the y-axis). + + When symbolic value for hradius and vradius are used, any calculation that + refers to the foci or the major or minor axis will assume that the ellipse + has its major radius on the x-axis. If this is not true then a manual + rotation is necessary. + + Examples + ======== + + >>> from sympy import Ellipse, Point, Rational + >>> e1 = Ellipse(Point(0, 0), 5, 1) + >>> e1.hradius, e1.vradius + (5, 1) + >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5)) + >>> e2 + Ellipse(Point2D(3, 1), 3, 9/5) + + """ + + def __contains__(self, o): + if isinstance(o, Point): + res = self.equation(x, y).subs({x: o.x, y: o.y}) + return trigsimp(simplify(res)) is S.Zero + elif isinstance(o, Ellipse): + return self == o + return False + + def __eq__(self, o): + """Is the other GeometryEntity the same as this ellipse?""" + return isinstance(o, Ellipse) and (self.center == o.center and + self.hradius == o.hradius and + self.vradius == o.vradius) + + def __hash__(self): + return super().__hash__() + + def __new__( + cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs): + + hradius = sympify(hradius) + vradius = sympify(vradius) + + if center is None: + center = Point(0, 0) + else: + if len(center) != 2: + raise ValueError('The center of "{}" must be a two dimensional point'.format(cls)) + center = Point(center, dim=2) + + if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2: + raise ValueError(filldedent(''' + Exactly two arguments of "hradius", "vradius", and + "eccentricity" must not be None.''')) + + if eccentricity is not None: + eccentricity = sympify(eccentricity) + if eccentricity.is_negative: + raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)") + elif hradius is None: + hradius = vradius / sqrt(1 - eccentricity**2) + elif vradius is None: + vradius = hradius * sqrt(1 - eccentricity**2) + + if hradius == vradius: + return Circle(center, hradius, **kwargs) + + if S.Zero in (hradius, vradius): + return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius)) + + if hradius.is_real is False or vradius.is_real is False: + raise GeometryError("Invalid value encountered when computing hradius / vradius.") + + return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs) + + def _svg(self, scale_factor=1., fill_color="#66cc99"): + """Returns SVG ellipse element for the Ellipse. + + Parameters + ========== + + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is "#66cc99". + """ + + c = N(self.center) + h, v = N(self.hradius), N(self.vradius) + return ( + '' + ).format(2. * scale_factor, fill_color, c.x, c.y, h, v) + + @property + def ambient_dimension(self): + return 2 + + @property + def apoapsis(self): + """The apoapsis of the ellipse. + + The greatest distance between the focus and the contour. + + Returns + ======= + + apoapsis : number + + See Also + ======== + + periapsis : Returns shortest distance between foci and contour + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.apoapsis + 2*sqrt(2) + 3 + + """ + return self.major * (1 + self.eccentricity) + + def arbitrary_point(self, parameter='t'): + """A parameterized point on the ellipse. + + Parameters + ========== + + parameter : str, optional + Default value is 't'. + + Returns + ======= + + arbitrary_point : Point + + Raises + ====== + + ValueError + When `parameter` already appears in the functions. + + See Also + ======== + + sympy.geometry.point.Point + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e1 = Ellipse(Point(0, 0), 3, 2) + >>> e1.arbitrary_point() + Point2D(3*cos(t), 2*sin(t)) + + """ + t = _symbol(parameter, real=True) + if t.name in (f.name for f in self.free_symbols): + raise ValueError(filldedent('Symbol %s already appears in object ' + 'and cannot be used as a parameter.' % t.name)) + return Point(self.center.x + self.hradius*cos(t), + self.center.y + self.vradius*sin(t)) + + @property + def area(self): + """The area of the ellipse. + + Returns + ======= + + area : number + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.area + 3*pi + + """ + return simplify(S.Pi * self.hradius * self.vradius) + + @property + def bounds(self): + """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding + rectangle for the geometric figure. + + """ + + h, v = self.hradius, self.vradius + return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v) + + @property + def center(self): + """The center of the ellipse. + + Returns + ======= + + center : number + + See Also + ======== + + sympy.geometry.point.Point + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.center + Point2D(0, 0) + + """ + return self.args[0] + + @property + def circumference(self): + """The circumference of the ellipse. + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.circumference + 12*elliptic_e(8/9) + + """ + if self.eccentricity == 1: + # degenerate + return 4*self.major + elif self.eccentricity == 0: + # circle + return 2*pi*self.hradius + else: + return 4*self.major*elliptic_e(self.eccentricity**2) + + @property + def eccentricity(self): + """The eccentricity of the ellipse. + + Returns + ======= + + eccentricity : number + + Examples + ======== + + >>> from sympy import Point, Ellipse, sqrt + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, sqrt(2)) + >>> e1.eccentricity + sqrt(7)/3 + + """ + return self.focus_distance / self.major + + def encloses_point(self, p): + """ + Return True if p is enclosed by (is inside of) self. + + Notes + ----- + Being on the border of self is considered False. + + Parameters + ========== + + p : Point + + Returns + ======= + + encloses_point : True, False or None + + See Also + ======== + + sympy.geometry.point.Point + + Examples + ======== + + >>> from sympy import Ellipse, S + >>> from sympy.abc import t + >>> e = Ellipse((0, 0), 3, 2) + >>> e.encloses_point((0, 0)) + True + >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half)) + False + >>> e.encloses_point((4, 0)) + False + + """ + p = Point(p, dim=2) + if p in self: + return False + + if len(self.foci) == 2: + # if the combined distance from the foci to p (h1 + h2) is less + # than the combined distance from the foci to the minor axis + # (which is the same as the major axis length) then p is inside + # the ellipse + h1, h2 = [f.distance(p) for f in self.foci] + test = 2*self.major - (h1 + h2) + else: + test = self.radius - self.center.distance(p) + + return fuzzy_bool(test.is_positive) + + def equation(self, x='x', y='y', _slope=None): + """ + Returns the equation of an ellipse aligned with the x and y axes; + when slope is given, the equation returned corresponds to an ellipse + with a major axis having that slope. + + Parameters + ========== + + x : str, optional + Label for the x-axis. Default value is 'x'. + y : str, optional + Label for the y-axis. Default value is 'y'. + _slope : Expr, optional + The slope of the major axis. Ignored when 'None'. + + Returns + ======= + + equation : SymPy expression + + See Also + ======== + + arbitrary_point : Returns parameterized point on ellipse + + Examples + ======== + + >>> from sympy import Point, Ellipse, pi + >>> from sympy.abc import x, y + >>> e1 = Ellipse(Point(1, 0), 3, 2) + >>> eq1 = e1.equation(x, y); eq1 + y**2/4 + (x/3 - 1/3)**2 - 1 + >>> eq2 = e1.equation(x, y, _slope=1); eq2 + (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1 + + A point on e1 satisfies eq1. Let's use one on the x-axis: + + >>> p1 = e1.center + Point(e1.major, 0) + >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0 + + When rotated the same as the rotated ellipse, about the center + point of the ellipse, it will satisfy the rotated ellipse's + equation, too: + + >>> r1 = p1.rotate(pi/4, e1.center) + >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0 + + References + ========== + + .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis + .. [2] https://en.wikipedia.org/wiki/Ellipse#Shifted_ellipse + + """ + + x = _symbol(x, real=True) + y = _symbol(y, real=True) + + dx = x - self.center.x + dy = y - self.center.y + + if _slope is not None: + L = (dy - _slope*dx)**2 + l = (_slope*dy + dx)**2 + h = 1 + _slope**2 + b = h*self.major**2 + a = h*self.minor**2 + return l/b + L/a - 1 + + else: + t1 = (dx/self.hradius)**2 + t2 = (dy/self.vradius)**2 + return t1 + t2 - 1 + + def evolute(self, x='x', y='y'): + """The equation of evolute of the ellipse. + + Parameters + ========== + + x : str, optional + Label for the x-axis. Default value is 'x'. + y : str, optional + Label for the y-axis. Default value is 'y'. + + Returns + ======= + + equation : SymPy expression + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e1 = Ellipse(Point(1, 0), 3, 2) + >>> e1.evolute() + 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3) + """ + if len(self.args) != 3: + raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.') + x = _symbol(x, real=True) + y = _symbol(y, real=True) + t1 = (self.hradius*(x - self.center.x))**Rational(2, 3) + t2 = (self.vradius*(y - self.center.y))**Rational(2, 3) + return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3) + + @property + def foci(self): + """The foci of the ellipse. + + Notes + ----- + The foci can only be calculated if the major/minor axes are known. + + Raises + ====== + + ValueError + When the major and minor axis cannot be determined. + + See Also + ======== + + sympy.geometry.point.Point + focus_distance : Returns the distance between focus and center + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.foci + (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0)) + + """ + c = self.center + hr, vr = self.hradius, self.vradius + if hr == vr: + return (c, c) + + # calculate focus distance manually, since focus_distance calls this + # routine + fd = sqrt(self.major**2 - self.minor**2) + if hr == self.minor: + # foci on the y-axis + return (c + Point(0, -fd), c + Point(0, fd)) + elif hr == self.major: + # foci on the x-axis + return (c + Point(-fd, 0), c + Point(fd, 0)) + + @property + def focus_distance(self): + """The focal distance of the ellipse. + + The distance between the center and one focus. + + Returns + ======= + + focus_distance : number + + See Also + ======== + + foci + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.focus_distance + 2*sqrt(2) + + """ + return Point.distance(self.center, self.foci[0]) + + @property + def hradius(self): + """The horizontal radius of the ellipse. + + Returns + ======= + + hradius : number + + See Also + ======== + + vradius, major, minor + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.hradius + 3 + + """ + return self.args[1] + + def intersection(self, o): + """The intersection of this ellipse and another geometrical entity + `o`. + + Parameters + ========== + + o : GeometryEntity + + Returns + ======= + + intersection : list of GeometryEntity objects + + Notes + ----- + Currently supports intersections with Point, Line, Segment, Ray, + Circle and Ellipse types. + + See Also + ======== + + sympy.geometry.entity.GeometryEntity + + Examples + ======== + + >>> from sympy import Ellipse, Point, Line + >>> e = Ellipse(Point(0, 0), 5, 7) + >>> e.intersection(Point(0, 0)) + [] + >>> e.intersection(Point(5, 0)) + [Point2D(5, 0)] + >>> e.intersection(Line(Point(0,0), Point(0, 1))) + [Point2D(0, -7), Point2D(0, 7)] + >>> e.intersection(Line(Point(5,0), Point(5, 1))) + [Point2D(5, 0)] + >>> e.intersection(Line(Point(6,0), Point(6, 1))) + [] + >>> e = Ellipse(Point(-1, 0), 4, 3) + >>> e.intersection(Ellipse(Point(1, 0), 4, 3)) + [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)] + >>> e.intersection(Ellipse(Point(5, 0), 4, 3)) + [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)] + >>> e.intersection(Ellipse(Point(100500, 0), 4, 3)) + [] + >>> e.intersection(Ellipse(Point(0, 0), 3, 4)) + [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)] + >>> e.intersection(Ellipse(Point(-1, 0), 3, 4)) + [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)] + """ + # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain + + if isinstance(o, Point): + if o in self: + return [o] + else: + return [] + + elif isinstance(o, (Segment2D, Ray2D)): + ellipse_equation = self.equation(x, y) + result = solve([ellipse_equation, Line( + o.points[0], o.points[1]).equation(x, y)], [x, y], + set=True)[1] + return list(ordered([Point(i) for i in result if i in o])) + + elif isinstance(o, Polygon): + return o.intersection(self) + + elif isinstance(o, (Ellipse, Line2D)): + if o == self: + return self + else: + ellipse_equation = self.equation(x, y) + return list(ordered([Point(i) for i in solve( + [ellipse_equation, o.equation(x, y)], [x, y], + set=True)[1]])) + elif isinstance(o, LinearEntity3D): + raise TypeError('Entity must be two dimensional, not three dimensional') + else: + raise TypeError('Intersection not handled for %s' % func_name(o)) + + def is_tangent(self, o): + """Is `o` tangent to the ellipse? + + Parameters + ========== + + o : GeometryEntity + An Ellipse, LinearEntity or Polygon + + Raises + ====== + + NotImplementedError + When the wrong type of argument is supplied. + + Returns + ======= + + is_tangent: boolean + True if o is tangent to the ellipse, False otherwise. + + See Also + ======== + + tangent_lines + + Examples + ======== + + >>> from sympy import Point, Ellipse, Line + >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3) + >>> e1 = Ellipse(p0, 3, 2) + >>> l1 = Line(p1, p2) + >>> e1.is_tangent(l1) + True + + """ + if isinstance(o, Point2D): + return False + elif isinstance(o, Ellipse): + intersect = self.intersection(o) + if isinstance(intersect, Ellipse): + return True + elif intersect: + return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect) + else: + return False + elif isinstance(o, Line2D): + hit = self.intersection(o) + if not hit: + return False + if len(hit) == 1: + return True + # might return None if it can't decide + return hit[0].equals(hit[1]) + elif isinstance(o, (Segment2D, Ray2D)): + intersect = self.intersection(o) + if len(intersect) == 1: + return o in self.tangent_lines(intersect[0])[0] + else: + return False + elif isinstance(o, Polygon): + return all(self.is_tangent(s) for s in o.sides) + elif isinstance(o, (LinearEntity3D, Point3D)): + raise TypeError('Entity must be two dimensional, not three dimensional') + else: + raise TypeError('Is_tangent not handled for %s' % func_name(o)) + + @property + def major(self): + """Longer axis of the ellipse (if it can be determined) else hradius. + + Returns + ======= + + major : number or expression + + See Also + ======== + + hradius, vradius, minor + + Examples + ======== + + >>> from sympy import Point, Ellipse, Symbol + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.major + 3 + + >>> a = Symbol('a') + >>> b = Symbol('b') + >>> Ellipse(p1, a, b).major + a + >>> Ellipse(p1, b, a).major + b + + >>> m = Symbol('m') + >>> M = m + 1 + >>> Ellipse(p1, m, M).major + m + 1 + + """ + ab = self.args[1:3] + if len(ab) == 1: + return ab[0] + a, b = ab + o = b - a < 0 + if o == True: + return a + elif o == False: + return b + return self.hradius + + @property + def minor(self): + """Shorter axis of the ellipse (if it can be determined) else vradius. + + Returns + ======= + + minor : number or expression + + See Also + ======== + + hradius, vradius, major + + Examples + ======== + + >>> from sympy import Point, Ellipse, Symbol + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.minor + 1 + + >>> a = Symbol('a') + >>> b = Symbol('b') + >>> Ellipse(p1, a, b).minor + b + >>> Ellipse(p1, b, a).minor + a + + >>> m = Symbol('m') + >>> M = m + 1 + >>> Ellipse(p1, m, M).minor + m + + """ + ab = self.args[1:3] + if len(ab) == 1: + return ab[0] + a, b = ab + o = a - b < 0 + if o == True: + return a + elif o == False: + return b + return self.vradius + + def normal_lines(self, p, prec=None): + """Normal lines between `p` and the ellipse. + + Parameters + ========== + + p : Point + + Returns + ======= + + normal_lines : list with 1, 2 or 4 Lines + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e = Ellipse((0, 0), 2, 3) + >>> c = e.center + >>> e.normal_lines(c + Point(1, 0)) + [Line2D(Point2D(0, 0), Point2D(1, 0))] + >>> e.normal_lines(c) + [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))] + + Off-axis points require the solution of a quartic equation. This + often leads to very large expressions that may be of little practical + use. An approximate solution of `prec` digits can be obtained by + passing in the desired value: + + >>> e.normal_lines((3, 3), prec=2) + [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)), + Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))] + + Whereas the above solution has an operation count of 12, the exact + solution has an operation count of 2020. + """ + p = Point(p, dim=2) + + # XXX change True to something like self.angle == 0 if the arbitrarily + # rotated ellipse is introduced. + # https://github.com/sympy/sympy/issues/2815) + if True: + rv = [] + if p.x == self.center.x: + rv.append(Line(self.center, slope=oo)) + if p.y == self.center.y: + rv.append(Line(self.center, slope=0)) + if rv: + # at these special orientations of p either 1 or 2 normals + # exist and we are done + return rv + + # find the 4 normal points and construct lines through them with + # the corresponding slope + eq = self.equation(x, y) + dydx = idiff(eq, y, x) + norm = -1/dydx + slope = Line(p, (x, y)).slope + seq = slope - norm + + # TODO: Replace solve with solveset, when this line is tested + yis = solve(seq, y)[0] + xeq = eq.subs(y, yis).as_numer_denom()[0].expand() + if len(xeq.free_symbols) == 1: + try: + # this is so much faster, it's worth a try + xsol = Poly(xeq, x).real_roots() + except (DomainError, PolynomialError, NotImplementedError): + # TODO: Replace solve with solveset, when these lines are tested + xsol = _nsort(solve(xeq, x), separated=True)[0] + points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol] + else: + raise NotImplementedError( + 'intersections for the general ellipse are not supported') + slopes = [norm.subs(zip((x, y), pt.args)) for pt in points] + if prec is not None: + points = [pt.n(prec) for pt in points] + slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes] + return [Line(pt, slope=s) for pt, s in zip(points, slopes)] + + @property + def periapsis(self): + """The periapsis of the ellipse. + + The shortest distance between the focus and the contour. + + Returns + ======= + + periapsis : number + + See Also + ======== + + apoapsis : Returns greatest distance between focus and contour + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.periapsis + 3 - 2*sqrt(2) + + """ + return self.major * (1 - self.eccentricity) + + @property + def semilatus_rectum(self): + """ + Calculates the semi-latus rectum of the Ellipse. + + Semi-latus rectum is defined as one half of the chord through a + focus parallel to the conic section directrix of a conic section. + + Returns + ======= + + semilatus_rectum : number + + See Also + ======== + + apoapsis : Returns greatest distance between focus and contour + + periapsis : The shortest distance between the focus and the contour + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.semilatus_rectum + 1/3 + + References + ========== + + .. [1] https://mathworld.wolfram.com/SemilatusRectum.html + .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum + + """ + return self.major * (1 - self.eccentricity ** 2) + + def auxiliary_circle(self): + """Returns a Circle whose diameter is the major axis of the ellipse. + + Examples + ======== + + >>> from sympy import Ellipse, Point, symbols + >>> c = Point(1, 2) + >>> Ellipse(c, 8, 7).auxiliary_circle() + Circle(Point2D(1, 2), 8) + >>> a, b = symbols('a b') + >>> Ellipse(c, a, b).auxiliary_circle() + Circle(Point2D(1, 2), Max(a, b)) + """ + return Circle(self.center, Max(self.hradius, self.vradius)) + + def director_circle(self): + """ + Returns a Circle consisting of all points where two perpendicular + tangent lines to the ellipse cross each other. + + Returns + ======= + + Circle + A director circle returned as a geometric object. + + Examples + ======== + + >>> from sympy import Ellipse, Point, symbols + >>> c = Point(3,8) + >>> Ellipse(c, 7, 9).director_circle() + Circle(Point2D(3, 8), sqrt(130)) + >>> a, b = symbols('a b') + >>> Ellipse(c, a, b).director_circle() + Circle(Point2D(3, 8), sqrt(a**2 + b**2)) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Director_circle + + """ + return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2)) + + def plot_interval(self, parameter='t'): + """The plot interval for the default geometric plot of the Ellipse. + + Parameters + ========== + + parameter : str, optional + Default value is 't'. + + Returns + ======= + + plot_interval : list + [parameter, lower_bound, upper_bound] + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e1 = Ellipse(Point(0, 0), 3, 2) + >>> e1.plot_interval() + [t, -pi, pi] + + """ + t = _symbol(parameter, real=True) + return [t, -S.Pi, S.Pi] + + def random_point(self, seed=None): + """A random point on the ellipse. + + Returns + ======= + + point : Point + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e1 = Ellipse(Point(0, 0), 3, 2) + >>> e1.random_point() # gives some random point + Point2D(...) + >>> p1 = e1.random_point(seed=0); p1.n(2) + Point2D(2.1, 1.4) + + Notes + ===== + + When creating a random point, one may simply replace the + parameter with a random number. When doing so, however, the + random number should be made a Rational or else the point + may not test as being in the ellipse: + + >>> from sympy.abc import t + >>> from sympy import Rational + >>> arb = e1.arbitrary_point(t); arb + Point2D(3*cos(t), 2*sin(t)) + >>> arb.subs(t, .1) in e1 + False + >>> arb.subs(t, Rational(.1)) in e1 + True + >>> arb.subs(t, Rational('.1')) in e1 + True + + See Also + ======== + sympy.geometry.point.Point + arbitrary_point : Returns parameterized point on ellipse + """ + t = _symbol('t', real=True) + x, y = self.arbitrary_point(t).args + # get a random value in [-1, 1) corresponding to cos(t) + # and confirm that it will test as being in the ellipse + if seed is not None: + rng = random.Random(seed) + else: + rng = random + # simplify this now or else the Float will turn s into a Float + r = Rational(rng.random()) + c = 2*r - 1 + s = sqrt(1 - c**2) + return Point(x.subs(cos(t), c), y.subs(sin(t), s)) + + def reflect(self, line): + """Override GeometryEntity.reflect since the radius + is not a GeometryEntity. + + Examples + ======== + + >>> from sympy import Circle, Line + >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) + Circle(Point2D(1, 0), -1) + >>> from sympy import Ellipse, Line, Point + >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0))) + Traceback (most recent call last): + ... + NotImplementedError: + General Ellipse is not supported but the equation of the reflected + Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 + + 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1 + + Notes + ===== + + Until the general ellipse (with no axis parallel to the x-axis) is + supported a NotImplemented error is raised and the equation whose + zeros define the rotated ellipse is given. + + """ + + if line.slope in (0, oo): + c = self.center + c = c.reflect(line) + return self.func(c, -self.hradius, self.vradius) + else: + x, y = [uniquely_named_symbol( + name, (self, line), modify=lambda s: '_' + s, real=True) + for name in 'xy'] + expr = self.equation(x, y) + p = Point(x, y).reflect(line) + result = expr.subs(zip((x, y), p.args + ), simultaneous=True) + raise NotImplementedError(filldedent( + 'General Ellipse is not supported but the equation ' + 'of the reflected Ellipse is given by the zeros of: ' + + "f(%s, %s) = %s" % (str(x), str(y), str(result)))) + + def rotate(self, angle=0, pt=None): + """Rotate ``angle`` radians counterclockwise about Point ``pt``. + + Note: since the general ellipse is not supported, only rotations that + are integer multiples of pi/2 are allowed. + + Examples + ======== + + >>> from sympy import Ellipse, pi + >>> Ellipse((1, 0), 2, 1).rotate(pi/2) + Ellipse(Point2D(0, 1), 1, 2) + >>> Ellipse((1, 0), 2, 1).rotate(pi) + Ellipse(Point2D(-1, 0), 2, 1) + """ + if self.hradius == self.vradius: + return self.func(self.center.rotate(angle, pt), self.hradius) + if (angle/S.Pi).is_integer: + return super().rotate(angle, pt) + if (2*angle/S.Pi).is_integer: + return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius) + # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes + raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.') + + def scale(self, x=1, y=1, pt=None): + """Override GeometryEntity.scale since it is the major and minor + axes which must be scaled and they are not GeometryEntities. + + Examples + ======== + + >>> from sympy import Ellipse + >>> Ellipse((0, 0), 2, 1).scale(2, 4) + Circle(Point2D(0, 0), 4) + >>> Ellipse((0, 0), 2, 1).scale(2) + Ellipse(Point2D(0, 0), 4, 1) + """ + c = self.center + if pt: + pt = Point(pt, dim=2) + return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) + h = self.hradius + v = self.vradius + return self.func(c.scale(x, y), hradius=h*x, vradius=v*y) + + def tangent_lines(self, p): + """Tangent lines between `p` and the ellipse. + + If `p` is on the ellipse, returns the tangent line through point `p`. + Otherwise, returns the tangent line(s) from `p` to the ellipse, or + None if no tangent line is possible (e.g., `p` inside ellipse). + + Parameters + ========== + + p : Point + + Returns + ======= + + tangent_lines : list with 1 or 2 Lines + + Raises + ====== + + NotImplementedError + Can only find tangent lines for a point, `p`, on the ellipse. + + See Also + ======== + + sympy.geometry.point.Point, sympy.geometry.line.Line + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> e1 = Ellipse(Point(0, 0), 3, 2) + >>> e1.tangent_lines(Point(3, 0)) + [Line2D(Point2D(3, 0), Point2D(3, -12))] + + """ + p = Point(p, dim=2) + if self.encloses_point(p): + return [] + + if p in self: + delta = self.center - p + rise = (self.vradius**2)*delta.x + run = -(self.hradius**2)*delta.y + p2 = Point(simplify(p.x + run), + simplify(p.y + rise)) + return [Line(p, p2)] + else: + if len(self.foci) == 2: + f1, f2 = self.foci + maj = self.hradius + test = (2*maj - + Point.distance(f1, p) - + Point.distance(f2, p)) + else: + test = self.radius - Point.distance(self.center, p) + if test.is_number and test.is_positive: + return [] + # else p is outside the ellipse or we can't tell. In case of the + # latter, the solutions returned will only be valid if + # the point is not inside the ellipse; if it is, nan will result. + eq = self.equation(x, y) + dydx = idiff(eq, y, x) + slope = Line(p, Point(x, y)).slope + + # TODO: Replace solve with solveset, when this line is tested + tangent_points = solve([slope - dydx, eq], [x, y]) + + # handle horizontal and vertical tangent lines + if len(tangent_points) == 1: + if tangent_points[0][ + 0] == p.x or tangent_points[0][1] == p.y: + return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))] + else: + return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])] + + # others + return [Line(p, tangent_points[0]), Line(p, tangent_points[1])] + + @property + def vradius(self): + """The vertical radius of the ellipse. + + Returns + ======= + + vradius : number + + See Also + ======== + + hradius, major, minor + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.vradius + 1 + + """ + return self.args[2] + + + def second_moment_of_area(self, point=None): + """Returns the second moment and product moment area of an ellipse. + + Parameters + ========== + + point : Point, two-tuple of sympifiable objects, or None(default=None) + point is the point about which second moment of area is to be found. + If "point=None" it will be calculated about the axis passing through the + centroid of the ellipse. + + Returns + ======= + + I_xx, I_yy, I_xy : number or SymPy expression + I_xx, I_yy are second moment of area of an ellise. + I_xy is product moment of area of an ellipse. + + Examples + ======== + + >>> from sympy import Point, Ellipse + >>> p1 = Point(0, 0) + >>> e1 = Ellipse(p1, 3, 1) + >>> e1.second_moment_of_area() + (3*pi/4, 27*pi/4, 0) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area + + """ + + I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4 + I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4 + I_xy = 0 + + if point is None: + return I_xx, I_yy, I_xy + + # parallel axis theorem + I_xx = I_xx + self.area*((point[1] - self.center.y)**2) + I_yy = I_yy + self.area*((point[0] - self.center.x)**2) + I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y) + + return I_xx, I_yy, I_xy + + + def polar_second_moment_of_area(self): + """Returns the polar second moment of area of an Ellipse + + It is a constituent of the second moment of area, linked through + the perpendicular axis theorem. While the planar second moment of + area describes an object's resistance to deflection (bending) when + subjected to a force applied to a plane parallel to the central + axis, the polar second moment of area describes an object's + resistance to deflection when subjected to a moment applied in a + plane perpendicular to the object's central axis (i.e. parallel to + the cross-section) + + Examples + ======== + + >>> from sympy import symbols, Circle, Ellipse + >>> c = Circle((5, 5), 4) + >>> c.polar_second_moment_of_area() + 128*pi + >>> a, b = symbols('a, b') + >>> e = Ellipse((0, 0), a, b) + >>> e.polar_second_moment_of_area() + pi*a**3*b/4 + pi*a*b**3/4 + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia + + """ + second_moment = self.second_moment_of_area() + return second_moment[0] + second_moment[1] + + + def section_modulus(self, point=None): + """Returns a tuple with the section modulus of an ellipse + + Section modulus is a geometric property of an ellipse defined as the + ratio of second moment of area to the distance of the extreme end of + the ellipse from the centroidal axis. + + Parameters + ========== + + point : Point, two-tuple of sympifyable objects, or None(default=None) + point is the point at which section modulus is to be found. + If "point=None" section modulus will be calculated for the + point farthest from the centroidal axis of the ellipse. + + Returns + ======= + + S_x, S_y: numbers or SymPy expressions + S_x is the section modulus with respect to the x-axis + S_y is the section modulus with respect to the y-axis + A negative sign indicates that the section modulus is + determined for a point below the centroidal axis. + + Examples + ======== + + >>> from sympy import Symbol, Ellipse, Circle, Point2D + >>> d = Symbol('d', positive=True) + >>> c = Circle((0, 0), d/2) + >>> c.section_modulus() + (pi*d**3/32, pi*d**3/32) + >>> e = Ellipse(Point2D(0, 0), 2, 4) + >>> e.section_modulus() + (8*pi, 4*pi) + >>> e.section_modulus((2, 2)) + (16*pi, 4*pi) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Section_modulus + + """ + x_c, y_c = self.center + if point is None: + # taking x and y as maximum distances from centroid + x_min, y_min, x_max, y_max = self.bounds + y = max(y_c - y_min, y_max - y_c) + x = max(x_c - x_min, x_max - x_c) + else: + # taking x and y as distances of the given point from the center + point = Point2D(point) + y = point.y - y_c + x = point.x - x_c + + second_moment = self.second_moment_of_area() + S_x = second_moment[0]/y + S_y = second_moment[1]/x + + return S_x, S_y + + +class Circle(Ellipse): + r"""A circle in space. + + Constructed simply from a center and a radius, from three + non-collinear points, or the equation of a circle. + + Parameters + ========== + + center : Point + radius : number or SymPy expression + points : sequence of three Points + equation : equation of a circle + + Attributes + ========== + + radius (synonymous with hradius, vradius, major and minor) + circumference + equation + + Raises + ====== + + GeometryError + When the given equation is not that of a circle. + When trying to construct circle from incorrect parameters. + + See Also + ======== + + Ellipse, sympy.geometry.point.Point + + Examples + ======== + + >>> from sympy import Point, Circle, Eq + >>> from sympy.abc import x, y, a, b + + A circle constructed from a center and radius: + + >>> c1 = Circle(Point(0, 0), 5) + >>> c1.hradius, c1.vradius, c1.radius + (5, 5, 5) + + A circle constructed from three points: + + >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) + >>> c2.hradius, c2.vradius, c2.radius, c2.center + (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2)) + + A circle can be constructed from an equation in the form + `ax^2 + by^2 + gx + hy + c = 0`, too: + + >>> Circle(x**2 + y**2 - 25) + Circle(Point2D(0, 0), 5) + + If the variables corresponding to x and y are named something + else, their name or symbol can be supplied: + + >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b) + Circle(Point2D(0, 0), 5) + """ + + def __new__(cls, *args, **kwargs): + evaluate = kwargs.get('evaluate', global_parameters.evaluate) + if len(args) == 1 and isinstance(args[0], (Expr, Eq)): + x = kwargs.get('x', 'x') + y = kwargs.get('y', 'y') + equation = args[0].expand() + if isinstance(equation, Eq): + equation = equation.lhs - equation.rhs + x = find(x, equation) + y = find(y, equation) + + try: + a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y) + except ValueError: + raise GeometryError("The given equation is not that of a circle.") + + if S.Zero in (a, b) or a != b: + raise GeometryError("The given equation is not that of a circle.") + + center_x = -c/a/2 + center_y = -d/b/2 + r2 = (center_x**2) + (center_y**2) - e/a + + return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate) + + else: + c, r = None, None + if len(args) == 3: + args = [Point(a, dim=2, evaluate=evaluate) for a in args] + t = Triangle(*args) + if not isinstance(t, Triangle): + return t + c = t.circumcenter + r = t.circumradius + elif len(args) == 2: + # Assume (center, radius) pair + c = Point(args[0], dim=2, evaluate=evaluate) + r = args[1] + # this will prohibit imaginary radius + try: + r = Point(r, 0, evaluate=evaluate).x + except ValueError: + raise GeometryError("Circle with imaginary radius is not permitted") + + if not (c is None or r is None): + if r == 0: + return c + return GeometryEntity.__new__(cls, c, r, **kwargs) + + raise GeometryError("Circle.__new__ received unknown arguments") + + def _eval_evalf(self, prec=15, **options): + pt, r = self.args + dps = prec_to_dps(prec) + pt = pt.evalf(n=dps, **options) + r = r.evalf(n=dps, **options) + return self.func(pt, r, evaluate=False) + + @property + def circumference(self): + """The circumference of the circle. + + Returns + ======= + + circumference : number or SymPy expression + + Examples + ======== + + >>> from sympy import Point, Circle + >>> c1 = Circle(Point(3, 4), 6) + >>> c1.circumference + 12*pi + + """ + return 2 * S.Pi * self.radius + + def equation(self, x='x', y='y'): + """The equation of the circle. + + Parameters + ========== + + x : str or Symbol, optional + Default value is 'x'. + y : str or Symbol, optional + Default value is 'y'. + + Returns + ======= + + equation : SymPy expression + + Examples + ======== + + >>> from sympy import Point, Circle + >>> c1 = Circle(Point(0, 0), 5) + >>> c1.equation() + x**2 + y**2 - 25 + + """ + x = _symbol(x, real=True) + y = _symbol(y, real=True) + t1 = (x - self.center.x)**2 + t2 = (y - self.center.y)**2 + return t1 + t2 - self.major**2 + + def intersection(self, o): + """The intersection of this circle with another geometrical entity. + + Parameters + ========== + + o : GeometryEntity + + Returns + ======= + + intersection : list of GeometryEntities + + Examples + ======== + + >>> from sympy import Point, Circle, Line, Ray + >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0) + >>> p4 = Point(5, 0) + >>> c1 = Circle(p1, 5) + >>> c1.intersection(p2) + [] + >>> c1.intersection(p4) + [Point2D(5, 0)] + >>> c1.intersection(Ray(p1, p2)) + [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)] + >>> c1.intersection(Line(p2, p3)) + [] + + """ + return Ellipse.intersection(self, o) + + @property + def radius(self): + """The radius of the circle. + + Returns + ======= + + radius : number or SymPy expression + + See Also + ======== + + Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius + + Examples + ======== + + >>> from sympy import Point, Circle + >>> c1 = Circle(Point(3, 4), 6) + >>> c1.radius + 6 + + """ + return self.args[1] + + def reflect(self, line): + """Override GeometryEntity.reflect since the radius + is not a GeometryEntity. + + Examples + ======== + + >>> from sympy import Circle, Line + >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) + Circle(Point2D(1, 0), -1) + """ + c = self.center + c = c.reflect(line) + return self.func(c, -self.radius) + + def scale(self, x=1, y=1, pt=None): + """Override GeometryEntity.scale since the radius + is not a GeometryEntity. + + Examples + ======== + + >>> from sympy import Circle + >>> Circle((0, 0), 1).scale(2, 2) + Circle(Point2D(0, 0), 2) + >>> Circle((0, 0), 1).scale(2, 4) + Ellipse(Point2D(0, 0), 2, 4) + """ + c = self.center + if pt: + pt = Point(pt, dim=2) + return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) + c = c.scale(x, y) + x, y = [abs(i) for i in (x, y)] + if x == y: + return self.func(c, x*self.radius) + h = v = self.radius + return Ellipse(c, hradius=h*x, vradius=v*y) + + @property + def vradius(self): + """ + This Ellipse property is an alias for the Circle's radius. + + Whereas hradius, major and minor can use Ellipse's conventions, + the vradius does not exist for a circle. It is always a positive + value in order that the Circle, like Polygons, will have an + area that can be positive or negative as determined by the sign + of the hradius. + + Examples + ======== + + >>> from sympy import Point, Circle + >>> c1 = Circle(Point(3, 4), 6) + >>> c1.vradius + 6 + """ + return abs(self.radius) + + +from .polygon import Polygon, Triangle diff --git a/shared/package-files/4a/4a90b1c3c851fce71b9b9b4dad47063d34c876e10675224fc5193212d2992e42/test_datetimelike.py b/shared/package-files/4a/4a90b1c3c851fce71b9b9b4dad47063d34c876e10675224fc5193212d2992e42/test_datetimelike.py new file mode 100644 index 0000000000000000000000000000000000000000..4961123a7ca0794aec3a880537cfbd25017207ae --- /dev/null +++ b/shared/package-files/4a/4a90b1c3c851fce71b9b9b4dad47063d34c876e10675224fc5193212d2992e42/test_datetimelike.py @@ -0,0 +1,1344 @@ +from __future__ import annotations + +import re +import warnings + +import numpy as np +import pytest + +from pandas._libs import ( + NaT, + OutOfBoundsDatetime, + Timestamp, +) +from pandas._libs.tslibs.dtypes import freq_to_period_freqstr +from pandas.compat.numpy import np_version_gt2 + +import pandas as pd +from pandas import ( + DatetimeIndex, + Period, + PeriodIndex, + TimedeltaIndex, +) +import pandas._testing as tm +from pandas.core.arrays import ( + DatetimeArray, + NumpyExtensionArray, + PeriodArray, + TimedeltaArray, +) + + +# TODO: more freq variants +@pytest.fixture(params=["D", "B", "W", "ME", "QE", "YE"]) +def freqstr(request): + """Fixture returning parametrized frequency in string format.""" + return request.param + + +@pytest.fixture +def period_index(freqstr): + """ + A fixture to provide PeriodIndex objects with different frequencies. + + Most PeriodArray behavior is already tested in PeriodIndex tests, + so here we just test that the PeriodArray behavior matches + the PeriodIndex behavior. + """ + # TODO: non-monotone indexes; NaTs, different start dates + with warnings.catch_warnings(): + # suppress deprecation of Period[B] + warnings.filterwarnings( + "ignore", message="Period with BDay freq", category=FutureWarning + ) + freqstr = freq_to_period_freqstr(1, freqstr) + pi = pd.period_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr) + return pi + + +@pytest.fixture +def datetime_index(freqstr): + """ + A fixture to provide DatetimeIndex objects with different frequencies. + + Most DatetimeArray behavior is already tested in DatetimeIndex tests, + so here we just test that the DatetimeArray behavior matches + the DatetimeIndex behavior. + """ + # TODO: non-monotone indexes; NaTs, different start dates, timezones + dti = pd.date_range(start=Timestamp("2000-01-01"), periods=100, freq=freqstr) + return dti + + +@pytest.fixture +def timedelta_index(): + """ + A fixture to provide TimedeltaIndex objects with different frequencies. + Most TimedeltaArray behavior is already tested in TimedeltaIndex tests, + so here we just test that the TimedeltaArray behavior matches + the TimedeltaIndex behavior. + """ + # TODO: flesh this out + return TimedeltaIndex(["1 Day", "3 Hours", "NaT"]) + + +class SharedTests: + index_cls: type[DatetimeIndex | PeriodIndex | TimedeltaIndex] + + @pytest.fixture + def arr1d(self): + """Fixture returning DatetimeArray with daily frequency.""" + data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + if self.array_cls is PeriodArray: + arr = self.array_cls(data, freq="D") + else: + arr = self.index_cls(data, freq="D")._data + return arr + + def test_compare_len1_raises(self, arr1d): + # make sure we raise when comparing with different lengths, specific + # to the case where one has length-1, which numpy would broadcast + arr = arr1d + idx = self.index_cls(arr) + + with pytest.raises(ValueError, match="Lengths must match"): + arr == arr[:1] + + # test the index classes while we're at it, GH#23078 + with pytest.raises(ValueError, match="Lengths must match"): + idx <= idx[[0]] + + @pytest.mark.parametrize( + "result", + [ + pd.date_range("2020", periods=3), + pd.date_range("2020", periods=3, tz="UTC"), + pd.timedelta_range("0 days", periods=3), + pd.period_range("2020Q1", periods=3, freq="Q"), + ], + ) + def test_compare_with_Categorical(self, result): + expected = pd.Categorical(result) + assert all(result == expected) + assert not any(result != expected) + + @pytest.mark.parametrize("reverse", [True, False]) + @pytest.mark.parametrize("as_index", [True, False]) + def test_compare_categorical_dtype(self, arr1d, as_index, reverse, ordered): + other = pd.Categorical(arr1d, ordered=ordered) + if as_index: + other = pd.CategoricalIndex(other) + + left, right = arr1d, other + if reverse: + left, right = right, left + + ones = np.ones(arr1d.shape, dtype=bool) + zeros = ~ones + + result = left == right + tm.assert_numpy_array_equal(result, ones) + + result = left != right + tm.assert_numpy_array_equal(result, zeros) + + if not reverse and not as_index: + # Otherwise Categorical raises TypeError bc it is not ordered + # TODO: we should probably get the same behavior regardless? + result = left < right + tm.assert_numpy_array_equal(result, zeros) + + result = left <= right + tm.assert_numpy_array_equal(result, ones) + + result = left > right + tm.assert_numpy_array_equal(result, zeros) + + result = left >= right + tm.assert_numpy_array_equal(result, ones) + + def test_take(self): + data = np.arange(100, dtype="i8") * 24 * 3600 * 10**9 + np.random.default_rng(2).shuffle(data) + + if self.array_cls is PeriodArray: + arr = PeriodArray(data, dtype="period[D]") + else: + arr = self.index_cls(data)._data + idx = self.index_cls._simple_new(arr) + + takers = [1, 4, 94] + result = arr.take(takers) + expected = idx.take(takers) + + tm.assert_index_equal(self.index_cls(result), expected) + + takers = np.array([1, 4, 94]) + result = arr.take(takers) + expected = idx.take(takers) + + tm.assert_index_equal(self.index_cls(result), expected) + + @pytest.mark.parametrize("fill_value", [2, 2.0, Timestamp(2021, 1, 1, 12).time]) + def test_take_fill_raises(self, fill_value, arr1d): + msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + arr1d.take([0, 1], allow_fill=True, fill_value=fill_value) + + def test_take_fill(self, arr1d): + arr = arr1d + + result = arr.take([-1, 1], allow_fill=True, fill_value=None) + assert result[0] is NaT + + result = arr.take([-1, 1], allow_fill=True, fill_value=np.nan) + assert result[0] is NaT + + result = arr.take([-1, 1], allow_fill=True, fill_value=NaT) + assert result[0] is NaT + + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + def test_take_fill_str(self, arr1d): + # Cast str fill_value matching other fill_value-taking methods + result = arr1d.take([-1, 1], allow_fill=True, fill_value=str(arr1d[-1])) + expected = arr1d[[-1, 1]] + tm.assert_equal(result, expected) + + msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + arr1d.take([-1, 1], allow_fill=True, fill_value="foo") + + def test_concat_same_type(self, arr1d): + arr = arr1d + idx = self.index_cls(arr) + idx = idx.insert(0, NaT) + arr = arr1d + + result = arr._concat_same_type([arr[:-1], arr[1:], arr]) + arr2 = arr.astype(object) + expected = self.index_cls(np.concatenate([arr2[:-1], arr2[1:], arr2])) + + tm.assert_index_equal(self.index_cls(result), expected) + + def test_unbox_scalar(self, arr1d): + result = arr1d._unbox_scalar(arr1d[0]) + expected = arr1d._ndarray.dtype.type + assert isinstance(result, expected) + + result = arr1d._unbox_scalar(NaT) + assert isinstance(result, expected) + + msg = f"'value' should be a {self.scalar_type.__name__}." + with pytest.raises(ValueError, match=msg): + arr1d._unbox_scalar("foo") + + def test_check_compatible_with(self, arr1d): + arr1d._check_compatible_with(arr1d[0]) + arr1d._check_compatible_with(arr1d[:1]) + arr1d._check_compatible_with(NaT) + + def test_scalar_from_string(self, arr1d): + result = arr1d._scalar_from_string(str(arr1d[0])) + assert result == arr1d[0] + + def test_reduce_invalid(self, arr1d): + msg = "does not support reduction 'not a method'" + with pytest.raises(TypeError, match=msg): + arr1d._reduce("not a method") + + @pytest.mark.parametrize("method", ["pad", "backfill"]) + def test_fillna_method_doesnt_change_orig(self, method): + data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + if self.array_cls is PeriodArray: + arr = self.array_cls(data, dtype="period[D]") + else: + arr = self.array_cls._from_sequence(data) + arr[4] = NaT + + fill_value = arr[3] if method == "pad" else arr[5] + + result = arr._pad_or_backfill(method=method) + assert result[4] == fill_value + + # check that the original was not changed + assert arr[4] is NaT + + def test_searchsorted(self): + data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + if self.array_cls is PeriodArray: + arr = self.array_cls(data, dtype="period[D]") + else: + arr = self.array_cls._from_sequence(data) + + # scalar + result = arr.searchsorted(arr[1]) + assert result == 1 + + result = arr.searchsorted(arr[2], side="right") + assert result == 3 + + # own-type + result = arr.searchsorted(arr[1:3]) + expected = np.array([1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = arr.searchsorted(arr[1:3], side="right") + expected = np.array([2, 3], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + # GH#29884 match numpy convention on whether NaT goes + # at the end or the beginning + result = arr.searchsorted(NaT) + assert result == 10 + + @pytest.mark.parametrize("box", [None, "index", "series"]) + def test_searchsorted_castable_strings(self, arr1d, box, string_storage): + arr = arr1d + if box is None: + pass + elif box == "index": + # Test the equivalent Index.searchsorted method while we're here + arr = self.index_cls(arr) + else: + # Test the equivalent Series.searchsorted method while we're here + arr = pd.Series(arr) + + # scalar + result = arr.searchsorted(str(arr[1])) + assert result == 1 + + result = arr.searchsorted(str(arr[2]), side="right") + assert result == 3 + + result = arr.searchsorted([str(x) for x in arr[1:3]]) + expected = np.array([1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + with pytest.raises( + TypeError, + match=re.escape( + f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " + "or array of those. Got 'str' instead." + ), + ): + arr.searchsorted("foo") + + with pd.option_context("string_storage", string_storage): + with pytest.raises( + TypeError, + match=re.escape( + f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " + "or array of those. Got string array instead." + ), + ): + arr.searchsorted([str(arr[1]), "baz"]) + + def test_getitem_near_implementation_bounds(self): + # We only check tz-naive for DTA bc the bounds are slightly different + # for other tzs + i8vals = np.asarray([NaT._value + n for n in range(1, 5)], dtype="i8") + if self.array_cls is PeriodArray: + arr = self.array_cls(i8vals, dtype="period[ns]") + else: + arr = self.index_cls(i8vals, freq="ns")._data + arr[0] # should not raise OutOfBoundsDatetime + + index = pd.Index(arr) + index[0] # should not raise OutOfBoundsDatetime + + ser = pd.Series(arr) + ser[0] # should not raise OutOfBoundsDatetime + + def test_getitem_2d(self, arr1d): + # 2d slicing on a 1D array + expected = type(arr1d)._simple_new( + arr1d._ndarray[:, np.newaxis], dtype=arr1d.dtype + ) + result = arr1d[:, np.newaxis] + tm.assert_equal(result, expected) + + # Lookup on a 2D array + arr2d = expected + expected = type(arr2d)._simple_new(arr2d._ndarray[:3, 0], dtype=arr2d.dtype) + result = arr2d[:3, 0] + tm.assert_equal(result, expected) + + # Scalar lookup + result = arr2d[-1, 0] + expected = arr1d[-1] + assert result == expected + + def test_iter_2d(self, arr1d): + data2d = arr1d._ndarray[:3, np.newaxis] + arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype) + result = list(arr2d) + assert len(result) == 3 + for x in result: + assert isinstance(x, type(arr1d)) + assert x.ndim == 1 + assert x.dtype == arr1d.dtype + + def test_repr_2d(self, arr1d): + data2d = arr1d._ndarray[:3, np.newaxis] + arr2d = type(arr1d)._simple_new(data2d, dtype=arr1d.dtype) + + result = repr(arr2d) + + if isinstance(arr2d, TimedeltaArray): + expected = ( + f"<{type(arr2d).__name__}>\n" + "[\n" + f"['{arr1d[0]._repr_base()}'],\n" + f"['{arr1d[1]._repr_base()}'],\n" + f"['{arr1d[2]._repr_base()}']\n" + "]\n" + f"Shape: (3, 1), dtype: {arr1d.dtype}" + ) + else: + expected = ( + f"<{type(arr2d).__name__}>\n" + "[\n" + f"['{arr1d[0]}'],\n" + f"['{arr1d[1]}'],\n" + f"['{arr1d[2]}']\n" + "]\n" + f"Shape: (3, 1), dtype: {arr1d.dtype}" + ) + + assert result == expected + + def test_setitem(self): + data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + if self.array_cls is PeriodArray: + arr = self.array_cls(data, dtype="period[D]") + else: + arr = self.index_cls(data, freq="D")._data + + arr[0] = arr[1] + expected = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + expected[0] = expected[1] + + tm.assert_numpy_array_equal(arr.asi8, expected) + + arr[:2] = arr[-2:] + expected[:2] = expected[-2:] + tm.assert_numpy_array_equal(arr.asi8, expected) + + @pytest.mark.parametrize( + "box", + [ + pd.Index, + pd.Series, + np.array, + list, + NumpyExtensionArray, + ], + ) + def test_setitem_object_dtype(self, box, arr1d): + expected = arr1d.copy()[::-1] + if expected.dtype.kind in ["m", "M"]: + expected = expected._with_freq(None) + + vals = expected + if box is list: + vals = list(vals) + elif box is np.array: + # if we do np.array(x).astype(object) then dt64 and td64 cast to ints + vals = np.array(vals.astype(object)) + elif box is NumpyExtensionArray: + vals = box(np.asarray(vals, dtype=object)) + else: + vals = box(vals).astype(object) + + arr1d[:] = vals + + tm.assert_equal(arr1d, expected) + + def test_setitem_strs(self, arr1d): + # Check that we parse strs in both scalar and listlike + + # Setting list-like of strs + expected = arr1d.copy() + expected[[0, 1]] = arr1d[-2:] + + result = arr1d.copy() + result[:2] = [str(x) for x in arr1d[-2:]] + tm.assert_equal(result, expected) + + # Same thing but now for just a scalar str + expected = arr1d.copy() + expected[0] = arr1d[-1] + + result = arr1d.copy() + result[0] = str(arr1d[-1]) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("as_index", [True, False]) + def test_setitem_categorical(self, arr1d, as_index): + expected = arr1d.copy()[::-1] + if not isinstance(expected, PeriodArray): + expected = expected._with_freq(None) + + cat = pd.Categorical(arr1d) + if as_index: + cat = pd.CategoricalIndex(cat) + + arr1d[:] = cat[::-1] + + tm.assert_equal(arr1d, expected) + + def test_setitem_raises(self, arr1d): + arr = arr1d[:10] + val = arr[0] + + with pytest.raises(IndexError, match="index 12 is out of bounds"): + arr[12] = val + + with pytest.raises(TypeError, match="value should be a.* 'object'"): + arr[0] = object() + + msg = "cannot set using a list-like indexer with a different length" + with pytest.raises(ValueError, match=msg): + # GH#36339 + arr[[]] = [arr[1]] + + msg = "cannot set using a slice indexer with a different length than" + with pytest.raises(ValueError, match=msg): + # GH#36339 + arr[1:1] = arr[:3] + + @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series]) + def test_setitem_numeric_raises(self, arr1d, box): + # We dont case e.g. int64 to our own dtype for setitem + + msg = ( + f"value should be a '{arr1d._scalar_type.__name__}', " + "'NaT', or array of those. Got" + ) + with pytest.raises(TypeError, match=msg): + arr1d[:2] = box([0, 1]) + + with pytest.raises(TypeError, match=msg): + arr1d[:2] = box([0.0, 1.0]) + + def test_inplace_arithmetic(self): + # GH#24115 check that iadd and isub are actually in-place + data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 + if self.array_cls is PeriodArray: + arr = self.array_cls(data, dtype="period[D]") + else: + arr = self.index_cls(data, freq="D")._data + + expected = arr + pd.Timedelta(days=1) + arr += pd.Timedelta(days=1) + tm.assert_equal(arr, expected) + + expected = arr - pd.Timedelta(days=1) + arr -= pd.Timedelta(days=1) + tm.assert_equal(arr, expected) + + def test_shift_fill_int_deprecated(self, arr1d): + # GH#31971, enforced in 2.0 + with pytest.raises(TypeError, match="value should be a"): + arr1d.shift(1, fill_value=1) + + def test_median(self, arr1d): + arr = arr1d + if len(arr) % 2 == 0: + # make it easier to define `expected` + arr = arr[:-1] + + expected = arr[len(arr) // 2] + + result = arr.median() + assert type(result) is type(expected) + assert result == expected + + arr[len(arr) // 2] = NaT + if not isinstance(expected, Period): + expected = arr[len(arr) // 2 - 1 : len(arr) // 2 + 2].mean() + + assert arr.median(skipna=False) is NaT + + result = arr.median() + assert type(result) is type(expected) + assert result == expected + + assert arr[:0].median() is NaT + assert arr[:0].median(skipna=False) is NaT + + # 2d Case + arr2 = arr.reshape(-1, 1) + + result = arr2.median(axis=None) + assert type(result) is type(expected) + assert result == expected + + assert arr2.median(axis=None, skipna=False) is NaT + + result = arr2.median(axis=0) + expected2 = type(arr)._from_sequence([expected], dtype=arr.dtype) + tm.assert_equal(result, expected2) + + result = arr2.median(axis=0, skipna=False) + expected2 = type(arr)._from_sequence([NaT], dtype=arr.dtype) + tm.assert_equal(result, expected2) + + result = arr2.median(axis=1) + tm.assert_equal(result, arr) + + result = arr2.median(axis=1, skipna=False) + tm.assert_equal(result, arr) + + def test_from_integer_array(self): + arr = np.array([1, 2, 3], dtype=np.int64) + data = pd.array(arr, dtype="Int64") + if self.array_cls is PeriodArray: + expected = self.array_cls(arr, dtype=self.example_dtype) + result = self.array_cls(data, dtype=self.example_dtype) + else: + expected = self.array_cls._from_sequence(arr, dtype=self.example_dtype) + result = self.array_cls._from_sequence(data, dtype=self.example_dtype) + + tm.assert_extension_array_equal(result, expected) + + +class TestDatetimeArray(SharedTests): + index_cls = DatetimeIndex + array_cls = DatetimeArray + scalar_type = Timestamp + example_dtype = "M8[ns]" + + @pytest.fixture + def arr1d(self, tz_naive_fixture, freqstr): + """ + Fixture returning DatetimeArray with parametrized frequency and + timezones + """ + tz = tz_naive_fixture + dti = pd.date_range("2016-01-01 01:01:00", periods=5, freq=freqstr, tz=tz) + dta = dti._data + return dta + + def test_round(self, arr1d): + # GH#24064 + dti = self.index_cls(arr1d) + + result = dti.round(freq="2min") + expected = dti - pd.Timedelta(minutes=1) + expected = expected._with_freq(None) + tm.assert_index_equal(result, expected) + + dta = dti._data + result = dta.round(freq="2min") + expected = expected._data._with_freq(None) + tm.assert_datetime_array_equal(result, expected) + + def test_array_interface(self, datetime_index): + arr = datetime_index._data + copy_false = None if np_version_gt2 else False + + # default asarray gives the same underlying data (for tz naive) + result = np.asarray(arr) + expected = arr._ndarray + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, copy=copy_false) + assert result is expected + tm.assert_numpy_array_equal(result, expected) + + # specifying M8[ns] gives the same result as default + result = np.asarray(arr, dtype="datetime64[ns]") + expected = arr._ndarray + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, dtype="datetime64[ns]", copy=copy_false) + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, dtype="datetime64[ns]") + if not np_version_gt2: + # TODO: GH 57739 + assert result is not expected + tm.assert_numpy_array_equal(result, expected) + + # to object dtype + result = np.asarray(arr, dtype=object) + expected = np.array(list(arr), dtype=object) + tm.assert_numpy_array_equal(result, expected) + + # to other dtype always copies + result = np.asarray(arr, dtype="int64") + assert result is not arr.asi8 + assert not np.may_share_memory(arr, result) + expected = arr.asi8.copy() + tm.assert_numpy_array_equal(result, expected) + + # other dtypes handled by numpy + for dtype in ["float64", str]: + result = np.asarray(arr, dtype=dtype) + expected = np.asarray(arr).astype(dtype) + tm.assert_numpy_array_equal(result, expected) + + def test_array_object_dtype(self, arr1d): + # GH#23524 + arr = arr1d + dti = self.index_cls(arr1d) + + expected = np.array(list(dti)) + + result = np.array(arr, dtype=object) + tm.assert_numpy_array_equal(result, expected) + + # also test the DatetimeIndex method while we're at it + result = np.array(dti, dtype=object) + tm.assert_numpy_array_equal(result, expected) + + def test_array_tz(self, arr1d): + # GH#23524 + arr = arr1d + dti = self.index_cls(arr1d) + copy_false = None if np_version_gt2 else False + + expected = dti.asi8.view("M8[ns]") + result = np.array(arr, dtype="M8[ns]") + tm.assert_numpy_array_equal(result, expected) + + result = np.array(arr, dtype="datetime64[ns]") + tm.assert_numpy_array_equal(result, expected) + + # check that we are not making copies when setting copy=copy_false + result = np.array(arr, dtype="M8[ns]", copy=copy_false) + assert result.base is expected.base + assert result.base is not None + result = np.array(arr, dtype="datetime64[ns]", copy=copy_false) + assert result.base is expected.base + assert result.base is not None + + def test_array_i8_dtype(self, arr1d): + arr = arr1d + dti = self.index_cls(arr1d) + copy_false = None if np_version_gt2 else False + + expected = dti.asi8 + result = np.array(arr, dtype="i8") + tm.assert_numpy_array_equal(result, expected) + + result = np.array(arr, dtype=np.int64) + tm.assert_numpy_array_equal(result, expected) + + # check that we are still making copies when setting copy=copy_false + result = np.array(arr, dtype="i8", copy=copy_false) + assert result.base is not expected.base + assert result.base is None + + def test_from_array_keeps_base(self): + # Ensure that DatetimeArray._ndarray.base isn't lost. + arr = np.array(["2000-01-01", "2000-01-02"], dtype="M8[ns]") + dta = DatetimeArray._from_sequence(arr) + + assert dta._ndarray is arr + dta = DatetimeArray._from_sequence(arr[:0]) + assert dta._ndarray.base is arr + + def test_from_dti(self, arr1d): + arr = arr1d + dti = self.index_cls(arr1d) + assert list(dti) == list(arr) + + # Check that Index.__new__ knows what to do with DatetimeArray + dti2 = pd.Index(arr) + assert isinstance(dti2, DatetimeIndex) + assert list(dti2) == list(arr) + + def test_astype_object(self, arr1d): + arr = arr1d + dti = self.index_cls(arr1d) + + asobj = arr.astype("O") + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == "O" + assert list(asobj) == list(dti) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_to_period(self, datetime_index, freqstr): + dti = datetime_index + arr = dti._data + + freqstr = freq_to_period_freqstr(1, freqstr) + expected = dti.to_period(freq=freqstr) + result = arr.to_period(freq=freqstr) + assert isinstance(result, PeriodArray) + + tm.assert_equal(result, expected._data) + + def test_to_period_2d(self, arr1d): + arr2d = arr1d.reshape(1, -1) + + warn = None if arr1d.tz is None else UserWarning + with tm.assert_produces_warning(warn): + result = arr2d.to_period("D") + expected = arr1d.to_period("D").reshape(1, -1) + tm.assert_period_array_equal(result, expected) + + @pytest.mark.parametrize("propname", DatetimeArray._bool_ops) + def test_bool_properties(self, arr1d, propname): + # in this case _bool_ops is just `is_leap_year` + dti = self.index_cls(arr1d) + arr = arr1d + assert dti.freq == arr.freq + + result = getattr(arr, propname) + expected = np.array(getattr(dti, propname), dtype=result.dtype) + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("propname", DatetimeArray._field_ops) + def test_int_properties(self, arr1d, propname): + dti = self.index_cls(arr1d) + arr = arr1d + + result = getattr(arr, propname) + expected = np.array(getattr(dti, propname), dtype=result.dtype) + + tm.assert_numpy_array_equal(result, expected) + + def test_take_fill_valid(self, arr1d, fixed_now_ts): + arr = arr1d + dti = self.index_cls(arr1d) + + now = fixed_now_ts.tz_localize(dti.tz) + result = arr.take([-1, 1], allow_fill=True, fill_value=now) + assert result[0] == now + + msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + # fill_value Timedelta invalid + arr.take([-1, 1], allow_fill=True, fill_value=now - now) + + with pytest.raises(TypeError, match=msg): + # fill_value Period invalid + arr.take([-1, 1], allow_fill=True, fill_value=Period("2014Q1")) + + tz = None if dti.tz is not None else "US/Eastern" + now = fixed_now_ts.tz_localize(tz) + msg = "Cannot compare tz-naive and tz-aware datetime-like objects" + with pytest.raises(TypeError, match=msg): + # Timestamp with mismatched tz-awareness + arr.take([-1, 1], allow_fill=True, fill_value=now) + + value = NaT._value + msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + # require NaT, not iNaT, as it could be confused with an integer + arr.take([-1, 1], allow_fill=True, fill_value=value) + + value = np.timedelta64("NaT", "ns") + with pytest.raises(TypeError, match=msg): + # require appropriate-dtype if we have a NA value + arr.take([-1, 1], allow_fill=True, fill_value=value) + + if arr.tz is not None: + # GH#37356 + # Assuming here that arr1d fixture does not include Australia/Melbourne + value = fixed_now_ts.tz_localize("Australia/Melbourne") + result = arr.take([-1, 1], allow_fill=True, fill_value=value) + + expected = arr.take( + [-1, 1], + allow_fill=True, + fill_value=value.tz_convert(arr.dtype.tz), + ) + tm.assert_equal(result, expected) + + def test_concat_same_type_invalid(self, arr1d): + # different timezones + arr = arr1d + + if arr.tz is None: + other = arr.tz_localize("UTC") + else: + other = arr.tz_localize(None) + + with pytest.raises(ValueError, match="to_concat must have the same"): + arr._concat_same_type([arr, other]) + + def test_concat_same_type_different_freq(self, unit): + # we *can* concatenate DTI with different freqs. + a = pd.date_range("2000", periods=2, freq="D", tz="US/Central", unit=unit)._data + b = pd.date_range("2000", periods=2, freq="h", tz="US/Central", unit=unit)._data + result = DatetimeArray._concat_same_type([a, b]) + expected = ( + pd.to_datetime( + [ + "2000-01-01 00:00:00", + "2000-01-02 00:00:00", + "2000-01-01 00:00:00", + "2000-01-01 01:00:00", + ] + ) + .tz_localize("US/Central") + .as_unit(unit) + ._data + ) + + tm.assert_datetime_array_equal(result, expected) + + def test_strftime(self, arr1d): + arr = arr1d + + result = arr.strftime("%Y %b") + expected = np.array([ts.strftime("%Y %b") for ts in arr], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + def test_strftime_nat(self): + # GH 29578 + arr = DatetimeIndex(["2019-01-01", NaT])._data + + result = arr.strftime("%Y-%m-%d") + expected = np.array(["2019-01-01", np.nan], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + +class TestTimedeltaArray(SharedTests): + index_cls = TimedeltaIndex + array_cls = TimedeltaArray + scalar_type = pd.Timedelta + example_dtype = "m8[ns]" + + def test_from_tdi(self): + tdi = TimedeltaIndex(["1 Day", "3 Hours"]) + arr = tdi._data + assert list(arr) == list(tdi) + + # Check that Index.__new__ knows what to do with TimedeltaArray + tdi2 = pd.Index(arr) + assert isinstance(tdi2, TimedeltaIndex) + assert list(tdi2) == list(arr) + + def test_astype_object(self): + tdi = TimedeltaIndex(["1 Day", "3 Hours"]) + arr = tdi._data + asobj = arr.astype("O") + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == "O" + assert list(asobj) == list(tdi) + + def test_to_pytimedelta(self, timedelta_index): + tdi = timedelta_index + arr = tdi._data + + expected = tdi.to_pytimedelta() + result = arr.to_pytimedelta() + + tm.assert_numpy_array_equal(result, expected) + + def test_total_seconds(self, timedelta_index): + tdi = timedelta_index + arr = tdi._data + + expected = tdi.total_seconds() + result = arr.total_seconds() + + tm.assert_numpy_array_equal(result, expected.values) + + @pytest.mark.parametrize("propname", TimedeltaArray._field_ops) + def test_int_properties(self, timedelta_index, propname): + tdi = timedelta_index + arr = tdi._data + + result = getattr(arr, propname) + expected = np.array(getattr(tdi, propname), dtype=result.dtype) + + tm.assert_numpy_array_equal(result, expected) + + def test_array_interface(self, timedelta_index): + arr = timedelta_index._data + copy_false = None if np_version_gt2 else False + + # default asarray gives the same underlying data + result = np.asarray(arr) + expected = arr._ndarray + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, copy=copy_false) + assert result is expected + tm.assert_numpy_array_equal(result, expected) + + # specifying m8[ns] gives the same result as default + result = np.asarray(arr, dtype="timedelta64[ns]") + expected = arr._ndarray + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, dtype="timedelta64[ns]", copy=copy_false) + assert result is expected + tm.assert_numpy_array_equal(result, expected) + result = np.array(arr, dtype="timedelta64[ns]") + if not np_version_gt2: + # TODO: GH 57739 + assert result is not expected + tm.assert_numpy_array_equal(result, expected) + + # to object dtype + result = np.asarray(arr, dtype=object) + expected = np.array(list(arr), dtype=object) + tm.assert_numpy_array_equal(result, expected) + + # to other dtype always copies + result = np.asarray(arr, dtype="int64") + assert result is not arr.asi8 + assert not np.may_share_memory(arr, result) + expected = arr.asi8.copy() + tm.assert_numpy_array_equal(result, expected) + + # other dtypes handled by numpy + for dtype in ["float64", str]: + result = np.asarray(arr, dtype=dtype) + expected = np.asarray(arr).astype(dtype) + tm.assert_numpy_array_equal(result, expected) + + def test_take_fill_valid(self, timedelta_index, fixed_now_ts): + tdi = timedelta_index + arr = tdi._data + + td1 = pd.Timedelta(days=1) + result = arr.take([-1, 1], allow_fill=True, fill_value=td1) + assert result[0] == td1 + + value = fixed_now_ts + msg = f"value should be a '{arr._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + # fill_value Timestamp invalid + arr.take([0, 1], allow_fill=True, fill_value=value) + + value = fixed_now_ts.to_period("D") + with pytest.raises(TypeError, match=msg): + # fill_value Period invalid + arr.take([0, 1], allow_fill=True, fill_value=value) + + value = np.datetime64("NaT", "ns") + with pytest.raises(TypeError, match=msg): + # require appropriate-dtype if we have a NA value + arr.take([-1, 1], allow_fill=True, fill_value=value) + + +@pytest.mark.filterwarnings(r"ignore:Period with BDay freq is deprecated:FutureWarning") +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") +class TestPeriodArray(SharedTests): + index_cls = PeriodIndex + array_cls = PeriodArray + scalar_type = Period + example_dtype = PeriodIndex([], freq="W").dtype + + @pytest.fixture + def arr1d(self, period_index): + """ + Fixture returning DatetimeArray from parametrized PeriodIndex objects + """ + return period_index._data + + def test_from_pi(self, arr1d): + pi = self.index_cls(arr1d) + arr = arr1d + assert list(arr) == list(pi) + + # Check that Index.__new__ knows what to do with PeriodArray + pi2 = pd.Index(arr) + assert isinstance(pi2, PeriodIndex) + assert list(pi2) == list(arr) + + def test_astype_object(self, arr1d): + pi = self.index_cls(arr1d) + arr = arr1d + asobj = arr.astype("O") + assert isinstance(asobj, np.ndarray) + assert asobj.dtype == "O" + assert list(asobj) == list(pi) + + def test_take_fill_valid(self, arr1d): + arr = arr1d + + value = NaT._value + msg = f"value should be a '{arr1d._scalar_type.__name__}' or 'NaT'. Got" + with pytest.raises(TypeError, match=msg): + # require NaT, not iNaT, as it could be confused with an integer + arr.take([-1, 1], allow_fill=True, fill_value=value) + + value = np.timedelta64("NaT", "ns") + with pytest.raises(TypeError, match=msg): + # require appropriate-dtype if we have a NA value + arr.take([-1, 1], allow_fill=True, fill_value=value) + + @pytest.mark.parametrize("how", ["S", "E"]) + def test_to_timestamp(self, how, arr1d): + pi = self.index_cls(arr1d) + arr = arr1d + + expected = DatetimeIndex(pi.to_timestamp(how=how))._data + result = arr.to_timestamp(how=how) + assert isinstance(result, DatetimeArray) + + tm.assert_equal(result, expected) + + def test_to_timestamp_roundtrip_bday(self): + # Case where infer_freq inside would choose "D" instead of "B" + dta = pd.date_range("2021-10-18", periods=3, freq="B")._data + parr = dta.to_period() + result = parr.to_timestamp() + assert result.freq == "B" + tm.assert_extension_array_equal(result, dta) + + dta2 = dta[::2] + parr2 = dta2.to_period() + result2 = parr2.to_timestamp() + assert result2.freq == "2B" + tm.assert_extension_array_equal(result2, dta2) + + parr3 = dta.to_period("2B") + result3 = parr3.to_timestamp() + assert result3.freq == "B" + tm.assert_extension_array_equal(result3, dta) + + def test_to_timestamp_out_of_bounds(self): + # GH#19643 previously overflowed silently + pi = pd.period_range("1500", freq="Y", periods=3) + msg = "Out of bounds nanosecond timestamp: 1500-01-01 00:00:00" + with pytest.raises(OutOfBoundsDatetime, match=msg): + pi.to_timestamp() + + with pytest.raises(OutOfBoundsDatetime, match=msg): + pi._data.to_timestamp() + + @pytest.mark.parametrize("propname", PeriodArray._bool_ops) + def test_bool_properties(self, arr1d, propname): + # in this case _bool_ops is just `is_leap_year` + pi = self.index_cls(arr1d) + arr = arr1d + + result = getattr(arr, propname) + expected = np.array(getattr(pi, propname)) + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("propname", PeriodArray._field_ops) + def test_int_properties(self, arr1d, propname): + pi = self.index_cls(arr1d) + arr = arr1d + + result = getattr(arr, propname) + expected = np.array(getattr(pi, propname)) + + tm.assert_numpy_array_equal(result, expected) + + def test_array_interface(self, arr1d): + arr = arr1d + + # default asarray gives objects + result = np.asarray(arr) + expected = np.array(list(arr), dtype=object) + tm.assert_numpy_array_equal(result, expected) + + # to object dtype (same as default) + result = np.asarray(arr, dtype=object) + tm.assert_numpy_array_equal(result, expected) + + result = np.asarray(arr, dtype="int64") + tm.assert_numpy_array_equal(result, arr.asi8) + + # to other dtypes + msg = r"float\(\) argument must be a string or a( real)? number, not 'Period'" + with pytest.raises(TypeError, match=msg): + np.asarray(arr, dtype="float64") + + result = np.asarray(arr, dtype="S20") + expected = np.asarray(arr).astype("S20") + tm.assert_numpy_array_equal(result, expected) + + def test_strftime(self, arr1d): + arr = arr1d + + result = arr.strftime("%Y") + expected = np.array([per.strftime("%Y") for per in arr], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + def test_strftime_nat(self): + # GH 29578 + arr = PeriodArray(PeriodIndex(["2019-01-01", NaT], dtype="period[D]")) + + result = arr.strftime("%Y-%m-%d") + expected = np.array(["2019-01-01", np.nan], dtype=object) + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize( + "arr,casting_nats", + [ + ( + TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data, + (NaT, np.timedelta64("NaT", "ns")), + ), + ( + pd.date_range("2000-01-01", periods=3, freq="D")._data, + (NaT, np.datetime64("NaT", "ns")), + ), + (pd.period_range("2000-01-01", periods=3, freq="D")._data, (NaT,)), + ], + ids=lambda x: type(x).__name__, +) +def test_casting_nat_setitem_array(arr, casting_nats): + expected = type(arr)._from_sequence([NaT, arr[1], arr[2]], dtype=arr.dtype) + + for nat in casting_nats: + arr = arr.copy() + arr[0] = nat + tm.assert_equal(arr, expected) + + +@pytest.mark.parametrize( + "arr,non_casting_nats", + [ + ( + TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data, + (np.datetime64("NaT", "ns"), NaT._value), + ), + ( + pd.date_range("2000-01-01", periods=3, freq="D")._data, + (np.timedelta64("NaT", "ns"), NaT._value), + ), + ( + pd.period_range("2000-01-01", periods=3, freq="D")._data, + (np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns"), NaT._value), + ), + ], + ids=lambda x: type(x).__name__, +) +def test_invalid_nat_setitem_array(arr, non_casting_nats): + msg = ( + "value should be a '(Timestamp|Timedelta|Period)', 'NaT', or array of those. " + "Got '(timedelta64|datetime64|int)' instead." + ) + + for nat in non_casting_nats: + with pytest.raises(TypeError, match=msg): + arr[0] = nat + + +@pytest.mark.parametrize( + "arr", + [ + pd.date_range("2000", periods=4).array, + pd.timedelta_range("2000", periods=4).array, + ], +) +def test_to_numpy_extra(arr): + arr[0] = NaT + original = arr.copy() + + result = arr.to_numpy() + assert np.isnan(result[0]) + + result = arr.to_numpy(dtype="int64") + assert result[0] == -9223372036854775808 + + result = arr.to_numpy(dtype="int64", na_value=0) + assert result[0] == 0 + + result = arr.to_numpy(na_value=arr[1].to_numpy()) + assert result[0] == result[1] + + result = arr.to_numpy(na_value=arr[1].to_numpy(copy=False)) + assert result[0] == result[1] + + tm.assert_equal(arr, original) + + +@pytest.mark.parametrize("as_index", [True, False]) +@pytest.mark.parametrize( + "values", + [ + pd.to_datetime(["2020-01-01", "2020-02-01"]), + pd.to_timedelta([1, 2], unit="D"), + PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"), + ], +) +@pytest.mark.parametrize( + "klass", + [ + list, + np.array, + pd.array, + pd.Series, + pd.Index, + pd.Categorical, + pd.CategoricalIndex, + ], +) +def test_searchsorted_datetimelike_with_listlike(values, klass, as_index): + # https://github.com/pandas-dev/pandas/issues/32762 + if not as_index: + values = values._data + + result = values.searchsorted(klass(values)) + expected = np.array([0, 1], dtype=result.dtype) + + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + pd.to_datetime(["2020-01-01", "2020-02-01"]), + pd.to_timedelta([1, 2], unit="D"), + PeriodIndex(["2020-01-01", "2020-02-01"], freq="D"), + ], +) +@pytest.mark.parametrize( + "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2] +) +def test_searchsorted_datetimelike_with_listlike_invalid_dtype(values, arg): + # https://github.com/pandas-dev/pandas/issues/32762 + msg = "[Unexpected type|Cannot compare]" + with pytest.raises(TypeError, match=msg): + values.searchsorted(arg) + + +@pytest.mark.parametrize("klass", [list, tuple, np.array, pd.Series]) +def test_period_index_construction_from_strings(klass): + # https://github.com/pandas-dev/pandas/issues/26109 + strings = ["2020Q1", "2020Q2"] * 2 + data = klass(strings) + result = PeriodIndex(data, freq="Q") + expected = PeriodIndex([Period(s) for s in strings]) + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) +def test_from_pandas_array(dtype): + # GH#24615 + data = np.array([1, 2, 3], dtype=dtype) + arr = NumpyExtensionArray(data) + + cls = {"M8[ns]": DatetimeArray, "m8[ns]": TimedeltaArray}[dtype] + + depr_msg = f"{cls.__name__}.__init__ is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = cls(arr) + expected = cls(data) + tm.assert_extension_array_equal(result, expected) + + result = cls._from_sequence(arr, dtype=dtype) + expected = cls._from_sequence(data, dtype=dtype) + tm.assert_extension_array_equal(result, expected) + + func = {"M8[ns]": pd.to_datetime, "m8[ns]": pd.to_timedelta}[dtype] + result = func(arr).array + expected = func(data).array + tm.assert_equal(result, expected) + + # Let's check the Indexes while we're here + idx_cls = {"M8[ns]": DatetimeIndex, "m8[ns]": TimedeltaIndex}[dtype] + result = idx_cls(arr) + expected = idx_cls(data) + tm.assert_index_equal(result, expected) diff --git a/shared/package-files/4a/4a914a69489e5c83bb21d896ed2cab79690a9d38b30ca5a0e3c2e66a10477802/linalg_svd_native.h b/shared/package-files/4a/4a914a69489e5c83bb21d896ed2cab79690a9d38b30ca5a0e3c2e66a10477802/linalg_svd_native.h new file mode 100644 index 0000000000000000000000000000000000000000..864d9e99a636faeaa854cec6e4fabef9a60b0bb0 --- /dev/null +++ b/shared/package-files/4a/4a914a69489e5c83bb21d896ed2cab79690a9d38b30ca5a0e3c2e66a10477802/linalg_svd_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple linalg_svd(const at::Tensor & A, bool full_matrices=true, ::std::optional driver=::std::nullopt); +TORCH_API ::std::tuple linalg_svd_out(const at::Tensor & A, bool full_matrices, ::std::optional driver, at::Tensor & U, at::Tensor & S, at::Tensor & Vh); +} // namespace native +} // namespace at diff --git a/shared/package-files/4a/4aab35af42c4d21618307892015d350bd9adfcced2ffcd28e2abb7701ff943e9/mps_convolution_backward_native.h b/shared/package-files/4a/4aab35af42c4d21618307892015d350bd9adfcced2ffcd28e2abb7701ff943e9/mps_convolution_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..21eb217a51e394736b0cb0f53efd460c7d846463 --- /dev/null +++ b/shared/package-files/4a/4aab35af42c4d21618307892015d350bd9adfcced2ffcd28e2abb7701ff943e9/mps_convolution_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple mps_convolution_backward_out_symint(const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, ::std::array output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +} // namespace native +} // namespace at diff --git a/shared/package-files/4a/4aacec53cacff45dd5a9acb9096b93ed868bb660e784fda42437600234765acd/add_if_then_else.h b/shared/package-files/4a/4aacec53cacff45dd5a9acb9096b93ed868bb660e784fda42437600234765acd/add_if_then_else.h new file mode 100644 index 0000000000000000000000000000000000000000..6495e1eaed5838bc5ae742739195e4ae1ca47919 --- /dev/null +++ b/shared/package-files/4a/4aacec53cacff45dd5a9acb9096b93ed868bb660e784fda42437600234765acd/add_if_then_else.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool AddIfThenElseOp(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/shared/package-files/4a/4ab277231acf43af63acbae7a98f8b77e6ddc04061cf69ba78b5ed9d04211ad4/FunctionalStorageImpl.h b/shared/package-files/4a/4ab277231acf43af63acbae7a98f8b77e6ddc04061cf69ba78b5ed9d04211ad4/FunctionalStorageImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..3f80171196fbc7bdb00c79d725ba521f49455d3d --- /dev/null +++ b/shared/package-files/4a/4ab277231acf43af63acbae7a98f8b77e6ddc04061cf69ba78b5ed9d04211ad4/FunctionalStorageImpl.h @@ -0,0 +1,208 @@ +#pragma once + +#include + +#include + +namespace at::functionalization { + +// See Note [Functionalization Pass In Core] + +// ViewMeta is a class used by the functionalization pass to navigate between +// a base tensor and a view tensor. +// For example, if I call `b = a.view1(...)` +// the functionalization pass will generate and store a ViewMeta on b that looks +// like: +// +// ViewMeta( +// [](const Tensor& base, int64_t mutated_view_idx) { +// return base.view1(...); +// }, +// [](const at::Tensor& base, const at::Tensor& mutated_view, +// int64_t mutated_view_idx) -> at::Tensor { +// return at::functionalization::impl::view1_inverse(base, mutated_view, +// ...); +// } +// +// The forward_fn lambda describes how to replay view1 on a tensor. +// +// The reverse_fn lambda describes how, given a tensor that is already a view, +// how to get the corresponding base tensor. See Note [Functionalization Pass: +// View Inverses] for details. +struct ViewMeta { + ViewMeta( + std::function forward, + std::function reverse, + bool has_symbolic_inputs, + bool is_multi_output = false, + bool is_as_strided = false, + int64_t out_idx = 0) + : forward_fn(std::move(forward)), + reverse_fn(std::move(reverse)), + out_index(out_idx), + is_multi_output(is_multi_output), + is_as_strided(is_as_strided), + has_symbolic_inputs(has_symbolic_inputs) {} + + std::function forward_fn; + std::function reverse_fn; + // See Note [out_idx in ViewMeta] + int64_t out_index; + + // Tells us if this is a multi-output view + bool is_multi_output; + + bool is_as_strided; + + // Tells us if this view operation has any symbolic inputs + bool has_symbolic_inputs; + + // Returns a copy of the current ViewMeta, if out_idx matches the current + // out_index. Otherwise, returns a new ViewMeta with the same forward/reverse + // functions, but a new out index. + ViewMeta to_out_idx(int64_t out_idx); +}; + +// FunctionalStorageImpl is a subclass of StorageImpl used by the +// functionalization pass. It has no underlying data (similar to meta storage). +// It also knows how to reflect mutations to tensors in the absence of a valid +// data pointer. +// +// A storage represents the state shared by (potentially multiple) views of the +// same tensor. For example, in the following code: +// +// b = a.view1(...) +// c = b.view2(...) +// b.add_(1) +// --> storage.add_update(b, {view1_meta}) +// +// The call to add_(1) will result in a call to alias.add_update(b, +// {view1_meta}), queueing up the mutation from b onto the alias. Later, suppose +// c is used in an expression (e.g. you try to print c, or pass it to an +// operator). Doing so will involve "syncing" c. First we apply any pending +// updates to the alias, and then we regenerate c by replaying its views off of +// the updated alias. E.g: +// +// print(str(c)) +// --> c.sync_() +// --> alias.apply_updates() // after this, the alias will be updated to +// reflect the mutation to b +struct TORCH_API FunctionalStorageImpl : public c10::StorageImpl { + public: + struct Update { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::Tensor new_val; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::vector view_metas; + }; + + explicit FunctionalStorageImpl(const Tensor& value); + + void add_update( + const Tensor& updated_val, + const std::vector& view_metas); + bool apply_updates(); + const Tensor& base() { + return base_; + } + size_t generation() const { + return generation_; + } + void freeze() { + frozen_ = true; + } + + c10::SymInt get_storage_size(bool before) { + if (before) { + return original_storage_size_; + } else { + return curr_storage_size_; + } + } + + ~FunctionalStorageImpl() override = default; + + void mark_mutation() { + mutation_counter_++; + } + void mark_mutation_during_no_grad_or_inference_mode() { + mutation_counter_during_no_grad_or_inference_mode_++; + } + void mark_mutation_hidden_from_autograd() { + mutation_counter_hidden_from_autograd_++; + } + + bool are_all_mutations_under_no_grad_or_inference_mode() const { + auto non_autograd_mutations = + mutation_counter_during_no_grad_or_inference_mode_ + + mutation_counter_hidden_from_autograd_; + // The <= is because both counters will technically be incremented, if we + // perform e.g. a triton kernel mutation under no_grad + return mutation_counter_ <= non_autograd_mutations; + } + + bool are_all_mutations_hidden_from_autograd() const { + // mutations under no_grad / inference_mode are technically not hidden from + // autograd - they change the version counter + return mutation_counter_ <= mutation_counter_hidden_from_autograd_; + } + + void mark_inductor_storage_resize(c10::SymInt new_size) { + inductor_storage_resized_ = true; + curr_storage_size_ = std::move(new_size); + } + + bool was_inductor_storage_resized() { + return inductor_storage_resized_; + } + + private: + // NB: base_ should always point to a tensor BELOW the current + // functionalization layer. This is mainly to avoid reference cycles. e.g. + // given `b = a.view(...)` Both a.storage_ and b.storage_ are a + // FunctionStorageImpl containing an Walualias, with contains a Tensor + // `base_`. In this case (where a and b are FunctionalTensorWrapper's), base_ + // should point not to a, but to a's unwrapped value, a.value_` See Note + // [Functionalization: Walualias Removal] for a diagram that shows this + // visually. + at::Tensor base_; + std::vector updates_; + // generation_ gets incremented every time a mutation is queued onto the + // alias. It is used to determine if a given tensor is "up to date", or if it + // needs to be regenerated from the alias. + size_t generation_ = 0; + // If frozen, no more mutations are allowed on this storage. Once frozen, a + // storage cannot be unfrozen. + bool frozen_ = false; + + // These mutation counters are bumped on the storage + // whenever a FunctionalTensorWrapper experiences a mutation. + // When the mutation is under no_grad, or comes from a triton kernel, we also + // bump the corresponding during_no_grad or hidden_from_autograd counters. Why + // do we need to detect these two situations separately from "normal" input + // mutations? (1) "normal" input mutations can mutate autograd metadata like + // .grad_fn, + // in which case they need to be replayed outside of the compiled graph + // (2) "no_grad" input mutations are generally safe to keep in the graph (and + // compile), + // but they bump the tensor's VC, so we need to mark_dirty() on the inputs + // in torch.compile + // (3) mutations that are fully hidden from autograd (e.g. from a triton + // kernel) + // do not mutate any autograd state, and be fully kept in the graph + // When we detect that an input was mutated, we need to be able to tell if: + // (1) all of the mutations were from triton kernels + // (2) all of the mutations were under no_grad + uint64_t mutation_counter_during_no_grad_or_inference_mode_ = 0; + uint64_t mutation_counter_ = 0; + uint64_t mutation_counter_hidden_from_autograd_ = 0; + + // Used to tell if: + // (1) There were any storage resizes on a graph input + // (2) The original/curr storage size tell us if these resizes result in a nop + bool inductor_storage_resized_ = false; + c10::SymInt original_storage_size_; + c10::SymInt curr_storage_size_; +}; + +} // namespace at::functionalization diff --git a/shared/package-files/4a/4ab7ff4fc7cc4e9162eb8640810a26d12d40e022c57caaedc0f07f79da0cbbbf/__init__.py b/shared/package-files/4a/4ab7ff4fc7cc4e9162eb8640810a26d12d40e022c57caaedc0f07f79da0cbbbf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8876d439feb41929ca9b64f3f023db499eac007b --- /dev/null +++ b/shared/package-files/4a/4ab7ff4fc7cc4e9162eb8640810a26d12d40e022c57caaedc0f07f79da0cbbbf/__init__.py @@ -0,0 +1,6 @@ +from .rewrite import reference_representation_rewrite + + +__all__ = [ + "reference_representation_rewrite", +] diff --git a/shared/package-files/4a/4ab9e6df62bf16cad8b9eeb99b1aec2cc42261bb3ce9516062f383a1da6304d7/quantize_handler.cpython-311.pyc b/shared/package-files/4a/4ab9e6df62bf16cad8b9eeb99b1aec2cc42261bb3ce9516062f383a1da6304d7/quantize_handler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a323f6c1edf083d1f0237ac7192ad71e5efe2bfd Binary files /dev/null and b/shared/package-files/4a/4ab9e6df62bf16cad8b9eeb99b1aec2cc42261bb3ce9516062f383a1da6304d7/quantize_handler.cpython-311.pyc differ diff --git a/shared/package-files/4a/4abaf032e375aca60e482aed8d700dd50ad282441821c72f6947942dbe2bb3d8/vmap.cpython-311.pyc b/shared/package-files/4a/4abaf032e375aca60e482aed8d700dd50ad282441821c72f6947942dbe2bb3d8/vmap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e14fecef309a8c9c1999835caa05bb6c3339d017 Binary files /dev/null and b/shared/package-files/4a/4abaf032e375aca60e482aed8d700dd50ad282441821c72f6947942dbe2bb3d8/vmap.cpython-311.pyc differ diff --git a/shared/package-files/4a/4ac6cb3af365781617469801b9c48b27ccc7e95ea78e0ed1fec646eb6137696d/test_hilbert.cpython-311.pyc b/shared/package-files/4a/4ac6cb3af365781617469801b9c48b27ccc7e95ea78e0ed1fec646eb6137696d/test_hilbert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38364f18da011dd528935a260f46ce71eb088e3f Binary files /dev/null and b/shared/package-files/4a/4ac6cb3af365781617469801b9c48b27ccc7e95ea78e0ed1fec646eb6137696d/test_hilbert.cpython-311.pyc differ diff --git a/shared/package-files/4a/4acaaefa016da89ef44633cddbbb2f2ddb0a3a4d0e0dfb190a95f1ec2481bb70/test_traveling_salesman.py b/shared/package-files/4a/4acaaefa016da89ef44633cddbbb2f2ddb0a3a4d0e0dfb190a95f1ec2481bb70/test_traveling_salesman.py new file mode 100644 index 0000000000000000000000000000000000000000..d512428692bde6183891a99638dcb03748c4701d --- /dev/null +++ b/shared/package-files/4a/4acaaefa016da89ef44633cddbbb2f2ddb0a3a4d0e0dfb190a95f1ec2481bb70/test_traveling_salesman.py @@ -0,0 +1,1013 @@ +"""Unit tests for the traveling_salesman module.""" + +import random + +import pytest + +import networkx as nx +import networkx.algorithms.approximation as nx_app + +pairwise = nx.utils.pairwise + + +def test_christofides_hamiltonian(): + random.seed(42) + G = nx.complete_graph(20) + for u, v in G.edges(): + G[u][v]["weight"] = random.randint(0, 10) + + H = nx.Graph() + H.add_edges_from(pairwise(nx_app.christofides(G))) + H.remove_edges_from(nx.find_cycle(H)) + assert len(H.edges) == 0 + + tree = nx.minimum_spanning_tree(G, weight="weight") + H = nx.Graph() + H.add_edges_from(pairwise(nx_app.christofides(G, tree))) + H.remove_edges_from(nx.find_cycle(H)) + assert len(H.edges) == 0 + + +def test_christofides_incomplete_graph(): + G = nx.complete_graph(10) + G.remove_edge(0, 1) + pytest.raises(nx.NetworkXError, nx_app.christofides, G) + + +def test_christofides_ignore_selfloops(): + G = nx.complete_graph(5) + G.add_edge(3, 3) + cycle = nx_app.christofides(G) + assert len(cycle) - 1 == len(G) == len(set(cycle)) + + +# set up graphs for other tests +class TestBase: + @classmethod + def setup_class(cls): + cls.DG = nx.DiGraph() + cls.DG.add_weighted_edges_from( + { + ("A", "B", 3), + ("A", "C", 17), + ("A", "D", 14), + ("B", "A", 3), + ("B", "C", 12), + ("B", "D", 16), + ("C", "A", 13), + ("C", "B", 12), + ("C", "D", 4), + ("D", "A", 14), + ("D", "B", 15), + ("D", "C", 2), + } + ) + cls.DG_cycle = ["D", "C", "B", "A", "D"] + cls.DG_cost = 31.0 + + cls.DG2 = nx.DiGraph() + cls.DG2.add_weighted_edges_from( + { + ("A", "B", 3), + ("A", "C", 17), + ("A", "D", 14), + ("B", "A", 30), + ("B", "C", 2), + ("B", "D", 16), + ("C", "A", 33), + ("C", "B", 32), + ("C", "D", 34), + ("D", "A", 14), + ("D", "B", 15), + ("D", "C", 2), + } + ) + cls.DG2_cycle = ["D", "A", "B", "C", "D"] + cls.DG2_cost = 53.0 + + cls.unweightedUG = nx.complete_graph(5, nx.Graph()) + cls.unweightedDG = nx.complete_graph(5, nx.DiGraph()) + + cls.incompleteUG = nx.Graph() + cls.incompleteUG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)}) + cls.incompleteDG = nx.DiGraph() + cls.incompleteDG.add_weighted_edges_from({(0, 1, 1), (1, 2, 3)}) + + cls.UG = nx.Graph() + cls.UG.add_weighted_edges_from( + { + ("A", "B", 3), + ("A", "C", 17), + ("A", "D", 14), + ("B", "C", 12), + ("B", "D", 16), + ("C", "D", 4), + } + ) + cls.UG_cycle = ["D", "C", "B", "A", "D"] + cls.UG_cost = 33.0 + + cls.UG2 = nx.Graph() + cls.UG2.add_weighted_edges_from( + { + ("A", "B", 1), + ("A", "C", 15), + ("A", "D", 5), + ("B", "C", 16), + ("B", "D", 8), + ("C", "D", 3), + } + ) + cls.UG2_cycle = ["D", "C", "B", "A", "D"] + cls.UG2_cost = 25.0 + + +def validate_solution(soln, cost, exp_soln, exp_cost): + assert soln == exp_soln + assert cost == exp_cost + + +def validate_symmetric_solution(soln, cost, exp_soln, exp_cost): + assert soln == exp_soln or soln == exp_soln[::-1] + assert cost == exp_cost + + +class TestGreedyTSP(TestBase): + def test_greedy(self): + cycle = nx_app.greedy_tsp(self.DG, source="D") + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 31.0) + + cycle = nx_app.greedy_tsp(self.DG2, source="D") + cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 78.0) + + cycle = nx_app.greedy_tsp(self.UG, source="D") + cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, ["D", "C", "B", "A", "D"], 33.0) + + cycle = nx_app.greedy_tsp(self.UG2, source="D") + cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, ["D", "C", "A", "B", "D"], 27.0) + + def test_not_complete_graph(self): + pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteUG) + pytest.raises(nx.NetworkXError, nx_app.greedy_tsp, self.incompleteDG) + + def test_not_weighted_graph(self): + nx_app.greedy_tsp(self.unweightedUG) + nx_app.greedy_tsp(self.unweightedDG) + + def test_two_nodes(self): + G = nx.Graph() + G.add_weighted_edges_from({(1, 2, 1)}) + cycle = nx_app.greedy_tsp(G) + cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, [1, 2, 1], 2) + + def test_ignore_selfloops(self): + G = nx.complete_graph(5) + G.add_edge(3, 3) + cycle = nx_app.greedy_tsp(G) + assert len(cycle) - 1 == len(G) == len(set(cycle)) + + +class TestSimulatedAnnealingTSP(TestBase): + tsp = staticmethod(nx_app.simulated_annealing_tsp) + + def test_simulated_annealing_directed(self): + cycle = self.tsp(self.DG, "greedy", source="D", seed=42) + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) + + initial_sol = ["D", "B", "A", "C", "D"] + cycle = self.tsp(self.DG, initial_sol, source="D", seed=42) + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) + + initial_sol = ["D", "A", "C", "B", "D"] + cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42) + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) + + cycle = self.tsp(self.DG2, "greedy", source="D", seed=42) + cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost) + + cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42) + cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost) + + def test_simulated_annealing_undirected(self): + cycle = self.tsp(self.UG, "greedy", source="D", seed=42) + cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, self.UG_cycle, self.UG_cost) + + cycle = self.tsp(self.UG2, "greedy", source="D", seed=42) + cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost) + + cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42) + cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost) + + def test_error_on_input_order_mistake(self): + # see issue #4846 https://github.com/networkx/networkx/issues/4846 + pytest.raises(TypeError, self.tsp, self.UG, weight="weight") + pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight") + + def test_not_complete_graph(self): + pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0) + pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0) + + def test_ignore_selfloops(self): + G = nx.complete_graph(5) + G.add_edge(3, 3) + cycle = self.tsp(G, "greedy") + assert len(cycle) - 1 == len(G) == len(set(cycle)) + + def test_not_weighted_graph(self): + self.tsp(self.unweightedUG, "greedy") + self.tsp(self.unweightedDG, "greedy") + + def test_two_nodes(self): + G = nx.Graph() + G.add_weighted_edges_from({(1, 2, 1)}) + + cycle = self.tsp(G, "greedy", source=1, seed=42) + cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, [1, 2, 1], 2) + + cycle = self.tsp(G, [1, 2, 1], source=1, seed=42) + cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + validate_solution(cycle, cost, [1, 2, 1], 2) + + def test_failure_of_costs_too_high_when_iterations_low(self): + # Simulated Annealing Version: + # set number of moves low and alpha high + cycle = self.tsp( + self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42 + ) + cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + assert cost > self.DG2_cost + + # Try with an incorrect initial guess + initial_sol = ["D", "A", "B", "C", "D"] + cycle = self.tsp( + self.DG, + initial_sol, + source="D", + move="1-0", + alpha=0.1, + N_inner=1, + max_iterations=1, + seed=42, + ) + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + assert cost > self.DG_cost + + +class TestThresholdAcceptingTSP(TestSimulatedAnnealingTSP): + tsp = staticmethod(nx_app.threshold_accepting_tsp) + + def test_failure_of_costs_too_high_when_iterations_low(self): + # Threshold Version: + # set number of moves low and number of iterations low + cycle = self.tsp( + self.DG2, + "greedy", + source="D", + move="1-0", + N_inner=1, + max_iterations=1, + seed=4, + ) + cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + assert cost > self.DG2_cost + + # set threshold too low + initial_sol = ["D", "A", "B", "C", "D"] + cycle = self.tsp( + self.DG, initial_sol, source="D", move="1-0", threshold=-3, seed=42 + ) + cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) + assert cost > self.DG_cost + + +# Tests for function traveling_salesman_problem +def test_TSP_method(): + G = nx.cycle_graph(9) + G[4][5]["weight"] = 10 + + # Test using the old currying method + def sa_tsp(G, weight): + return nx_app.simulated_annealing_tsp(G, "greedy", weight, source=4, seed=1) + + path = nx_app.traveling_salesman_problem( + G, + method=sa_tsp, + cycle=False, + ) + assert path == [4, 3, 2, 1, 0, 8, 7, 6, 5] + + +def test_TSP_unweighted(): + G = nx.cycle_graph(9) + path = nx_app.traveling_salesman_problem(G, nodes=[3, 6], cycle=False) + assert path in ([3, 4, 5, 6], [6, 5, 4, 3]) + + cycle = nx_app.traveling_salesman_problem(G, nodes=[3, 6]) + assert cycle in ([3, 4, 5, 6, 5, 4, 3], [6, 5, 4, 3, 4, 5, 6]) + + +def test_TSP_weighted(): + G = nx.cycle_graph(9) + G[0][1]["weight"] = 2 + G[1][2]["weight"] = 2 + G[2][3]["weight"] = 2 + G[3][4]["weight"] = 4 + G[4][5]["weight"] = 5 + G[5][6]["weight"] = 4 + G[6][7]["weight"] = 2 + G[7][8]["weight"] = 2 + G[8][0]["weight"] = 2 + tsp = nx_app.traveling_salesman_problem + + # path between 3 and 6 + expected_paths = ([3, 2, 1, 0, 8, 7, 6], [6, 7, 8, 0, 1, 2, 3]) + # cycle between 3 and 6 + expected_cycles = ( + [3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3], + [6, 7, 8, 0, 1, 2, 3, 2, 1, 0, 8, 7, 6], + ) + # path through all nodes + expected_tourpaths = ([5, 6, 7, 8, 0, 1, 2, 3, 4], [4, 3, 2, 1, 0, 8, 7, 6, 5]) + + # Check default method + cycle = tsp(G, nodes=[3, 6], weight="weight") + assert cycle in expected_cycles + + path = tsp(G, nodes=[3, 6], weight="weight", cycle=False) + assert path in expected_paths + + tourpath = tsp(G, weight="weight", cycle=False) + assert tourpath in expected_tourpaths + + # Check all methods + methods = [ + (nx_app.christofides, {}), + (nx_app.greedy_tsp, {}), + ( + nx_app.simulated_annealing_tsp, + {"init_cycle": "greedy"}, + ), + ( + nx_app.threshold_accepting_tsp, + {"init_cycle": "greedy"}, + ), + ] + for method, kwargs in methods: + cycle = tsp(G, nodes=[3, 6], weight="weight", method=method, **kwargs) + assert cycle in expected_cycles + + path = tsp( + G, nodes=[3, 6], weight="weight", method=method, cycle=False, **kwargs + ) + assert path in expected_paths + + tourpath = tsp(G, weight="weight", method=method, cycle=False, **kwargs) + assert tourpath in expected_tourpaths + + +def test_TSP_incomplete_graph_short_path(): + G = nx.cycle_graph(9) + G.add_edges_from([(4, 9), (9, 10), (10, 11), (11, 0)]) + G[4][5]["weight"] = 5 + + cycle = nx_app.traveling_salesman_problem(G) + assert len(cycle) == 17 and len(set(cycle)) == 12 + + # make sure that cutting one edge out of complete graph formulation + # cuts out many edges out of the path of the TSP + path = nx_app.traveling_salesman_problem(G, cycle=False) + assert len(path) == 13 and len(set(path)) == 12 + + +def test_TSP_alternate_weight(): + G = nx.complete_graph(9) + G[0][1]["weight"] = 2 + G[1][2]["weight"] = 2 + G[2][3]["weight"] = 2 + G[3][4]["weight"] = 4 + G[4][5]["weight"] = 5 + G[5][6]["weight"] = 4 + G[6][7]["weight"] = 2 + G[7][8]["weight"] = 2 + G[8][0]["weight"] = 2 + + H = nx.complete_graph(9) + H[0][1]["distance"] = 2 + H[1][2]["distance"] = 2 + H[2][3]["distance"] = 2 + H[3][4]["distance"] = 4 + H[4][5]["distance"] = 5 + H[5][6]["distance"] = 4 + H[6][7]["distance"] = 2 + H[7][8]["distance"] = 2 + H[8][0]["distance"] = 2 + + assert nx_app.traveling_salesman_problem( + G, weight="weight" + ) == nx_app.traveling_salesman_problem(H, weight="distance") + + +def test_held_karp_ascent(): + """ + Test the Held-Karp relaxation with the ascent method + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + # Adjacency matrix from page 1153 of the 1970 Held and Karp paper + # which have been edited to be directional, but also symmetric + G_array = np.array( + [ + [0, 97, 60, 73, 17, 52], + [97, 0, 41, 52, 90, 30], + [60, 41, 0, 21, 35, 41], + [73, 52, 21, 0, 95, 46], + [17, 90, 35, 95, 0, 81], + [52, 30, 41, 46, 81, 0], + ] + ) + + solution_edges = [(1, 3), (2, 4), (3, 2), (4, 0), (5, 1), (0, 5)] + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + # Check that the optimal weights are the same + assert round(opt_hk, 2) == 207.00 + # Check that the z_stars are the same + solution = nx.DiGraph() + solution.add_edges_from(solution_edges) + assert nx.utils.edges_equal(z_star.edges, solution.edges) + + +def test_ascent_fractional_solution(): + """ + Test the ascent method using a modified version of Figure 2 on page 1140 + in 'The Traveling Salesman Problem and Minimum Spanning Trees' by Held and + Karp + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + # This version of Figure 2 has all of the edge weights multiplied by 100 + # and is a complete directed graph with infinite edge weights for the + # edges not listed in the original graph + G_array = np.array( + [ + [0, 100, 100, 100000, 100000, 1], + [100, 0, 100, 100000, 1, 100000], + [100, 100, 0, 1, 100000, 100000], + [100000, 100000, 1, 0, 100, 100], + [100000, 1, 100000, 100, 0, 100], + [1, 100000, 100000, 100, 100, 0], + ] + ) + + solution_z_star = { + (0, 1): 5 / 12, + (0, 2): 5 / 12, + (0, 5): 5 / 6, + (1, 0): 5 / 12, + (1, 2): 1 / 3, + (1, 4): 5 / 6, + (2, 0): 5 / 12, + (2, 1): 1 / 3, + (2, 3): 5 / 6, + (3, 2): 5 / 6, + (3, 4): 1 / 3, + (3, 5): 1 / 2, + (4, 1): 5 / 6, + (4, 3): 1 / 3, + (4, 5): 1 / 2, + (5, 0): 5 / 6, + (5, 3): 1 / 2, + (5, 4): 1 / 2, + } + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + # Check that the optimal weights are the same + assert round(opt_hk, 2) == 303.00 + # Check that the z_stars are the same + assert {key: round(z_star[key], 4) for key in z_star} == { + key: round(solution_z_star[key], 4) for key in solution_z_star + } + + +def test_ascent_method_asymmetric(): + """ + Tests the ascent method using a truly asymmetric graph for which the + solution has been brute forced + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + [0, 26, 63, 59, 69, 31, 41], + [62, 0, 91, 53, 75, 87, 47], + [47, 82, 0, 90, 15, 9, 18], + [68, 19, 5, 0, 58, 34, 93], + [11, 58, 53, 55, 0, 61, 79], + [88, 75, 13, 76, 98, 0, 40], + [41, 61, 55, 88, 46, 45, 0], + ] + ) + + solution_edges = [(0, 1), (1, 3), (3, 2), (2, 5), (5, 6), (4, 0), (6, 4)] + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + # Check that the optimal weights are the same + assert round(opt_hk, 2) == 190.00 + # Check that the z_stars match. + solution = nx.DiGraph() + solution.add_edges_from(solution_edges) + assert nx.utils.edges_equal(z_star.edges, solution.edges) + + +def test_ascent_method_asymmetric_2(): + """ + Tests the ascent method using a truly asymmetric graph for which the + solution has been brute forced + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + [0, 45, 39, 92, 29, 31], + [72, 0, 4, 12, 21, 60], + [81, 6, 0, 98, 70, 53], + [49, 71, 59, 0, 98, 94], + [74, 95, 24, 43, 0, 47], + [56, 43, 3, 65, 22, 0], + ] + ) + + solution_edges = [(0, 5), (5, 4), (1, 3), (3, 0), (2, 1), (4, 2)] + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + # Check that the optimal weights are the same + assert round(opt_hk, 2) == 144.00 + # Check that the z_stars match. + solution = nx.DiGraph() + solution.add_edges_from(solution_edges) + assert nx.utils.edges_equal(z_star.edges, solution.edges) + + +def test_held_karp_ascent_asymmetric_3(): + """ + Tests the ascent method using a truly asymmetric graph with a fractional + solution for which the solution has been brute forced. + + In this graph their are two different optimal, integral solutions (which + are also the overall atsp solutions) to the Held Karp relaxation. However, + this particular graph has two different tours of optimal value and the + possible solutions in the held_karp_ascent function are not stored in an + ordered data structure. + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + [0, 1, 5, 2, 7, 4], + [7, 0, 7, 7, 1, 4], + [4, 7, 0, 9, 2, 1], + [7, 2, 7, 0, 4, 4], + [5, 5, 4, 4, 0, 3], + [3, 9, 1, 3, 4, 0], + ] + ) + + solution1_edges = [(0, 3), (1, 4), (2, 5), (3, 1), (4, 2), (5, 0)] + + solution2_edges = [(0, 3), (3, 1), (1, 4), (4, 5), (2, 0), (5, 2)] + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + assert round(opt_hk, 2) == 13.00 + # Check that the z_stars are the same + solution1 = nx.DiGraph() + solution1.add_edges_from(solution1_edges) + solution2 = nx.DiGraph() + solution2.add_edges_from(solution2_edges) + assert nx.utils.edges_equal(z_star.edges, solution1.edges) or nx.utils.edges_equal( + z_star.edges, solution2.edges + ) + + +def test_held_karp_ascent_fractional_asymmetric(): + """ + Tests the ascent method using a truly asymmetric graph with a fractional + solution for which the solution has been brute forced + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + [0, 100, 150, 100000, 100000, 1], + [150, 0, 100, 100000, 1, 100000], + [100, 150, 0, 1, 100000, 100000], + [100000, 100000, 1, 0, 150, 100], + [100000, 2, 100000, 100, 0, 150], + [2, 100000, 100000, 150, 100, 0], + ] + ) + + solution_z_star = { + (0, 1): 5 / 12, + (0, 2): 5 / 12, + (0, 5): 5 / 6, + (1, 0): 5 / 12, + (1, 2): 5 / 12, + (1, 4): 5 / 6, + (2, 0): 5 / 12, + (2, 1): 5 / 12, + (2, 3): 5 / 6, + (3, 2): 5 / 6, + (3, 4): 5 / 12, + (3, 5): 5 / 12, + (4, 1): 5 / 6, + (4, 3): 5 / 12, + (4, 5): 5 / 12, + (5, 0): 5 / 6, + (5, 3): 5 / 12, + (5, 4): 5 / 12, + } + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + opt_hk, z_star = tsp.held_karp_ascent(G) + + # Check that the optimal weights are the same + assert round(opt_hk, 2) == 304.00 + # Check that the z_stars are the same + assert {key: round(z_star[key], 4) for key in z_star} == { + key: round(solution_z_star[key], 4) for key in solution_z_star + } + + +def test_spanning_tree_distribution(): + """ + Test that we can create an exponential distribution of spanning trees such + that the probability of each tree is proportional to the product of edge + weights. + + Results of this test have been confirmed with hypothesis testing from the + created distribution. + + This test uses the symmetric, fractional Held Karp solution. + """ + import networkx.algorithms.approximation.traveling_salesman as tsp + + pytest.importorskip("numpy") + pytest.importorskip("scipy") + + z_star = { + (0, 1): 5 / 12, + (0, 2): 5 / 12, + (0, 5): 5 / 6, + (1, 0): 5 / 12, + (1, 2): 1 / 3, + (1, 4): 5 / 6, + (2, 0): 5 / 12, + (2, 1): 1 / 3, + (2, 3): 5 / 6, + (3, 2): 5 / 6, + (3, 4): 1 / 3, + (3, 5): 1 / 2, + (4, 1): 5 / 6, + (4, 3): 1 / 3, + (4, 5): 1 / 2, + (5, 0): 5 / 6, + (5, 3): 1 / 2, + (5, 4): 1 / 2, + } + + solution_gamma = { + (0, 1): -0.6383, + (0, 2): -0.6827, + (0, 5): 0, + (1, 2): -1.0781, + (1, 4): 0, + (2, 3): 0, + (5, 3): -0.2820, + (5, 4): -0.3327, + (4, 3): -0.9927, + } + + # The undirected support of z_star + G = nx.MultiGraph() + for u, v in z_star: + if (u, v) in G.edges or (v, u) in G.edges: + continue + G.add_edge(u, v) + + gamma = tsp.spanning_tree_distribution(G, z_star) + + assert {key: round(gamma[key], 4) for key in gamma} == solution_gamma + + +def test_asadpour_tsp(): + """ + Test the complete asadpour tsp algorithm with the fractional, symmetric + Held Karp solution. This test also uses an incomplete graph as input. + """ + # This version of Figure 2 has all of the edge weights multiplied by 100 + # and the 0 weight edges have a weight of 1. + pytest.importorskip("numpy") + pytest.importorskip("scipy") + + edge_list = [ + (0, 1, 100), + (0, 2, 100), + (0, 5, 1), + (1, 2, 100), + (1, 4, 1), + (2, 3, 1), + (3, 4, 100), + (3, 5, 100), + (4, 5, 100), + (1, 0, 100), + (2, 0, 100), + (5, 0, 1), + (2, 1, 100), + (4, 1, 1), + (3, 2, 1), + (4, 3, 100), + (5, 3, 100), + (5, 4, 100), + ] + + G = nx.DiGraph() + G.add_weighted_edges_from(edge_list) + + tour = nx_app.traveling_salesman_problem( + G, weight="weight", method=nx_app.asadpour_atsp, seed=19 + ) + + # Check that the returned list is a valid tour. Because this is an + # incomplete graph, the conditions are not as strict. We need the tour to + # + # Start and end at the same node + # Pass through every vertex at least once + # Have a total cost at most ln(6) / ln(ln(6)) = 3.0723 times the optimal + # + # For the second condition it is possible to have the tour pass through the + # same vertex more then. Imagine that the tour on the complete version takes + # an edge not in the original graph. In the output this is substituted with + # the shortest path between those vertices, allowing vertices to appear more + # than once. + # + # Even though we are using a fixed seed, multiple tours have been known to + # be returned. The first two are from the original development of this test, + # and the third one from issue #5913 on GitHub. If other tours are returned, + # add it on the list of expected tours. + expected_tours = [ + [1, 4, 5, 0, 2, 3, 2, 1], + [3, 2, 0, 1, 4, 5, 3], + [3, 2, 1, 0, 5, 4, 3], + ] + + assert tour in expected_tours + + +def test_asadpour_real_world(): + """ + This test uses airline prices between the six largest cities in the US. + + * New York City -> JFK + * Los Angeles -> LAX + * Chicago -> ORD + * Houston -> IAH + * Phoenix -> PHX + * Philadelphia -> PHL + + Flight prices from August 2021 using Delta or American airlines to get + nonstop flight. The brute force solution found the optimal tour to cost $872 + + This test also uses the `source` keyword argument to ensure that the tour + always starts at city 0. + """ + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + # JFK LAX ORD IAH PHX PHL + [0, 243, 199, 208, 169, 183], # JFK + [277, 0, 217, 123, 127, 252], # LAX + [297, 197, 0, 197, 123, 177], # ORD + [303, 169, 197, 0, 117, 117], # IAH + [257, 127, 160, 117, 0, 319], # PHX + [183, 332, 217, 117, 319, 0], # PHL + ] + ) + + node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"] + + expected_tours = [ + ["JFK", "LAX", "PHX", "ORD", "IAH", "PHL", "JFK"], + ["JFK", "ORD", "PHX", "LAX", "IAH", "PHL", "JFK"], + ] + + G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph) + + tour = nx_app.traveling_salesman_problem( + G, weight="weight", method=nx_app.asadpour_atsp, seed=37, source="JFK" + ) + + assert tour in expected_tours + + +def test_asadpour_real_world_path(): + """ + This test uses airline prices between the six largest cities in the US. This + time using a path, not a cycle. + + * New York City -> JFK + * Los Angeles -> LAX + * Chicago -> ORD + * Houston -> IAH + * Phoenix -> PHX + * Philadelphia -> PHL + + Flight prices from August 2021 using Delta or American airlines to get + nonstop flight. The brute force solution found the optimal tour to cost $872 + """ + np = pytest.importorskip("numpy") + pytest.importorskip("scipy") + + G_array = np.array( + [ + # JFK LAX ORD IAH PHX PHL + [0, 243, 199, 208, 169, 183], # JFK + [277, 0, 217, 123, 127, 252], # LAX + [297, 197, 0, 197, 123, 177], # ORD + [303, 169, 197, 0, 117, 117], # IAH + [257, 127, 160, 117, 0, 319], # PHX + [183, 332, 217, 117, 319, 0], # PHL + ] + ) + + node_list = ["JFK", "LAX", "ORD", "IAH", "PHX", "PHL"] + + expected_paths = [ + ["ORD", "PHX", "LAX", "IAH", "PHL", "JFK"], + ["JFK", "PHL", "IAH", "ORD", "PHX", "LAX"], + ] + + G = nx.from_numpy_array(G_array, nodelist=node_list, create_using=nx.DiGraph) + + path = nx_app.traveling_salesman_problem( + G, weight="weight", cycle=False, method=nx_app.asadpour_atsp, seed=56 + ) + + assert path in expected_paths + + +def test_asadpour_disconnected_graph(): + """ + Test that the proper exception is raised when asadpour_atsp is given an + disconnected graph. + """ + + G = nx.complete_graph(4, create_using=nx.DiGraph) + # have to set edge weights so that if the exception is not raised, the + # function will complete and we will fail the test + nx.set_edge_attributes(G, 1, "weight") + G.add_node(5) + + pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G) + + +def test_asadpour_incomplete_graph(): + """ + Test that the proper exception is raised when asadpour_atsp is given an + incomplete graph + """ + + G = nx.complete_graph(4, create_using=nx.DiGraph) + # have to set edge weights so that if the exception is not raised, the + # function will complete and we will fail the test + nx.set_edge_attributes(G, 1, "weight") + G.remove_edge(0, 1) + + pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G) + + +def test_asadpour_empty_graph(): + """ + Test the asadpour_atsp function with an empty graph + """ + G = nx.DiGraph() + + pytest.raises(nx.NetworkXError, nx_app.asadpour_atsp, G) + + +def test_asadpour_small_graphs(): + # 1 node + G = nx.path_graph(1, create_using=nx.DiGraph) + with pytest.raises(nx.NetworkXError, match="at least two nodes"): + nx_app.asadpour_atsp(G) + + # 2 nodes + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 7), (1, 0, 8)]) + assert nx_app.asadpour_atsp(G) in [[0, 1], [1, 0]] + assert nx_app.asadpour_atsp(G, source=1) == [1, 0] + assert nx_app.asadpour_atsp(G, source=0) == [0, 1] + + +@pytest.mark.slow +def test_asadpour_integral_held_karp(): + """ + This test uses an integral held karp solution and the held karp function + will return a graph rather than a dict, bypassing most of the asadpour + algorithm. + + At first glance, this test probably doesn't look like it ensures that we + skip the rest of the asadpour algorithm, but it does. We are not fixing a + see for the random number generator, so if we sample any spanning trees + the approximation would be different basically every time this test is + executed but it is not since held karp is deterministic and we do not + reach the portion of the code with the dependence on random numbers. + """ + np = pytest.importorskip("numpy") + + G_array = np.array( + [ + [0, 26, 63, 59, 69, 31, 41], + [62, 0, 91, 53, 75, 87, 47], + [47, 82, 0, 90, 15, 9, 18], + [68, 19, 5, 0, 58, 34, 93], + [11, 58, 53, 55, 0, 61, 79], + [88, 75, 13, 76, 98, 0, 40], + [41, 61, 55, 88, 46, 45, 0], + ] + ) + + G = nx.from_numpy_array(G_array, create_using=nx.DiGraph) + + for _ in range(2): + tour = nx_app.traveling_salesman_problem(G, method=nx_app.asadpour_atsp) + + assert [1, 3, 2, 5, 2, 6, 4, 0, 1] == tour + + +def test_directed_tsp_impossible(): + """ + Test the asadpour algorithm with a graph without a hamiltonian circuit + """ + pytest.importorskip("numpy") + + # In this graph, once we leave node 0 we cannot return + edges = [ + (0, 1, 10), + (0, 2, 11), + (0, 3, 12), + (1, 2, 4), + (1, 3, 6), + (2, 1, 3), + (2, 3, 2), + (3, 1, 5), + (3, 2, 1), + ] + + G = nx.DiGraph() + G.add_weighted_edges_from(edges) + + pytest.raises(nx.NetworkXError, nx_app.traveling_salesman_problem, G) diff --git a/shared/package-files/4a/4acfc9cde3c85cebd06675eefa05c56d9d3ff2771d64b477dc8bf3fc5fde5909/itt.py b/shared/package-files/4a/4acfc9cde3c85cebd06675eefa05c56d9d3ff2771d64b477dc8bf3fc5fde5909/itt.py new file mode 100644 index 0000000000000000000000000000000000000000..9d4bda2b3420bdb367033aba2c0ef426bdd2a59a --- /dev/null +++ b/shared/package-files/4a/4acfc9cde3c85cebd06675eefa05c56d9d3ff2771d64b477dc8bf3fc5fde5909/itt.py @@ -0,0 +1,80 @@ +# mypy: allow-untyped-defs +from contextlib import contextmanager + + +try: + from torch._C import _itt +except ImportError: + + class _ITTStub: + @staticmethod + def _fail(*args, **kwargs): + raise RuntimeError( + "ITT functions not installed. Are you sure you have a ITT build?" + ) + + @staticmethod + def is_available(): + return False + + rangePush = _fail + rangePop = _fail + mark = _fail + + _itt = _ITTStub() # type: ignore[assignment] + + +__all__ = ["is_available", "range_push", "range_pop", "mark", "range"] + + +def is_available(): + """ + Check if ITT feature is available or not + """ + return _itt.is_available() + + +def range_push(msg): + """ + Pushes a range onto a stack of nested range span. Returns zero-based + depth of the range that is started. + + Arguments: + msg (str): ASCII message to associate with range + """ + return _itt.rangePush(msg) + + +def range_pop(): + """ + Pops a range off of a stack of nested range spans. Returns the + zero-based depth of the range that is ended. + """ + return _itt.rangePop() + + +def mark(msg): + """ + Describe an instantaneous event that occurred at some point. + + Arguments: + msg (str): ASCII message to associate with the event. + """ + return _itt.mark(msg) + + +@contextmanager +def range(msg, *args, **kwargs): + """ + Context manager / decorator that pushes an ITT range at the beginning + of its scope, and pops it at the end. If extra arguments are given, + they are passed as arguments to msg.format(). + + Args: + msg (str): message to associate with the range + """ + range_push(msg.format(*args, **kwargs)) + try: + yield + finally: + range_pop() diff --git a/shared/package-files/4a/4ad975b7255007b35f97f6236efcb873a7225d5534803c21e6a0e6f17bbde1c2/mock_cache.cpython-311.pyc b/shared/package-files/4a/4ad975b7255007b35f97f6236efcb873a7225d5534803c21e6a0e6f17bbde1c2/mock_cache.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cf8b0882502697aa4c72f94ddf1301adaf5e441 Binary files /dev/null and b/shared/package-files/4a/4ad975b7255007b35f97f6236efcb873a7225d5534803c21e6a0e6f17bbde1c2/mock_cache.cpython-311.pyc differ diff --git a/shared/package-files/4a/4ada0f6d2a546200b2fd5b63ff5a7e9f317e5a329e22570df095f2cfb05f8787/version.cpython-311.pyc b/shared/package-files/4a/4ada0f6d2a546200b2fd5b63ff5a7e9f317e5a329e22570df095f2cfb05f8787/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfab429c927006cdf6c7f40b418561d55d1cc41a Binary files /dev/null and b/shared/package-files/4a/4ada0f6d2a546200b2fd5b63ff5a7e9f317e5a329e22570df095f2cfb05f8787/version.cpython-311.pyc differ diff --git a/shared/package-files/4a/4adc5e9f7601f3273e0408c768cef9592dc8b9b2a3117b6b1150918656463a63/resize_cpu_dispatch.h b/shared/package-files/4a/4adc5e9f7601f3273e0408c768cef9592dc8b9b2a3117b6b1150918656463a63/resize_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6164659f754b3278bbf2ea1aa70e019fc8a9ef96 --- /dev/null +++ b/shared/package-files/4a/4adc5e9f7601f3273e0408c768cef9592dc8b9b2a3117b6b1150918656463a63/resize_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API const at::Tensor & resize_(const at::Tensor & self, at::IntArrayRef size, ::std::optional memory_format=::std::nullopt); +TORCH_API const at::Tensor & resize__symint(const at::Tensor & self, c10::SymIntArrayRef size, ::std::optional memory_format=::std::nullopt); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/4a/4ade272b173e8c7bd42c308b4477d0db21bd152a96d38566ff8cc33d513644aa/item.h b/shared/package-files/4a/4ade272b173e8c7bd42c308b4477d0db21bd152a96d38566ff8cc33d513644aa/item.h new file mode 100644 index 0000000000000000000000000000000000000000..e035a318d6a2f400806178ada27315e8d34315b2 --- /dev/null +++ b/shared/package-files/4a/4ade272b173e8c7bd42c308b4477d0db21bd152a96d38566ff8cc33d513644aa/item.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/shared/package-files/4a/4ae3af6022e34f04474826b83a4081925629c1979d8da6a50553cbcef7ad8701/python_call.h b/shared/package-files/4a/4ae3af6022e34f04474826b83a4081925629c1979d8da6a50553cbcef7ad8701/python_call.h new file mode 100644 index 0000000000000000000000000000000000000000..e635fa1213dbbb7b95948234b9aafabe66df2604 --- /dev/null +++ b/shared/package-files/4a/4ae3af6022e34f04474826b83a4081925629c1979d8da6a50553cbcef7ad8701/python_call.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +namespace torch::distributed::rpc { + +// RPC call representing calling a Python function over RPC. +class TORCH_API PythonCall final : public RpcCommandBase { + public: + PythonCall(SerializedPyObj&& serializedPyObj, bool isAsyncExecution); + + c10::intrusive_ptr toMessageImpl() && override; + + static std::unique_ptr fromMessage(const Message& message); + + const SerializedPyObj& serializedPyObj() const; + + inline bool isAsyncExecution() const { + return isAsyncExecution_; + } + + private: + SerializedPyObj serializedPyObj_; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const bool isAsyncExecution_; +}; + +} // namespace torch::distributed::rpc diff --git a/shared/package-files/4a/4ae5ad1d50806dc5152b05c75e7431788412aa93c8429364c4635e93e807ec53/__init__.cpython-311.pyc b/shared/package-files/4a/4ae5ad1d50806dc5152b05c75e7431788412aa93c8429364c4635e93e807ec53/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ec5a9e9935ff83ea4ef650a354be69614d3b08e Binary files /dev/null and b/shared/package-files/4a/4ae5ad1d50806dc5152b05c75e7431788412aa93c8429364c4635e93e807ec53/__init__.cpython-311.pyc differ diff --git a/shared/package-files/4a/4ae649f6edbc439e919737a79330e4ca5a171207f54d34676e84a533d117209c/conv.cpython-311.pyc b/shared/package-files/4a/4ae649f6edbc439e919737a79330e4ca5a171207f54d34676e84a533d117209c/conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ebb57d0b233100ede350ce006209c232fcdf252 Binary files /dev/null and b/shared/package-files/4a/4ae649f6edbc439e919737a79330e4ca5a171207f54d34676e84a533d117209c/conv.cpython-311.pyc differ diff --git a/shared/package-files/4a/4ae7c9ffa0e16a8e603fe9b83f31010e00f4bc4b364d84057399a65dcb2d67ba/__init__.cpython-311.pyc b/shared/package-files/4a/4ae7c9ffa0e16a8e603fe9b83f31010e00f4bc4b364d84057399a65dcb2d67ba/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83338adb7b4bf38519558e9a89dd347417b44eea Binary files /dev/null and b/shared/package-files/4a/4ae7c9ffa0e16a8e603fe9b83f31010e00f4bc4b364d84057399a65dcb2d67ba/__init__.cpython-311.pyc differ diff --git a/shared/package-files/4a/4ae966e587e030d61757d69f07c77abc76cec6420badca7016e58a31b66824e6/test_to_string.cpython-311.pyc b/shared/package-files/4a/4ae966e587e030d61757d69f07c77abc76cec6420badca7016e58a31b66824e6/test_to_string.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c05f7ad8e24847ad18088d63ec6ed52f9c8ac66a Binary files /dev/null and b/shared/package-files/4a/4ae966e587e030d61757d69f07c77abc76cec6420badca7016e58a31b66824e6/test_to_string.cpython-311.pyc differ diff --git a/shared/package-files/4a/4aed866f12a83686765a7e8ee20bec2bf41458a6fe58ea9a7c25d9594c19fb2d/log10_ops.h b/shared/package-files/4a/4aed866f12a83686765a7e8ee20bec2bf41458a6fe58ea9a7c25d9594c19fb2d/log10_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..1ce7125dd2c3d2bad9466c9b230e2b593842e258 --- /dev/null +++ b/shared/package-files/4a/4aed866f12a83686765a7e8ee20bec2bf41458a6fe58ea9a7c25d9594c19fb2d/log10_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API log10 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log10"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log10(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API log10_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log10_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "log10_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API log10_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::log10"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "log10.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/4a/4aedb1dc83181bfc21c97a565ab24b4a8ccfb77fadc1713bc42a58b8676fad90/fake_quantize_per_channel_affine_cachemask_backward_native.h b/shared/package-files/4a/4aedb1dc83181bfc21c97a565ab24b4a8ccfb77fadc1713bc42a58b8676fad90/fake_quantize_per_channel_affine_cachemask_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..288ec7f789e7474ccdc2fa2656dab66a19fed5e5 --- /dev/null +++ b/shared/package-files/4a/4aedb1dc83181bfc21c97a565ab24b4a8ccfb77fadc1713bc42a58b8676fad90/fake_quantize_per_channel_affine_cachemask_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor fake_quantize_per_channel_affine_cachemask_backward(const at::Tensor & grad, const at::Tensor & mask); +} // namespace native +} // namespace at diff --git a/shared/package-files/4a/4af104774f1903b2b80704a350b37b1ed0dd04e8684a3a6ce4dbe61c2804c939/__init__.cpython-311.pyc b/shared/package-files/4a/4af104774f1903b2b80704a350b37b1ed0dd04e8684a3a6ce4dbe61c2804c939/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..664b01ece3e9d67d1c9ff7b089fb3becedc6aff5 Binary files /dev/null and b/shared/package-files/4a/4af104774f1903b2b80704a350b37b1ed0dd04e8684a3a6ce4dbe61c2804c939/__init__.cpython-311.pyc differ diff --git a/shared/package-files/4a/4af4d5654a4c59f786bdaab2254a787bd15820ef251492dc6d172604d58ef26d/test_numbers.py b/shared/package-files/4a/4af4d5654a4c59f786bdaab2254a787bd15820ef251492dc6d172604d58ef26d/test_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..10d14b6ac09fb0ab102c37cb99405440bd0bbffb --- /dev/null +++ b/shared/package-files/4a/4af4d5654a4c59f786bdaab2254a787bd15820ef251492dc6d172604d58ef26d/test_numbers.py @@ -0,0 +1,2335 @@ +import numbers as nums +import decimal +from sympy.concrete.summations import Sum +from sympy.core import (EulerGamma, Catalan, TribonacciConstant, + GoldenRatio) +from sympy.core.containers import Tuple +from sympy.core.expr import unchanged +from sympy.core.logic import fuzzy_not +from sympy.core.mul import Mul +from sympy.core.numbers import (mpf_norm, seterr, + Integer, I, pi, comp, Rational, E, nan, + oo, AlgebraicNumber, Number, Float, zoo, equal_valued, + int_valued, all_close) +from sympy.core.intfunc import (igcd, igcdex, igcd2, igcd_lehmer, + ilcm, integer_nthroot, isqrt, integer_log, mod_inverse) +from sympy.core.power import Pow +from sympy.core.relational import Ge, Gt, Le, Lt +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.integers import floor +from sympy.functions.combinatorial.numbers import fibonacci +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.miscellaneous import sqrt, cbrt +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.polys.domains.realfield import RealField +from sympy.printing.latex import latex +from sympy.printing.repr import srepr +from sympy.simplify import simplify +from sympy.polys.domains.groundtypes import PythonRational +from sympy.utilities.decorator import conserve_mpmath_dps +from sympy.utilities.iterables import permutations +from sympy.testing.pytest import (XFAIL, raises, _both_exp_pow, + warns_deprecated_sympy) +from sympy import Add + +from mpmath import mpf +import mpmath +from sympy.core import numbers +t = Symbol('t', real=False) + +_ninf = float(-oo) +_inf = float(oo) + + +def same_and_same_prec(a, b): + # stricter matching for Floats + return a == b and a._prec == b._prec + + +def test_seterr(): + seterr(divide=True) + raises(ValueError, lambda: S.Zero/S.Zero) + seterr(divide=False) + assert S.Zero / S.Zero is S.NaN + + +def test_mod(): + x = S.Half + y = Rational(3, 4) + z = Rational(5, 18043) + + assert x % x == 0 + assert x % y == S.Half + assert x % z == Rational(3, 36086) + assert y % x == Rational(1, 4) + assert y % y == 0 + assert y % z == Rational(9, 72172) + assert z % x == Rational(5, 18043) + assert z % y == Rational(5, 18043) + assert z % z == 0 + + a = Float(2.6) + + assert (a % .2) == 0.0 + assert (a % 2).round(15) == 0.6 + assert (a % 0.5).round(15) == 0.1 + + p = Symbol('p', infinite=True) + + assert oo % oo is nan + assert zoo % oo is nan + assert 5 % oo is nan + assert p % 5 is nan + + # In these two tests, if the precision of m does + # not match the precision of the ans, then it is + # likely that the change made now gives an answer + # with degraded accuracy. + r = Rational(500, 41) + f = Float('.36', 3) + m = r % f + ans = Float(r % Rational(f), 3) + assert m == ans and m._prec == ans._prec + f = Float('8.36', 3) + m = f % r + ans = Float(Rational(f) % r, 3) + assert m == ans and m._prec == ans._prec + + s = S.Zero + + assert s % float(1) == 0.0 + + # No rounding required since these numbers can be represented + # exactly. + assert Rational(3, 4) % Float(1.1) == 0.75 + assert Float(1.5) % Rational(5, 4) == 0.25 + assert Rational(5, 4).__rmod__(Float('1.5')) == 0.25 + assert Float('1.5').__rmod__(Float('2.75')) == Float('1.25') + assert 2.75 % Float('1.5') == Float('1.25') + + a = Integer(7) + b = Integer(4) + + assert type(a % b) == Integer + assert a % b == Integer(3) + assert Integer(1) % Rational(2, 3) == Rational(1, 3) + assert Rational(7, 5) % Integer(1) == Rational(2, 5) + assert Integer(2) % 1.5 == 0.5 + + assert Integer(3).__rmod__(Integer(10)) == Integer(1) + assert Integer(10) % 4 == Integer(2) + assert 15 % Integer(4) == Integer(3) + + +def test_divmod(): + x = Symbol("x") + assert divmod(S(12), S(8)) == Tuple(1, 4) + assert divmod(-S(12), S(8)) == Tuple(-2, 4) + assert divmod(S.Zero, S.One) == Tuple(0, 0) + raises(ZeroDivisionError, lambda: divmod(S.Zero, S.Zero)) + raises(ZeroDivisionError, lambda: divmod(S.One, S.Zero)) + assert divmod(S(12), 8) == Tuple(1, 4) + assert divmod(12, S(8)) == Tuple(1, 4) + assert S(1024)//x == 1024//x == floor(1024/x) + + assert divmod(S("2"), S("3/2")) == Tuple(S("1"), S("1/2")) + assert divmod(S("3/2"), S("2")) == Tuple(S("0"), S("3/2")) + assert divmod(S("2"), S("3.5")) == Tuple(S("0"), S("2.")) + assert divmod(S("3.5"), S("2")) == Tuple(S("1"), S("1.5")) + assert divmod(S("2"), S("1/3")) == Tuple(S("6"), S("0")) + assert divmod(S("1/3"), S("2")) == Tuple(S("0"), S("1/3")) + assert divmod(S("2"), S("1/10")) == Tuple(S("20"), S("0")) + assert divmod(S("2"), S(".1"))[0] == 19 + assert divmod(S("0.1"), S("2")) == Tuple(S("0"), S("0.1")) + assert divmod(S("2"), 2) == Tuple(S("1"), S("0")) + assert divmod(2, S("2")) == Tuple(S("1"), S("0")) + assert divmod(S("2"), 1.5) == Tuple(S("1"), S("0.5")) + assert divmod(1.5, S("2")) == Tuple(S("0"), S("1.5")) + assert divmod(0.3, S("2")) == Tuple(S("0"), S("0.3")) + assert divmod(S("3/2"), S("3.5")) == Tuple(S("0"), S(3/2)) + assert divmod(S("3.5"), S("3/2")) == Tuple(S("2"), S("0.5")) + assert divmod(S("3/2"), S("1/3")) == Tuple(S("4"), S("1/6")) + assert divmod(S("1/3"), S("3/2")) == Tuple(S("0"), S("1/3")) + assert divmod(S("3/2"), S("0.1"))[0] == 14 + assert divmod(S("0.1"), S("3/2")) == Tuple(S("0"), S("0.1")) + assert divmod(S("3/2"), 2) == Tuple(S("0"), S("3/2")) + assert divmod(2, S("3/2")) == Tuple(S("1"), S("1/2")) + assert divmod(S("3/2"), 1.5) == Tuple(S("1"), S("0.")) + assert divmod(1.5, S("3/2")) == Tuple(S("1"), S("0.")) + assert divmod(S("3/2"), 0.3) == Tuple(S("5"), S("0.")) + assert divmod(0.3, S("3/2")) == Tuple(S("0"), S("0.3")) + assert divmod(S("1/3"), S("3.5")) == (0, 1/3) + assert divmod(S("3.5"), S("0.1")) == Tuple(S("35"), S("0.")) + assert divmod(S("0.1"), S("3.5")) == Tuple(S("0"), S("0.1")) + assert divmod(S("3.5"), 2) == Tuple(S("1"), S("1.5")) + assert divmod(2, S("3.5")) == Tuple(S("0"), S("2.")) + assert divmod(S("3.5"), 1.5) == Tuple(S("2"), S("0.5")) + assert divmod(1.5, S("3.5")) == Tuple(S("0"), S("1.5")) + assert divmod(0.3, S("3.5")) == Tuple(S("0"), S("0.3")) + assert divmod(S("0.1"), S("1/3")) == Tuple(S("0"), S("0.1")) + assert divmod(S("1/3"), 2) == Tuple(S("0"), S("1/3")) + assert divmod(2, S("1/3")) == Tuple(S("6"), S("0")) + assert divmod(S("1/3"), 1.5) == (0, 1/3) + assert divmod(0.3, S("1/3")) == (0, 0.3) + assert divmod(S("0.1"), 2) == (0, 0.1) + assert divmod(2, S("0.1"))[0] == 19 + assert divmod(S("0.1"), 1.5) == (0, 0.1) + assert divmod(1.5, S("0.1")) == Tuple(S("15"), S("0.")) + assert divmod(S("0.1"), 0.3) == Tuple(S("0"), S("0.1")) + + assert str(divmod(S("2"), 0.3)) == '(6, 0.2)' + assert str(divmod(S("3.5"), S("1/3"))) == '(10, 0.166666666666667)' + assert str(divmod(S("3.5"), 0.3)) == '(11, 0.2)' + assert str(divmod(S("1/3"), S("0.1"))) == '(3, 0.0333333333333333)' + assert str(divmod(1.5, S("1/3"))) == '(4, 0.166666666666667)' + assert str(divmod(S("1/3"), 0.3)) == '(1, 0.0333333333333333)' + assert str(divmod(0.3, S("0.1"))) == '(2, 0.1)' + + assert divmod(-3, S(2)) == (-2, 1) + assert divmod(S(-3), S(2)) == (-2, 1) + assert divmod(S(-3), 2) == (-2, 1) + + assert divmod(oo, 1) == (S.NaN, S.NaN) + assert divmod(S.NaN, 1) == (S.NaN, S.NaN) + assert divmod(1, S.NaN) == (S.NaN, S.NaN) + ans = [(-1, oo), (-1, oo), (0, 0), (0, 1), (0, 2)] + OO = float('inf') + ANS = [tuple(map(float, i)) for i in ans] + assert [divmod(i, oo) for i in range(-2, 3)] == ans + ans = [(0, -2), (0, -1), (0, 0), (-1, -oo), (-1, -oo)] + ANS = [tuple(map(float, i)) for i in ans] + assert [divmod(i, -oo) for i in range(-2, 3)] == ans + assert [divmod(i, -OO) for i in range(-2, 3)] == ANS + + # sympy's divmod gives an Integer for the quotient rather than a float + dmod = lambda a, b: tuple([j if i else int(j) for i, j in enumerate(divmod(a, b))]) + for a in (4, 4., 4.25, 0, 0., -4, -4. -4.25): + for b in (2, 2., 2.5, -2, -2., -2.5): + assert divmod(S(a), S(b)) == dmod(a, b) + + +def test_igcd(): + assert igcd(0, 0) == 0 + assert igcd(0, 1) == 1 + assert igcd(1, 0) == 1 + assert igcd(0, 7) == 7 + assert igcd(7, 0) == 7 + assert igcd(7, 1) == 1 + assert igcd(1, 7) == 1 + assert igcd(-1, 0) == 1 + assert igcd(0, -1) == 1 + assert igcd(-1, -1) == 1 + assert igcd(-1, 7) == 1 + assert igcd(7, -1) == 1 + assert igcd(8, 2) == 2 + assert igcd(4, 8) == 4 + assert igcd(8, 16) == 8 + assert igcd(7, -3) == 1 + assert igcd(-7, 3) == 1 + assert igcd(-7, -3) == 1 + assert igcd(*[10, 20, 30]) == 10 + raises(TypeError, lambda: igcd()) + raises(TypeError, lambda: igcd(2)) + raises(ValueError, lambda: igcd(0, None)) + raises(ValueError, lambda: igcd(1, 2.2)) + for args in permutations((45.1, 1, 30)): + raises(ValueError, lambda: igcd(*args)) + for args in permutations((1, 2, None)): + raises(ValueError, lambda: igcd(*args)) + + +def test_igcd_lehmer(): + a, b = fibonacci(10001), fibonacci(10000) + # len(str(a)) == 2090 + # small divisors, long Euclidean sequence + assert igcd_lehmer(a, b) == 1 + c = fibonacci(100) + assert igcd_lehmer(a*c, b*c) == c + # big divisor + assert igcd_lehmer(a, 10**1000) == 1 + # swapping argument + assert igcd_lehmer(1, 2) == igcd_lehmer(2, 1) + + +def test_igcd2(): + # short loop + assert igcd2(2**100 - 1, 2**99 - 1) == 1 + # Lehmer's algorithm + a, b = int(fibonacci(10001)), int(fibonacci(10000)) + assert igcd2(a, b) == 1 + + +def test_ilcm(): + assert ilcm(0, 0) == 0 + assert ilcm(1, 0) == 0 + assert ilcm(0, 1) == 0 + assert ilcm(1, 1) == 1 + assert ilcm(2, 1) == 2 + assert ilcm(8, 2) == 8 + assert ilcm(8, 6) == 24 + assert ilcm(8, 7) == 56 + assert ilcm(*[10, 20, 30]) == 60 + raises(ValueError, lambda: ilcm(8.1, 7)) + raises(ValueError, lambda: ilcm(8, 7.1)) + raises(TypeError, lambda: ilcm(8)) + + +def test_igcdex(): + assert igcdex(2, 3) == (-1, 1, 1) + assert igcdex(10, 12) == (-1, 1, 2) + assert igcdex(100, 2004) == (-20, 1, 4) + assert igcdex(0, 0) == (0, 0, 0) + assert igcdex(1, 0) == (1, 0, 1) + + +def _strictly_equal(a, b): + return (a.p, a.q, type(a.p), type(a.q)) == \ + (b.p, b.q, type(b.p), type(b.q)) + + +def _test_rational_new(cls): + """ + Tests that are common between Integer and Rational. + """ + assert cls(0) is S.Zero + assert cls(1) is S.One + assert cls(-1) is S.NegativeOne + # These look odd, but are similar to int(): + assert cls('1') is S.One + assert cls('-1') is S.NegativeOne + + i = Integer(10) + assert _strictly_equal(i, cls('10')) + assert _strictly_equal(i, cls('10')) + assert _strictly_equal(i, cls(int(10))) + assert _strictly_equal(i, cls(i)) + + raises(TypeError, lambda: cls(Symbol('x'))) + + +def test_Integer_new(): + """ + Test for Integer constructor + """ + _test_rational_new(Integer) + + assert _strictly_equal(Integer(0.9), S.Zero) + assert _strictly_equal(Integer(10.5), Integer(10)) + raises(ValueError, lambda: Integer("10.5")) + assert Integer(Rational('1.' + '9'*20)) == 1 + + +def test_Rational_new(): + """" + Test for Rational constructor + """ + _test_rational_new(Rational) + + n1 = S.Half + assert n1 == Rational(Integer(1), 2) + assert n1 == Rational(Integer(1), Integer(2)) + assert n1 == Rational(1, Integer(2)) + assert n1 == Rational(S.Half) + assert 1 == Rational(n1, n1) + assert Rational(3, 2) == Rational(S.Half, Rational(1, 3)) + assert Rational(3, 1) == Rational(1, Rational(1, 3)) + n3_4 = Rational(3, 4) + assert Rational('3/4') == n3_4 + assert -Rational('-3/4') == n3_4 + assert Rational('.76').limit_denominator(4) == n3_4 + assert Rational(19, 25).limit_denominator(4) == n3_4 + assert Rational('19/25').limit_denominator(4) == n3_4 + assert Rational(1.0, 3) == Rational(1, 3) + assert Rational(1, 3.0) == Rational(1, 3) + assert Rational(Float(0.5)) == S.Half + assert Rational('1e2/1e-2') == Rational(10000) + assert Rational('1 234') == Rational(1234) + assert Rational('1/1 234') == Rational(1, 1234) + assert Rational(-1, 0) is S.ComplexInfinity + assert Rational(1, 0) is S.ComplexInfinity + # Make sure Rational doesn't lose precision on Floats + assert Rational(pi.evalf(100)).evalf(100) == pi.evalf(100) + raises(TypeError, lambda: Rational('3**3')) + raises(TypeError, lambda: Rational('1/2 + 2/3')) + + # handle fractions.Fraction instances + try: + import fractions + assert Rational(fractions.Fraction(1, 2)) == S.Half + except ImportError: + pass + + assert Rational(PythonRational(2, 6)) == Rational(1, 3) + + with warns_deprecated_sympy(): + assert Rational(2, 4, gcd=1).q == 4 + with warns_deprecated_sympy(): + n = Rational(2, -4, gcd=1) + assert n.q == 4 + assert n.p == -2 + + assert Rational.from_coprime_ints(3, 5) == Rational(3, 5) + + +def test_issue_24543(): + for p in ('1.5', 1.5, 2): + for q in ('1.5', 1.5, 2): + assert Rational(p, q).as_numer_denom() == Rational('%s/%s'%(p,q)).as_numer_denom() + + assert Rational('0.5', '100') == Rational(1, 200) + + +def test_Number_new(): + """" + Test for Number constructor + """ + # Expected behavior on numbers and strings + assert Number(1) is S.One + assert Number(2).__class__ is Integer + assert Number(-622).__class__ is Integer + assert Number(5, 3).__class__ is Rational + assert Number(5.3).__class__ is Float + assert Number('1') is S.One + assert Number('2').__class__ is Integer + assert Number('-622').__class__ is Integer + assert Number('5/3').__class__ is Rational + assert Number('5.3').__class__ is Float + raises(ValueError, lambda: Number('cos')) + raises(TypeError, lambda: Number(cos)) + a = Rational(3, 5) + assert Number(a) is a # Check idempotence on Numbers + u = ['inf', '-inf', 'nan', 'iNF', '+inf'] + v = [oo, -oo, nan, oo, oo] + for i, a in zip(u, v): + assert Number(i) is a, (i, Number(i), a) + + +def test_Number_cmp(): + n1 = Number(1) + n2 = Number(2) + n3 = Number(-3) + + assert n1 < n2 + assert n1 <= n2 + assert n3 < n1 + assert n2 > n3 + assert n2 >= n3 + + raises(TypeError, lambda: n1 < S.NaN) + raises(TypeError, lambda: n1 <= S.NaN) + raises(TypeError, lambda: n1 > S.NaN) + raises(TypeError, lambda: n1 >= S.NaN) + + +def test_Rational_cmp(): + n1 = Rational(1, 4) + n2 = Rational(1, 3) + n3 = Rational(2, 4) + n4 = Rational(2, -4) + n5 = Rational(0) + n6 = Rational(1) + n7 = Rational(3) + n8 = Rational(-3) + + assert n8 < n5 + assert n5 < n6 + assert n6 < n7 + assert n8 < n7 + assert n7 > n8 + assert (n1 + 1)**n2 < 2 + assert ((n1 + n6)/n7) < 1 + + assert n4 < n3 + assert n2 < n3 + assert n1 < n2 + assert n3 > n1 + assert not n3 < n1 + assert not (Rational(-1) > 0) + assert Rational(-1) < 0 + + raises(TypeError, lambda: n1 < S.NaN) + raises(TypeError, lambda: n1 <= S.NaN) + raises(TypeError, lambda: n1 > S.NaN) + raises(TypeError, lambda: n1 >= S.NaN) + + +def test_Float(): + def eq(a, b): + t = Float("1.0E-15") + return (-t < a - b < t) + + equal_pairs = [ + (0, 0.0), # This is just how Python works... + (0, S.Zero), + (0.0, Float(0)), + ] + unequal_pairs = [ + (0.0, S.Zero), + (0, Float(0)), + (S.Zero, Float(0)), + ] + for p1, p2 in equal_pairs: + assert (p1 == p2) is True + assert (p1 != p2) is False + assert (p2 == p1) is True + assert (p2 != p1) is False + for p1, p2 in unequal_pairs: + assert (p1 == p2) is False + assert (p1 != p2) is True + assert (p2 == p1) is False + assert (p2 != p1) is True + + assert S.Zero.is_zero + + a = Float(2) ** Float(3) + assert eq(a.evalf(), Float(8)) + assert eq((pi ** -1).evalf(), Float("0.31830988618379067")) + a = Float(2) ** Float(4) + assert eq(a.evalf(), Float(16)) + assert (S(.3) == S(.5)) is False + + mpf = (0, 5404319552844595, -52, 53) + x_str = Float((0, '13333333333333', -52, 53)) + x_0xstr = Float((0, '0x13333333333333', -52, 53)) + x2_str = Float((0, '26666666666666', -53, 54)) + x_hex = Float((0, int(0x13333333333333), -52, 53)) + x_dec = Float(mpf) + assert x_str == x_0xstr == x_hex == x_dec == Float(1.2) + # x2_str was entered slightly malformed in that the mantissa + # was even -- it should be odd and the even part should be + # included with the exponent, but this is resolved by normalization + # ONLY IF REQUIREMENTS of mpf_norm are met: the bitcount must + # be exact: double the mantissa ==> increase bc by 1 + assert Float(1.2)._mpf_ == mpf + assert x2_str._mpf_ == mpf + + assert Float((0, int(0), -123, -1)) is S.NaN + assert Float((0, int(0), -456, -2)) is S.Infinity + assert Float((1, int(0), -789, -3)) is S.NegativeInfinity + # if you don't give the full signature, it's not special + assert Float((0, int(0), -123)) == Float(0) + assert Float((0, int(0), -456)) == Float(0) + assert Float((1, int(0), -789)) == Float(0) + + raises(ValueError, lambda: Float((0, 7, 1, 3), '')) + + assert Float('0.0').is_finite is True + assert Float('0.0').is_negative is False + assert Float('0.0').is_positive is False + assert Float('0.0').is_infinite is False + assert Float('0.0').is_zero is True + + # rationality properties + # if the integer test fails then the use of intlike + # should be removed from gamma_functions.py + assert Float(1).is_integer is None + assert Float(1).is_rational is None + assert Float(1).is_irrational is None + assert sqrt(2).n(15).is_rational is None + assert sqrt(2).n(15).is_irrational is None + + # do not automatically evalf + def teq(a): + assert (a.evalf() == a) is False + assert (a.evalf() != a) is True + assert (a == a.evalf()) is False + assert (a != a.evalf()) is True + + teq(pi) + teq(2*pi) + teq(cos(0.1, evaluate=False)) + + # long integer + i = 12345678901234567890 + assert same_and_same_prec(Float(12, ''), Float('12', '')) + assert same_and_same_prec(Float(Integer(i), ''), Float(i, '')) + assert same_and_same_prec(Float(i, ''), Float(str(i), 20)) + assert same_and_same_prec(Float(str(i)), Float(i, '')) + assert same_and_same_prec(Float(i), Float(i, '')) + + # inexact floats (repeating binary = denom not multiple of 2) + # cannot have precision greater than 15 + assert Float(.125, 22)._prec == 76 + assert Float(2.0, 22)._prec == 76 + # only default prec is equal, even for exactly representable float + assert Float(.125, 22) != .125 + #assert Float(2.0, 22) == 2 + assert float(Float('.12500000000000001', '')) == .125 + raises(ValueError, lambda: Float(.12500000000000001, '')) + + # allow spaces + assert Float('123 456.123 456') == Float('123456.123456') + assert Integer('123 456') == Integer('123456') + assert Rational('123 456.123 456') == Rational('123456.123456') + assert Float(' .3e2') == Float('0.3e2') + # but treat them as strictly ass underscore between digits: only 1 + raises(ValueError, lambda: Float('1 2')) + + # allow underscore between digits + assert Float('1_23.4_56') == Float('123.456') + # assert Float('1_23.4_5_6', 12) == Float('123.456', 12) + # ...but not in all cases (per Py 3.6) + raises(ValueError, lambda: Float('1_')) + raises(ValueError, lambda: Float('1__2')) + raises(ValueError, lambda: Float('_1')) + raises(ValueError, lambda: Float('_inf')) + + # allow auto precision detection + assert Float('.1', '') == Float(.1, 1) + assert Float('.125', '') == Float(.125, 3) + assert Float('.100', '') == Float(.1, 3) + assert Float('2.0', '') == Float('2', 2) + + raises(ValueError, lambda: Float("12.3d-4", "")) + raises(ValueError, lambda: Float(12.3, "")) + raises(ValueError, lambda: Float('.')) + raises(ValueError, lambda: Float('-.')) + + zero = Float('0.0') + assert Float('-0') == zero + assert Float('.0') == zero + assert Float('-.0') == zero + assert Float('-0.0') == zero + assert Float(0.0) == zero + assert Float(0) == zero + assert Float(0, '') == Float('0', '') + assert Float(1) == Float(1.0) + assert Float(S.Zero) == zero + assert Float(S.One) == Float(1.0) + + assert Float(decimal.Decimal('0.1'), 3) == Float('.1', 3) + assert Float(decimal.Decimal('nan')) is S.NaN + assert Float(decimal.Decimal('Infinity')) is S.Infinity + assert Float(decimal.Decimal('-Infinity')) is S.NegativeInfinity + + assert '{:.3f}'.format(Float(4.236622)) == '4.237' + assert '{:.35f}'.format(Float(pi.n(40), 40)) == \ + '3.14159265358979323846264338327950288' + + # unicode + assert Float('0.73908513321516064100000000') == \ + Float('0.73908513321516064100000000') + assert Float('0.73908513321516064100000000', 28) == \ + Float('0.73908513321516064100000000', 28) + + # binary precision + # Decimal value 0.1 cannot be expressed precisely as a base 2 fraction + a = Float(S.One/10, dps=15) + b = Float(S.One/10, dps=16) + p = Float(S.One/10, precision=53) + q = Float(S.One/10, precision=54) + assert a._mpf_ == p._mpf_ + assert not a._mpf_ == q._mpf_ + assert not b._mpf_ == q._mpf_ + + # Precision specifying errors + raises(ValueError, lambda: Float("1.23", dps=3, precision=10)) + raises(ValueError, lambda: Float("1.23", dps="", precision=10)) + raises(ValueError, lambda: Float("1.23", dps=3, precision="")) + raises(ValueError, lambda: Float("1.23", dps="", precision="")) + + # from NumberSymbol + assert same_and_same_prec(Float(pi, 32), pi.evalf(32)) + assert same_and_same_prec(Float(Catalan), Catalan.evalf()) + + # oo and nan + u = ['inf', '-inf', 'nan', 'iNF', '+inf'] + v = [oo, -oo, nan, oo, oo] + for i, a in zip(u, v): + assert Float(i) is a + + +def test_zero_not_false(): + # https://github.com/sympy/sympy/issues/20796 + assert (S(0.0) == S.false) is False + assert (S.false == S(0.0)) is False + assert (S(0) == S.false) is False + assert (S.false == S(0)) is False + + +@conserve_mpmath_dps +def test_float_mpf(): + import mpmath + mpmath.mp.dps = 100 + mp_pi = mpmath.pi() + + assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) + + mpmath.mp.dps = 15 + + assert Float(mp_pi, 100) == Float(mp_pi._mpf_, 100) == pi.evalf(100) + + +def test_Float_RealElement(): + repi = RealField(dps=100)(pi.evalf(100)) + # We still have to pass the precision because Float doesn't know what + # RealElement is, but make sure it keeps full precision from the result. + assert Float(repi, 100) == pi.evalf(100) + + +def test_Float_default_to_highprec_from_str(): + s = str(pi.evalf(128)) + assert same_and_same_prec(Float(s), Float(s, '')) + + +def test_Float_eval(): + a = Float(3.2) + assert (a**2).is_Float + + +def test_Float_issue_2107(): + a = Float(0.1, 10) + b = Float("0.1", 10) + + assert a - a == 0 + assert a + (-a) == 0 + assert S.Zero + a - a == 0 + assert S.Zero + a + (-a) == 0 + + assert b - b == 0 + assert b + (-b) == 0 + assert S.Zero + b - b == 0 + assert S.Zero + b + (-b) == 0 + + +def test_issue_14289(): + from sympy.polys.numberfields import to_number_field + + a = 1 - sqrt(2) + b = to_number_field(a) + assert b.as_expr() == a + assert b.minpoly(a).expand() == 0 + + +def test_Float_from_tuple(): + a = Float((0, '1L', 0, 1)) + b = Float((0, '1', 0, 1)) + assert a == b + + +def test_Infinity(): + assert oo != 1 + assert 1*oo is oo + assert 1 != oo + assert oo != -oo + assert oo != Symbol("x")**3 + assert oo + 1 is oo + assert 2 + oo is oo + assert 3*oo + 2 is oo + assert S.Half**oo == 0 + assert S.Half**(-oo) is oo + assert -oo*3 is -oo + assert oo + oo is oo + assert -oo + oo*(-5) is -oo + assert 1/oo == 0 + assert 1/(-oo) == 0 + assert 8/oo == 0 + assert oo % 2 is nan + assert 2 % oo is nan + assert oo/oo is nan + assert oo/-oo is nan + assert -oo/oo is nan + assert -oo/-oo is nan + assert oo - oo is nan + assert oo - -oo is oo + assert -oo - oo is -oo + assert -oo - -oo is nan + assert oo + -oo is nan + assert -oo + oo is nan + assert oo + oo is oo + assert -oo + oo is nan + assert oo + -oo is nan + assert -oo + -oo is -oo + assert oo*oo is oo + assert -oo*oo is -oo + assert oo*-oo is -oo + assert -oo*-oo is oo + assert oo/0 is oo + assert -oo/0 is -oo + assert 0/oo == 0 + assert 0/-oo == 0 + assert oo*0 is nan + assert -oo*0 is nan + assert 0*oo is nan + assert 0*-oo is nan + assert oo + 0 is oo + assert -oo + 0 is -oo + assert 0 + oo is oo + assert 0 + -oo is -oo + assert oo - 0 is oo + assert -oo - 0 is -oo + assert 0 - oo is -oo + assert 0 - -oo is oo + assert oo/2 is oo + assert -oo/2 is -oo + assert oo/-2 is -oo + assert -oo/-2 is oo + assert oo*2 is oo + assert -oo*2 is -oo + assert oo*-2 is -oo + assert 2/oo == 0 + assert 2/-oo == 0 + assert -2/oo == 0 + assert -2/-oo == 0 + assert 2*oo is oo + assert 2*-oo is -oo + assert -2*oo is -oo + assert -2*-oo is oo + assert 2 + oo is oo + assert 2 - oo is -oo + assert -2 + oo is oo + assert -2 - oo is -oo + assert 2 + -oo is -oo + assert 2 - -oo is oo + assert -2 + -oo is -oo + assert -2 - -oo is oo + assert S(2) + oo is oo + assert S(2) - oo is -oo + assert oo/I == -oo*I + assert -oo/I == oo*I + assert oo*float(1) == _inf and (oo*float(1)) is oo + assert -oo*float(1) == _ninf and (-oo*float(1)) is -oo + assert oo/float(1) == _inf and (oo/float(1)) is oo + assert -oo/float(1) == _ninf and (-oo/float(1)) is -oo + assert oo*float(-1) == _ninf and (oo*float(-1)) is -oo + assert -oo*float(-1) == _inf and (-oo*float(-1)) is oo + assert oo/float(-1) == _ninf and (oo/float(-1)) is -oo + assert -oo/float(-1) == _inf and (-oo/float(-1)) is oo + assert oo + float(1) == _inf and (oo + float(1)) is oo + assert -oo + float(1) == _ninf and (-oo + float(1)) is -oo + assert oo - float(1) == _inf and (oo - float(1)) is oo + assert -oo - float(1) == _ninf and (-oo - float(1)) is -oo + assert float(1)*oo == _inf and (float(1)*oo) is oo + assert float(1)*-oo == _ninf and (float(1)*-oo) is -oo + assert float(1)/oo == 0 + assert float(1)/-oo == 0 + assert float(-1)*oo == _ninf and (float(-1)*oo) is -oo + assert float(-1)*-oo == _inf and (float(-1)*-oo) is oo + assert float(-1)/oo == 0 + assert float(-1)/-oo == 0 + assert float(1) + oo is oo + assert float(1) + -oo is -oo + assert float(1) - oo is -oo + assert float(1) - -oo is oo + assert oo == float(oo) + assert (oo != float(oo)) is False + assert type(float(oo)) is float + assert -oo == float(-oo) + assert (-oo != float(-oo)) is False + assert type(float(-oo)) is float + + assert Float('nan') is nan + assert nan*1.0 is nan + assert -1.0*nan is nan + assert nan*oo is nan + assert nan*-oo is nan + assert nan/oo is nan + assert nan/-oo is nan + assert nan + oo is nan + assert nan + -oo is nan + assert nan - oo is nan + assert nan - -oo is nan + assert -oo * S.Zero is nan + + assert oo*nan is nan + assert -oo*nan is nan + assert oo/nan is nan + assert -oo/nan is nan + assert oo + nan is nan + assert -oo + nan is nan + assert oo - nan is nan + assert -oo - nan is nan + assert S.Zero * oo is nan + assert oo.is_Rational is False + assert isinstance(oo, Rational) is False + + assert S.One/oo == 0 + assert -S.One/oo == 0 + assert S.One/-oo == 0 + assert -S.One/-oo == 0 + assert S.One*oo is oo + assert -S.One*oo is -oo + assert S.One*-oo is -oo + assert -S.One*-oo is oo + assert S.One/nan is nan + assert S.One - -oo is oo + assert S.One + nan is nan + assert S.One - nan is nan + assert nan - S.One is nan + assert nan/S.One is nan + assert -oo - S.One is -oo + + +def test_Infinity_2(): + x = Symbol('x') + assert oo*x != oo + assert oo*(pi - 1) is oo + assert oo*(1 - pi) is -oo + + assert (-oo)*x != -oo + assert (-oo)*(pi - 1) is -oo + assert (-oo)*(1 - pi) is oo + + assert (-1)**S.NaN is S.NaN + assert oo - _inf is S.NaN + assert oo + _ninf is S.NaN + assert oo*0 is S.NaN + assert oo/_inf is S.NaN + assert oo/_ninf is S.NaN + assert oo**S.NaN is S.NaN + assert -oo + _inf is S.NaN + assert -oo - _ninf is S.NaN + assert -oo*S.NaN is S.NaN + assert -oo*0 is S.NaN + assert -oo/_inf is S.NaN + assert -oo/_ninf is S.NaN + assert -oo/S.NaN is S.NaN + assert abs(-oo) is oo + assert all((-oo)**i is S.NaN for i in (oo, -oo, S.NaN)) + assert (-oo)**3 is -oo + assert (-oo)**2 is oo + assert abs(S.ComplexInfinity) is oo + + +def test_Mul_Infinity_Zero(): + assert Float(0)*_inf is nan + assert Float(0)*_ninf is nan + assert Float(0)*_inf is nan + assert Float(0)*_ninf is nan + assert _inf*Float(0) is nan + assert _ninf*Float(0) is nan + assert _inf*Float(0) is nan + assert _ninf*Float(0) is nan + + +def test_Div_By_Zero(): + assert 1/S.Zero is zoo + assert 1/Float(0) is zoo + assert 0/S.Zero is nan + assert 0/Float(0) is nan + assert S.Zero/0 is nan + assert Float(0)/0 is nan + assert -1/S.Zero is zoo + assert -1/Float(0) is zoo + + +@_both_exp_pow +def test_Infinity_inequations(): + assert oo > pi + assert not (oo < pi) + assert exp(-3) < oo + + assert _inf > pi + assert not (_inf < pi) + assert exp(-3) < _inf + + raises(TypeError, lambda: oo < I) + raises(TypeError, lambda: oo <= I) + raises(TypeError, lambda: oo > I) + raises(TypeError, lambda: oo >= I) + raises(TypeError, lambda: -oo < I) + raises(TypeError, lambda: -oo <= I) + raises(TypeError, lambda: -oo > I) + raises(TypeError, lambda: -oo >= I) + + raises(TypeError, lambda: I < oo) + raises(TypeError, lambda: I <= oo) + raises(TypeError, lambda: I > oo) + raises(TypeError, lambda: I >= oo) + raises(TypeError, lambda: I < -oo) + raises(TypeError, lambda: I <= -oo) + raises(TypeError, lambda: I > -oo) + raises(TypeError, lambda: I >= -oo) + + assert oo > -oo and oo >= -oo + assert (oo < -oo) == False and (oo <= -oo) == False + assert -oo < oo and -oo <= oo + assert (-oo > oo) == False and (-oo >= oo) == False + + assert (oo < oo) == False # issue 7775 + assert (oo > oo) == False + assert (-oo > -oo) == False and (-oo < -oo) == False + assert oo >= oo and oo <= oo and -oo >= -oo and -oo <= -oo + assert (-oo < -_inf) == False + assert (oo > _inf) == False + assert -oo >= -_inf + assert oo <= _inf + + x = Symbol('x') + b = Symbol('b', finite=True, real=True) + assert (x < oo) == Lt(x, oo) # issue 7775 + assert b < oo and b > -oo and b <= oo and b >= -oo + assert oo > b and oo >= b and (oo < b) == False and (oo <= b) == False + assert (-oo > b) == False and (-oo >= b) == False and -oo < b and -oo <= b + assert (oo < x) == Lt(oo, x) and (oo > x) == Gt(oo, x) + assert (oo <= x) == Le(oo, x) and (oo >= x) == Ge(oo, x) + assert (-oo < x) == Lt(-oo, x) and (-oo > x) == Gt(-oo, x) + assert (-oo <= x) == Le(-oo, x) and (-oo >= x) == Ge(-oo, x) + + +def test_NaN(): + assert nan is nan + assert nan != 1 + assert 1*nan is nan + assert 1 != nan + assert -nan is nan + assert oo != Symbol("x")**3 + assert 2 + nan is nan + assert 3*nan + 2 is nan + assert -nan*3 is nan + assert nan + nan is nan + assert -nan + nan*(-5) is nan + assert 8/nan is nan + raises(TypeError, lambda: nan > 0) + raises(TypeError, lambda: nan < 0) + raises(TypeError, lambda: nan >= 0) + raises(TypeError, lambda: nan <= 0) + raises(TypeError, lambda: 0 < nan) + raises(TypeError, lambda: 0 > nan) + raises(TypeError, lambda: 0 <= nan) + raises(TypeError, lambda: 0 >= nan) + assert nan**0 == 1 # as per IEEE 754 + assert 1**nan is nan # IEEE 754 is not the best choice for symbolic work + # test Pow._eval_power's handling of NaN + assert Pow(nan, 0, evaluate=False)**2 == 1 + for n in (1, 1., S.One, S.NegativeOne, Float(1)): + assert n + nan is nan + assert n - nan is nan + assert nan + n is nan + assert nan - n is nan + assert n/nan is nan + assert nan/n is nan + + +def test_special_numbers(): + assert isinstance(S.NaN, Number) is True + assert isinstance(S.Infinity, Number) is True + assert isinstance(S.NegativeInfinity, Number) is True + + assert S.NaN.is_number is True + assert S.Infinity.is_number is True + assert S.NegativeInfinity.is_number is True + assert S.ComplexInfinity.is_number is True + + assert isinstance(S.NaN, Rational) is False + assert isinstance(S.Infinity, Rational) is False + assert isinstance(S.NegativeInfinity, Rational) is False + + assert S.NaN.is_rational is not True + assert S.Infinity.is_rational is not True + assert S.NegativeInfinity.is_rational is not True + + +def test_powers(): + assert integer_nthroot(1, 2) == (1, True) + assert integer_nthroot(1, 5) == (1, True) + assert integer_nthroot(2, 1) == (2, True) + assert integer_nthroot(2, 2) == (1, False) + assert integer_nthroot(2, 5) == (1, False) + assert integer_nthroot(4, 2) == (2, True) + assert integer_nthroot(123**25, 25) == (123, True) + assert integer_nthroot(123**25 + 1, 25) == (123, False) + assert integer_nthroot(123**25 - 1, 25) == (122, False) + assert integer_nthroot(1, 1) == (1, True) + assert integer_nthroot(0, 1) == (0, True) + assert integer_nthroot(0, 3) == (0, True) + assert integer_nthroot(10000, 1) == (10000, True) + assert integer_nthroot(4, 2) == (2, True) + assert integer_nthroot(16, 2) == (4, True) + assert integer_nthroot(26, 2) == (5, False) + assert integer_nthroot(1234567**7, 7) == (1234567, True) + assert integer_nthroot(1234567**7 + 1, 7) == (1234567, False) + assert integer_nthroot(1234567**7 - 1, 7) == (1234566, False) + b = 25**1000 + assert integer_nthroot(b, 1000) == (25, True) + assert integer_nthroot(b + 1, 1000) == (25, False) + assert integer_nthroot(b - 1, 1000) == (24, False) + c = 10**400 + c2 = c**2 + assert integer_nthroot(c2, 2) == (c, True) + assert integer_nthroot(c2 + 1, 2) == (c, False) + assert integer_nthroot(c2 - 1, 2) == (c - 1, False) + assert integer_nthroot(2, 10**10) == (1, False) + + p, r = integer_nthroot(int(factorial(10000)), 100) + assert p % (10**10) == 5322420655 + assert not r + + # Test that this is fast + assert integer_nthroot(2, 10**10) == (1, False) + + # output should be int if possible + assert type(integer_nthroot(2**61, 2)[0]) is int + + +def test_integer_nthroot_overflow(): + assert integer_nthroot(10**(50*50), 50) == (10**50, True) + assert integer_nthroot(10**100000, 10000) == (10**10, True) + + +def test_integer_log(): + raises(ValueError, lambda: integer_log(2, 1)) + raises(ValueError, lambda: integer_log(0, 2)) + raises(ValueError, lambda: integer_log(1.1, 2)) + raises(ValueError, lambda: integer_log(1, 2.2)) + + assert integer_log(1, 2) == (0, True) + assert integer_log(1, 3) == (0, True) + assert integer_log(2, 3) == (0, False) + assert integer_log(3, 3) == (1, True) + assert integer_log(3*2, 3) == (1, False) + assert integer_log(3**2, 3) == (2, True) + assert integer_log(3*4, 3) == (2, False) + assert integer_log(3**3, 3) == (3, True) + assert integer_log(27, 5) == (2, False) + assert integer_log(2, 3) == (0, False) + assert integer_log(-4, 2) == (2, False) + assert integer_log(-16, 4) == (0, False) + assert integer_log(-4, -2) == (2, False) + assert integer_log(4, -2) == (2, True) + assert integer_log(-8, -2) == (3, True) + assert integer_log(8, -2) == (3, False) + assert integer_log(-9, 3) == (0, False) + assert integer_log(-9, -3) == (2, False) + assert integer_log(9, -3) == (2, True) + assert integer_log(-27, -3) == (3, True) + assert integer_log(27, -3) == (3, False) + + +def test_isqrt(): + from math import sqrt as _sqrt + limit = 4503599761588223 + assert int(_sqrt(limit)) == integer_nthroot(limit, 2)[0] + assert int(_sqrt(limit + 1)) != integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + 1) == integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + S.Half) == integer_nthroot(limit, 2)[0] + assert isqrt(limit + 1 + S.Half) == integer_nthroot(limit + 1, 2)[0] + assert isqrt(limit + 2 + S.Half) == integer_nthroot(limit + 2, 2)[0] + + # Regression tests for https://github.com/sympy/sympy/issues/17034 + assert isqrt(4503599761588224) == 67108864 + assert isqrt(9999999999999999) == 99999999 + + # Other corner cases, especially involving non-integers. + raises(ValueError, lambda: isqrt(-1)) + raises(ValueError, lambda: isqrt(-10**1000)) + raises(ValueError, lambda: isqrt(Rational(-1, 2))) + + tiny = Rational(1, 10**1000) + raises(ValueError, lambda: isqrt(-tiny)) + assert isqrt(1-tiny) == 0 + assert isqrt(4503599761588224-tiny) == 67108864 + assert isqrt(10**100 - tiny) == 10**50 - 1 + + +def test_powers_Integer(): + """Test Integer._eval_power""" + # check infinity + assert S.One ** S.Infinity is S.NaN + assert S.NegativeOne** S.Infinity is S.NaN + assert S(2) ** S.Infinity is S.Infinity + assert S(-2)** S.Infinity == zoo + assert S(0) ** S.Infinity is S.Zero + + # check Nan + assert S.One ** S.NaN is S.NaN + assert S.NegativeOne ** S.NaN is S.NaN + + # check for exact roots + assert S.NegativeOne ** Rational(6, 5) == - (-1)**(S.One/5) + assert sqrt(S(4)) == 2 + assert sqrt(S(-4)) == I * 2 + assert S(16) ** Rational(1, 4) == 2 + assert S(-16) ** Rational(1, 4) == 2 * (-1)**Rational(1, 4) + assert S(9) ** Rational(3, 2) == 27 + assert S(-9) ** Rational(3, 2) == -27*I + assert S(27) ** Rational(2, 3) == 9 + assert S(-27) ** Rational(2, 3) == 9 * (S.NegativeOne ** Rational(2, 3)) + assert (-2) ** Rational(-2, 1) == Rational(1, 4) + + # not exact roots + assert sqrt(-3) == I*sqrt(3) + assert (3) ** (Rational(3, 2)) == 3 * sqrt(3) + assert (-3) ** (Rational(3, 2)) == - 3 * sqrt(-3) + assert (-3) ** (Rational(5, 2)) == 9 * I * sqrt(3) + assert (-3) ** (Rational(7, 2)) == - I * 27 * sqrt(3) + assert (2) ** (Rational(3, 2)) == 2 * sqrt(2) + assert (2) ** (Rational(-3, 2)) == sqrt(2) / 4 + assert (81) ** (Rational(2, 3)) == 9 * (S(3) ** (Rational(2, 3))) + assert (-81) ** (Rational(2, 3)) == 9 * (S(-3) ** (Rational(2, 3))) + assert (-3) ** Rational(-7, 3) == \ + -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 + assert (-3) ** Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 + + # join roots + assert sqrt(6) + sqrt(24) == 3*sqrt(6) + assert sqrt(2) * sqrt(3) == sqrt(6) + + # separate symbols & constansts + x = Symbol("x") + assert sqrt(49 * x) == 7 * sqrt(x) + assert sqrt((3 - sqrt(pi)) ** 2) == 3 - sqrt(pi) + + # check that it is fast for big numbers + assert (2**64 + 1) ** Rational(4, 3) + assert (2**64 + 1) ** Rational(17, 25) + + # negative rational power and negative base + assert (-3) ** Rational(-7, 3) == \ + -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 + assert (-3) ** Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 + assert (-2) ** Rational(-10, 3) == \ + (-1)**Rational(2, 3)*2**Rational(2, 3)/16 + assert abs(Pow(-2, Rational(-10, 3)).n() - + Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16 + + # negative base and rational power with some simplification + assert (-8) ** Rational(2, 5) == \ + 2*(-1)**Rational(2, 5)*2**Rational(1, 5) + assert (-4) ** Rational(9, 5) == \ + -8*(-1)**Rational(4, 5)*2**Rational(3, 5) + + assert S(1234).factors() == {617: 1, 2: 1} + assert Rational(2*3, 3*5*7).factors() == {2: 1, 5: -1, 7: -1} + + # test that eval_power factors numbers bigger than + # the current limit in factor_trial_division (2**15) + from sympy.ntheory.generate import nextprime + n = nextprime(2**15) + assert sqrt(n**2) == n + assert sqrt(n**3) == n*sqrt(n) + assert sqrt(4*n) == 2*sqrt(n) + + # check that factors of base with powers sharing gcd with power are removed + assert (2**4*3)**Rational(1, 6) == 2**Rational(2, 3)*3**Rational(1, 6) + assert (2**4*3)**Rational(5, 6) == 8*2**Rational(1, 3)*3**Rational(5, 6) + + # check that bases sharing a gcd are exptracted + assert 2**Rational(1, 3)*3**Rational(1, 4)*6**Rational(1, 5) == \ + 2**Rational(8, 15)*3**Rational(9, 20) + assert sqrt(8)*24**Rational(1, 3)*6**Rational(1, 5) == \ + 4*2**Rational(7, 10)*3**Rational(8, 15) + assert sqrt(8)*(-24)**Rational(1, 3)*(-6)**Rational(1, 5) == \ + 4*(-3)**Rational(8, 15)*2**Rational(7, 10) + assert 2**Rational(1, 3)*2**Rational(8, 9) == 2*2**Rational(2, 9) + assert 2**Rational(2, 3)*6**Rational(1, 3) == 2*3**Rational(1, 3) + assert 2**Rational(2, 3)*6**Rational(8, 9) == \ + 2*2**Rational(5, 9)*3**Rational(8, 9) + assert (-2)**Rational(2, S(3))*(-4)**Rational(1, S(3)) == -2*2**Rational(1, 3) + assert 3*Pow(3, 2, evaluate=False) == 3**3 + assert 3*Pow(3, Rational(-1, 3), evaluate=False) == 3**Rational(2, 3) + assert (-2)**Rational(1, 3)*(-3)**Rational(1, 4)*(-5)**Rational(5, 6) == \ + -(-1)**Rational(5, 12)*2**Rational(1, 3)*3**Rational(1, 4) * \ + 5**Rational(5, 6) + + assert Integer(-2)**Symbol('', even=True) == \ + Integer(2)**Symbol('', even=True) + assert (-1)**Float(.5) == 1.0*I + + +def test_powers_Rational(): + """Test Rational._eval_power""" + # check infinity + assert S.Half ** S.Infinity == 0 + assert Rational(3, 2) ** S.Infinity is S.Infinity + assert Rational(-1, 2) ** S.Infinity == 0 + assert Rational(-3, 2) ** S.Infinity == zoo + + # check Nan + assert Rational(3, 4) ** S.NaN is S.NaN + assert Rational(-2, 3) ** S.NaN is S.NaN + + # exact roots on numerator + assert sqrt(Rational(4, 3)) == 2 * sqrt(3) / 3 + assert Rational(4, 3) ** Rational(3, 2) == 8 * sqrt(3) / 9 + assert sqrt(Rational(-4, 3)) == I * 2 * sqrt(3) / 3 + assert Rational(-4, 3) ** Rational(3, 2) == - I * 8 * sqrt(3) / 9 + assert Rational(27, 2) ** Rational(1, 3) == 3 * (2 ** Rational(2, 3)) / 2 + assert Rational(5**3, 8**3) ** Rational(4, 3) == Rational(5**4, 8**4) + + # exact root on denominator + assert sqrt(Rational(1, 4)) == S.Half + assert sqrt(Rational(1, -4)) == I * S.Half + assert sqrt(Rational(3, 4)) == sqrt(3) / 2 + assert sqrt(Rational(3, -4)) == I * sqrt(3) / 2 + assert Rational(5, 27) ** Rational(1, 3) == (5 ** Rational(1, 3)) / 3 + + # not exact roots + assert sqrt(S.Half) == sqrt(2) / 2 + assert sqrt(Rational(-4, 7)) == I * sqrt(Rational(4, 7)) + assert Rational(-3, 2)**Rational(-7, 3) == \ + -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27 + assert Rational(-3, 2)**Rational(-2, 3) == \ + -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3 + assert Rational(-3, 2)**Rational(-10, 3) == \ + 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81 + assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() - + Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16 + + # negative integer power and negative rational base + assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4) + + a = Rational(1, 10) + assert a**Float(a, 2) == Float(a, 2)**Float(a, 2) + assert Rational(-2, 3)**Symbol('', even=True) == \ + Rational(2, 3)**Symbol('', even=True) + + +def test_powers_Float(): + assert str((S('-1/10')**S('3/10')).n()) == str(Float(-.1)**(.3)) + + +def test_lshift_Integer(): + assert Integer(0) << Integer(2) == Integer(0) + assert Integer(0) << 2 == Integer(0) + assert 0 << Integer(2) == Integer(0) + + assert Integer(0b11) << Integer(0) == Integer(0b11) + assert Integer(0b11) << 0 == Integer(0b11) + assert 0b11 << Integer(0) == Integer(0b11) + + assert Integer(0b11) << Integer(2) == Integer(0b11 << 2) + assert Integer(0b11) << 2 == Integer(0b11 << 2) + assert 0b11 << Integer(2) == Integer(0b11 << 2) + + assert Integer(-0b11) << Integer(2) == Integer(-0b11 << 2) + assert Integer(-0b11) << 2 == Integer(-0b11 << 2) + assert -0b11 << Integer(2) == Integer(-0b11 << 2) + + raises(TypeError, lambda: Integer(2) << 0.0) + raises(TypeError, lambda: 0.0 << Integer(2)) + raises(ValueError, lambda: Integer(1) << Integer(-1)) + + +def test_rshift_Integer(): + assert Integer(0) >> Integer(2) == Integer(0) + assert Integer(0) >> 2 == Integer(0) + assert 0 >> Integer(2) == Integer(0) + + assert Integer(0b11) >> Integer(0) == Integer(0b11) + assert Integer(0b11) >> 0 == Integer(0b11) + assert 0b11 >> Integer(0) == Integer(0b11) + + assert Integer(0b11) >> Integer(2) == Integer(0) + assert Integer(0b11) >> 2 == Integer(0) + assert 0b11 >> Integer(2) == Integer(0) + + assert Integer(-0b11) >> Integer(2) == Integer(-1) + assert Integer(-0b11) >> 2 == Integer(-1) + assert -0b11 >> Integer(2) == Integer(-1) + + assert Integer(0b1100) >> Integer(2) == Integer(0b1100 >> 2) + assert Integer(0b1100) >> 2 == Integer(0b1100 >> 2) + assert 0b1100 >> Integer(2) == Integer(0b1100 >> 2) + + assert Integer(-0b1100) >> Integer(2) == Integer(-0b1100 >> 2) + assert Integer(-0b1100) >> 2 == Integer(-0b1100 >> 2) + assert -0b1100 >> Integer(2) == Integer(-0b1100 >> 2) + + raises(TypeError, lambda: Integer(0b10) >> 0.0) + raises(TypeError, lambda: 0.0 >> Integer(2)) + raises(ValueError, lambda: Integer(1) >> Integer(-1)) + + +def test_and_Integer(): + assert Integer(0b01010101) & Integer(0b10101010) == Integer(0) + assert Integer(0b01010101) & 0b10101010 == Integer(0) + assert 0b01010101 & Integer(0b10101010) == Integer(0) + + assert Integer(0b01010101) & Integer(0b11011011) == Integer(0b01010001) + assert Integer(0b01010101) & 0b11011011 == Integer(0b01010001) + assert 0b01010101 & Integer(0b11011011) == Integer(0b01010001) + + assert -Integer(0b01010101) & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) + assert Integer(-0b01010101) & 0b11011011 == Integer(-0b01010101 & 0b11011011) + assert -0b01010101 & Integer(0b11011011) == Integer(-0b01010101 & 0b11011011) + + assert Integer(0b01010101) & -Integer(0b11011011) == Integer(0b01010101 & -0b11011011) + assert Integer(0b01010101) & -0b11011011 == Integer(0b01010101 & -0b11011011) + assert 0b01010101 & Integer(-0b11011011) == Integer(0b01010101 & -0b11011011) + + raises(TypeError, lambda: Integer(2) & 0.0) + raises(TypeError, lambda: 0.0 & Integer(2)) + + +def test_xor_Integer(): + assert Integer(0b01010101) ^ Integer(0b11111111) == Integer(0b10101010) + assert Integer(0b01010101) ^ 0b11111111 == Integer(0b10101010) + assert 0b01010101 ^ Integer(0b11111111) == Integer(0b10101010) + + assert Integer(0b01010101) ^ Integer(0b11011011) == Integer(0b10001110) + assert Integer(0b01010101) ^ 0b11011011 == Integer(0b10001110) + assert 0b01010101 ^ Integer(0b11011011) == Integer(0b10001110) + + assert -Integer(0b01010101) ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) + assert Integer(-0b01010101) ^ 0b11011011 == Integer(-0b01010101 ^ 0b11011011) + assert -0b01010101 ^ Integer(0b11011011) == Integer(-0b01010101 ^ 0b11011011) + + assert Integer(0b01010101) ^ -Integer(0b11011011) == Integer(0b01010101 ^ -0b11011011) + assert Integer(0b01010101) ^ -0b11011011 == Integer(0b01010101 ^ -0b11011011) + assert 0b01010101 ^ Integer(-0b11011011) == Integer(0b01010101 ^ -0b11011011) + + raises(TypeError, lambda: Integer(2) ^ 0.0) + raises(TypeError, lambda: 0.0 ^ Integer(2)) + + +def test_or_Integer(): + assert Integer(0b01010101) | Integer(0b10101010) == Integer(0b11111111) + assert Integer(0b01010101) | 0b10101010 == Integer(0b11111111) + assert 0b01010101 | Integer(0b10101010) == Integer(0b11111111) + + assert Integer(0b01010101) | Integer(0b11011011) == Integer(0b11011111) + assert Integer(0b01010101) | 0b11011011 == Integer(0b11011111) + assert 0b01010101 | Integer(0b11011011) == Integer(0b11011111) + + assert -Integer(0b01010101) | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) + assert Integer(-0b01010101) | 0b11011011 == Integer(-0b01010101 | 0b11011011) + assert -0b01010101 | Integer(0b11011011) == Integer(-0b01010101 | 0b11011011) + + assert Integer(0b01010101) | -Integer(0b11011011) == Integer(0b01010101 | -0b11011011) + assert Integer(0b01010101) | -0b11011011 == Integer(0b01010101 | -0b11011011) + assert 0b01010101 | Integer(-0b11011011) == Integer(0b01010101 | -0b11011011) + + raises(TypeError, lambda: Integer(2) | 0.0) + raises(TypeError, lambda: 0.0 | Integer(2)) + + +def test_invert_Integer(): + assert ~Integer(0b01010101) == Integer(-0b01010110) + assert ~Integer(0b01010101) == Integer(~0b01010101) + assert ~(~Integer(0b01010101)) == Integer(0b01010101) + + +def test_abs1(): + assert Rational(1, 6) != Rational(-1, 6) + assert abs(Rational(1, 6)) == abs(Rational(-1, 6)) + + +def test_accept_int(): + assert not Float(4) == 4 + assert Float(4) != 4 + assert Float(4) == 4.0 + + +def test_dont_accept_str(): + assert Float("0.2") != "0.2" + assert not (Float("0.2") == "0.2") + + +def test_int(): + a = Rational(5) + assert int(a) == 5 + a = Rational(9, 10) + assert int(a) == int(-a) == 0 + assert 1/(-1)**Rational(2, 3) == -(-1)**Rational(1, 3) + # issue 10368 + a = Rational(32442016954, 78058255275) + assert type(int(a)) is type(int(-a)) is int + + +def test_int_NumberSymbols(): + assert int(Catalan) == 0 + assert int(EulerGamma) == 0 + assert int(pi) == 3 + assert int(E) == 2 + assert int(GoldenRatio) == 1 + assert int(TribonacciConstant) == 1 + for i in [Catalan, E, EulerGamma, GoldenRatio, TribonacciConstant, pi]: + a, b = i.approximation_interval(Integer) + ia = int(i) + assert ia == a + assert isinstance(ia, int) + assert b == a + 1 + assert a.is_Integer and b.is_Integer + + +def test_real_bug(): + x = Symbol("x") + assert str(2.0*x*x) in ["(2.0*x)*x", "2.0*x**2", "2.00000000000000*x**2"] + assert str(2.1*x*x) != "(2.0*x)*x" + + +def test_bug_sqrt(): + assert ((sqrt(Rational(2)) + 1)*(sqrt(Rational(2)) - 1)).expand() == 1 + + +def test_pi_Pi(): + "Test that pi (instance) is imported, but Pi (class) is not" + from sympy import pi # noqa + with raises(ImportError): + from sympy import Pi # noqa + + +def test_no_len(): + # there should be no len for numbers + raises(TypeError, lambda: len(Rational(2))) + raises(TypeError, lambda: len(Rational(2, 3))) + raises(TypeError, lambda: len(Integer(2))) + + +def test_issue_3321(): + assert sqrt(Rational(1, 5)) == Rational(1, 5)**S.Half + assert 5 * sqrt(Rational(1, 5)) == sqrt(5) + + +def test_issue_3692(): + assert ((-1)**Rational(1, 6)).expand(complex=True) == I/2 + sqrt(3)/2 + assert ((-5)**Rational(1, 6)).expand(complex=True) == \ + 5**Rational(1, 6)*I/2 + 5**Rational(1, 6)*sqrt(3)/2 + assert ((-64)**Rational(1, 6)).expand(complex=True) == I + sqrt(3) + + +def test_issue_3423(): + x = Symbol("x") + assert sqrt(x - 1).as_base_exp() == (x - 1, S.Half) + assert sqrt(x - 1) != I*sqrt(1 - x) + + +def test_issue_3449(): + x = Symbol("x") + assert sqrt(x - 1).subs(x, 5) == 2 + + +def test_issue_13890(): + x = Symbol("x") + e = (-x/4 - S.One/12)**x - 1 + f = simplify(e) + a = Rational(9, 5) + assert abs(e.subs(x,a).evalf() - f.subs(x,a).evalf()) < 1e-15 + + +def test_Integer_factors(): + def F(i): + return Integer(i).factors() + + assert F(1) == {} + assert F(2) == {2: 1} + assert F(3) == {3: 1} + assert F(4) == {2: 2} + assert F(5) == {5: 1} + assert F(6) == {2: 1, 3: 1} + assert F(7) == {7: 1} + assert F(8) == {2: 3} + assert F(9) == {3: 2} + assert F(10) == {2: 1, 5: 1} + assert F(11) == {11: 1} + assert F(12) == {2: 2, 3: 1} + assert F(13) == {13: 1} + assert F(14) == {2: 1, 7: 1} + assert F(15) == {3: 1, 5: 1} + assert F(16) == {2: 4} + assert F(17) == {17: 1} + assert F(18) == {2: 1, 3: 2} + assert F(19) == {19: 1} + assert F(20) == {2: 2, 5: 1} + assert F(21) == {3: 1, 7: 1} + assert F(22) == {2: 1, 11: 1} + assert F(23) == {23: 1} + assert F(24) == {2: 3, 3: 1} + assert F(25) == {5: 2} + assert F(26) == {2: 1, 13: 1} + assert F(27) == {3: 3} + assert F(28) == {2: 2, 7: 1} + assert F(29) == {29: 1} + assert F(30) == {2: 1, 3: 1, 5: 1} + assert F(31) == {31: 1} + assert F(32) == {2: 5} + assert F(33) == {3: 1, 11: 1} + assert F(34) == {2: 1, 17: 1} + assert F(35) == {5: 1, 7: 1} + assert F(36) == {2: 2, 3: 2} + assert F(37) == {37: 1} + assert F(38) == {2: 1, 19: 1} + assert F(39) == {3: 1, 13: 1} + assert F(40) == {2: 3, 5: 1} + assert F(41) == {41: 1} + assert F(42) == {2: 1, 3: 1, 7: 1} + assert F(43) == {43: 1} + assert F(44) == {2: 2, 11: 1} + assert F(45) == {3: 2, 5: 1} + assert F(46) == {2: 1, 23: 1} + assert F(47) == {47: 1} + assert F(48) == {2: 4, 3: 1} + assert F(49) == {7: 2} + assert F(50) == {2: 1, 5: 2} + assert F(51) == {3: 1, 17: 1} + + +def test_Rational_factors(): + def F(p, q, visual=None): + return Rational(p, q).factors(visual=visual) + + assert F(2, 3) == {2: 1, 3: -1} + assert F(2, 9) == {2: 1, 3: -2} + assert F(2, 15) == {2: 1, 3: -1, 5: -1} + assert F(6, 10) == {3: 1, 5: -1} + + +def test_issue_4107(): + assert pi*(E + 10) + pi*(-E - 10) != 0 + assert pi*(E + 10**10) + pi*(-E - 10**10) != 0 + assert pi*(E + 10**20) + pi*(-E - 10**20) != 0 + assert pi*(E + 10**80) + pi*(-E - 10**80) != 0 + + assert (pi*(E + 10) + pi*(-E - 10)).expand() == 0 + assert (pi*(E + 10**10) + pi*(-E - 10**10)).expand() == 0 + assert (pi*(E + 10**20) + pi*(-E - 10**20)).expand() == 0 + assert (pi*(E + 10**80) + pi*(-E - 10**80)).expand() == 0 + + +def test_IntegerInteger(): + a = Integer(4) + b = Integer(a) + + assert a == b + + +def test_Rational_gcd_lcm_cofactors(): + assert Integer(4).gcd(2) == Integer(2) + assert Integer(4).lcm(2) == Integer(4) + assert Integer(4).gcd(Integer(2)) == Integer(2) + assert Integer(4).lcm(Integer(2)) == Integer(4) + a, b = 720**99911, 480**12342 + assert Integer(a).lcm(b) == a*b/Integer(a).gcd(b) + + assert Integer(4).gcd(3) == Integer(1) + assert Integer(4).lcm(3) == Integer(12) + assert Integer(4).gcd(Integer(3)) == Integer(1) + assert Integer(4).lcm(Integer(3)) == Integer(12) + + assert Rational(4, 3).gcd(2) == Rational(2, 3) + assert Rational(4, 3).lcm(2) == Integer(4) + assert Rational(4, 3).gcd(Integer(2)) == Rational(2, 3) + assert Rational(4, 3).lcm(Integer(2)) == Integer(4) + + assert Integer(4).gcd(Rational(2, 9)) == Rational(2, 9) + assert Integer(4).lcm(Rational(2, 9)) == Integer(4) + + assert Rational(4, 3).gcd(Rational(2, 9)) == Rational(2, 9) + assert Rational(4, 3).lcm(Rational(2, 9)) == Rational(4, 3) + assert Rational(4, 5).gcd(Rational(2, 9)) == Rational(2, 45) + assert Rational(4, 5).lcm(Rational(2, 9)) == Integer(4) + assert Rational(5, 9).lcm(Rational(3, 7)) == Rational(Integer(5).lcm(3),Integer(9).gcd(7)) + + assert Integer(4).cofactors(2) == (Integer(2), Integer(2), Integer(1)) + assert Integer(4).cofactors(Integer(2)) == \ + (Integer(2), Integer(2), Integer(1)) + + assert Integer(4).gcd(Float(2.0)) == Float(1.0) + assert Integer(4).lcm(Float(2.0)) == Float(8.0) + assert Integer(4).cofactors(Float(2.0)) == (Float(1.0), Float(4.0), Float(2.0)) + + assert S.Half.gcd(Float(2.0)) == Float(1.0) + assert S.Half.lcm(Float(2.0)) == Float(1.0) + assert S.Half.cofactors(Float(2.0)) == \ + (Float(1.0), Float(0.5), Float(2.0)) + + +def test_Float_gcd_lcm_cofactors(): + assert Float(2.0).gcd(Integer(4)) == Float(1.0) + assert Float(2.0).lcm(Integer(4)) == Float(8.0) + assert Float(2.0).cofactors(Integer(4)) == (Float(1.0), Float(2.0), Float(4.0)) + + assert Float(2.0).gcd(S.Half) == Float(1.0) + assert Float(2.0).lcm(S.Half) == Float(1.0) + assert Float(2.0).cofactors(S.Half) == \ + (Float(1.0), Float(2.0), Float(0.5)) + + +def test_issue_4611(): + assert abs(pi._evalf(50) - 3.14159265358979) < 1e-10 + assert abs(E._evalf(50) - 2.71828182845905) < 1e-10 + assert abs(Catalan._evalf(50) - 0.915965594177219) < 1e-10 + assert abs(EulerGamma._evalf(50) - 0.577215664901533) < 1e-10 + assert abs(GoldenRatio._evalf(50) - 1.61803398874989) < 1e-10 + assert abs(TribonacciConstant._evalf(50) - 1.83928675521416) < 1e-10 + + x = Symbol("x") + assert (pi + x).evalf() == pi.evalf() + x + assert (E + x).evalf() == E.evalf() + x + assert (Catalan + x).evalf() == Catalan.evalf() + x + assert (EulerGamma + x).evalf() == EulerGamma.evalf() + x + assert (GoldenRatio + x).evalf() == GoldenRatio.evalf() + x + assert (TribonacciConstant + x).evalf() == TribonacciConstant.evalf() + x + + +@conserve_mpmath_dps +def test_conversion_to_mpmath(): + assert mpmath.mpmathify(Integer(1)) == mpmath.mpf(1) + assert mpmath.mpmathify(S.Half) == mpmath.mpf(0.5) + assert mpmath.mpmathify(Float('1.23', 15)) == mpmath.mpf('1.23') + + assert mpmath.mpmathify(I) == mpmath.mpc(1j) + + assert mpmath.mpmathify(1 + 2*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1.0 + 2*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1 + 2.0*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(1.0 + 2.0*I) == mpmath.mpc(1 + 2j) + assert mpmath.mpmathify(S.Half + S.Half*I) == mpmath.mpc(0.5 + 0.5j) + + assert mpmath.mpmathify(2*I) == mpmath.mpc(2j) + assert mpmath.mpmathify(2.0*I) == mpmath.mpc(2j) + assert mpmath.mpmathify(S.Half*I) == mpmath.mpc(0.5j) + + mpmath.mp.dps = 100 + assert mpmath.mpmathify(pi.evalf(100) + pi.evalf(100)*I) == mpmath.pi + mpmath.pi*mpmath.j + assert mpmath.mpmathify(pi.evalf(100)*I) == mpmath.pi*mpmath.j + + +def test_relational(): + # real + x = S(.1) + assert (x != cos) is True + assert (x == cos) is False + + # rational + x = Rational(1, 3) + assert (x != cos) is True + assert (x == cos) is False + + # integer defers to rational so these tests are omitted + + # number symbol + x = pi + assert (x != cos) is True + assert (x == cos) is False + + +def test_Integer_as_index(): + assert 'hello'[Integer(2):] == 'llo' + + +def test_Rational_int(): + assert int( Rational(7, 5)) == 1 + assert int( S.Half) == 0 + assert int(Rational(-1, 2)) == 0 + assert int(-Rational(7, 5)) == -1 + + +def test_zoo(): + b = Symbol('b', finite=True) + nz = Symbol('nz', nonzero=True) + p = Symbol('p', positive=True) + n = Symbol('n', negative=True) + im = Symbol('i', imaginary=True) + c = Symbol('c', complex=True) + pb = Symbol('pb', positive=True) + nb = Symbol('nb', negative=True) + imb = Symbol('ib', imaginary=True, finite=True) + for i in [I, S.Infinity, S.NegativeInfinity, S.Zero, S.One, S.Pi, S.Half, S(3), log(3), + b, nz, p, n, im, pb, nb, imb, c]: + if i.is_finite and (i.is_real or i.is_imaginary): + assert i + zoo is zoo + assert i - zoo is zoo + assert zoo + i is zoo + assert zoo - i is zoo + elif i.is_finite is not False: + assert (i + zoo).is_Add + assert (i - zoo).is_Add + assert (zoo + i).is_Add + assert (zoo - i).is_Add + else: + assert (i + zoo) is S.NaN + assert (i - zoo) is S.NaN + assert (zoo + i) is S.NaN + assert (zoo - i) is S.NaN + + if fuzzy_not(i.is_zero) and (i.is_extended_real or i.is_imaginary): + assert i*zoo is zoo + assert zoo*i is zoo + elif i.is_zero: + assert i*zoo is S.NaN + assert zoo*i is S.NaN + else: + assert (i*zoo).is_Mul + assert (zoo*i).is_Mul + + if fuzzy_not((1/i).is_zero) and (i.is_real or i.is_imaginary): + assert zoo/i is zoo + elif (1/i).is_zero: + assert zoo/i is S.NaN + elif i.is_zero: + assert zoo/i is zoo + else: + assert (zoo/i).is_Mul + + assert (I*oo).is_Mul # allow directed infinity + assert zoo + zoo is S.NaN + assert zoo * zoo is zoo + assert zoo - zoo is S.NaN + assert zoo/zoo is S.NaN + assert zoo**zoo is S.NaN + assert zoo**0 is S.One + assert zoo**2 is zoo + assert 1/zoo is S.Zero + + assert Mul.flatten([S.NegativeOne, oo, S(0)]) == ([S.NaN], [], None) + + +def test_issue_4122(): + x = Symbol('x', nonpositive=True) + assert oo + x is oo + x = Symbol('x', extended_nonpositive=True) + assert (oo + x).is_Add + x = Symbol('x', finite=True) + assert (oo + x).is_Add # x could be imaginary + x = Symbol('x', nonnegative=True) + assert oo + x is oo + x = Symbol('x', extended_nonnegative=True) + assert oo + x is oo + x = Symbol('x', finite=True, real=True) + assert oo + x is oo + + # similarly for negative infinity + x = Symbol('x', nonnegative=True) + assert -oo + x is -oo + x = Symbol('x', extended_nonnegative=True) + assert (-oo + x).is_Add + x = Symbol('x', finite=True) + assert (-oo + x).is_Add + x = Symbol('x', nonpositive=True) + assert -oo + x is -oo + x = Symbol('x', extended_nonpositive=True) + assert -oo + x is -oo + x = Symbol('x', finite=True, real=True) + assert -oo + x is -oo + + +def test_GoldenRatio_expand(): + assert GoldenRatio.expand(func=True) == S.Half + sqrt(5)/2 + + +def test_TribonacciConstant_expand(): + assert TribonacciConstant.expand(func=True) == \ + (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 + + +def test_as_content_primitive(): + assert S.Zero.as_content_primitive() == (1, 0) + assert S.Half.as_content_primitive() == (S.Half, 1) + assert (Rational(-1, 2)).as_content_primitive() == (S.Half, -1) + assert S(3).as_content_primitive() == (3, 1) + assert S(3.1).as_content_primitive() == (1, 3.1) + + +def test_hashing_sympy_integers(): + # Test for issue 5072 + assert {Integer(3)} == {int(3)} + assert hash(Integer(4)) == hash(int(4)) + + +def test_rounding_issue_4172(): + assert int((E**100).round()) == \ + 26881171418161354484126255515800135873611119 + assert int((pi**100).round()) == \ + 51878483143196131920862615246303013562686760680406 + assert int((Rational(1)/EulerGamma**100).round()) == \ + 734833795660954410469466 + + +@XFAIL +def test_mpmath_issues(): + from mpmath.libmp.libmpf import _normalize + import mpmath.libmp as mlib + rnd = mlib.round_nearest + mpf = (0, int(0), -123, -1, 53, rnd) # nan + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + mpf = (0, int(0), -456, -2, 53, rnd) # +inf + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + mpf = (1, int(0), -789, -3, 53, rnd) # -inf + assert _normalize(mpf, 53) != (0, int(0), 0, 0) + + from mpmath.libmp.libmpf import fnan + assert mlib.mpf_eq(fnan, fnan) + + +def test_Catalan_EulerGamma_prec(): + n = GoldenRatio + f = Float(n.n(), 5) + assert f._mpf_ == (0, int(212079), -17, 18) + assert f._prec == 20 + assert n._as_mpf_val(20) == f._mpf_ + + n = EulerGamma + f = Float(n.n(), 5) + assert f._mpf_ == (0, int(302627), -19, 19) + assert f._prec == 20 + assert n._as_mpf_val(20) == f._mpf_ + + +def test_Catalan_rewrite(): + k = Dummy('k', integer=True, nonnegative=True) + assert Catalan.rewrite(Sum).dummy_eq( + Sum((-1)**k/(2*k + 1)**2, (k, 0, oo))) + assert Catalan.rewrite() == Catalan + + +def test_bool_eq(): + assert 0 == False + assert S(0) == False + assert S(0) != S.false + assert 1 == True + assert S.One == True + assert S.One != S.true + + +def test_Float_eq(): + # Floats with different precision should not compare equal + assert Float(.5, 10) != Float(.5, 11) != Float(.5, 1) + # but floats that aren't exact in base-2 still + # don't compare the same because they have different + # underlying mpf values + assert Float(.12, 3) != Float(.12, 4) + assert Float(.12, 3) != .12 + assert 0.12 != Float(.12, 3) + assert Float('.12', 22) != .12 + # issue 11707 + # but Float/Rational -- except for 0 -- + # are exact so Rational(x) = Float(y) only if + # Rational(x) == Rational(Float(y)) + assert Float('1.1') != Rational(11, 10) + assert Rational(11, 10) != Float('1.1') + # coverage + assert not Float(3) == 2 + assert not Float(3) == Float(2) + assert not Float(3) == 3 + assert not Float(2**2) == S.Half + assert Float(2**2) == 4.0 + assert not Float(2**-2) == 1 + assert Float(2**-1) == 0.5 + assert not Float(2*3) == 3 + assert not Float(2*3) == 0.5 + assert Float(2*3) == 6.0 + assert not Float(2*3) == 6 + assert not Float(2*3) == 8 + assert not Float(.75) == Rational(3, 4) + assert Float(.75) == 0.75 + assert Float(5/18) == 5/18 + # 4473 + assert Float(2.) != 3 + assert not Float((0,1,-3)) == S.One/8 + assert Float((0,1,-3)) == 1/8 + assert Float((0,1,-3)) != S.One/9 + # 16196 + assert not 2 == Float(2) # unlike Python + assert t**2 != t**2.0 + + +def test_issue_6640(): + from mpmath.libmp.libmpf import finf, fninf + # fnan is not included because Float no longer returns fnan, + # but otherwise, the same sort of test could apply + assert Float(finf).is_zero is False + assert Float(fninf).is_zero is False + assert bool(Float(0)) is False + + +def test_issue_6349(): + assert Float('23.e3', '')._prec == 10 + assert Float('23e3', '')._prec == 20 + assert Float('23000', '')._prec == 20 + assert Float('-23000', '')._prec == 20 + + +def test_mpf_norm(): + assert mpf_norm((1, 0, 1, 0), 10) == mpf('0')._mpf_ + assert Float._new((1, 0, 1, 0), 10)._mpf_ == mpf('0')._mpf_ + + +def test_latex(): + assert latex(pi) == r"\pi" + assert latex(E) == r"e" + assert latex(GoldenRatio) == r"\phi" + assert latex(TribonacciConstant) == r"\text{TribonacciConstant}" + assert latex(EulerGamma) == r"\gamma" + assert latex(oo) == r"\infty" + assert latex(-oo) == r"-\infty" + assert latex(zoo) == r"\tilde{\infty}" + assert latex(nan) == r"\text{NaN}" + assert latex(I) == r"i" + + +def test_issue_7742(): + assert -oo % 1 is nan + + +def test_simplify_AlgebraicNumber(): + A = AlgebraicNumber + e = 3**(S.One/6)*(3 + (135 + 78*sqrt(3))**Rational(2, 3))/(45 + 26*sqrt(3))**(S.One/3) + assert simplify(A(e)) == A(12) # wester test_C20 + + e = (41 + 29*sqrt(2))**(S.One/5) + assert simplify(A(e)) == A(1 + sqrt(2)) # wester test_C21 + + e = (3 + 4*I)**Rational(3, 2) + assert simplify(A(e)) == A(2 + 11*I) # issue 4401 + + +def test_Float_idempotence(): + x = Float('1.23', '') + y = Float(x) + z = Float(x, 15) + assert same_and_same_prec(y, x) + assert not same_and_same_prec(z, x) + x = Float(10**20) + y = Float(x) + z = Float(x, 15) + assert same_and_same_prec(y, x) + assert not same_and_same_prec(z, x) + + +def test_comp1(): + # sqrt(2) = 1.414213 5623730950... + a = sqrt(2).n(7) + assert comp(a, 1.4142129) is False + assert comp(a, 1.4142130) + # ... + assert comp(a, 1.4142141) + assert comp(a, 1.4142142) is False + assert comp(sqrt(2).n(2), '1.4') + assert comp(sqrt(2).n(2), Float(1.4, 2), '') + assert comp(sqrt(2).n(2), 1.4, '') + assert comp(sqrt(2).n(2), Float(1.4, 3), '') is False + assert comp(sqrt(2) + sqrt(3)*I, 1.4 + 1.7*I, .1) + assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.89, .1) + assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*0.90, .1) + assert comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.07, .1) + assert not comp(sqrt(2) + sqrt(3)*I, (1.5 + 1.7*I)*1.08, .1) + assert [(i, j) + for i in range(130, 150) + for j in range(170, 180) + if comp((sqrt(2)+ I*sqrt(3)).n(3), i/100. + I*j/100.)] == [ + (141, 173), (142, 173)] + raises(ValueError, lambda: comp(t, '1')) + raises(ValueError, lambda: comp(t, 1)) + assert comp(0, 0.0) + assert comp(.5, S.Half) + assert comp(2 + sqrt(2), 2.0 + sqrt(2)) + assert not comp(0, 1) + assert not comp(2, sqrt(2)) + assert not comp(2 + I, 2.0 + sqrt(2)) + assert not comp(2.0 + sqrt(2), 2 + I) + assert not comp(2.0 + sqrt(2), sqrt(3)) + assert comp(1/pi.n(4), 0.3183, 1e-5) + assert not comp(1/pi.n(4), 0.3183, 8e-6) + + +def test_issue_9491(): + assert oo**zoo is nan + + +def test_issue_10063(): + assert 2**Float(3) == Float(8) + + +def test_issue_10020(): + assert oo**I is S.NaN + assert oo**(1 + I) is S.ComplexInfinity + assert oo**(-1 + I) is S.Zero + assert (-oo)**I is S.NaN + assert (-oo)**(-1 + I) is S.Zero + assert oo**t == Pow(oo, t, evaluate=False) + assert (-oo)**t == Pow(-oo, t, evaluate=False) + + +def test_invert_numbers(): + assert S(2).invert(5) == 3 + assert S(2).invert(Rational(5, 2)) == S.Half + assert S(2).invert(5.) == S.Half + assert S(2).invert(S(5)) == 3 + assert S(2.).invert(5) == 0.5 + assert S(sqrt(2)).invert(5) == 1/sqrt(2) + assert S(sqrt(2)).invert(sqrt(3)) == 1/sqrt(2) + + +def test_mod_inverse(): + assert mod_inverse(3, 11) == 4 + assert mod_inverse(5, 11) == 9 + assert mod_inverse(21124921, 521512) == 7713 + assert mod_inverse(124215421, 5125) == 2981 + assert mod_inverse(214, 12515) == 1579 + assert mod_inverse(5823991, 3299) == 1442 + assert mod_inverse(123, 44) == 39 + assert mod_inverse(2, 5) == 3 + assert mod_inverse(-2, 5) == 2 + assert mod_inverse(2, -5) == -2 + assert mod_inverse(-2, -5) == -3 + assert mod_inverse(-3, -7) == -5 + x = Symbol('x') + assert S(2).invert(x) == S.Half + raises(TypeError, lambda: mod_inverse(2, x)) + raises(ValueError, lambda: mod_inverse(2, S.Half)) + raises(ValueError, lambda: mod_inverse(2, cos(1)**2 + sin(1)**2)) + + +def test_golden_ratio_rewrite_as_sqrt(): + assert GoldenRatio.rewrite(sqrt) == S.Half + sqrt(5)*S.Half + + +def test_tribonacci_constant_rewrite_as_sqrt(): + assert TribonacciConstant.rewrite(sqrt) == \ + (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 + + +def test_comparisons_with_unknown_type(): + class Foo: + """ + Class that is unaware of Basic, and relies on both classes returning + the NotImplemented singleton for equivalence to evaluate to False. + + """ + + ni, nf, nr = Integer(3), Float(1.0), Rational(1, 3) + foo = Foo() + + for n in ni, nf, nr, oo, -oo, zoo, nan: + assert n != foo + assert foo != n + assert not n == foo + assert not foo == n + raises(TypeError, lambda: n < foo) + raises(TypeError, lambda: foo > n) + raises(TypeError, lambda: n > foo) + raises(TypeError, lambda: foo < n) + raises(TypeError, lambda: n <= foo) + raises(TypeError, lambda: foo >= n) + raises(TypeError, lambda: n >= foo) + raises(TypeError, lambda: foo <= n) + + class Bar: + """ + Class that considers itself equal to any instance of Number except + infinities and nans, and relies on SymPy types returning the + NotImplemented singleton for symmetric equality relations. + + """ + def __eq__(self, other): + if other in (oo, -oo, zoo, nan): + return False + if isinstance(other, Number): + return True + return NotImplemented + + def __ne__(self, other): + return not self == other + + bar = Bar() + + for n in ni, nf, nr: + assert n == bar + assert bar == n + assert not n != bar + assert not bar != n + + for n in oo, -oo, zoo, nan: + assert n != bar + assert bar != n + assert not n == bar + assert not bar == n + + for n in ni, nf, nr, oo, -oo, zoo, nan: + raises(TypeError, lambda: n < bar) + raises(TypeError, lambda: bar > n) + raises(TypeError, lambda: n > bar) + raises(TypeError, lambda: bar < n) + raises(TypeError, lambda: n <= bar) + raises(TypeError, lambda: bar >= n) + raises(TypeError, lambda: n >= bar) + raises(TypeError, lambda: bar <= n) + + +def test_NumberSymbol_comparison(): + from sympy.core.tests.test_relational import rel_check + rpi = Rational('905502432259640373/288230376151711744') + fpi = Float(float(pi)) + assert rel_check(rpi, fpi) + + +def test_Integer_precision(): + # Make sure Integer inputs for keyword args work + assert Float('1.0', dps=Integer(15))._prec == 53 + assert Float('1.0', precision=Integer(15))._prec == 15 + assert type(Float('1.0', precision=Integer(15))._prec) == int + assert sympify(srepr(Float('1.0', precision=15))) == Float('1.0', precision=15) + + +def test_numpy_to_float(): + from sympy.testing.pytest import skip + from sympy.external import import_module + np = import_module('numpy') + if not np: + skip('numpy not installed. Abort numpy tests.') + + def check_prec_and_relerr(npval, ratval): + prec = np.finfo(npval).nmant + 1 + x = Float(npval) + assert x._prec == prec + y = Float(ratval, precision=prec) + assert abs((x - y)/y) < 2**(-(prec + 1)) + + check_prec_and_relerr(np.float16(2.0/3), Rational(2, 3)) + check_prec_and_relerr(np.float32(2.0/3), Rational(2, 3)) + check_prec_and_relerr(np.float64(2.0/3), Rational(2, 3)) + # extended precision, on some arch/compilers: + x = np.longdouble(2)/3 + check_prec_and_relerr(x, Rational(2, 3)) + y = Float(x, precision=10) + assert same_and_same_prec(y, Float(Rational(2, 3), precision=10)) + + raises(TypeError, lambda: Float(np.complex64(1+2j))) + raises(TypeError, lambda: Float(np.complex128(1+2j))) + + +def test_Integer_ceiling_floor(): + a = Integer(4) + + assert a.floor() == a + assert a.ceiling() == a + + +def test_ComplexInfinity(): + assert zoo.floor() is zoo + assert zoo.ceiling() is zoo + assert zoo**zoo is S.NaN + + +def test_Infinity_floor_ceiling_power(): + assert oo.floor() is oo + assert oo.ceiling() is oo + assert oo**S.NaN is S.NaN + assert oo**zoo is S.NaN + + +def test_One_power(): + assert S.One**12 is S.One + assert S.NegativeOne**S.NaN is S.NaN + + +def test_NegativeInfinity(): + assert (-oo).floor() is -oo + assert (-oo).ceiling() is -oo + assert (-oo)**11 is -oo + assert (-oo)**12 is oo + + +def test_issue_6133(): + raises(TypeError, lambda: (-oo < None)) + raises(TypeError, lambda: (S(-2) < None)) + raises(TypeError, lambda: (oo < None)) + raises(TypeError, lambda: (oo > None)) + raises(TypeError, lambda: (S(2) < None)) + + +def test_abc(): + x = numbers.Float(5) + assert(isinstance(x, nums.Number)) + assert(isinstance(x, numbers.Number)) + assert(isinstance(x, nums.Real)) + y = numbers.Rational(1, 3) + assert(isinstance(y, nums.Number)) + assert(y.numerator == 1) + assert(y.denominator == 3) + assert(isinstance(y, nums.Rational)) + z = numbers.Integer(3) + assert(isinstance(z, nums.Number)) + assert(isinstance(z, numbers.Number)) + assert(isinstance(z, nums.Rational)) + assert(isinstance(z, numbers.Rational)) + assert(isinstance(z, nums.Integral)) + + +def test_floordiv(): + assert S(2)//S.Half == 4 + + +def test_negation(): + assert -S.Zero is S.Zero + assert -Float(0) is not S.Zero and -Float(0) == 0.0 + + +def test_exponentiation_of_0(): + x = Symbol('x') + assert 0**-x == zoo**x + assert unchanged(Pow, 0, x) + x = Symbol('x', zero=True) + assert 0**-x == S.One + assert 0**x == S.One + + +def test_int_valued(): + x = Symbol('x') + assert int_valued(x) == False + assert int_valued(S.Half) == False + assert int_valued(S.One) == True + assert int_valued(Float(1)) == True + assert int_valued(Float(1.1)) == False + assert int_valued(pi) == False + + +def test_equal_valued(): + x = Symbol('x') + + equal_values = [ + [1, 1.0, S(1), S(1.0), S(1).n(5)], + [2, 2.0, S(2), S(2.0), S(2).n(5)], + [-1, -1.0, -S(1), -S(1.0), -S(1).n(5)], + [0.5, S(0.5), S(1)/2], + [-0.5, -S(0.5), -S(1)/2], + [0, 0.0, S(0), S(0.0), S(0).n()], + [pi], [pi.n()], # <-- not equal + [S(1)/10], [0.1, S(0.1)], # <-- not equal + [S(0.1).n(5)], + [oo], + [cos(x/2)], [cos(0.5*x)], # <-- no recursion + ] + + for m, values_m in enumerate(equal_values): + for value_i in values_m: + + # All values in same list equal + for value_j in values_m: + assert equal_valued(value_i, value_j) is True + + # Not equal to anything in any other list: + for n, values_n in enumerate(equal_values): + if n == m: + continue + for value_j in values_n: + assert equal_valued(value_i, value_j) is False + + +def test_all_close(): + x = Symbol('x') + y = Symbol('y') + z = Symbol('z') + assert all_close(2, 2) is True + assert all_close(2, 2.0000) is True + assert all_close(2, 2.0001) is False + assert all_close(1/3, 1/3.0001) is False + assert all_close(1/3, 1/3.0001, 1e-3, 1e-3) is True + assert all_close(1/3, Rational(1, 3)) is True + assert all_close(0.1*exp(0.2*x), exp(x/5)/10) is True + # The expressions should be structurally the same modulo identity: + assert all_close(1.4142135623730951, sqrt(2)) is False + assert all_close(1.4142135623730951, sqrt(2).evalf()) is True + assert all_close(x + 1e-20, x) is True + # We should be able to match terms of an Add/Mul in any order + assert all_close(Add(1, 2, evaluate=False), Add(2, 1, evaluate=False)) + # coverage + assert not all_close(2*x, 3*x) + assert all_close(2*x, 3*x, 1) + assert not all_close(2*x, 3*x, 0, 0.5) + assert all_close(2*x, 3*x, 0, 1) + assert not all_close(y*x, z*x) + assert all_close(2*x*exp(1.0*x), 2.0*x*exp(x)) + assert not all_close(2*x*exp(1.0*x), 2.0*x*exp(2.*x)) + assert all_close(x + 2.*y, 1.*x + 2*y) + assert all_close(x + exp(2.*x)*y, 1.*x + exp(2*x)*y) + assert not all_close(x + exp(2.*x)*y, 1.*x + 2*exp(2*x)*y) + assert not all_close(x + exp(2.*x)*y, 1.*x + exp(3*x)*y) + assert not all_close(x + 2.*y, 1.*x + 3*y) diff --git a/shared/package-files/4a/4af65a28eaac1b454ba01ffc4fa53044061a66bd47bc707e3c1c485c23260b71/fix_print.cpython-311.pyc b/shared/package-files/4a/4af65a28eaac1b454ba01ffc4fa53044061a66bd47bc707e3c1c485c23260b71/fix_print.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..277bd17413c373ff631c029e294a8a2bcbe45b6e Binary files /dev/null and b/shared/package-files/4a/4af65a28eaac1b454ba01ffc4fa53044061a66bd47bc707e3c1c485c23260b71/fix_print.cpython-311.pyc differ diff --git a/shared/package-files/4a/4af73e70c3f1beee3720a8cd00b78e7c60da48181e604b6c6893be70caf41b36/random_graphs.cpython-311.pyc b/shared/package-files/4a/4af73e70c3f1beee3720a8cd00b78e7c60da48181e604b6c6893be70caf41b36/random_graphs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4654b7258a5260957859c8aefb2560a2ed03438c Binary files /dev/null and b/shared/package-files/4a/4af73e70c3f1beee3720a8cd00b78e7c60da48181e604b6c6893be70caf41b36/random_graphs.cpython-311.pyc differ diff --git a/shared/package-files/55/5506003eb9118d31b7f670fdefdaa23e0243a19e4a1ff461fc62015a8aa35b95/ast.cpython-311.pyc b/shared/package-files/55/5506003eb9118d31b7f670fdefdaa23e0243a19e4a1ff461fc62015a8aa35b95/ast.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a2d75156e92acc9cc6703bcbfbd75569c2d125 Binary files /dev/null and b/shared/package-files/55/5506003eb9118d31b7f670fdefdaa23e0243a19e4a1ff461fc62015a8aa35b95/ast.cpython-311.pyc differ diff --git a/shared/package-files/55/550d11e4eb1d25b69ab176396b86666e86566018def6378673bff6d25d6a1697/_tool_component.py b/shared/package-files/55/550d11e4eb1d25b69ab176396b86666e86566018def6378673bff6d25d6a1697/_tool_component.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2ddd20454870faa3657d7bb15934a19093aaee --- /dev/null +++ b/shared/package-files/55/550d11e4eb1d25b69ab176396b86666e86566018def6378673bff6d25d6a1697/_tool_component.py @@ -0,0 +1,123 @@ +# DO NOT EDIT! This file was generated by jschema_to_python version 0.0.1.dev29, +# with extension for dataclasses and type annotation. + +from __future__ import annotations + +import dataclasses +from typing import Any, List, Literal, Optional + +from torch.onnx._internal.diagnostics.infra.sarif import ( + _artifact_location, + _multiformat_message_string, + _property_bag, + _reporting_descriptor, + _tool_component_reference, + _translation_metadata, +) + + +@dataclasses.dataclass +class ToolComponent(object): + """A component, such as a plug-in or the driver, of the analysis tool that was run.""" + + name: str = dataclasses.field(metadata={"schema_property_name": "name"}) + associated_component: Optional[_tool_component_reference.ToolComponentReference] = ( + dataclasses.field( + default=None, metadata={"schema_property_name": "associatedComponent"} + ) + ) + contents: List[Literal["localizedData", "nonLocalizedData"]] = dataclasses.field( + default_factory=lambda: ["localizedData", "nonLocalizedData"], + metadata={"schema_property_name": "contents"}, + ) + dotted_quad_file_version: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "dottedQuadFileVersion"} + ) + download_uri: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "downloadUri"} + ) + full_description: Optional[_multiformat_message_string.MultiformatMessageString] = ( + dataclasses.field( + default=None, metadata={"schema_property_name": "fullDescription"} + ) + ) + full_name: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "fullName"} + ) + global_message_strings: Any = dataclasses.field( + default=None, metadata={"schema_property_name": "globalMessageStrings"} + ) + guid: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "guid"} + ) + information_uri: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "informationUri"} + ) + is_comprehensive: Optional[bool] = dataclasses.field( + default=None, metadata={"schema_property_name": "isComprehensive"} + ) + language: str = dataclasses.field( + default="en-US", metadata={"schema_property_name": "language"} + ) + localized_data_semantic_version: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "localizedDataSemanticVersion"} + ) + locations: Optional[List[_artifact_location.ArtifactLocation]] = dataclasses.field( + default=None, metadata={"schema_property_name": "locations"} + ) + minimum_required_localized_data_semantic_version: Optional[str] = dataclasses.field( + default=None, + metadata={ + "schema_property_name": "minimumRequiredLocalizedDataSemanticVersion" + }, + ) + notifications: Optional[List[_reporting_descriptor.ReportingDescriptor]] = ( + dataclasses.field( + default=None, metadata={"schema_property_name": "notifications"} + ) + ) + organization: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "organization"} + ) + product: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "product"} + ) + product_suite: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "productSuite"} + ) + properties: Optional[_property_bag.PropertyBag] = dataclasses.field( + default=None, metadata={"schema_property_name": "properties"} + ) + release_date_utc: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "releaseDateUtc"} + ) + rules: Optional[List[_reporting_descriptor.ReportingDescriptor]] = ( + dataclasses.field(default=None, metadata={"schema_property_name": "rules"}) + ) + semantic_version: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "semanticVersion"} + ) + short_description: Optional[ + _multiformat_message_string.MultiformatMessageString + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "shortDescription"} + ) + supported_taxonomies: Optional[ + List[_tool_component_reference.ToolComponentReference] + ] = dataclasses.field( + default=None, metadata={"schema_property_name": "supportedTaxonomies"} + ) + taxa: Optional[List[_reporting_descriptor.ReportingDescriptor]] = dataclasses.field( + default=None, metadata={"schema_property_name": "taxa"} + ) + translation_metadata: Optional[_translation_metadata.TranslationMetadata] = ( + dataclasses.field( + default=None, metadata={"schema_property_name": "translationMetadata"} + ) + ) + version: Optional[str] = dataclasses.field( + default=None, metadata={"schema_property_name": "version"} + ) + + +# flake8: noqa diff --git a/shared/package-files/55/55375e160147fe4f2d56d5dba32fe8e4fc7514919995dcc9f9346a1c2157b76a/threshold_meta.h b/shared/package-files/55/55375e160147fe4f2d56d5dba32fe8e4fc7514919995dcc9f9346a1c2157b76a/threshold_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..17f263cf7853d94049a661e8d29741e5e8ecc073 --- /dev/null +++ b/shared/package-files/55/55375e160147fe4f2d56d5dba32fe8e4fc7514919995dcc9f9346a1c2157b76a/threshold_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_threshold : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Scalar & threshold, const at::Scalar & value); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/55/553c0ce39014fff454bdd4454bd53c6599890375b5fdd528ac19334c9221b650/taskgroups.py b/shared/package-files/55/553c0ce39014fff454bdd4454bd53c6599890375b5fdd528ac19334c9221b650/taskgroups.py new file mode 100644 index 0000000000000000000000000000000000000000..bfdbe63049f9bdb7e068a8a60aec1b2794b4d3d2 --- /dev/null +++ b/shared/package-files/55/553c0ce39014fff454bdd4454bd53c6599890375b5fdd528ac19334c9221b650/taskgroups.py @@ -0,0 +1,234 @@ +# Adapted with permission from the EdgeDB project; +# license: PSFL. + + +__all__ = ["TaskGroup"] + +from . import events +from . import exceptions +from . import tasks + + +class TaskGroup: + """Asynchronous context manager for managing groups of tasks. + + Example use: + + async with asyncio.TaskGroup() as group: + task1 = group.create_task(some_coroutine(...)) + task2 = group.create_task(other_coroutine(...)) + print("Both tasks have completed now.") + + All tasks are awaited when the context manager exits. + + Any exceptions other than `asyncio.CancelledError` raised within + a task will cancel all remaining tasks and wait for them to exit. + The exceptions are then combined and raised as an `ExceptionGroup`. + """ + def __init__(self): + self._entered = False + self._exiting = False + self._aborting = False + self._loop = None + self._parent_task = None + self._parent_cancel_requested = False + self._tasks = set() + self._errors = [] + self._base_error = None + self._on_completed_fut = None + + def __repr__(self): + info = [''] + if self._tasks: + info.append(f'tasks={len(self._tasks)}') + if self._errors: + info.append(f'errors={len(self._errors)}') + if self._aborting: + info.append('cancelling') + elif self._entered: + info.append('entered') + + info_str = ' '.join(info) + return f'' + + async def __aenter__(self): + if self._entered: + raise RuntimeError( + f"TaskGroup {self!r} has already been entered") + if self._loop is None: + self._loop = events.get_running_loop() + self._parent_task = tasks.current_task(self._loop) + if self._parent_task is None: + raise RuntimeError( + f'TaskGroup {self!r} cannot determine the parent task') + self._entered = True + + return self + + async def __aexit__(self, et, exc, tb): + self._exiting = True + + if (exc is not None and + self._is_base_error(exc) and + self._base_error is None): + self._base_error = exc + + propagate_cancellation_error = \ + exc if et is exceptions.CancelledError else None + if self._parent_cancel_requested: + # If this flag is set we *must* call uncancel(). + if self._parent_task.uncancel() == 0: + # If there are no pending cancellations left, + # don't propagate CancelledError. + propagate_cancellation_error = None + + if et is not None: + if not self._aborting: + # Our parent task is being cancelled: + # + # async with TaskGroup() as g: + # g.create_task(...) + # await ... # <- CancelledError + # + # or there's an exception in "async with": + # + # async with TaskGroup() as g: + # g.create_task(...) + # 1 / 0 + # + self._abort() + + # We use while-loop here because "self._on_completed_fut" + # can be cancelled multiple times if our parent task + # is being cancelled repeatedly (or even once, when + # our own cancellation is already in progress) + while self._tasks: + if self._on_completed_fut is None: + self._on_completed_fut = self._loop.create_future() + + try: + await self._on_completed_fut + except exceptions.CancelledError as ex: + if not self._aborting: + # Our parent task is being cancelled: + # + # async def wrapper(): + # async with TaskGroup() as g: + # g.create_task(foo) + # + # "wrapper" is being cancelled while "foo" is + # still running. + propagate_cancellation_error = ex + self._abort() + + self._on_completed_fut = None + + assert not self._tasks + + if self._base_error is not None: + raise self._base_error + + # Propagate CancelledError if there is one, except if there + # are other errors -- those have priority. + if propagate_cancellation_error and not self._errors: + raise propagate_cancellation_error + + if et is not None and et is not exceptions.CancelledError: + self._errors.append(exc) + + if self._errors: + # Exceptions are heavy objects that can have object + # cycles (bad for GC); let's not keep a reference to + # a bunch of them. + try: + me = BaseExceptionGroup('unhandled errors in a TaskGroup', self._errors) + raise me from None + finally: + self._errors = None + + def create_task(self, coro, *, name=None, context=None): + """Create a new task in this group and return it. + + Similar to `asyncio.create_task`. + """ + if not self._entered: + raise RuntimeError(f"TaskGroup {self!r} has not been entered") + if self._exiting and not self._tasks: + raise RuntimeError(f"TaskGroup {self!r} is finished") + if self._aborting: + raise RuntimeError(f"TaskGroup {self!r} is shutting down") + if context is None: + task = self._loop.create_task(coro) + else: + task = self._loop.create_task(coro, context=context) + tasks._set_task_name(task, name) + task.add_done_callback(self._on_task_done) + self._tasks.add(task) + return task + + # Since Python 3.8 Tasks propagate all exceptions correctly, + # except for KeyboardInterrupt and SystemExit which are + # still considered special. + + def _is_base_error(self, exc: BaseException) -> bool: + assert isinstance(exc, BaseException) + return isinstance(exc, (SystemExit, KeyboardInterrupt)) + + def _abort(self): + self._aborting = True + + for t in self._tasks: + if not t.done(): + t.cancel() + + def _on_task_done(self, task): + self._tasks.discard(task) + + if self._on_completed_fut is not None and not self._tasks: + if not self._on_completed_fut.done(): + self._on_completed_fut.set_result(True) + + if task.cancelled(): + return + + exc = task.exception() + if exc is None: + return + + self._errors.append(exc) + if self._is_base_error(exc) and self._base_error is None: + self._base_error = exc + + if self._parent_task.done(): + # Not sure if this case is possible, but we want to handle + # it anyways. + self._loop.call_exception_handler({ + 'message': f'Task {task!r} has errored out but its parent ' + f'task {self._parent_task} is already completed', + 'exception': exc, + 'task': task, + }) + return + + if not self._aborting and not self._parent_cancel_requested: + # If parent task *is not* being cancelled, it means that we want + # to manually cancel it to abort whatever is being run right now + # in the TaskGroup. But we want to mark parent task as + # "not cancelled" later in __aexit__. Example situation that + # we need to handle: + # + # async def foo(): + # try: + # async with TaskGroup() as g: + # g.create_task(crash_soon()) + # await something # <- this needs to be canceled + # # by the TaskGroup, e.g. + # # foo() needs to be cancelled + # except Exception: + # # Ignore any exceptions raised in the TaskGroup + # pass + # await something_else # this line has to be called + # # after TaskGroup is finished. + self._abort() + self._parent_cancel_requested = True + self._parent_task.cancel() diff --git a/shared/package-files/55/553d766bf4c977437c772306e8df4271653594d0a60df692bba5064c354f9c2d/_scaled_dot_product_attention_math_for_mps_ops.h b/shared/package-files/55/553d766bf4c977437c772306e8df4271653594d0a60df692bba5064c354f9c2d/_scaled_dot_product_attention_math_for_mps_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..afafa8f7d8edaf1153c9ca89d53cf5c8bd20780e --- /dev/null +++ b/shared/package-files/55/553d766bf4c977437c772306e8df4271653594d0a60df692bba5064c354f9c2d/_scaled_dot_product_attention_math_for_mps_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _scaled_dot_product_attention_math_for_mps { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const ::std::optional &, double, bool, const ::std::optional &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_scaled_dot_product_attention_math_for_mps"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_scaled_dot_product_attention_math_for_mps(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & attn_mask, double dropout_p, bool is_causal, const ::std::optional & dropout_mask, ::std::optional scale); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & attn_mask, double dropout_p, bool is_causal, const ::std::optional & dropout_mask, ::std::optional scale); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/55/555e0c43e01c97d45b570a7f13aedb654f4d2e8e4fa26cd333d5dc63f287ceaf/_sfdp_pattern_18.cpython-311.pyc b/shared/package-files/55/555e0c43e01c97d45b570a7f13aedb654f4d2e8e4fa26cd333d5dc63f287ceaf/_sfdp_pattern_18.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a8f882d0e7efb08aaf4ea0fc0ac6c8f38a4afc1 Binary files /dev/null and b/shared/package-files/55/555e0c43e01c97d45b570a7f13aedb654f4d2e8e4fa26cd333d5dc63f287ceaf/_sfdp_pattern_18.cpython-311.pyc differ diff --git a/shared/package-files/55/5575a0b345e375e1466c7cae8d4e29f739f6510c6e4770203a29037c29603418/glu_backward_ops.h b/shared/package-files/55/5575a0b345e375e1466c7cae8d4e29f739f6510c6e4770203a29037c29603418/glu_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..407f42659ed5dc610443fc577705cb08e1a66350 --- /dev/null +++ b/shared/package-files/55/5575a0b345e375e1466c7cae8d4e29f739f6510c6e4770203a29037c29603418/glu_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API glu_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::glu_backward"; + static constexpr const char* overload_name = "grad_input"; + static constexpr const char* schema_str = "glu_backward.grad_input(Tensor grad_output, Tensor self, int dim, *, Tensor(a!) grad_input) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, int64_t dim, at::Tensor & grad_input); +}; + +struct TORCH_API glu_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::glu_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, int64_t dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/55/5589772b889fff6de2212f817bc301486d0e299a3eeb18311e2376da569e032a/test_c_parser.py b/shared/package-files/55/5589772b889fff6de2212f817bc301486d0e299a3eeb18311e2376da569e032a/test_c_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b74622e40030cba180cb4fc354216ccca119baec --- /dev/null +++ b/shared/package-files/55/5589772b889fff6de2212f817bc301486d0e299a3eeb18311e2376da569e032a/test_c_parser.py @@ -0,0 +1,5248 @@ +from sympy.parsing.sym_expr import SymPyExpression +from sympy.testing.pytest import raises, XFAIL +from sympy.external import import_module + +cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) + +if cin: + from sympy.codegen.ast import (Variable, String, Return, + FunctionDefinition, Integer, Float, Declaration, CodeBlock, + FunctionPrototype, FunctionCall, NoneToken, Assignment, Type, + IntBaseType, SignedIntType, UnsignedIntType, FloatType, + AddAugmentedAssignment, SubAugmentedAssignment, + MulAugmentedAssignment, DivAugmentedAssignment, + ModAugmentedAssignment, While) + from sympy.codegen.cnodes import (PreDecrement, PostDecrement, + PreIncrement, PostIncrement) + from sympy.core import (Add, Mul, Mod, Pow, Rational, + StrictLessThan, LessThan, StrictGreaterThan, GreaterThan, + Equality, Unequality) + from sympy.logic.boolalg import And, Not, Or + from sympy.core.symbol import Symbol + from sympy.logic.boolalg import (false, true) + import os + + def test_variable(): + c_src1 = ( + 'int a;' + '\n' + + 'int b;' + '\n' + ) + c_src2 = ( + 'float a;' + '\n' + + 'float b;' + '\n' + ) + c_src3 = ( + 'int a;' + '\n' + + 'float b;' + '\n' + + 'int c;' + ) + c_src4 = ( + 'int x = 1, y = 6.78;' + '\n' + + 'float p = 2, q = 9.67;' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + + assert res1[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ) + + assert res1[1] == Declaration( + Variable( + Symbol('b'), + type=IntBaseType(String('intc')) + ) + ) + + assert res2[0] == Declaration( + Variable( + Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ) + assert res2[1] == Declaration( + Variable( + Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ) + + assert res3[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ) + + assert res3[1] == Declaration( + Variable( + Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ) + + assert res3[2] == Declaration( + Variable( + Symbol('c'), + type=IntBaseType(String('intc')) + ) + ) + + assert res4[0] == Declaration( + Variable( + Symbol('x'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res4[1] == Declaration( + Variable( + Symbol('y'), + type=IntBaseType(String('intc')), + value=Integer(6) + ) + ) + + assert res4[2] == Declaration( + Variable( + Symbol('p'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.0', precision=53) + ) + ) + + assert res4[3] == Declaration( + Variable( + Symbol('q'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('9.67', precision=53) + ) + ) + + + def test_int(): + c_src1 = 'int a = 1;' + c_src2 = ( + 'int a = 1;' + '\n' + + 'int b = 2;' + '\n' + ) + c_src3 = 'int a = 2.345, b = 5.67;' + c_src4 = 'int p = 6, q = 23.45;' + c_src5 = "int x = '0', y = 'a';" + c_src6 = "int r = true, s = false;" + + # cin.TypeKind.UCHAR + c_src_type1 = ( + "signed char a = 1, b = 5.1;" + ) + + # cin.TypeKind.SHORT + c_src_type2 = ( + "short a = 1, b = 5.1;" + "signed short c = 1, d = 5.1;" + "short int e = 1, f = 5.1;" + "signed short int g = 1, h = 5.1;" + ) + + # cin.TypeKind.INT + c_src_type3 = ( + "signed int a = 1, b = 5.1;" + "int c = 1, d = 5.1;" + ) + + # cin.TypeKind.LONG + c_src_type4 = ( + "long a = 1, b = 5.1;" + "long int c = 1, d = 5.1;" + ) + + # cin.TypeKind.UCHAR + c_src_type5 = "unsigned char a = 1, b = 5.1;" + + # cin.TypeKind.USHORT + c_src_type6 = ( + "unsigned short a = 1, b = 5.1;" + "unsigned short int c = 1, d = 5.1;" + ) + + # cin.TypeKind.UINT + c_src_type7 = "unsigned int a = 1, b = 5.1;" + + # cin.TypeKind.ULONG + c_src_type8 = ( + "unsigned long a = 1, b = 5.1;" + "unsigned long int c = 1, d = 5.1;" + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + res6 = SymPyExpression(c_src6, 'c').return_expr() + + res_type1 = SymPyExpression(c_src_type1, 'c').return_expr() + res_type2 = SymPyExpression(c_src_type2, 'c').return_expr() + res_type3 = SymPyExpression(c_src_type3, 'c').return_expr() + res_type4 = SymPyExpression(c_src_type4, 'c').return_expr() + res_type5 = SymPyExpression(c_src_type5, 'c').return_expr() + res_type6 = SymPyExpression(c_src_type6, 'c').return_expr() + res_type7 = SymPyExpression(c_src_type7, 'c').return_expr() + res_type8 = SymPyExpression(c_src_type8, 'c').return_expr() + + assert res1[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res2[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res2[1] == Declaration( + Variable( + Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res3[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res3[1] == Declaration( + Variable( + Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(5) + ) + ) + + assert res4[0] == Declaration( + Variable( + Symbol('p'), + type=IntBaseType(String('intc')), + value=Integer(6) + ) + ) + + assert res4[1] == Declaration( + Variable( + Symbol('q'), + type=IntBaseType(String('intc')), + value=Integer(23) + ) + ) + + assert res5[0] == Declaration( + Variable( + Symbol('x'), + type=IntBaseType(String('intc')), + value=Integer(48) + ) + ) + + assert res5[1] == Declaration( + Variable( + Symbol('y'), + type=IntBaseType(String('intc')), + value=Integer(97) + ) + ) + + assert res6[0] == Declaration( + Variable( + Symbol('r'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res6[1] == Declaration( + Variable( + Symbol('s'), + type=IntBaseType(String('intc')), + value=Integer(0) + ) + ) + + assert res_type1[0] == Declaration( + Variable( + Symbol('a'), + type=SignedIntType( + String('int8'), + nbits=Integer(8) + ), + value=Integer(1) + ) + ) + + assert res_type1[1] == Declaration( + Variable( + Symbol('b'), + type=SignedIntType( + String('int8'), + nbits=Integer(8) + ), + value=Integer(5) + ) + ) + + assert res_type2[0] == Declaration( + Variable( + Symbol('a'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type2[1] == Declaration( + Variable( + Symbol('b'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type2[2] == Declaration( + Variable(Symbol('c'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type2[3] == Declaration( + Variable( + Symbol('d'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type2[4] == Declaration( + Variable( + Symbol('e'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type2[5] == Declaration( + Variable( + Symbol('f'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type2[6] == Declaration( + Variable( + Symbol('g'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type2[7] == Declaration( + Variable( + Symbol('h'), + type=SignedIntType( + String('int16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type3[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res_type3[1] == Declaration( + Variable( + Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(5) + ) + ) + + assert res_type3[2] == Declaration( + Variable( + Symbol('c'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res_type3[3] == Declaration( + Variable( + Symbol('d'), + type=IntBaseType(String('intc')), + value=Integer(5) + ) + ) + + assert res_type4[0] == Declaration( + Variable( + Symbol('a'), + type=SignedIntType( + String('int64'), + nbits=Integer(64) + ), + value=Integer(1) + ) + ) + + assert res_type4[1] == Declaration( + Variable( + Symbol('b'), + type=SignedIntType( + String('int64'), + nbits=Integer(64) + ), + value=Integer(5) + ) + ) + + assert res_type4[2] == Declaration( + Variable( + Symbol('c'), + type=SignedIntType( + String('int64'), + nbits=Integer(64) + ), + value=Integer(1) + ) + ) + + assert res_type4[3] == Declaration( + Variable( + Symbol('d'), + type=SignedIntType( + String('int64'), + nbits=Integer(64) + ), + value=Integer(5) + ) + ) + + assert res_type5[0] == Declaration( + Variable( + Symbol('a'), + type=UnsignedIntType( + String('uint8'), + nbits=Integer(8) + ), + value=Integer(1) + ) + ) + + assert res_type5[1] == Declaration( + Variable( + Symbol('b'), + type=UnsignedIntType( + String('uint8'), + nbits=Integer(8) + ), + value=Integer(5) + ) + ) + + assert res_type6[0] == Declaration( + Variable( + Symbol('a'), + type=UnsignedIntType( + String('uint16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type6[1] == Declaration( + Variable( + Symbol('b'), + type=UnsignedIntType( + String('uint16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type6[2] == Declaration( + Variable( + Symbol('c'), + type=UnsignedIntType( + String('uint16'), + nbits=Integer(16) + ), + value=Integer(1) + ) + ) + + assert res_type6[3] == Declaration( + Variable( + Symbol('d'), + type=UnsignedIntType( + String('uint16'), + nbits=Integer(16) + ), + value=Integer(5) + ) + ) + + assert res_type7[0] == Declaration( + Variable( + Symbol('a'), + type=UnsignedIntType( + String('uint32'), + nbits=Integer(32) + ), + value=Integer(1) + ) + ) + + assert res_type7[1] == Declaration( + Variable( + Symbol('b'), + type=UnsignedIntType( + String('uint32'), + nbits=Integer(32) + ), + value=Integer(5) + ) + ) + + assert res_type8[0] == Declaration( + Variable( + Symbol('a'), + type=UnsignedIntType( + String('uint64'), + nbits=Integer(64) + ), + value=Integer(1) + ) + ) + + assert res_type8[1] == Declaration( + Variable( + Symbol('b'), + type=UnsignedIntType( + String('uint64'), + nbits=Integer(64) + ), + value=Integer(5) + ) + ) + + assert res_type8[2] == Declaration( + Variable( + Symbol('c'), + type=UnsignedIntType( + String('uint64'), + nbits=Integer(64) + ), + value=Integer(1) + ) + ) + + assert res_type8[3] == Declaration( + Variable( + Symbol('d'), + type=UnsignedIntType( + String('uint64'), + nbits=Integer(64) + ), + value=Integer(5) + ) + ) + + + def test_float(): + c_src1 = 'float a = 1.0;' + c_src2 = ( + 'float a = 1.25;' + '\n' + + 'float b = 2.39;' + '\n' + ) + c_src3 = 'float x = 1, y = 2;' + c_src4 = 'float p = 5, e = 7.89;' + c_src5 = 'float r = true, s = false;' + + # cin.TypeKind.FLOAT + c_src_type1 = 'float x = 1, y = 2.5;' + + # cin.TypeKind.DOUBLE + c_src_type2 = 'double x = 1, y = 2.5;' + + # cin.TypeKind.LONGDOUBLE + c_src_type3 = 'long double x = 1, y = 2.5;' + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + + res_type1 = SymPyExpression(c_src_type1, 'c').return_expr() + res_type2 = SymPyExpression(c_src_type2, 'c').return_expr() + res_type3 = SymPyExpression(c_src_type3, 'c').return_expr() + + assert res1[0] == Declaration( + Variable( + Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res2[0] == Declaration( + Variable( + Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.25', precision=53) + ) + ) + + assert res2[1] == Declaration( + Variable( + Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.3900000000000001', precision=53) + ) + ) + + assert res3[0] == Declaration( + Variable( + Symbol('x'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res3[1] == Declaration( + Variable( + Symbol('y'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.0', precision=53) + ) + ) + + assert res4[0] == Declaration( + Variable( + Symbol('p'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('5.0', precision=53) + ) + ) + + assert res4[1] == Declaration( + Variable( + Symbol('e'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('7.89', precision=53) + ) + ) + + assert res5[0] == Declaration( + Variable( + Symbol('r'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res5[1] == Declaration( + Variable( + Symbol('s'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('0.0', precision=53) + ) + ) + + assert res_type1[0] == Declaration( + Variable( + Symbol('x'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res_type1[1] == Declaration( + Variable( + Symbol('y'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.5', precision=53) + ) + ) + assert res_type2[0] == Declaration( + Variable( + Symbol('x'), + type=FloatType( + String('float64'), + nbits=Integer(64), + nmant=Integer(52), + nexp=Integer(11) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res_type2[1] == Declaration( + Variable( + Symbol('y'), + type=FloatType( + String('float64'), + nbits=Integer(64), + nmant=Integer(52), + nexp=Integer(11) + ), + value=Float('2.5', precision=53) + ) + ) + + assert res_type3[0] == Declaration( + Variable( + Symbol('x'), + type=FloatType( + String('float80'), + nbits=Integer(80), + nmant=Integer(63), + nexp=Integer(15) + ), + value=Float('1.0', precision=53) + ) + ) + + assert res_type3[1] == Declaration( + Variable( + Symbol('y'), + type=FloatType( + String('float80'), + nbits=Integer(80), + nmant=Integer(63), + nexp=Integer(15) + ), + value=Float('2.5', precision=53) + ) + ) + + + def test_bool(): + c_src1 = ( + 'bool a = true, b = false;' + ) + + c_src2 = ( + 'bool a = 1, b = 0;' + ) + + c_src3 = ( + 'bool a = 10, b = 20;' + ) + + c_src4 = ( + 'bool a = 19.1, b = 9.0, c = 0.0;' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + + assert res1[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=true + ) + ) + + assert res1[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=false + ) + ) + + assert res2[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=true) + ) + + assert res2[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=false + ) + ) + + assert res3[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=true + ) + ) + + assert res3[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=true + ) + ) + + assert res4[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=true) + ) + + assert res4[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=true + ) + ) + + assert res4[2] == Declaration( + Variable(Symbol('c'), + type=Type(String('bool')), + value=false + ) + ) + + @XFAIL # this is expected to fail because of a bug in the C parser. + def test_function(): + c_src1 = ( + 'void fun1()' + '\n' + + '{' + '\n' + + 'int a;' + '\n' + + '}' + ) + c_src2 = ( + 'int fun2()' + '\n' + + '{'+ '\n' + + 'int a;' + '\n' + + 'return a;' + '\n' + + '}' + ) + c_src3 = ( + 'float fun3()' + '\n' + + '{' + '\n' + + 'float b;' + '\n' + + 'return b;' + '\n' + + '}' + ) + c_src4 = ( + 'float fun4()' + '\n' + + '{}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + + assert res1[0] == FunctionDefinition( + NoneToken(), + name=String('fun1'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ) + ) + ) + + assert res2[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun2'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Return('a') + ) + ) + + assert res3[0] == FunctionDefinition( + FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + name=String('fun3'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Return('b') + ) + ) + + assert res4[0] == FunctionPrototype( + FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + name=String('fun4'), + parameters=() + ) + + @XFAIL # this is expected to fail because of a bug in the C parser. + def test_parameters(): + c_src1 = ( + 'void fun1( int a)' + '\n' + + '{' + '\n' + + 'int i;' + '\n' + + '}' + ) + c_src2 = ( + 'int fun2(float x, float y)' + '\n' + + '{'+ '\n' + + 'int a;' + '\n' + + 'return a;' + '\n' + + '}' + ) + c_src3 = ( + 'float fun3(int p, float q, int r)' + '\n' + + '{' + '\n' + + 'float b;' + '\n' + + 'return b;' + '\n' + + '}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + + assert res1[0] == FunctionDefinition( + NoneToken(), + name=String('fun1'), + parameters=( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ), + ), + body=CodeBlock( + Declaration( + Variable( + Symbol('i'), + type=IntBaseType(String('intc')) + ) + ) + ) + ) + + assert res2[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun2'), + parameters=( + Variable( + Symbol('x'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ), + Variable( + Symbol('y'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + body=CodeBlock( + Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Return('a') + ) + ) + + assert res3[0] == FunctionDefinition( + FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + name=String('fun3'), + parameters=( + Variable( + Symbol('p'), + type=IntBaseType(String('intc')) + ), + Variable( + Symbol('q'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ), + Variable( + Symbol('r'), + type=IntBaseType(String('intc')) + ) + ), + body=CodeBlock( + Declaration( + Variable( + Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Return('b') + ) + ) + + @XFAIL # this is expected to fail because of a bug in the C parser. + def test_function_call(): + c_src1 = ( + 'int fun1(int x)' + '\n' + + '{' + '\n' + + 'return x;' + '\n' + + '}' + '\n' + + 'void caller()' + '\n' + + '{' + '\n' + + 'int x = fun1(2);' + '\n' + + '}' + ) + + c_src2 = ( + 'int fun2(int a, int b, int c)' + '\n' + + '{' + '\n' + + 'return a;' + '\n' + + '}' + '\n' + + 'void caller()' + '\n' + + '{' + '\n' + + 'int y = fun2(2, 3, 4);' + '\n' + + '}' + ) + + c_src3 = ( + 'int fun3(int a, int b, int c)' + '\n' + + '{' + '\n' + + 'return b;' + '\n' + + '}' + '\n' + + 'void caller()' + '\n' + + '{' + '\n' + + 'int p;' + '\n' + + 'int q;' + '\n' + + 'int r;' + '\n' + + 'int z = fun3(p, q, r);' + '\n' + + '}' + ) + + c_src4 = ( + 'int fun4(float a, float b, int c)' + '\n' + + '{' + '\n' + + 'return c;' + '\n' + + '}' + '\n' + + 'void caller()' + '\n' + + '{' + '\n' + + 'float x;' + '\n' + + 'float y;' + '\n' + + 'int z;' + '\n' + + 'int i = fun4(x, y, z)' + '\n' + + '}' + ) + + c_src5 = ( + 'int fun()' + '\n' + + '{' + '\n' + + 'return 1;' + '\n' + + '}' + '\n' + + 'void caller()' + '\n' + + '{' + '\n' + + 'int a = fun()' + '\n' + + '}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + + + assert res1[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun1'), + parameters=(Variable(Symbol('x'), + type=IntBaseType(String('intc')) + ), + ), + body=CodeBlock( + Return('x') + ) + ) + + assert res1[1] == FunctionDefinition( + NoneToken(), + name=String('caller'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('x'), + value=FunctionCall(String('fun1'), + function_args=( + Integer(2), + ) + ) + ) + ) + ) + ) + + assert res2[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun2'), + parameters=(Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ), + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ), + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + body=CodeBlock( + Return('a') + ) + ) + + assert res2[1] == FunctionDefinition( + NoneToken(), + name=String('caller'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('y'), + value=FunctionCall( + String('fun2'), + function_args=( + Integer(2), + Integer(3), + Integer(4) + ) + ) + ) + ) + ) + ) + + assert res3[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun3'), + parameters=( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ), + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ), + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + body=CodeBlock( + Return('b') + ) + ) + + assert res3[1] == FunctionDefinition( + NoneToken(), + name=String('caller'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('p'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('q'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('r'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('z'), + value=FunctionCall( + String('fun3'), + function_args=( + Symbol('p'), + Symbol('q'), + Symbol('r') + ) + ) + ) + ) + ) + ) + + assert res4[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun4'), + parameters=(Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ), + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ), + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + body=CodeBlock( + Return('c') + ) + ) + + assert res4[1] == FunctionDefinition( + NoneToken(), + name=String('caller'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('x'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Declaration( + Variable(Symbol('y'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Declaration( + Variable(Symbol('z'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('i'), + value=FunctionCall(String('fun4'), + function_args=( + Symbol('x'), + Symbol('y'), + Symbol('z') + ) + ) + ) + ) + ) + ) + + assert res5[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('fun'), + parameters=(), + body=CodeBlock( + Return('') + ) + ) + + assert res5[1] == FunctionDefinition( + NoneToken(), + name=String('caller'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + value=FunctionCall(String('fun'), + function_args=() + ) + ) + ) + ) + ) + + + def test_parse(): + c_src1 = ( + 'int a;' + '\n' + + 'int b;' + '\n' + ) + c_src2 = ( + 'void fun1()' + '\n' + + '{' + '\n' + + 'int a;' + '\n' + + '}' + ) + + f1 = open('..a.h', 'w') + f2 = open('..b.h', 'w') + + f1.write(c_src1) + f2. write(c_src2) + + f1.close() + f2.close() + + res1 = SymPyExpression('..a.h', 'c').return_expr() + res2 = SymPyExpression('..b.h', 'c').return_expr() + + os.remove('..a.h') + os.remove('..b.h') + + assert res1[0] == Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ) + assert res1[1] == Declaration( + Variable( + Symbol('b'), + type=IntBaseType(String('intc')) + ) + ) + assert res2[0] == FunctionDefinition( + NoneToken(), + name=String('fun1'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')) + ) + ) + ) + ) + + + def test_binary_operators(): + c_src1 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = 1;' + '\n' + + '}' + ) + c_src2 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 0;' + '\n' + + 'a = a + 1;' + '\n' + + 'a = 3*a - 10;' + '\n' + + '}' + ) + c_src3 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 10;' + '\n' + + 'a = 1 + a - 3 * 6;' + '\n' + + '}' + ) + c_src4 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'int b;' + '\n' + + 'a = 100;' + '\n' + + 'b = a*a + a*a + a + 19*a + 1 + 24;' + '\n' + + '}' + ) + c_src5 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'int b;' + '\n' + + 'int c;' + '\n' + + 'int d;' + '\n' + + 'a = 1;' + '\n' + + 'b = 2;' + '\n' + + 'c = b;' + '\n' + + 'd = ((a+b)*(a+c))*((c-d)*(a+c));' + '\n' + + '}' + ) + c_src6 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'int b;' + '\n' + + 'int c;' + '\n' + + 'int d;' + '\n' + + 'a = 1;' + '\n' + + 'b = 2;' + '\n' + + 'c = 3;' + '\n' + + 'd = (a*a*a*a + 3*b*b + b + b + c*d);' + '\n' + + '}' + ) + c_src7 = ( + 'void func()'+ + '{' + '\n' + + 'float a;' + '\n' + + 'a = 1.01;' + '\n' + + '}' + ) + + c_src8 = ( + 'void func()'+ + '{' + '\n' + + 'float a;' + '\n' + + 'a = 10.0 + 2.5;' + '\n' + + '}' + ) + + c_src9 = ( + 'void func()'+ + '{' + '\n' + + 'float a;' + '\n' + + 'a = 10.0 / 2.5;' + '\n' + + '}' + ) + + c_src10 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = 100 / 4;' + '\n' + + '}' + ) + + c_src11 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = 20 - 100 / 4 * 5 + 10;' + '\n' + + '}' + ) + + c_src12 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = (20 - 100) / 4 * (5 + 10);' + '\n' + + '}' + ) + + c_src13 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'int b;' + '\n' + + 'float c;' + '\n' + + 'c = b/a;' + '\n' + + '}' + ) + + c_src14 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 2;' + '\n' + + 'int d = 5;' + '\n' + + 'int n = 10;' + '\n' + + 'int s;' + '\n' + + 's = (a/2)*(2*a + (n-1)*d);' + '\n' + + '}' + ) + + c_src15 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = 1 % 2;' + '\n' + + '}' + ) + + c_src16 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 2;' + '\n' + + 'int b;' + '\n' + + 'b = a % 3;' + '\n' + + '}' + ) + + c_src17 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int c;' + '\n' + + 'c = a % b;' + '\n' + + '}' + ) + + c_src18 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int mod = 1000000007;' + '\n' + + 'int c;' + '\n' + + 'c = (a + b * (100/a)) % mod;' + '\n' + + '}' + ) + + c_src19 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int mod = 1000000007;' + '\n' + + 'int c;' + '\n' + + 'c = ((a % mod + b % mod) % mod' \ + '* (a % mod - b % mod) % mod) % mod;' + '\n' + + '}' + ) + + c_src20 = ( + 'void func()'+ + '{' + '\n' + + 'bool a' + '\n' + + 'bool b;' + '\n' + + 'a = 1 == 2;' + '\n' + + 'b = 1 != 2;' + '\n' + + '}' + ) + + c_src21 = ( + 'void func()'+ + '{' + '\n' + + 'bool a;' + '\n' + + 'bool b;' + '\n' + + 'bool c;' + '\n' + + 'bool d;' + '\n' + + 'a = 1 == 2;' + '\n' + + 'b = 1 <= 2;' + '\n' + + 'c = 1 > 2;' + '\n' + + 'd = 1 >= 2;' + '\n' + + '}' + ) + + c_src22 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 1;' + '\n' + + 'int b = 2;' + '\n' + + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + 'bool c7;' + '\n' + + 'bool c8;' + '\n' + + + 'c1 = a == 1;' + '\n' + + 'c2 = b == 2;' + '\n' + + + 'c3 = 1 != a;' + '\n' + + 'c4 = 1 != b;' + '\n' + + + 'c5 = a < 0;' + '\n' + + 'c6 = b <= 10;' + '\n' + + 'c7 = a > 0;' + '\n' + + 'c8 = b >= 11;' + '\n' + + '}' + ) + + c_src23 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 3;' + '\n' + + 'int b = 4;' + '\n' + + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + + 'c1 = a == b;' + '\n' + + 'c2 = a != b;' + '\n' + + 'c3 = a < b;' + '\n' + + 'c4 = a <= b;' + '\n' + + 'c5 = a > b;' + '\n' + + 'c6 = a >= b;' + '\n' + + '}' + ) + + c_src24 = ( + 'void func()'+ + '{' + '\n' + + 'float a = 1.25' + 'float b = 2.5;' + '\n' + + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + + 'c1 = a == 1.25;' + '\n' + + 'c2 = b == 2.54;' + '\n' + + + 'c3 = 1.2 != a;' + '\n' + + 'c4 = 1.5 != b;' + '\n' + + '}' + ) + + c_src25 = ( + 'void func()'+ + '{' + '\n' + + 'float a = 1.25' + '\n' + + 'float b = 2.5;' + '\n' + + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + + 'c1 = a == b;' + '\n' + + 'c2 = a != b;' + '\n' + + 'c3 = a < b;' + '\n' + + 'c4 = a <= b;' + '\n' + + 'c5 = a > b;' + '\n' + + 'c6 = a >= b;' + '\n' + + '}' + ) + + c_src26 = ( + 'void func()'+ + '{' + '\n' + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + + 'c1 = true == true;' + '\n' + + 'c2 = true == false;' + '\n' + + 'c3 = false == false;' + '\n' + + + 'c4 = true != true;' + '\n' + + 'c5 = true != false;' + '\n' + + 'c6 = false != false;' + '\n' + + '}' + ) + + c_src27 = ( + 'void func()'+ + '{' + '\n' + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + + 'c1 = true && true;' + '\n' + + 'c2 = true && false;' + '\n' + + 'c3 = false && false;' + '\n' + + + 'c4 = true || true;' + '\n' + + 'c5 = true || false;' + '\n' + + 'c6 = false || false;' + '\n' + + '}' + ) + + c_src28 = ( + 'void func()'+ + '{' + '\n' + + 'bool a;' + '\n' + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + + 'c1 = a && true;' + '\n' + + 'c2 = false && a;' + '\n' + + + 'c3 = true || a;' + '\n' + + 'c4 = a || false;' + '\n' + + '}' + ) + + c_src29 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + + 'c1 = a && 1;' + '\n' + + 'c2 = a && 0;' + '\n' + + + 'c3 = a || 1;' + '\n' + + 'c4 = 0 || a;' + '\n' + + '}' + ) + + c_src30 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'int b;' + '\n' + + 'bool c;'+ '\n' + + 'bool d;'+ '\n' + + + 'bool c1;' + '\n' + + 'bool c2;' + '\n' + + 'bool c3;' + '\n' + + 'bool c4;' + '\n' + + 'bool c5;' + '\n' + + 'bool c6;' + '\n' + + + 'c1 = a && b;' + '\n' + + 'c2 = a && c;' + '\n' + + 'c3 = c && d;' + '\n' + + + 'c4 = a || b;' + '\n' + + 'c5 = a || c;' + '\n' + + 'c6 = c || d;' + '\n' + + '}' + ) + + c_src_raise1 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = -1;' + '\n' + + '}' + ) + + c_src_raise2 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = -+1;' + '\n' + + '}' + ) + + c_src_raise3 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = 2*-2;' + '\n' + + '}' + ) + + c_src_raise4 = ( + 'void func()'+ + '{' + '\n' + + 'int a;' + '\n' + + 'a = (int)2.0;' + '\n' + + '}' + ) + + c_src_raise5 = ( + 'void func()'+ + '{' + '\n' + + 'int a=100;' + '\n' + + 'a = (a==100)?(1):(0);' + '\n' + + '}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + res6 = SymPyExpression(c_src6, 'c').return_expr() + res7 = SymPyExpression(c_src7, 'c').return_expr() + res8 = SymPyExpression(c_src8, 'c').return_expr() + res9 = SymPyExpression(c_src9, 'c').return_expr() + res10 = SymPyExpression(c_src10, 'c').return_expr() + res11 = SymPyExpression(c_src11, 'c').return_expr() + res12 = SymPyExpression(c_src12, 'c').return_expr() + res13 = SymPyExpression(c_src13, 'c').return_expr() + res14 = SymPyExpression(c_src14, 'c').return_expr() + res15 = SymPyExpression(c_src15, 'c').return_expr() + res16 = SymPyExpression(c_src16, 'c').return_expr() + res17 = SymPyExpression(c_src17, 'c').return_expr() + res18 = SymPyExpression(c_src18, 'c').return_expr() + res19 = SymPyExpression(c_src19, 'c').return_expr() + res20 = SymPyExpression(c_src20, 'c').return_expr() + res21 = SymPyExpression(c_src21, 'c').return_expr() + res22 = SymPyExpression(c_src22, 'c').return_expr() + res23 = SymPyExpression(c_src23, 'c').return_expr() + res24 = SymPyExpression(c_src24, 'c').return_expr() + res25 = SymPyExpression(c_src25, 'c').return_expr() + res26 = SymPyExpression(c_src26, 'c').return_expr() + res27 = SymPyExpression(c_src27, 'c').return_expr() + res28 = SymPyExpression(c_src28, 'c').return_expr() + res29 = SymPyExpression(c_src29, 'c').return_expr() + res30 = SymPyExpression(c_src30, 'c').return_expr() + + assert res1[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Assignment(Variable(Symbol('a')), Integer(1)) + ) + ) + + assert res2[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(0))), + Assignment( + Variable(Symbol('a')), + Add(Symbol('a'), + Integer(1)) + ), + Assignment(Variable(Symbol('a')), + Add( + Mul( + Integer(3), + Symbol('a')), + Integer(-10) + ) + ) + ) + ) + + assert res3[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ), + Assignment( + Variable(Symbol('a')), + Add( + Symbol('a'), + Integer(-17) + ) + ) + ) + ) + + assert res4[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(100)), + Assignment( + Variable(Symbol('b')), + Add( + Mul( + Integer(2), + Pow( + Symbol('a'), + Integer(2)) + ), + Mul( + Integer(20), + Symbol('a')), + Integer(25) + ) + ) + ) + ) + + assert res5[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(1)), + Assignment( + Variable(Symbol('b')), + Integer(2) + ), + Assignment( + Variable(Symbol('c')), + Symbol('b')), + Assignment( + Variable(Symbol('d')), + Mul( + Add( + Symbol('a'), + Symbol('b')), + Pow( + Add( + Symbol('a'), + Symbol('c') + ), + Integer(2) + ), + Add( + Symbol('c'), + Mul( + Integer(-1), + Symbol('d') + ) + ) + ) + ) + ) + ) + + assert res6[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(1) + ), + Assignment( + Variable(Symbol('b')), + Integer(2) + ), + Assignment( + Variable(Symbol('c')), + Integer(3) + ), + Assignment( + Variable(Symbol('d')), + Add( + Pow( + Symbol('a'), + Integer(4) + ), + Mul( + Integer(3), + Pow( + Symbol('b'), + Integer(2) + ) + ), + Mul( + Integer(2), + Symbol('b') + ), + Mul( + Symbol('c'), + Symbol('d') + ) + ) + ) + ) + ) + + assert res7[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Assignment( + Variable(Symbol('a')), + Float('1.01', precision=53) + ) + ) + ) + + assert res8[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Assignment( + Variable(Symbol('a')), + Float('12.5', precision=53) + ) + ) + ) + + assert res9[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Assignment( + Variable(Symbol('a')), + Float('4.0', precision=53) + ) + ) + ) + + assert res10[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(25) + ) + ) + ) + + assert res11[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(-95) + ) + ) + ) + + assert res12[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(-300) + ) + ) + ) + + assert res13[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('c'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Assignment( + Variable(Symbol('c')), + Mul( + Pow( + Symbol('a'), + Integer(-1) + ), + Symbol('b') + ) + ) + ) + ) + + assert res14[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ), + Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')), + value=Integer(5) + ) + ), + Declaration( + Variable(Symbol('n'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ), + Declaration( + Variable(Symbol('s'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('s')), + Mul( + Rational(1, 2), + Symbol('a'), + Add( + Mul( + Integer(2), + Symbol('a') + ), + Mul( + Symbol('d'), + Add( + Symbol('n'), + Integer(-1) + ) + ) + ) + ) + ) + ) + ) + + assert res15[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('a')), + Integer(1) + ) + ) + ) + + assert res16[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('b')), + Mod( + Symbol('a'), + Integer(3) + ) + ) + ) + ) + + assert res17[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('c')), + Mod( + Symbol('a'), + Symbol('b') + ) + ) + ) + ) + + assert res18[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ), + Declaration( + Variable(Symbol('mod'), + type=IntBaseType(String('intc')), + value=Integer(1000000007) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('c')), + Mod( + Add( + Symbol('a'), + Mul( + Integer(100), + Pow( + Symbol('a'), + Integer(-1) + ), + Symbol('b') + ) + ), + Symbol('mod') + ) + ) + ) + ) + + assert res19[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ), + Declaration( + Variable(Symbol('mod'), + type=IntBaseType(String('intc')), + value=Integer(1000000007) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')) + ) + ), + Assignment( + Variable(Symbol('c')), + Mod( + Mul( + Add( + Mod( + Symbol('a'), + Symbol('mod') + ), + Mul( + Integer(-1), + Mod( + Symbol('b'), + Symbol('mod') + ) + ) + ), + Mod( + Add( + Symbol('a'), + Symbol('b') + ), + Symbol('mod') + ) + ), + Symbol('mod') + ) + ) + ) + ) + + assert res20[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('a')), + false + ), + Assignment( + Variable(Symbol('b')), + true + ) + ) + ) + + assert res21[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('d'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('a')), + false + ), + Assignment( + Variable(Symbol('b')), + true + ), + Assignment( + Variable(Symbol('c')), + false + ), + Assignment( + Variable(Symbol('d')), + false + ) + ) + ) + + assert res22[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c7'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c8'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Equality( + Symbol('a'), + Integer(1) + ) + ), + Assignment( + Variable(Symbol('c2')), + Equality( + Symbol('b'), + Integer(2) + ) + ), + Assignment( + Variable(Symbol('c3')), + Unequality( + Integer(1), + Symbol('a') + ) + ), + Assignment( + Variable(Symbol('c4')), + Unequality( + Integer(1), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c5')), + StrictLessThan( + Symbol('a'), + Integer(0) + ) + ), + Assignment( + Variable(Symbol('c6')), + LessThan( + Symbol('b'), + Integer(10) + ) + ), + Assignment( + Variable(Symbol('c7')), + StrictGreaterThan( + Symbol('a'), + Integer(0) + ) + ), + Assignment( + Variable(Symbol('c8')), + GreaterThan( + Symbol('b'), + Integer(11) + ) + ) + ) + ) + + assert res23[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(4) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Equality( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c2')), + Unequality( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c3')), + StrictLessThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c4')), + LessThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c5')), + StrictGreaterThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c6')), + GreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + ) + + assert res24[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Equality( + Symbol('a'), + Float('1.25', precision=53) + ) + ), + Assignment( + Variable(Symbol('c3')), + Unequality( + Float('1.2', precision=53), + Symbol('a') + ) + ) + ) + ) + + + assert res25[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.25', precision=53) + ) + ), + Declaration( + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.5', precision=53) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool') + ) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Equality( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c2')), + Unequality( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c3')), + StrictLessThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c4')), + LessThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c5')), + StrictGreaterThan( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c6')), + GreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + ) + + assert res26[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), body=CodeBlock( + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + true + ), + Assignment( + Variable(Symbol('c2')), + false + ), + Assignment( + Variable(Symbol('c3')), + true + ), + Assignment( + Variable(Symbol('c4')), + false + ), + Assignment( + Variable(Symbol('c5')), + true + ), + Assignment( + Variable(Symbol('c6')), + false + ) + ) + ) + + assert res27[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + true + ), + Assignment( + Variable(Symbol('c2')), + false + ), + Assignment( + Variable(Symbol('c3')), + false + ), + Assignment( + Variable(Symbol('c4')), + true + ), + Assignment( + Variable(Symbol('c5')), + true + ), + Assignment( + Variable(Symbol('c6')), + false) + ) + ) + + assert res28[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Symbol('a') + ), + Assignment( + Variable(Symbol('c2')), + false + ), + Assignment( + Variable(Symbol('c3')), + true + ), + Assignment( + Variable(Symbol('c4')), + Symbol('a') + ) + ) + ) + + assert res29[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + Symbol('a') + ), + Assignment( + Variable(Symbol('c2')), + false + ), + Assignment( + Variable(Symbol('c3')), + true + ), + Assignment( + Variable(Symbol('c4')), + Symbol('a') + ) + ) + ) + + assert res30[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')) + ) + ), + Declaration( + Variable(Symbol('c'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('d'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')) + ) + ), + Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')) + ) + ), + Assignment( + Variable(Symbol('c1')), + And( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c2')), + And( + Symbol('a'), + Symbol('c') + ) + ), + Assignment( + Variable(Symbol('c3')), + And( + Symbol('c'), + Symbol('d') + ) + ), + Assignment( + Variable(Symbol('c4')), + Or( + Symbol('a'), + Symbol('b') + ) + ), + Assignment( + Variable(Symbol('c5')), + Or( + Symbol('a'), + Symbol('c') + ) + ), + Assignment( + Variable(Symbol('c6')), + Or( + Symbol('c'), + Symbol('d') + ) + ) + ) + ) + + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise3, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise4, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise5, 'c')) + + + @XFAIL + def test_var_decl(): + c_src1 = ( + 'int b = 100;' + '\n' + + 'int a = b;' + '\n' + ) + + c_src2 = ( + 'int a = 1;' + '\n' + + 'int b = a + 1;' + '\n' + ) + + c_src3 = ( + 'float a = 10.0 + 2.5;' + '\n' + + 'float b = a * 20.0;' + '\n' + ) + + c_src4 = ( + 'int a = 1 + 100 - 3 * 6;' + '\n' + ) + + c_src5 = ( + 'int a = (((1 + 100) * 12) - 3) * (6 - 10);' + '\n' + ) + + c_src6 = ( + 'int b = 2;' + '\n' + + 'int c = 3;' + '\n' + + 'int a = b + c * 4;' + '\n' + ) + + c_src7 = ( + 'int b = 1;' + '\n' + + 'int c = b + 2;' + '\n' + + 'int a = 10 * b * b * c;' + '\n' + ) + + c_src8 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 1;' + '\n' + + 'int b = 2;' + '\n' + + 'int temp = a;' + '\n' + + 'a = b;' + '\n' + + 'b = temp;' + '\n' + + '}' + ) + + c_src9 = ( + 'int a = 1;' + '\n' + + 'int b = 2;' + '\n' + + 'int c = a;' + '\n' + + 'int d = a + b + c;' + '\n' + + 'int e = a*a*a + 3*a*a*b + 3*a*b*b + b*b*b;' + '\n' + 'int f = (a + b + c) * (a + b - c);' + '\n' + + 'int g = (a + b + c + d)*(a + b + c + d)*(a * (b - c));' + + '\n' + ) + + c_src10 = ( + 'float a = 10.0;' + '\n' + + 'float b = 2.5;' + '\n' + + 'float c = a*a + 2*a*b + b*b;' + '\n' + ) + + c_src11 = ( + 'float a = 10.0 / 2.5;' + '\n' + ) + + c_src12 = ( + 'int a = 100 / 4;' + '\n' + ) + + c_src13 = ( + 'int a = 20 - 100 / 4 * 5 + 10;' + '\n' + ) + + c_src14 = ( + 'int a = (20 - 100) / 4 * (5 + 10);' + '\n' + ) + + c_src15 = ( + 'int a = 4;' + '\n' + + 'int b = 2;' + '\n' + + 'float c = b/a;' + '\n' + ) + + c_src16 = ( + 'int a = 2;' + '\n' + + 'int d = 5;' + '\n' + + 'int n = 10;' + '\n' + + 'int s = (a/2)*(2*a + (n-1)*d);' + '\n' + ) + + c_src17 = ( + 'int a = 1 % 2;' + '\n' + ) + + c_src18 = ( + 'int a = 2;' + '\n' + + 'int b = a % 3;' + '\n' + ) + + c_src19 = ( + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int c = a % b;' + '\n' + ) + + c_src20 = ( + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int mod = 1000000007;' + '\n' + + 'int c = (a + b * (100/a)) % mod;' + '\n' + ) + + c_src21 = ( + 'int a = 100;' + '\n' + + 'int b = 3;' + '\n' + + 'int mod = 1000000007;' + '\n' + + 'int c = ((a % mod + b % mod) % mod *' \ + '(a % mod - b % mod) % mod) % mod;' + '\n' + ) + + c_src22 = ( + 'bool a = 1 == 2, b = 1 != 2;' + ) + + c_src23 = ( + 'bool a = 1 < 2, b = 1 <= 2, c = 1 > 2, d = 1 >= 2;' + ) + + c_src24 = ( + 'int a = 1, b = 2;' + '\n' + + + 'bool c1 = a == 1;' + '\n' + + 'bool c2 = b == 2;' + '\n' + + + 'bool c3 = 1 != a;' + '\n' + + 'bool c4 = 1 != b;' + '\n' + + + 'bool c5 = a < 0;' + '\n' + + 'bool c6 = b <= 10;' + '\n' + + 'bool c7 = a > 0;' + '\n' + + 'bool c8 = b >= 11;' + + ) + + c_src25 = ( + 'int a = 3, b = 4;' + '\n' + + + 'bool c1 = a == b;' + '\n' + + 'bool c2 = a != b;' + '\n' + + 'bool c3 = a < b;' + '\n' + + 'bool c4 = a <= b;' + '\n' + + 'bool c5 = a > b;' + '\n' + + 'bool c6 = a >= b;' + ) + + c_src26 = ( + 'float a = 1.25, b = 2.5;' + '\n' + + + 'bool c1 = a == 1.25;' + '\n' + + 'bool c2 = b == 2.54;' + '\n' + + + 'bool c3 = 1.2 != a;' + '\n' + + 'bool c4 = 1.5 != b;' + ) + + c_src27 = ( + 'float a = 1.25, b = 2.5;' + '\n' + + + 'bool c1 = a == b;' + '\n' + + 'bool c2 = a != b;' + '\n' + + 'bool c3 = a < b;' + '\n' + + 'bool c4 = a <= b;' + '\n' + + 'bool c5 = a > b;' + '\n' + + 'bool c6 = a >= b;' + ) + + c_src28 = ( + 'bool c1 = true == true;' + '\n' + + 'bool c2 = true == false;' + '\n' + + 'bool c3 = false == false;' + '\n' + + + 'bool c4 = true != true;' + '\n' + + 'bool c5 = true != false;' + '\n' + + 'bool c6 = false != false;' + ) + + c_src29 = ( + 'bool c1 = true && true;' + '\n' + + 'bool c2 = true && false;' + '\n' + + 'bool c3 = false && false;' + '\n' + + + 'bool c4 = true || true;' + '\n' + + 'bool c5 = true || false;' + '\n' + + 'bool c6 = false || false;' + ) + + c_src30 = ( + 'bool a = false;' + '\n' + + + 'bool c1 = a && true;' + '\n' + + 'bool c2 = false && a;' + '\n' + + + 'bool c3 = true || a;' + '\n' + + 'bool c4 = a || false;' + ) + + c_src31 = ( + 'int a = 1;' + '\n' + + + 'bool c1 = a && 1;' + '\n' + + 'bool c2 = a && 0;' + '\n' + + + 'bool c3 = a || 1;' + '\n' + + 'bool c4 = 0 || a;' + ) + + c_src32 = ( + 'int a = 1, b = 0;' + '\n' + + 'bool c = false, d = true;'+ '\n' + + + 'bool c1 = a && b;' + '\n' + + 'bool c2 = a && c;' + '\n' + + 'bool c3 = c && d;' + '\n' + + + 'bool c4 = a || b;' + '\n' + + 'bool c5 = a || c;' + '\n' + + 'bool c6 = c || d;' + ) + + c_src_raise1 = ( + "char a = 'b';" + ) + + c_src_raise2 = ( + 'int a[] = {10, 20};' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + res6 = SymPyExpression(c_src6, 'c').return_expr() + res7 = SymPyExpression(c_src7, 'c').return_expr() + res8 = SymPyExpression(c_src8, 'c').return_expr() + res9 = SymPyExpression(c_src9, 'c').return_expr() + res10 = SymPyExpression(c_src10, 'c').return_expr() + res11 = SymPyExpression(c_src11, 'c').return_expr() + res12 = SymPyExpression(c_src12, 'c').return_expr() + res13 = SymPyExpression(c_src13, 'c').return_expr() + res14 = SymPyExpression(c_src14, 'c').return_expr() + res15 = SymPyExpression(c_src15, 'c').return_expr() + res16 = SymPyExpression(c_src16, 'c').return_expr() + res17 = SymPyExpression(c_src17, 'c').return_expr() + res18 = SymPyExpression(c_src18, 'c').return_expr() + res19 = SymPyExpression(c_src19, 'c').return_expr() + res20 = SymPyExpression(c_src20, 'c').return_expr() + res21 = SymPyExpression(c_src21, 'c').return_expr() + res22 = SymPyExpression(c_src22, 'c').return_expr() + res23 = SymPyExpression(c_src23, 'c').return_expr() + res24 = SymPyExpression(c_src24, 'c').return_expr() + res25 = SymPyExpression(c_src25, 'c').return_expr() + res26 = SymPyExpression(c_src26, 'c').return_expr() + res27 = SymPyExpression(c_src27, 'c').return_expr() + res28 = SymPyExpression(c_src28, 'c').return_expr() + res29 = SymPyExpression(c_src29, 'c').return_expr() + res30 = SymPyExpression(c_src30, 'c').return_expr() + res31 = SymPyExpression(c_src31, 'c').return_expr() + res32 = SymPyExpression(c_src32, 'c').return_expr() + + assert res1[0] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ) + + assert res1[1] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Symbol('b') + ) + ) + + assert res2[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res2[1] == Declaration(Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('a'), + Integer(1) + ) + ) + ) + + assert res3[0] == Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('12.5', precision=53) + ) + ) + + assert res3[1] == Declaration( + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Mul( + Float('20.0', precision=53), + Symbol('a') + ) + ) + ) + + assert res4[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(83) + ) + ) + + assert res5[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(-4836) + ) + ) + + assert res6[0] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res6[1] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res6[2] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('b'), + Mul( + Integer(4), + Symbol('c') + ) + ) + ) + ) + + assert res7[0] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res7[1] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('b'), + Integer(2) + ) + ) + ) + + assert res7[2] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Mul( + Integer(10), + Pow( + Symbol('b'), + Integer(2) + ), + Symbol('c') + ) + ) + ) + + assert res8[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ), + Declaration( + Variable(Symbol('temp'), + type=IntBaseType(String('intc')), + value=Symbol('a') + ) + ), + Assignment( + Variable(Symbol('a')), + Symbol('b') + ), + Assignment( + Variable(Symbol('b')), + Symbol('temp') + ) + ) + ) + + assert res9[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res9[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res9[2] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Symbol('a') + ) + ) + + assert res9[3] == Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('a'), + Symbol('b'), + Symbol('c') + ) + ) + ) + + assert res9[4] == Declaration( + Variable(Symbol('e'), + type=IntBaseType(String('intc')), + value=Add( + Pow( + Symbol('a'), + Integer(3) + ), + Mul( + Integer(3), + Pow( + Symbol('a'), + Integer(2) + ), + Symbol('b') + ), + Mul( + Integer(3), + Symbol('a'), + Pow( + Symbol('b'), + Integer(2) + ) + ), + Pow( + Symbol('b'), + Integer(3) + ) + ) + ) + ) + + assert res9[5] == Declaration( + Variable(Symbol('f'), + type=IntBaseType(String('intc')), + value=Mul( + Add( + Symbol('a'), + Symbol('b'), + Mul( + Integer(-1), + Symbol('c') + ) + ), + Add( + Symbol('a'), + Symbol('b'), + Symbol('c') + ) + ) + ) + ) + + assert res9[6] == Declaration( + Variable(Symbol('g'), + type=IntBaseType(String('intc')), + value=Mul( + Symbol('a'), + Add( + Symbol('b'), + Mul( + Integer(-1), + Symbol('c') + ) + ), + Pow( + Add( + Symbol('a'), + Symbol('b'), + Symbol('c'), + Symbol('d') + ), + Integer(2) + ) + ) + ) + ) + + assert res10[0] == Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('10.0', precision=53) + ) + ) + + assert res10[1] == Declaration( + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.5', precision=53) + ) + ) + + assert res10[2] == Declaration( + Variable(Symbol('c'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Add( + Pow( + Symbol('a'), + Integer(2) + ), + Mul( + Integer(2), + Symbol('a'), + Symbol('b') + ), + Pow( + Symbol('b'), + Integer(2) + ) + ) + ) + ) + + assert res11[0] == Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('4.0', precision=53) + ) + ) + + assert res12[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(25) + ) + ) + + assert res13[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(-95) + ) + ) + + assert res14[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(-300) + ) + ) + + assert res15[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(4) + ) + ) + + assert res15[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res15[2] == Declaration( + Variable(Symbol('c'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Mul( + Pow( + Symbol('a'), + Integer(-1) + ), + Symbol('b') + ) + ) + ) + + assert res16[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res16[1] == Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')), + value=Integer(5) + ) + ) + + assert res16[2] == Declaration( + Variable(Symbol('n'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ) + + assert res16[3] == Declaration( + Variable(Symbol('s'), + type=IntBaseType(String('intc')), + value=Mul( + Rational(1, 2), + Symbol('a'), + Add( + Mul( + Integer(2), + Symbol('a') + ), + Mul( + Symbol('d'), + Add( + Symbol('n'), + Integer(-1) + ) + ) + ) + ) + ) + ) + + assert res17[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res18[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res18[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Mod( + Symbol('a'), + Integer(3) + ) + ) + ) + + assert res19[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ) + assert res19[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res19[2] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Mod( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res20[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ) + + assert res20[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res20[2] == Declaration( + Variable(Symbol('mod'), + type=IntBaseType(String('intc')), + value=Integer(1000000007) + ) + ) + + assert res20[3] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Mod( + Add( + Symbol('a'), + Mul( + Integer(100), + Pow( + Symbol('a'), + Integer(-1) + ), + Symbol('b') + ) + ), + Symbol('mod') + ) + ) + ) + + assert res21[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ) + + assert res21[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res21[2] == Declaration( + Variable(Symbol('mod'), + type=IntBaseType(String('intc')), + value=Integer(1000000007) + ) + ) + + assert res21[3] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Mod( + Mul( + Add( + Symbol('a'), + Mul( + Integer(-1), + Symbol('b') + ) + ), + Add( + Symbol('a'), + Symbol('b') + ) + ), + Symbol('mod') + ) + ) + ) + + assert res22[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=false + ) + ) + + assert res22[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=true + ) + ) + + assert res23[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=true + ) + ) + + assert res23[1] == Declaration( + Variable(Symbol('b'), + type=Type(String('bool')), + value=true + ) + ) + + assert res23[2] == Declaration( + Variable(Symbol('c'), + type=Type(String('bool')), + value=false + ) + ) + + assert res23[3] == Declaration( + Variable(Symbol('d'), + type=Type(String('bool')), + value=false + ) + ) + + assert res24[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res24[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res24[2] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=Equality( + Symbol('a'), + Integer(1) + ) + ) + ) + + assert res24[3] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=Equality( + Symbol('b'), + Integer(2) + ) + ) + ) + + assert res24[4] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=Unequality( + Integer(1), + Symbol('a') + ) + ) + ) + + assert res24[5] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=Unequality( + Integer(1), + Symbol('b') + ) + ) + ) + + assert res24[6] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=StrictLessThan(Symbol('a'), + Integer(0) + ) + ) + ) + + assert res24[7] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=LessThan( + Symbol('b'), + Integer(10) + ) + ) + ) + + assert res24[8] == Declaration( + Variable(Symbol('c7'), + type=Type(String('bool')), + value=StrictGreaterThan( + Symbol('a'), + Integer(0) + ) + ) + ) + + assert res24[9] == Declaration( + Variable(Symbol('c8'), + type=Type(String('bool')), + value=GreaterThan( + Symbol('b'), + Integer(11) + ) + ) + ) + + assert res25[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res25[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(4) + ) + ) + + assert res25[2] == Declaration(Variable(Symbol('c1'), + type=Type(String('bool')), + value=Equality( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res25[3] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=Unequality( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res25[4] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=StrictLessThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res25[5] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=LessThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res25[6] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=StrictGreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res25[7] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=GreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res26[0] == Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.25', precision=53) + ) + ) + + assert res26[1] == Declaration( + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.5', precision=53) + ) + ) + + assert res26[2] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=Equality( + Symbol('a'), + Float('1.25', precision=53) + ) + ) + ) + + assert res26[3] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=Equality( + Symbol('b'), + Float('2.54', precision=53) + ) + ) + ) + + assert res26[4] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=Unequality( + Float('1.2', precision=53), + Symbol('a') + ) + ) + ) + + assert res26[5] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=Unequality( + Float('1.5', precision=53), + Symbol('b') + ) + ) + ) + + assert res27[0] == Declaration( + Variable(Symbol('a'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('1.25', precision=53) + ) + ) + + assert res27[1] == Declaration( + Variable(Symbol('b'), + type=FloatType( + String('float32'), + nbits=Integer(32), + nmant=Integer(23), + nexp=Integer(8) + ), + value=Float('2.5', precision=53) + ) + ) + + assert res27[2] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=Equality( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res27[3] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=Unequality( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res27[4] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=StrictLessThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res27[5] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=LessThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res27[6] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=StrictGreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res27[7] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=GreaterThan( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res28[0] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=true + ) + ) + + assert res28[1] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=false + ) + ) + + assert res28[2] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=true + ) + ) + + assert res28[3] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=false + ) + ) + + assert res28[4] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=true + ) + ) + + assert res28[5] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=false + ) + ) + + assert res29[0] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=true + ) + ) + + assert res29[1] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=false + ) + ) + + assert res29[2] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=false + ) + ) + + assert res29[3] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=true + ) + ) + + assert res29[4] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=true + ) + ) + + assert res29[5] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=false + ) + ) + + assert res30[0] == Declaration( + Variable(Symbol('a'), + type=Type(String('bool')), + value=false + ) + ) + + assert res30[1] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=Symbol('a') + ) + ) + + assert res30[2] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=false + ) + ) + + assert res30[3] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=true + ) + ) + + assert res30[4] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=Symbol('a') + ) + ) + + assert res31[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res31[1] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=Symbol('a') + ) + ) + + assert res31[2] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=false + ) + ) + + assert res31[3] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=true + ) + ) + + assert res31[4] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=Symbol('a') + ) + ) + + assert res32[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res32[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(0) + ) + ) + + assert res32[2] == Declaration( + Variable(Symbol('c'), + type=Type(String('bool')), + value=false + ) + ) + + assert res32[3] == Declaration( + Variable(Symbol('d'), + type=Type(String('bool')), + value=true + ) + ) + + assert res32[4] == Declaration( + Variable(Symbol('c1'), + type=Type(String('bool')), + value=And( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res32[5] == Declaration( + Variable(Symbol('c2'), + type=Type(String('bool')), + value=And( + Symbol('a'), + Symbol('c') + ) + ) + ) + + assert res32[6] == Declaration( + Variable(Symbol('c3'), + type=Type(String('bool')), + value=And( + Symbol('c'), + Symbol('d') + ) + ) + ) + + assert res32[7] == Declaration( + Variable(Symbol('c4'), + type=Type(String('bool')), + value=Or( + Symbol('a'), + Symbol('b') + ) + ) + ) + + assert res32[8] == Declaration( + Variable(Symbol('c5'), + type=Type(String('bool')), + value=Or( + Symbol('a'), + Symbol('c') + ) + ) + ) + + assert res32[9] == Declaration( + Variable(Symbol('c6'), + type=Type(String('bool')), + value=Or( + Symbol('c'), + Symbol('d') + ) + ) + ) + + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) + + + def test_paren_expr(): + c_src1 = ( + 'int a = (1);' + 'int b = (1 + 2 * 3);' + ) + + c_src2 = ( + 'int a = 1, b = 2, c = 3;' + 'int d = (a);' + 'int e = (a + 1);' + 'int f = (a + b * c - d / e);' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + + assert res1[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res1[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(7) + ) + ) + + assert res2[0] == Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(1) + ) + ) + + assert res2[1] == Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(2) + ) + ) + + assert res2[2] == Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Integer(3) + ) + ) + + assert res2[3] == Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')), + value=Symbol('a') + ) + ) + + assert res2[4] == Declaration( + Variable(Symbol('e'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('a'), + Integer(1) + ) + ) + ) + + assert res2[5] == Declaration( + Variable(Symbol('f'), + type=IntBaseType(String('intc')), + value=Add( + Symbol('a'), + Mul( + Symbol('b'), + Symbol('c') + ), + Mul( + Integer(-1), + Symbol('d'), + Pow( + Symbol('e'), + Integer(-1) + ) + ) + ) + ) + ) + + + def test_unary_operators(): + c_src1 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 10;' + '\n' + + 'int b = 20;' + '\n' + + '++a;' + '\n' + + '--b;' + '\n' + + 'a++;' + '\n' + + 'b--;' + '\n' + + '}' + ) + + c_src2 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 10;' + '\n' + + 'int b = -100;' + '\n' + + 'int c = +19;' + '\n' + + 'int d = ++a;' + '\n' + + 'int e = --b;' + '\n' + + 'int f = a++;' + '\n' + + 'int g = b--;' + '\n' + + 'bool h = !false;' + '\n' + + 'bool i = !d;' + '\n' + + 'bool j = !0;' + '\n' + + 'bool k = !10.0;' + '\n' + + '}' + ) + + c_src_raise1 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 10;' + '\n' + + 'int b = ~a;' + '\n' + + '}' + ) + + c_src_raise2 = ( + 'void func()'+ + '{' + '\n' + + 'int a = 10;' + '\n' + + 'int b = *&a;' + '\n' + + '}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + + assert res1[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(20) + ) + ), + PreIncrement(Symbol('a')), + PreDecrement(Symbol('b')), + PostIncrement(Symbol('a')), + PostDecrement(Symbol('b')) + ) + ) + + assert res2[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ), + Declaration( + Variable(Symbol('b'), + type=IntBaseType(String('intc')), + value=Integer(-100) + ) + ), + Declaration( + Variable(Symbol('c'), + type=IntBaseType(String('intc')), + value=Integer(19) + ) + ), + Declaration( + Variable(Symbol('d'), + type=IntBaseType(String('intc')), + value=PreIncrement(Symbol('a')) + ) + ), + Declaration( + Variable(Symbol('e'), + type=IntBaseType(String('intc')), + value=PreDecrement(Symbol('b')) + ) + ), + Declaration( + Variable(Symbol('f'), + type=IntBaseType(String('intc')), + value=PostIncrement(Symbol('a')) + ) + ), + Declaration( + Variable(Symbol('g'), + type=IntBaseType(String('intc')), + value=PostDecrement(Symbol('b')) + ) + ), + Declaration( + Variable(Symbol('h'), + type=Type(String('bool')), + value=true + ) + ), + Declaration( + Variable(Symbol('i'), + type=Type(String('bool')), + value=Not(Symbol('d')) + ) + ), + Declaration( + Variable(Symbol('j'), + type=Type(String('bool')), + value=true + ) + ), + Declaration( + Variable(Symbol('k'), + type=Type(String('bool')), + value=false + ) + ) + ) + ) + + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) + raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) + + + def test_compound_assignment_operator(): + c_src = ( + 'void func()'+ + '{' + '\n' + + 'int a = 100;' + '\n' + + 'a += 10;' + '\n' + + 'a -= 10;' + '\n' + + 'a *= 10;' + '\n' + + 'a /= 10;' + '\n' + + 'a %= 10;' + '\n' + + '}' + ) + + res = SymPyExpression(c_src, 'c').return_expr() + + assert res[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('a'), + type=IntBaseType(String('intc')), + value=Integer(100) + ) + ), + AddAugmentedAssignment( + Variable(Symbol('a')), + Integer(10) + ), + SubAugmentedAssignment( + Variable(Symbol('a')), + Integer(10) + ), + MulAugmentedAssignment( + Variable(Symbol('a')), + Integer(10) + ), + DivAugmentedAssignment( + Variable(Symbol('a')), + Integer(10) + ), + ModAugmentedAssignment( + Variable(Symbol('a')), + Integer(10) + ) + ) + ) + + @XFAIL # this is expected to fail because of a bug in the C parser. + def test_while_stmt(): + c_src1 = ( + 'void func()'+ + '{' + '\n' + + 'int i = 0;' + '\n' + + 'while(i < 10)' + '\n' + + '{' + '\n' + + 'i++;' + '\n' + + '}' + '}' + ) + + c_src2 = ( + 'void func()'+ + '{' + '\n' + + 'int i = 0;' + '\n' + + 'while(i < 10)' + '\n' + + 'i++;' + '\n' + + '}' + ) + + c_src3 = ( + 'void func()'+ + '{' + '\n' + + 'int i = 10;' + '\n' + + 'int cnt = 0;' + '\n' + + 'while(i > 0)' + '\n' + + '{' + '\n' + + 'i--;' + '\n' + + 'cnt++;' + '\n' + + '}' + '\n' + + '}' + ) + + c_src4 = ( + 'int digit_sum(int n)'+ + '{' + '\n' + + 'int sum = 0;' + '\n' + + 'while(n > 0)' + '\n' + + '{' + '\n' + + 'sum += (n % 10);' + '\n' + + 'n /= 10;' + '\n' + + '}' + '\n' + + 'return sum;' + '\n' + + '}' + ) + + c_src5 = ( + 'void func()'+ + '{' + '\n' + + 'while(1);' + '\n' + + '}' + ) + + res1 = SymPyExpression(c_src1, 'c').return_expr() + res2 = SymPyExpression(c_src2, 'c').return_expr() + res3 = SymPyExpression(c_src3, 'c').return_expr() + res4 = SymPyExpression(c_src4, 'c').return_expr() + res5 = SymPyExpression(c_src5, 'c').return_expr() + + assert res1[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable(Symbol('i'), + type=IntBaseType(String('intc')), + value=Integer(0) + ) + ), + While( + StrictLessThan( + Symbol('i'), + Integer(10) + ), + body=CodeBlock( + PostIncrement( + Symbol('i') + ) + ) + ) + ) + ) + + assert res2[0] == res1[0] + + assert res3[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + Declaration( + Variable( + Symbol('i'), + type=IntBaseType(String('intc')), + value=Integer(10) + ) + ), + Declaration( + Variable( + Symbol('cnt'), + type=IntBaseType(String('intc')), + value=Integer(0) + ) + ), + While( + StrictGreaterThan( + Symbol('i'), + Integer(0) + ), + body=CodeBlock( + PostDecrement( + Symbol('i') + ), + PostIncrement( + Symbol('cnt') + ) + ) + ) + ) + ) + + assert res4[0] == FunctionDefinition( + IntBaseType(String('intc')), + name=String('digit_sum'), + parameters=( + Variable( + Symbol('n'), + type=IntBaseType(String('intc')) + ), + ), + body=CodeBlock( + Declaration( + Variable( + Symbol('sum'), + type=IntBaseType(String('intc')), + value=Integer(0) + ) + ), + While( + StrictGreaterThan( + Symbol('n'), + Integer(0) + ), + body=CodeBlock( + AddAugmentedAssignment( + Variable( + Symbol('sum') + ), + Mod( + Symbol('n'), + Integer(10) + ) + ), + DivAugmentedAssignment( + Variable( + Symbol('n') + ), + Integer(10) + ) + ) + ), + Return('sum') + ) + ) + + assert res5[0] == FunctionDefinition( + NoneToken(), + name=String('func'), + parameters=(), + body=CodeBlock( + While( + Integer(1), + body=CodeBlock( + NoneToken() + ) + ) + ) + ) + + +else: + def test_raise(): + from sympy.parsing.c.c_parser import CCodeConverter + raises(ImportError, lambda: CCodeConverter()) + raises(ImportError, lambda: SymPyExpression(' ', mode = 'c')) diff --git a/shared/package-files/55/558de429bbd323cc5a505560c92309bba28a5be803304ea29c2dd3a7ab4394b4/buffer.cpython-311.pyc b/shared/package-files/55/558de429bbd323cc5a505560c92309bba28a5be803304ea29c2dd3a7ab4394b4/buffer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf9886e03bbde5ead3901f213094aad09b2a3be Binary files /dev/null and b/shared/package-files/55/558de429bbd323cc5a505560c92309bba28a5be803304ea29c2dd3a7ab4394b4/buffer.cpython-311.pyc differ diff --git a/shared/package-files/55/55c5c0acc2e36c37716fda74db73ffdf439ad2b3bbe39e6d7ea8b48e2444326b/fake_impls.cpython-311.pyc b/shared/package-files/55/55c5c0acc2e36c37716fda74db73ffdf439ad2b3bbe39e6d7ea8b48e2444326b/fake_impls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1824c1eee3e18ea18125454ab9be732182f7991a Binary files /dev/null and b/shared/package-files/55/55c5c0acc2e36c37716fda74db73ffdf439ad2b3bbe39e6d7ea8b48e2444326b/fake_impls.cpython-311.pyc differ diff --git a/shared/package-files/55/55dfe0ea34d8e2bc9efa016afdef13ed5ef346e4dc5559c89025ae22c41bbcaf/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h b/shared/package-files/55/55dfe0ea34d8e2bc9efa016afdef13ed5ef346e4dc5559c89025ae22c41bbcaf/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8f844c84e66b4b82970cade33e371c6e5176c228 --- /dev/null +++ b/shared/package-files/55/55dfe0ea34d8e2bc9efa016afdef13ed5ef346e4dc5559c89025ae22c41bbcaf/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor binary_cross_entropy_with_logits(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_with_logits_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_with_logits_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, const ::std::optional & pos_weight, int64_t reduction, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/55/55f58ec77d1f66efdabcc6d6ab1b5b2c370b8bef71ea2b9098b7f26ad9c57376/test_partfrac.py b/shared/package-files/55/55f58ec77d1f66efdabcc6d6ab1b5b2c370b8bef71ea2b9098b7f26ad9c57376/test_partfrac.py new file mode 100644 index 0000000000000000000000000000000000000000..83c5d48383d20e67dbb53c081093ad35e654c9a0 --- /dev/null +++ b/shared/package-files/55/55f58ec77d1f66efdabcc6d6ab1b5b2c370b8bef71ea2b9098b7f26ad9c57376/test_partfrac.py @@ -0,0 +1,249 @@ +"""Tests for algorithms for partial fraction decomposition of rational +functions. """ + +from sympy.polys.partfrac import ( + apart_undetermined_coeffs, + apart, + apart_list, assemble_partfrac_list +) + +from sympy.core.expr import Expr +from sympy.core.function import Lambda +from sympy.core.numbers import (E, I, Rational, pi, all_close) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.dense import Matrix +from sympy.polys.polytools import (Poly, factor) +from sympy.polys.rationaltools import together +from sympy.polys.rootoftools import RootSum +from sympy.testing.pytest import raises, XFAIL +from sympy.abc import x, y, a, b, c + + +def test_apart(): + assert apart(1) == 1 + assert apart(1, x) == 1 + + f, g = (x**2 + 1)/(x + 1), 2/(x + 1) + x - 1 + + assert apart(f, full=False) == g + assert apart(f, full=True) == g + + f, g = 1/(x + 2)/(x + 1), 1/(1 + x) - 1/(2 + x) + + assert apart(f, full=False) == g + assert apart(f, full=True) == g + + f, g = 1/(x + 1)/(x + 5), -1/(5 + x)/4 + 1/(1 + x)/4 + + assert apart(f, full=False) == g + assert apart(f, full=True) == g + + assert apart((E*x + 2)/(x - pi)*(x - 1), x) == \ + 2 - E + E*pi + E*x + (E*pi + 2)*(pi - 1)/(x - pi) + + assert apart(Eq((x**2 + 1)/(x + 1), x), x) == Eq(x - 1 + 2/(x + 1), x) + + assert apart(x/2, y) == x/2 + + f, g = (x+y)/(2*x - y), Rational(3, 2)*y/(2*x - y) + S.Half + + assert apart(f, x, full=False) == g + assert apart(f, x, full=True) == g + + f, g = (x+y)/(2*x - y), 3*x/(2*x - y) - 1 + + assert apart(f, y, full=False) == g + assert apart(f, y, full=True) == g + + raises(NotImplementedError, lambda: apart(1/(x + 1)/(y + 2))) + + +def test_apart_matrix(): + M = Matrix(2, 2, lambda i, j: 1/(x + i + 1)/(x + j)) + + assert apart(M) == Matrix([ + [1/x - 1/(x + 1), (x + 1)**(-2)], + [1/(2*x) - (S.Half)/(x + 2), 1/(x + 1) - 1/(x + 2)], + ]) + + +def test_apart_symbolic(): + f = a*x**4 + (2*b + 2*a*c)*x**3 + (4*b*c - a**2 + a*c**2)*x**2 + \ + (-2*a*b + 2*b*c**2)*x - b**2 + g = a**2*x**4 + (2*a*b + 2*c*a**2)*x**3 + (4*a*b*c + b**2 + + a**2*c**2)*x**2 + (2*c*b**2 + 2*a*b*c**2)*x + b**2*c**2 + + assert apart(f/g, x) == 1/a - 1/(x + c)**2 - b**2/(a*(a*x + b)**2) + + assert apart(1/((x + a)*(x + b)*(x + c)), x) == \ + 1/((a - c)*(b - c)*(c + x)) - 1/((a - b)*(b - c)*(b + x)) + \ + 1/((a - b)*(a - c)*(a + x)) + + +def _make_extension_example(): + # https://github.com/sympy/sympy/issues/18531 + from sympy.core import Mul + def mul2(expr): + # 2-arg mul hack... + return Mul(2, expr, evaluate=False) + + f = ((x**2 + 1)**3/((x - 1)**2*(x + 1)**2*(-x**2 + 2*x + 1)*(x**2 + 2*x - 1))) + g = (1/mul2(x - sqrt(2) + 1) + - 1/mul2(x - sqrt(2) - 1) + + 1/mul2(x + 1 + sqrt(2)) + - 1/mul2(x - 1 + sqrt(2)) + + 1/mul2((x + 1)**2) + + 1/mul2((x - 1)**2)) + return f, g + + +def test_apart_extension(): + f = 2/(x**2 + 1) + g = I/(x + I) - I/(x - I) + + assert apart(f, extension=I) == g + assert apart(f, gaussian=True) == g + + f = x/((x - 2)*(x + I)) + + assert factor(together(apart(f)).expand()) == f + + f, g = _make_extension_example() + + # XXX: Only works with dotprodsimp. See test_apart_extension_xfail below + from sympy.matrices import dotprodsimp + with dotprodsimp(True): + assert apart(f, x, extension={sqrt(2)}) == g + + +def test_apart_extension_xfail(): + f, g = _make_extension_example() + assert apart(f, x, extension={sqrt(2)}) == g + + +def test_apart_full(): + f = 1/(x**2 + 1) + + assert apart(f, full=False) == f + assert apart(f, full=True).dummy_eq( + -RootSum(x**2 + 1, Lambda(a, a/(x - a)), auto=False)/2) + + f = 1/(x**3 + x + 1) + + assert apart(f, full=False) == f + assert apart(f, full=True).dummy_eq( + RootSum(x**3 + x + 1, + Lambda(a, (a**2*Rational(6, 31) - a*Rational(9, 31) + Rational(4, 31))/(x - a)), auto=False)) + + f = 1/(x**5 + 1) + + assert apart(f, full=False) == \ + (Rational(-1, 5))*((x**3 - 2*x**2 + 3*x - 4)/(x**4 - x**3 + x**2 - + x + 1)) + (Rational(1, 5))/(x + 1) + assert apart(f, full=True).dummy_eq( + -RootSum(x**4 - x**3 + x**2 - x + 1, + Lambda(a, a/(x - a)), auto=False)/5 + (Rational(1, 5))/(x + 1)) + + +def test_apart_full_floats(): + # https://github.com/sympy/sympy/issues/26648 + f = ( + 6.43369157032015e-9*x**3 + 1.35203404799555e-5*x**2 + + 0.00357538393743079*x + 0.085 + )/( + 4.74334912634438e-11*x**4 + 4.09576274286244e-6*x**3 + + 0.00334241812250921*x**2 + 0.15406018058983*x + 1.0 + ) + + expected = ( + 133.599202650992/(x + 85524.0054884464) + + 1.07757928431867/(x + 774.88576677949) + + 0.395006955518971/(x + 40.7977016133126) + + 0.564264854137341/(x + 7.79746609204661) + ) + + f_apart = apart(f, full=True).evalf() + + # There is a significant floating point error in this operation. + assert all_close(f_apart, expected, rtol=1e-3, atol=1e-5) + + +def test_apart_undetermined_coeffs(): + p = Poly(2*x - 3) + q = Poly(x**9 - x**8 - x**6 + x**5 - 2*x**2 + 3*x - 1) + r = (-x**7 - x**6 - x**5 + 4)/(x**8 - x**5 - 2*x + 1) + 1/(x - 1) + + assert apart_undetermined_coeffs(p, q) == r + + p = Poly(1, x, domain='ZZ[a,b]') + q = Poly((x + a)*(x + b), x, domain='ZZ[a,b]') + r = 1/((a - b)*(b + x)) - 1/((a - b)*(a + x)) + + assert apart_undetermined_coeffs(p, q) == r + + +def test_apart_list(): + from sympy.utilities.iterables import numbered_symbols + def dummy_eq(i, j): + if type(i) in (list, tuple): + return all(dummy_eq(i, j) for i, j in zip(i, j)) + return i == j or i.dummy_eq(j) + + w0, w1, w2 = Symbol("w0"), Symbol("w1"), Symbol("w2") + _a = Dummy("a") + + f = (-2*x - 2*x**2) / (3*x**2 - 6*x) + got = apart_list(f, x, dummies=numbered_symbols("w")) + ans = (-1, Poly(Rational(2, 3), x, domain='QQ'), + [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)]) + assert dummy_eq(got, ans) + + got = apart_list(2/(x**2-2), x, dummies=numbered_symbols("w")) + ans = (1, Poly(0, x, domain='ZZ'), [(Poly(w0**2 - 2, w0, domain='ZZ'), + Lambda(_a, _a/2), + Lambda(_a, -_a + x), 1)]) + assert dummy_eq(got, ans) + + f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) + got = apart_list(f, x, dummies=numbered_symbols("w")) + ans = (1, Poly(0, x, domain='ZZ'), + [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), + (Poly(w1**2 - 1, w1, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), + (Poly(w2 + 1, w2, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) + assert dummy_eq(got, ans) + + +def test_assemble_partfrac_list(): + f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) + pfd = apart_list(f) + assert assemble_partfrac_list(pfd) == -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) + + a = Dummy("a") + pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)]) + assert assemble_partfrac_list(pfd) == -1/(sqrt(2)*(x + sqrt(2))) + 1/(sqrt(2)*(x - sqrt(2))) + + +@XFAIL +def test_noncommutative_pseudomultivariate(): + # apart doesn't go inside noncommutative expressions + class foo(Expr): + is_commutative=False + e = x/(x + x*y) + c = 1/(1 + y) + assert apart(e + foo(e)) == c + foo(c) + assert apart(e*foo(e)) == c*foo(c) + +def test_noncommutative(): + class foo(Expr): + is_commutative=False + e = x/(x + x*y) + c = 1/(1 + y) + assert apart(e + foo()) == c + foo() + +def test_issue_5798(): + assert apart( + 2*x/(x**2 + 1) - (x - 1)/(2*(x**2 + 1)) + 1/(2*(x + 1)) - 2/x) == \ + (3*x + 1)/(x**2 + 1)/2 + 1/(x + 1)/2 - 2/x diff --git a/shared/package-files/55/55fe7ac94bd2d6e5b73a355131739842913b36e38318fcab644327d5b0305d6c/_histogramdd_from_bin_cts_compositeexplicitautograd_dispatch.h b/shared/package-files/55/55fe7ac94bd2d6e5b73a355131739842913b36e38318fcab644327d5b0305d6c/_histogramdd_from_bin_cts_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3fa5922b641e16962e38bdefbce4837e8087ae25 --- /dev/null +++ b/shared/package-files/55/55fe7ac94bd2d6e5b73a355131739842913b36e38318fcab644327d5b0305d6c/_histogramdd_from_bin_cts_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _histogramdd_from_bin_cts_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef bins, ::std::optional> range=::std::nullopt, const ::std::optional & weight={}, bool density=false); +TORCH_API at::Tensor & _histogramdd_from_bin_cts_outf(const at::Tensor & self, at::IntArrayRef bins, ::std::optional> range, const ::std::optional & weight, bool density, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/75/750b8451913a283388b828166f505eb3b0be804465f4849649e33e2b1850e513/test_kclique.cpython-311.pyc b/shared/package-files/75/750b8451913a283388b828166f505eb3b0be804465f4849649e33e2b1850e513/test_kclique.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867ead3e9a2bdca9bab919590b3df99421980dbe Binary files /dev/null and b/shared/package-files/75/750b8451913a283388b828166f505eb3b0be804465f4849649e33e2b1850e513/test_kclique.cpython-311.pyc differ diff --git a/shared/package-files/75/750f29dd852754655fd80a152c83db8c5971f76afa54e625450ef5b6d44dece8/QnnpackUtils.h b/shared/package-files/75/750f29dd852754655fd80a152c83db8c5971f76afa54e625450ef5b6d44dece8/QnnpackUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..2fb60fd88b3c002acf43a90f2b8b4d241de3ae38 --- /dev/null +++ b/shared/package-files/75/750f29dd852754655fd80a152c83db8c5971f76afa54e625450ef5b6d44dece8/QnnpackUtils.h @@ -0,0 +1,523 @@ +#pragma once + +#ifdef USE_PYTORCH_QNNPACK +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +inline int kPaddingChannels = 8; +struct QnnpackOperatorDeleter { + void operator()(pytorch_qnnp_operator_t op) { + pytorch_qnnp_delete_operator(op); + } +}; + +// PackedWeight struct for QNNPACK stores the original Weight and Bias as +// QNNPACK currently does not support an unpack function. +// For PyTorch Mobile, once the model is scripted and serialized we don't need +// to call unpack, so we can save some memory by checking for this case and free +// the original weights after packing. +// Input scale is set to null in pre-pack step. QNNPACK needs bias quantized +// with input scale which is available at runtime in pytorch. During runtime if +// input scale value changes then we requantize bias with the updated scale. For +// inference we expect the graph to be static so the input scale should not +// change across consecutive inference calls. +struct PackedLinearWeightsQnnp : public LinearPackedParamsBase { + PackedLinearWeightsQnnp( + std::unique_ptr w, + at::Tensor orig_weight, + at::Tensor bias, + std::optional input_scale, + at::Tensor w_scales, + std::vector&& w_zps) + : w(std::move(w)), + orig_weight(std::move(orig_weight)), + bias_(at::native::mobile::allocate_padded_contiguous_if_needed( + bias, bias.suggest_memory_format())), + per_channel_(this->orig_weight.qscheme() == at::kPerChannelAffine), + input_scale(std::move(input_scale)), + w_scales(std::move(w_scales)), + w_zero_points(std::move(w_zps)), + q_scheme(this->orig_weight.qscheme()) { + weight_sizes = this->orig_weight.sizes().vec(); + } + + std::unique_ptr w; + at::Tensor orig_weight; + at::Tensor bias_; + bool per_channel_; + std::optional input_scale; + at::Tensor w_scales; + std::vector w_zero_points; + std::vector requantization_scales; + std::vector weight_sizes; + c10::QScheme q_scheme; + + at::Tensor apply( + at::Tensor input, + double output_scale, + int64_t output_zero_point) override; + at::Tensor apply_relu( + at::Tensor input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_dynamic(at::Tensor input, bool reduce_range=false) override; + at::Tensor apply_dynamic_relu(at::Tensor input, bool reduce_range=false) override; + + std::tuple> unpack() override; + + std::optional bias() override { + return bias_; + } + + static c10::intrusive_ptr prepack( + at::Tensor weight, + std::optional bias); + + bool per_channel() const { + return per_channel_; + } + + private: + std::mutex qnnp_mutex_; + +#ifdef USE_XNNPACK + xnnpack_operator xnnp_linear_op; + + template + at::Tensor apply_impl_xnnp( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); +#endif // USE_XNNPACK + + template + at::Tensor apply_impl( + at::Tensor input, + double output_scale, + int64_t output_zero_point); + + template + at::Tensor apply_dynamic_impl(at::Tensor input, bool reduce_range); +}; + +template +struct PackedConvWeightsQnnp : public ConvPackedParamsBase { + PackedConvWeightsQnnp( + std::unique_ptr w, + at::Tensor orig_weight, + at::Tensor bias, + torch::List stride, + torch::List padding, + torch::List output_padding, + torch::List dilation, + int64_t groups, + bool transpose, + std::optional input_scale, + std::vector kernel, + at::Tensor w_scale, + std::vector&& w_zps, + bool is_per_channel) + : w(std::move(w)), + orig_weight(std::move(orig_weight)), + bias(std::move(bias)), + stride_(std::move(stride)), + padding_(std::move(padding)), + output_padding_(std::move(output_padding)), + dilation_(std::move(dilation)), + groups_(groups), + transpose_(transpose), + is_per_channel_(is_per_channel), + input_scale(input_scale), + kernel_(std::move(kernel)), + w_scales(std::move(w_scale)), + w_zero_points(std::move(w_zps)) { + const bool any_padding = std::any_of( + padding_.begin(), padding_.end(), [](const auto& e) { return e != 0; }); + const size_t kernel_size = + std::accumulate(kernel_.begin(), kernel_.end(), 1, std::multiplies<>()); + + const size_t group_input_channels = transpose + ? this->orig_weight.size(0) / groups + : this->orig_weight.size(1); + const size_t group_output_channels = transpose + ? this->orig_weight.size(1) + : this->orig_weight.size(0) / groups; + + const size_t kernel_depth = kSpatialDim == 3 ? kernel_[0] : 1; + const size_t kernel_height = kernel_[kSpatialDim - 2]; + const size_t kernel_width = kernel_[kSpatialDim - 1]; + + pytorch_qnnp_ukernel_type ukernel_type; + if (transpose_) { + ukernel_type = pytorch_qnnp_ukernel_type_conv; + } else { + ukernel_type = pytorch_qnnp_ukernel_type_none; + + const bool has_depthwise_dimensions = + (kSpatialDim == 2 && + ((kernel_height == 3 && kernel_width == 3) || + (kernel_height == 5 && kernel_width == 5))) || + (kSpatialDim == 3 && kernel_height == 3 && kernel_width == 3 && + kernel_depth == 3); + const bool has_depthwise_grouping = + group_input_channels == 1 && group_output_channels == 1 && groups > 1; + + if (has_depthwise_dimensions && has_depthwise_grouping) { + ukernel_type = pytorch_qnnp_ukernel_type_dwconv; + } else if ( + kernel_size == 1 && + std::all_of( + stride_.begin(), + stride_.end(), + [](const auto& e) { return e == 1; }) && + !any_padding) { + ukernel_type = group_input_channels >= SIZE_MAX + ? pytorch_qnnp_ukernel_type_xzp_gemm + : pytorch_qnnp_ukernel_type_gemm; + } else { + ukernel_type = pytorch_qnnp_ukernel_type_conv; + } + } + + if (is_per_channel && ukernel_type == pytorch_qnnp_ukernel_type_xzp_gemm) { + TORCH_INTERNAL_ASSERT( + false, "Per channel quantized weights are not supported for XZP kernels"); + } + + pytorch_qnnp_operator_t convolution{nullptr}; + // Initially all the params are set to zero. + convolution = static_cast( + calloc(1, sizeof(struct pytorch_qnnp_operator))); + if (convolution == nullptr) { + TORCH_INTERNAL_ASSERT( + false, "failed to allocate %zu bytes for pytorch_qnnp_operator structure", + sizeof(struct pytorch_qnnp_operator)); + } + + convolution_op = + std::unique_ptr( + convolution); + + // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) + convolution->ukernel_type = ukernel_type; + convolution->groups = groups; + convolution->group_input_channels = group_input_channels; + convolution->group_output_channels = group_output_channels; + convolution->kernel_depth = kernel_depth; + convolution->kernel_height = kernel_height; + convolution->kernel_width = kernel_width; + convolution->stride_depth = kSpatialDim == 3 ? stride_[0] : 1; + convolution->stride_height = stride_[kSpatialDim - 2]; + convolution->stride_width = stride_[kSpatialDim - 1]; + convolution->dilation_depth = kSpatialDim == 3 ? dilation_[0] : 1; + convolution->dilation_height = dilation_[kSpatialDim - 2]; + convolution->dilation_width = dilation_[kSpatialDim - 1]; + convolution->input_padding_height = padding_[kSpatialDim - 2]; + convolution->input_padding_width = padding_[kSpatialDim - 1]; + convolution->input_padding_depth = kSpatialDim == 3 ? padding_[0] : 0; + convolution->per_channel = is_per_channel_; + convolution->transpose = transpose_; + + const uint32_t kr = pytorch_qnnp_params.q8conv.kr; + const size_t k_stride = (group_input_channels + (kr - 1)) & -kr; + + size_t zero_size = sizeof(uint8_t) * k_stride; + size_t zero_offset = 0; + + if (transpose_) { + convolution->adjustment_width = output_padding_[1]; + convolution->adjustment_height = output_padding_[0]; + if (group_input_channels < 8) { + zero_size += 8; + zero_offset = 8; + } + } else { + zero_buffer_size = 0; + if (any_padding) { + zero_size = 0; + zero_offset = 0; + if (ukernel_type == pytorch_qnnp_ukernel_type_dwconv) { + const uint32_t cr = pytorch_qnnp_params.q8dw9.cr; + const size_t group_stride = (groups + (cr - 1)) & -cr; + if (groups >= 8) { + zero_size = sizeof(uint8_t) * group_stride; + zero_offset = 0; + } else { + zero_size = sizeof(uint8_t) * group_stride + 8; + zero_offset = sizeof(uint8_t) * 8; + } + } else if ( + ukernel_type == pytorch_qnnp_ukernel_type_conv || + ukernel_type == pytorch_qnnp_ukernel_type_gemm) { + if (group_input_channels >= 8) { + zero_size = sizeof(uint8_t) * k_stride; + zero_offset = 0; + } else { + zero_size = sizeof(uint8_t) * k_stride + 8; + zero_offset = 8; + } + } + } + } + + // NOLINTNEXTLINE(clang-analyzer-optin.portability.UnixAPI) + void* zero_buffer = malloc(zero_size); + if (zero_buffer == nullptr) { + pytorch_qnnp_delete_operator(convolution); + TORCH_INTERNAL_ASSERT( + false, "failed to allocate %zu bytes for zero padding", + zero_size); + } + // Need to set to input zero point + // memset(zero_buffer, input_zero_point, zero_size); + zero_buffer_size = zero_size; + convolution->zero_buffer = zero_buffer; + convolution->zero_pointer = (void*)((uintptr_t)zero_buffer + zero_offset); + } + + std::unique_ptr convolution_op; + #ifdef USE_XNNPACK + xnnpack_operator xnnp_convolution_op; + #endif // USE_XNNPACK + std::unique_ptr w; + at::Tensor orig_weight; + at::Tensor bias; + torch::List stride_; + torch::List padding_; + torch::List output_padding_; + torch::List dilation_; + int64_t groups_; + bool transpose_; + bool is_per_channel_; + std::optional input_scale; + std::vector kernel_; + at::Tensor w_scales; + std::vector w_zero_points; + std::vector requantization_scales; + size_t zero_buffer_size; + + at::Tensor apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_dynamic( + const at::Tensor& input, + bool reduce_range=false) override; + + std::tuple> unpack() override; + + static c10::intrusive_ptr> prepack( + at::Tensor weight, + std::optional bias, + torch::List stride, + torch::List padding, + torch::List output_padding, + torch::List dilation, + int64_t groups, + bool transpose); + + torch::List stride() const override { + return stride_; + } + + torch::List padding() const override { + return padding_; + } + + torch::List output_padding() const override { + return output_padding_; + } + + torch::List dilation() const override { + return dilation_; + } + + int64_t groups() const override { + return groups_; + } + + bool transpose() const override { + return transpose_; + } + + bool per_channel() const { + return is_per_channel_; + } + + private: + std::mutex qnnp_mutex_; + template + at::Tensor apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); + +#ifdef USE_XNNPACK + template + at::Tensor apply_impl_xnnp( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); +#endif // USE_XNNPACK +}; + +enum class Activation : uint8_t { NONE = 0, RELU = 1 }; + +#if defined(__ANDROID__) && !defined(__NDK_MAJOR__) +template +inline float Round(const float x) { + return ::nearbyintf(x); +} +inline double Round(const double x) { + return ::nearbyint(x); +} +#else +template +inline T Round(const T x) { + return std::nearbyint(x); +} +#endif + +template +inline T QuantizeValue(float scale, int32_t zero_point, float value) { + const int32_t qmin = std::numeric_limits::min(); + const int32_t qmax = std::numeric_limits::max(); + auto r = zero_point + static_cast(Round(value / scale)); + r = std::max(r, qmin); + r = std::min(r, qmax); + return static_cast(r); +} + +template +inline std::pair activationLimits( + float scale, + int32_t zero_point, + Activation Ac) { + switch (Ac) { + case Activation::NONE: + return {std::numeric_limits::min(), + std::numeric_limits::max()}; + case Activation::RELU: + return {QuantizeValue(scale, zero_point, 0.0), + std::numeric_limits::max()}; + default: +#ifdef _MSC_VER + __assume(0); +#else + __builtin_unreachable(); +#endif + } +} + +namespace at::native::qnnp_avgpool_helper { +Tensor qnnpack_avg_pool2d( + Tensor input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override); +} // namespace at::native::qnnp_avgpool_helper + +namespace { +[[maybe_unused]] std::vector generate_requantization_scales( + const at::Tensor& weight_scales, + const float input_scale, + const float output_scale, + std::vector& requant_scales) { + // Since weight scale is allocated with padding + // weight_scales.numel() gives us padded num elements. + const auto num_output_channels_padded = weight_scales.numel(); + float *const weight_scales_data = weight_scales.data_ptr(); + if (static_cast(requant_scales.size()) < num_output_channels_padded) { + requant_scales.resize(num_output_channels_padded); + } + for (const auto i : c10::irange(num_output_channels_padded)) { + const auto inverse_output_scale = 1.f /output_scale; + requant_scales[i] = (weight_scales_data[i] * input_scale) * inverse_output_scale; + TORCH_CHECK( + (requant_scales[i] > 0.0f && std::isnormal(requant_scales[i])), + "failed to create op with requantization scale: ", + requant_scales[i], + ": requantization scale must be finite and positive"); + } + return requant_scales; +} + +[[maybe_unused]] std::pair, at::Tensor> +make_zero_points_and_scales_tensor( + const at::Tensor& weight_contig, + bool transpose = false, + uint32_t groups = 1) { + const int out_ch_idx = transpose ? 1 : 0; + const auto num_output_channels = weight_contig.size(out_ch_idx) * (transpose ? groups : 1); + // Add 8 to account for bufferring needed by QNNPACK. + const auto num_output_channels_padded = num_output_channels + kPaddingChannels; + const auto qtype = weight_contig.qscheme(); + std::vector weight_zp(num_output_channels_padded, 0); + // Adjust weight zero point, similar to weight data. + if (qtype == at::kPerTensorAffine) { + for (const auto i : c10::irange(num_output_channels)) { + weight_zp[i] = (uint8_t)(weight_contig.q_zero_point() + 128); + } + } else if (qtype == at::kPerChannelAffine) { + TORCH_CHECK( + weight_contig.q_per_channel_zero_points().scalar_type() == at::kLong, + "Per channel zero points dtype must be long int."); + const int64_t* per_channel_zero_points = + weight_contig.q_per_channel_zero_points().data_ptr(); + for (const auto i : c10::irange(num_output_channels)) { + weight_zp[i] = (uint8_t)(per_channel_zero_points[i] + 128); + } + } else { + TORCH_INTERNAL_ASSERT(false, "Unsupported quantization scheme."); + } + at:: Tensor weight_scales = + at::empty( + {num_output_channels_padded}, + at::device(at::kCPU).dtype(at::kFloat)); + float *const weight_scales_data = weight_scales.data_ptr(); + if (qtype == at::kPerTensorAffine) { + for (const auto i : c10::irange(num_output_channels)) { + weight_scales_data[i] = weight_contig.q_scale(); + } + } else if (qtype == at::kPerChannelAffine) { + TORCH_CHECK( + weight_contig.q_per_channel_scales().scalar_type() == at::kDouble, + "Per channel scales dtype must be double."); + const double *const per_channel_scales = + weight_contig.q_per_channel_scales().data_ptr(); + for (const auto i : c10::irange(num_output_channels)) { + weight_scales_data[i] = static_cast(per_channel_scales[i]); + } + } else { + TORCH_INTERNAL_ASSERT(false, "Unsupported quantization scheme."); + } + for (const auto i : c10::irange(num_output_channels, num_output_channels_padded)) { + weight_scales_data[i] = 1.f; + } + return {weight_zp, weight_scales}; +} +} // namespace + +#endif diff --git a/shared/package-files/75/750f824056bbb5399594202f99d46c4e8801c25f2487345845c9362b3a2ff5b8/_tzpath.cpython-311.pyc b/shared/package-files/75/750f824056bbb5399594202f99d46c4e8801c25f2487345845c9362b3a2ff5b8/_tzpath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f0c1fc46efcb87b2157d013ca6303867ffe4add Binary files /dev/null and b/shared/package-files/75/750f824056bbb5399594202f99d46c4e8801c25f2487345845c9362b3a2ff5b8/_tzpath.cpython-311.pyc differ diff --git a/shared/package-files/75/7516f0bd9defc709eac34f659d1a8ebb8ef97f8eb10cf368ed5de873577f3f65/test_matpow.py b/shared/package-files/75/7516f0bd9defc709eac34f659d1a8ebb8ef97f8eb10cf368ed5de873577f3f65/test_matpow.py new file mode 100644 index 0000000000000000000000000000000000000000..2afb5fdc2aa652c321de52aba43db63da60941fd --- /dev/null +++ b/shared/package-files/75/7516f0bd9defc709eac34f659d1a8ebb8ef97f8eb10cf368ed5de873577f3f65/test_matpow.py @@ -0,0 +1,217 @@ +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.simplify.powsimp import powsimp +from sympy.testing.pytest import raises +from sympy.core.expr import unchanged +from sympy.core import symbols, S +from sympy.matrices import Identity, MatrixSymbol, ImmutableMatrix, ZeroMatrix, OneMatrix, Matrix +from sympy.matrices.exceptions import NonSquareMatrixError +from sympy.matrices.expressions import MatPow, MatAdd, MatMul +from sympy.matrices.expressions.inverse import Inverse +from sympy.matrices.expressions.matexpr import MatrixElement + +n, m, l, k = symbols('n m l k', integer=True) +A = MatrixSymbol('A', n, m) +B = MatrixSymbol('B', m, l) +C = MatrixSymbol('C', n, n) +D = MatrixSymbol('D', n, n) +E = MatrixSymbol('E', m, n) + + +def test_entry_matrix(): + X = ImmutableMatrix([[1, 2], [3, 4]]) + assert MatPow(X, 0)[0, 0] == 1 + assert MatPow(X, 0)[0, 1] == 0 + assert MatPow(X, 1)[0, 0] == 1 + assert MatPow(X, 1)[0, 1] == 2 + assert MatPow(X, 2)[0, 0] == 7 + + +def test_entry_symbol(): + from sympy.concrete import Sum + assert MatPow(C, 0)[0, 0] == 1 + assert MatPow(C, 0)[0, 1] == 0 + assert MatPow(C, 1)[0, 0] == C[0, 0] + assert isinstance(MatPow(C, 2)[0, 0], Sum) + assert isinstance(MatPow(C, n)[0, 0], MatrixElement) + + +def test_as_explicit_symbol(): + X = MatrixSymbol('X', 2, 2) + assert MatPow(X, 0).as_explicit() == ImmutableMatrix(Identity(2)) + assert MatPow(X, 1).as_explicit() == X.as_explicit() + assert MatPow(X, 2).as_explicit() == (X.as_explicit())**2 + assert MatPow(X, n).as_explicit() == ImmutableMatrix([ + [(X ** n)[0, 0], (X ** n)[0, 1]], + [(X ** n)[1, 0], (X ** n)[1, 1]], + ]) + + a = MatrixSymbol("a", 3, 1) + b = MatrixSymbol("b", 3, 1) + c = MatrixSymbol("c", 3, 1) + + expr = (a.T*b)**S.Half + assert expr.as_explicit() == Matrix([[sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])]]) + + expr = c*(a.T*b)**S.Half + m = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0]) + assert expr.as_explicit() == Matrix([[c[0, 0]*m], [c[1, 0]*m], [c[2, 0]*m]]) + + expr = (a*b.T)**S.Half + denom = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0]) + expected = (a*b.T).as_explicit()/denom + assert expr.as_explicit() == expected + + expr = X**-1 + det = X[0, 0]*X[1, 1] - X[1, 0]*X[0, 1] + expected = Matrix([[X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]])/det + assert expr.as_explicit() == expected + + expr = X**m + assert expr.as_explicit() == X.as_explicit()**m + + +def test_as_explicit_matrix(): + A = ImmutableMatrix([[1, 2], [3, 4]]) + assert MatPow(A, 0).as_explicit() == ImmutableMatrix(Identity(2)) + assert MatPow(A, 1).as_explicit() == A + assert MatPow(A, 2).as_explicit() == A**2 + assert MatPow(A, -1).as_explicit() == A.inv() + assert MatPow(A, -2).as_explicit() == (A.inv())**2 + # less expensive than testing on a 2x2 + A = ImmutableMatrix([4]) + assert MatPow(A, S.Half).as_explicit() == A**S.Half + + +def test_doit_symbol(): + assert MatPow(C, 0).doit() == Identity(n) + assert MatPow(C, 1).doit() == C + assert MatPow(C, -1).doit() == C.I + for r in [2, S.Half, S.Pi, n]: + assert MatPow(C, r).doit() == MatPow(C, r) + + +def test_doit_matrix(): + X = ImmutableMatrix([[1, 2], [3, 4]]) + assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2)) + assert MatPow(X, 1).doit() == X + assert MatPow(X, 2).doit() == X**2 + assert MatPow(X, -1).doit() == X.inv() + assert MatPow(X, -2).doit() == (X.inv())**2 + # less expensive than testing on a 2x2 + assert MatPow(ImmutableMatrix([4]), S.Half).doit() == ImmutableMatrix([2]) + X = ImmutableMatrix([[0, 2], [0, 4]]) # det() == 0 + raises(ValueError, lambda: MatPow(X,-1).doit()) + raises(ValueError, lambda: MatPow(X,-2).doit()) + + +def test_nonsquare(): + A = MatrixSymbol('A', 2, 3) + B = ImmutableMatrix([[1, 2, 3], [4, 5, 6]]) + for r in [-1, 0, 1, 2, S.Half, S.Pi, n]: + raises(NonSquareMatrixError, lambda: MatPow(A, r)) + raises(NonSquareMatrixError, lambda: MatPow(B, r)) + + +def test_doit_equals_pow(): #17179 + X = ImmutableMatrix ([[1,0],[0,1]]) + assert MatPow(X, n).doit() == X**n == X + + +def test_doit_nested_MatrixExpr(): + X = ImmutableMatrix([[1, 2], [3, 4]]) + Y = ImmutableMatrix([[2, 3], [4, 5]]) + assert MatPow(MatMul(X, Y), 2).doit() == (X*Y)**2 + assert MatPow(MatAdd(X, Y), 2).doit() == (X + Y)**2 + + +def test_identity_power(): + k = Identity(n) + assert MatPow(k, 4).doit() == k + assert MatPow(k, n).doit() == k + assert MatPow(k, -3).doit() == k + assert MatPow(k, 0).doit() == k + l = Identity(3) + assert MatPow(l, n).doit() == l + assert MatPow(l, -1).doit() == l + assert MatPow(l, 0).doit() == l + + +def test_zero_power(): + z1 = ZeroMatrix(n, n) + assert MatPow(z1, 3).doit() == z1 + raises(ValueError, lambda:MatPow(z1, -1).doit()) + assert MatPow(z1, 0).doit() == Identity(n) + assert MatPow(z1, n).doit() == z1 + raises(ValueError, lambda:MatPow(z1, -2).doit()) + z2 = ZeroMatrix(4, 4) + assert MatPow(z2, n).doit() == z2 + raises(ValueError, lambda:MatPow(z2, -3).doit()) + assert MatPow(z2, 2).doit() == z2 + assert MatPow(z2, 0).doit() == Identity(4) + raises(ValueError, lambda:MatPow(z2, -1).doit()) + + +def test_OneMatrix_power(): + o = OneMatrix(3, 3) + assert o ** 0 == Identity(3) + assert o ** 1 == o + assert o * o == o ** 2 == 3 * o + assert o * o * o == o ** 3 == 9 * o + + o = OneMatrix(n, n) + assert o * o == o ** 2 == n * o + # powsimp necessary as n ** (n - 2) * n does not produce n ** (n - 1) + assert powsimp(o ** (n - 1) * o) == o ** n == n ** (n - 1) * o + + +def test_transpose_power(): + from sympy.matrices.expressions.transpose import Transpose as TP + + assert (C*D).T**5 == ((C*D)**5).T == (D.T * C.T)**5 + assert ((C*D).T**5).T == (C*D)**5 + + assert (C.T.I.T)**7 == C**-7 + assert (C.T**l).T**k == C**(l*k) + + assert ((E.T * A.T)**5).T == (A*E)**5 + assert ((A*E).T**5).T**7 == (A*E)**35 + assert TP(TP(C**2 * D**3)**5).doit() == (C**2 * D**3)**5 + + assert ((D*C)**-5).T**-5 == ((D*C)**25).T + assert (((D*C)**l).T**k).T == (D*C)**(l*k) + + +def test_Inverse(): + assert Inverse(MatPow(C, 0)).doit() == Identity(n) + assert Inverse(MatPow(C, 1)).doit() == Inverse(C) + assert Inverse(MatPow(C, 2)).doit() == MatPow(C, -2) + assert Inverse(MatPow(C, -1)).doit() == C + + assert MatPow(Inverse(C), 0).doit() == Identity(n) + assert MatPow(Inverse(C), 1).doit() == Inverse(C) + assert MatPow(Inverse(C), 2).doit() == MatPow(C, -2) + assert MatPow(Inverse(C), -1).doit() == C + + +def test_combine_powers(): + assert (C ** 1) ** 1 == C + assert (C ** 2) ** 3 == MatPow(C, 6) + assert (C ** -2) ** -3 == MatPow(C, 6) + assert (C ** -1) ** -1 == C + assert (((C ** 2) ** 3) ** 4) ** 5 == MatPow(C, 120) + assert (C ** n) ** n == C ** (n ** 2) + + +def test_unchanged(): + assert unchanged(MatPow, C, 0) + assert unchanged(MatPow, C, 1) + assert unchanged(MatPow, Inverse(C), -1) + assert unchanged(Inverse, MatPow(C, -1), -1) + assert unchanged(MatPow, MatPow(C, -1), -1) + assert unchanged(MatPow, MatPow(C, 1), 1) + + +def test_no_exponentiation(): + # if this passes, Pow.as_numer_denom should recognize + # MatAdd as exponent + raises(NotImplementedError, lambda: 3**(-2*C)) diff --git a/shared/package-files/75/75173a4a4dc94a9e656b8027ee1b4a4d292cd6bbe4d412f7cbf1806f491915ae/RegisterFunctionalization.cpp b/shared/package-files/75/75173a4a4dc94a9e656b8027ee1b4a4d292cd6bbe4d412f7cbf1806f491915ae/RegisterFunctionalization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7efb5b6a4bb24cc6ad2ae78555118410ab3f5e48 --- /dev/null +++ b/shared/package-files/75/75173a4a4dc94a9e656b8027ee1b4a4d292cd6bbe4d412f7cbf1806f491915ae/RegisterFunctionalization.cpp @@ -0,0 +1,115 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +// needed for the meta tensor calls to get stride info in functionalization +#include +// needed for special handling of copy_(). +// See Note [functionalizating copy_() and not preserving strides] +#include +#include + +$ops_headers +#endif + +namespace at { +namespace functionalization { + +// This keyset is used by functionalization when it calls into meta kernels +// to accurately propagate stride metadata. +// Exclude any modes: the purpose of calling into meta kernels is only as an implementation +// detail to perform shape inference, and we don't want any modal keys to run. +// Specifically, we want to prevent functionalization and Python modes from running. +constexpr auto exclude_keys_for_meta_dispatch = + c10::functorch_transforms_ks | + c10::DispatchKeySet({ + c10::DispatchKey::FuncTorchDynamicLayerBackMode, + c10::DispatchKey::FuncTorchDynamicLayerFrontMode, + c10::DispatchKey::Python, + c10::DispatchKey::PreDispatch, + + }); + +// Helper around at::has_internal_overlap. +// The ATen util is used in hot-path eager mode: it's always fast, +// but might return TOO_HARD sometimes. +// During functionalization, we're ok taking a bit longer +// to detect memory overlap. +inline bool has_internal_overlap_helper(const at::Tensor t) { + auto has_overlap = at::has_internal_overlap(t); + if (has_overlap == at::MemOverlap::Yes) return true; + if (has_overlap == at::MemOverlap::No) return false; + return false; +} + + +inline Tensor to_meta(const Tensor& t) { + if (!t.defined()) return t; + return at::native::empty_strided_meta_symint(t.sym_sizes(), t.sym_strides(), +/*dtype=*/t.scalar_type(), /*layout=*/t.layout(), +/*device=*/c10::Device(kMeta), /*pin_memory=*/std::nullopt); +} + +inline std::optional to_meta(const std::optional& t) { + if (t.has_value()) { + return to_meta(*t); + } + return std::nullopt; +} + +inline std::vector to_meta(at::ITensorListRef t_list) { + std::vector outputs; + outputs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + outputs.push_back(to_meta(tensor)); + } + return outputs; +} + +inline c10::List to_meta(const c10::List& t_list) { + c10::List outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(to_meta(t_list[i])); + } + return outputs; +} + +inline c10::List<::std::optional> to_meta(const c10::List<::std::optional>& t_list) { + c10::List<::std::optional> outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(to_meta(t_list[i])); + } + return outputs; +} + +static bool disable_meta_reference() { + static auto env = std::getenv("TORCH_DISABLE_FUNCTIONALIZATION_META_REFERENCE"); + return env != nullptr && std::strcmp(env, "1") == 0; +} + + +${func_definitions} + +} // namespace functionalization + +namespace { + +TORCH_LIBRARY_IMPL(aten, Functionalize, m) { + ${func_registrations}; +} + +} // namespace + +} // namespace at diff --git a/shared/package-files/75/75184e0f8b95d85d4181acbff95128b9ae6f64b97ecb6cac96a9c95f0264ee40/__init__.cpython-311.pyc b/shared/package-files/75/75184e0f8b95d85d4181acbff95128b9ae6f64b97ecb6cac96a9c95f0264ee40/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..773ffc6f626440238599a0bddf8c41602a67ec4d Binary files /dev/null and b/shared/package-files/75/75184e0f8b95d85d4181acbff95128b9ae6f64b97ecb6cac96a9c95f0264ee40/__init__.cpython-311.pyc differ diff --git a/shared/package-files/75/752926a3cd33c06fc7b5de7e35baa05ffa9e73c51a1473778bafc0ce1614ac48/base_backend.cpython-311.pyc b/shared/package-files/75/752926a3cd33c06fc7b5de7e35baa05ffa9e73c51a1473778bafc0ce1614ac48/base_backend.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01294b17f8ac2953bfb76710f89978f9f43de7ae Binary files /dev/null and b/shared/package-files/75/752926a3cd33c06fc7b5de7e35baa05ffa9e73c51a1473778bafc0ce1614ac48/base_backend.cpython-311.pyc differ diff --git a/shared/package-files/75/753280191ec3a9da2833a91b57ed52dbcdf09b12f6a0ced042b9708c8e57fd26/test_print.cpython-311.pyc b/shared/package-files/75/753280191ec3a9da2833a91b57ed52dbcdf09b12f6a0ced042b9708c8e57fd26/test_print.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fee4e7bb09996c2643b0c0bee534d6cd30c691e Binary files /dev/null and b/shared/package-files/75/753280191ec3a9da2833a91b57ed52dbcdf09b12f6a0ced042b9708c8e57fd26/test_print.cpython-311.pyc differ diff --git a/shared/package-files/75/7532bf09d4fe326ff346838bf8cc1be2870103ffe1db004500083a56f02279b4/str.py b/shared/package-files/75/7532bf09d4fe326ff346838bf8cc1be2870103ffe1db004500083a56f02279b4/str.py new file mode 100644 index 0000000000000000000000000000000000000000..9975776fbb73bec9c956fe359387fa8036995795 --- /dev/null +++ b/shared/package-files/75/7532bf09d4fe326ff346838bf8cc1be2870103ffe1db004500083a56f02279b4/str.py @@ -0,0 +1,1021 @@ +""" +A Printer for generating readable representation of most SymPy classes. +""" + +from __future__ import annotations +from typing import Any + +from sympy.core import S, Rational, Pow, Basic, Mul, Number +from sympy.core.mul import _keep_coeff +from sympy.core.numbers import Integer +from sympy.core.relational import Relational +from sympy.core.sorting import default_sort_key +from sympy.utilities.iterables import sift +from .precedence import precedence, PRECEDENCE +from .printer import Printer, print_function + +from mpmath.libmp import prec_to_dps, to_str as mlib_to_str + + +class StrPrinter(Printer): + printmethod = "_sympystr" + _default_settings: dict[str, Any] = { + "order": None, + "full_prec": "auto", + "sympy_integers": False, + "abbrev": False, + "perm_cyclic": True, + "min": None, + "max": None, + "dps" : None + } + + _relationals: dict[str, str] = {} + + def parenthesize(self, item, level, strict=False): + if (precedence(item) < level) or ((not strict) and precedence(item) <= level): + return "(%s)" % self._print(item) + else: + return self._print(item) + + def stringify(self, args, sep, level=0): + return sep.join([self.parenthesize(item, level) for item in args]) + + def emptyPrinter(self, expr): + if isinstance(expr, str): + return expr + elif isinstance(expr, Basic): + return repr(expr) + else: + return str(expr) + + def _print_Add(self, expr, order=None): + terms = self._as_ordered_terms(expr, order=order) + + prec = precedence(expr) + l = [] + for term in terms: + t = self._print(term) + if t.startswith('-') and not term.is_Add: + sign = "-" + t = t[1:] + else: + sign = "+" + if precedence(term) < prec or term.is_Add: + l.extend([sign, "(%s)" % t]) + else: + l.extend([sign, t]) + sign = l.pop(0) + if sign == '+': + sign = "" + return sign + ' '.join(l) + + def _print_BooleanTrue(self, expr): + return "True" + + def _print_BooleanFalse(self, expr): + return "False" + + def _print_Not(self, expr): + return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) + + def _print_And(self, expr): + args = list(expr.args) + for j, i in enumerate(args): + if isinstance(i, Relational) and ( + i.canonical.rhs is S.NegativeInfinity): + args.insert(0, args.pop(j)) + return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"]) + + def _print_Or(self, expr): + return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) + + def _print_Xor(self, expr): + return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) + + def _print_AppliedPredicate(self, expr): + return '%s(%s)' % ( + self._print(expr.function), self.stringify(expr.arguments, ", ")) + + def _print_Basic(self, expr): + l = [self._print(o) for o in expr.args] + return expr.__class__.__name__ + "(%s)" % ", ".join(l) + + def _print_BlockMatrix(self, B): + if B.blocks.shape == (1, 1): + self._print(B.blocks[0, 0]) + return self._print(B.blocks) + + def _print_Catalan(self, expr): + return 'Catalan' + + def _print_ComplexInfinity(self, expr): + return 'zoo' + + def _print_ConditionSet(self, s): + args = tuple([self._print(i) for i in (s.sym, s.condition)]) + if s.base_set is S.UniversalSet: + return 'ConditionSet(%s, %s)' % args + args += (self._print(s.base_set),) + return 'ConditionSet(%s, %s, %s)' % args + + def _print_Derivative(self, expr): + dexpr = expr.expr + dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] + return 'Derivative(%s)' % ", ".join((self._print(arg) for arg in [dexpr] + dvars)) + + def _print_dict(self, d): + keys = sorted(d.keys(), key=default_sort_key) + items = [] + + for key in keys: + item = "%s: %s" % (self._print(key), self._print(d[key])) + items.append(item) + + return "{%s}" % ", ".join(items) + + def _print_Dict(self, expr): + return self._print_dict(expr) + + def _print_RandomDomain(self, d): + if hasattr(d, 'as_boolean'): + return 'Domain: ' + self._print(d.as_boolean()) + elif hasattr(d, 'set'): + return ('Domain: ' + self._print(d.symbols) + ' in ' + + self._print(d.set)) + else: + return 'Domain on ' + self._print(d.symbols) + + def _print_Dummy(self, expr): + return '_' + expr.name + + def _print_EulerGamma(self, expr): + return 'EulerGamma' + + def _print_Exp1(self, expr): + return 'E' + + def _print_ExprCondPair(self, expr): + return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) + + def _print_Function(self, expr): + return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") + + def _print_GoldenRatio(self, expr): + return 'GoldenRatio' + + def _print_Heaviside(self, expr): + # Same as _print_Function but uses pargs to suppress default 1/2 for + # 2nd args + return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ") + + def _print_TribonacciConstant(self, expr): + return 'TribonacciConstant' + + def _print_ImaginaryUnit(self, expr): + return 'I' + + def _print_Infinity(self, expr): + return 'oo' + + def _print_Integral(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Integral(%s, %s)' % (self._print(expr.function), L) + + def _print_Interval(self, i): + fin = 'Interval{m}({a}, {b})' + a, b, l, r = i.args + if a.is_infinite and b.is_infinite: + m = '' + elif a.is_infinite and not r: + m = '' + elif b.is_infinite and not l: + m = '' + elif not l and not r: + m = '' + elif l and r: + m = '.open' + elif l: + m = '.Lopen' + else: + m = '.Ropen' + return fin.format(**{'a': a, 'b': b, 'm': m}) + + def _print_AccumulationBounds(self, i): + return "AccumBounds(%s, %s)" % (self._print(i.min), + self._print(i.max)) + + def _print_Inverse(self, I): + return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) + + def _print_Lambda(self, obj): + expr = obj.expr + sig = obj.signature + if len(sig) == 1 and sig[0].is_symbol: + sig = sig[0] + return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) + + def _print_LatticeOp(self, expr): + args = sorted(expr.args, key=default_sort_key) + return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) + + def _print_Limit(self, expr): + e, z, z0, dir = expr.args + return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) + + + def _print_list(self, expr): + return "[%s]" % self.stringify(expr, ", ") + + def _print_List(self, expr): + return self._print_list(expr) + + def _print_MatrixBase(self, expr): + return expr._format_str(self) + + def _print_MatrixElement(self, expr): + return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) + + def _print_MatrixSlice(self, expr): + def strslice(x, dim): + x = list(x) + if x[2] == 1: + del x[2] + if x[0] == 0: + x[0] = '' + if x[1] == dim: + x[1] = '' + return ':'.join((self._print(arg) for arg in x)) + return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + + strslice(expr.rowslice, expr.parent.rows) + ', ' + + strslice(expr.colslice, expr.parent.cols) + ']') + + def _print_DeferredVector(self, expr): + return expr.name + + def _print_Mul(self, expr): + + prec = precedence(expr) + + # Check for unevaluated Mul. In this case we need to make sure the + # identities are visible, multiple Rational factors are not combined + # etc so we display in a straight-forward form that fully preserves all + # args and their order. + args = expr.args + if args[0] is S.One or any( + isinstance(a, Number) or + a.is_Pow and all(ai.is_Integer for ai in a.args) + for a in args[1:]): + d, n = sift(args, lambda x: + isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), + binary=True) + for i, di in enumerate(d): + if di.exp.is_Number: + e = -di.exp + else: + dargs = list(di.exp.args) + dargs[0] = -dargs[0] + e = Mul._from_args(dargs) + d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base + + pre = [] + # don't parenthesize first factor if negative + if n and not n[0].is_Add and n[0].could_extract_minus_sign(): + pre = [self._print(n.pop(0))] + + nfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in n] + if not nfactors: + nfactors = ['1'] + + # don't parenthesize first of denominator unless singleton + if len(d) > 1 and d[0].could_extract_minus_sign(): + pre = [self._print(d.pop(0))] + else: + pre = [] + dfactors = pre + [self.parenthesize(a, prec, strict=False) + for a in d] + + n = '*'.join(nfactors) + d = '*'.join(dfactors) + if len(dfactors) > 1: + return '%s/(%s)' % (n, d) + elif dfactors: + return '%s/%s' % (n, d) + return n + + c, e = expr.as_coeff_Mul() + if c < 0: + expr = _keep_coeff(-c, e) + sign = "-" + else: + sign = "" + + a = [] # items in the numerator + b = [] # items that are in the denominator (if any) + + pow_paren = [] # Will collect all pow with more than one base element and exp = -1 + + if self.order not in ('old', 'none'): + args = expr.as_ordered_factors() + else: + # use make_args in case expr was something like -x -> x + args = Mul.make_args(expr) + + # Gather args for numerator/denominator + def apow(i): + b, e = i.as_base_exp() + eargs = list(Mul.make_args(e)) + if eargs[0] is S.NegativeOne: + eargs = eargs[1:] + else: + eargs[0] = -eargs[0] + e = Mul._from_args(eargs) + if isinstance(i, Pow): + return i.func(b, e, evaluate=False) + return i.func(e, evaluate=False) + for item in args: + if (item.is_commutative and + isinstance(item, Pow) and + bool(item.exp.as_coeff_Mul()[0] < 0)): + if item.exp is not S.NegativeOne: + b.append(apow(item)) + else: + if (len(item.args[0].args) != 1 and + isinstance(item.base, (Mul, Pow))): + # To avoid situations like #14160 + pow_paren.append(item) + b.append(item.base) + elif item.is_Rational and item is not S.Infinity: + if item.p != 1: + a.append(Rational(item.p)) + if item.q != 1: + b.append(Rational(item.q)) + else: + a.append(item) + + a = a or [S.One] + + a_str = [self.parenthesize(x, prec, strict=False) for x in a] + b_str = [self.parenthesize(x, prec, strict=False) for x in b] + + # To parenthesize Pow with exp = -1 and having more than one Symbol + for item in pow_paren: + if item.base in b: + b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] + + if not b: + return sign + '*'.join(a_str) + elif len(b) == 1: + return sign + '*'.join(a_str) + "/" + b_str[0] + else: + return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) + + def _print_MatMul(self, expr): + c, m = expr.as_coeff_mmul() + + sign = "" + if c.is_number: + re, im = c.as_real_imag() + if im.is_zero and re.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + elif re.is_zero and im.is_negative: + expr = _keep_coeff(-c, m) + sign = "-" + + return sign + '*'.join( + [self.parenthesize(arg, precedence(expr)) for arg in expr.args] + ) + + def _print_ElementwiseApplyFunction(self, expr): + return "{}.({})".format( + expr.function, + self._print(expr.expr), + ) + + def _print_NaN(self, expr): + return 'nan' + + def _print_NegativeInfinity(self, expr): + return '-oo' + + def _print_Order(self, expr): + if not expr.variables or all(p is S.Zero for p in expr.point): + if len(expr.variables) <= 1: + return 'O(%s)' % self._print(expr.expr) + else: + return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) + else: + return 'O(%s)' % self.stringify(expr.args, ', ', 0) + + def _print_Ordinal(self, expr): + return expr.__str__() + + def _print_Cycle(self, expr): + return expr.__str__() + + def _print_Permutation(self, expr): + from sympy.combinatorics.permutations import Permutation, Cycle + from sympy.utilities.exceptions import sympy_deprecation_warning + + perm_cyclic = Permutation.print_cyclic + if perm_cyclic is not None: + sympy_deprecation_warning( + f""" + Setting Permutation.print_cyclic is deprecated. Instead use + init_printing(perm_cyclic={perm_cyclic}). + """, + deprecated_since_version="1.6", + active_deprecations_target="deprecated-permutation-print_cyclic", + stacklevel=7, + ) + else: + perm_cyclic = self._settings.get("perm_cyclic", True) + + if perm_cyclic: + if not expr.size: + return '()' + # before taking Cycle notation, see if the last element is + # a singleton and move it to the head of the string + s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] + last = s.rfind('(') + if not last == 0 and ',' not in s[last:]: + s = s[last:] + s[:last] + s = s.replace(',', '') + return s + else: + s = expr.support() + if not s: + if expr.size < 5: + return 'Permutation(%s)' % self._print(expr.array_form) + return 'Permutation([], size=%s)' % self._print(expr.size) + trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) + use = full = self._print(expr.array_form) + if len(trim) < len(full): + use = trim + return 'Permutation(%s)' % use + + def _print_Subs(self, obj): + expr, old, new = obj.args + if len(obj.point) == 1: + old = old[0] + new = new[0] + return "Subs(%s, %s, %s)" % ( + self._print(expr), self._print(old), self._print(new)) + + def _print_TensorIndex(self, expr): + return expr._print() + + def _print_TensorHead(self, expr): + return expr._print() + + def _print_Tensor(self, expr): + return expr._print() + + def _print_TensMul(self, expr): + # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" + sign, args = expr._get_args_for_traditional_printer() + return sign + "*".join( + [self.parenthesize(arg, precedence(expr)) for arg in args] + ) + + def _print_TensAdd(self, expr): + return expr._print() + + def _print_ArraySymbol(self, expr): + return self._print(expr.name) + + def _print_ArrayElement(self, expr): + return "%s[%s]" % ( + self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices])) + + def _print_PermutationGroup(self, expr): + p = [' %s' % self._print(a) for a in expr.args] + return 'PermutationGroup([\n%s])' % ',\n'.join(p) + + def _print_Pi(self, expr): + return 'pi' + + def _print_PolyRing(self, ring): + return "Polynomial ring in %s over %s with %s order" % \ + (", ".join((self._print(rs) for rs in ring.symbols)), + self._print(ring.domain), self._print(ring.order)) + + def _print_FracField(self, field): + return "Rational function field in %s over %s with %s order" % \ + (", ".join((self._print(fs) for fs in field.symbols)), + self._print(field.domain), self._print(field.order)) + + def _print_FreeGroupElement(self, elm): + return elm.__str__() + + def _print_GaussianElement(self, poly): + return "(%s + %s*I)" % (poly.x, poly.y) + + def _print_PolyElement(self, poly): + return poly.str(self, PRECEDENCE, "%s**%s", "*") + + def _print_FracElement(self, frac): + if frac.denom == 1: + return self._print(frac.numer) + else: + numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) + denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) + return numer + "/" + denom + + def _print_Poly(self, expr): + ATOM_PREC = PRECEDENCE["Atom"] - 1 + terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] + + for monom, coeff in expr.terms(): + s_monom = [] + + for i, e in enumerate(monom): + if e > 0: + if e == 1: + s_monom.append(gens[i]) + else: + s_monom.append(gens[i] + "**%d" % e) + + s_monom = "*".join(s_monom) + + if coeff.is_Add: + if s_monom: + s_coeff = "(" + self._print(coeff) + ")" + else: + s_coeff = self._print(coeff) + else: + if s_monom: + if coeff is S.One: + terms.extend(['+', s_monom]) + continue + + if coeff is S.NegativeOne: + terms.extend(['-', s_monom]) + continue + + s_coeff = self._print(coeff) + + if not s_monom: + s_term = s_coeff + else: + s_term = s_coeff + "*" + s_monom + + if s_term.startswith('-'): + terms.extend(['-', s_term[1:]]) + else: + terms.extend(['+', s_term]) + + if terms[0] in ('-', '+'): + modifier = terms.pop(0) + + if modifier == '-': + terms[0] = '-' + terms[0] + + format = expr.__class__.__name__ + "(%s, %s" + + from sympy.polys.polyerrors import PolynomialError + + try: + format += ", modulus=%s" % expr.get_modulus() + except PolynomialError: + format += ", domain='%s'" % expr.get_domain() + + format += ")" + + for index, item in enumerate(gens): + if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): + gens[index] = item[1:len(item) - 1] + + return format % (' '.join(terms), ', '.join(gens)) + + def _print_UniversalSet(self, p): + return 'UniversalSet' + + def _print_AlgebraicNumber(self, expr): + if expr.is_aliased: + return self._print(expr.as_poly().as_expr()) + else: + return self._print(expr.as_expr()) + + def _print_Pow(self, expr, rational=False): + """Printing helper function for ``Pow`` + + Parameters + ========== + + rational : bool, optional + If ``True``, it will not attempt printing ``sqrt(x)`` or + ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` + instead. + + See examples for additional details + + Examples + ======== + + >>> from sympy import sqrt, StrPrinter + >>> from sympy.abc import x + + How ``rational`` keyword works with ``sqrt``: + + >>> printer = StrPrinter() + >>> printer._print_Pow(sqrt(x), rational=True) + 'x**(1/2)' + >>> printer._print_Pow(sqrt(x), rational=False) + 'sqrt(x)' + >>> printer._print_Pow(1/sqrt(x), rational=True) + 'x**(-1/2)' + >>> printer._print_Pow(1/sqrt(x), rational=False) + '1/sqrt(x)' + + Notes + ===== + + ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, + so there is no need of defining a separate printer for ``sqrt``. + Instead, it should be handled here as well. + """ + PREC = precedence(expr) + + if expr.exp is S.Half and not rational: + return "sqrt(%s)" % self._print(expr.base) + + if expr.is_commutative: + if -expr.exp is S.Half and not rational: + # Note: Don't test "expr.exp == -S.Half" here, because that will + # match -0.5, which we don't want. + return "%s/sqrt(%s)" % tuple((self._print(arg) for arg in (S.One, expr.base))) + if expr.exp is -S.One: + # Similarly to the S.Half case, don't test with "==" here. + return '%s/%s' % (self._print(S.One), + self.parenthesize(expr.base, PREC, strict=False)) + + e = self.parenthesize(expr.exp, PREC, strict=False) + if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: + # the parenthesized exp should be '(Rational(a, b))' so strip parens, + # but just check to be sure. + if e.startswith('(Rational'): + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) + + def _print_UnevaluatedExpr(self, expr): + return self._print(expr.args[0]) + + def _print_MatPow(self, expr): + PREC = precedence(expr) + return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), + self.parenthesize(expr.exp, PREC, strict=False)) + + def _print_Integer(self, expr): + if self._settings.get("sympy_integers", False): + return "S(%s)" % (expr) + return str(expr.p) + + def _print_Integers(self, expr): + return 'Integers' + + def _print_Naturals(self, expr): + return 'Naturals' + + def _print_Naturals0(self, expr): + return 'Naturals0' + + def _print_Rationals(self, expr): + return 'Rationals' + + def _print_Reals(self, expr): + return 'Reals' + + def _print_Complexes(self, expr): + return 'Complexes' + + def _print_EmptySet(self, expr): + return 'EmptySet' + + def _print_EmptySequence(self, expr): + return 'EmptySequence' + + def _print_int(self, expr): + return str(expr) + + def _print_mpz(self, expr): + return str(expr) + + def _print_Rational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + if self._settings.get("sympy_integers", False): + return "S(%s)/%s" % (expr.p, expr.q) + return "%s/%s" % (expr.p, expr.q) + + def _print_PythonRational(self, expr): + if expr.q == 1: + return str(expr.p) + else: + return "%d/%d" % (expr.p, expr.q) + + def _print_Fraction(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_mpq(self, expr): + if expr.denominator == 1: + return str(expr.numerator) + else: + return "%s/%s" % (expr.numerator, expr.denominator) + + def _print_Float(self, expr): + prec = expr._prec + dps = self._settings.get('dps', None) + if dps is None: + dps = 0 if prec < 5 else prec_to_dps(expr._prec) + if self._settings["full_prec"] is True: + strip = False + elif self._settings["full_prec"] is False: + strip = True + elif self._settings["full_prec"] == "auto": + strip = self._print_level > 1 + low = self._settings["min"] if "min" in self._settings else None + high = self._settings["max"] if "max" in self._settings else None + rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) + if rv.startswith('-.0'): + rv = '-0.' + rv[3:] + elif rv.startswith('.0'): + rv = '0.' + rv[2:] + rv = rv.removeprefix('+') # e.g., +inf -> inf + return rv + + def _print_Relational(self, expr): + + charmap = { + "==": "Eq", + "!=": "Ne", + ":=": "Assignment", + '+=': "AddAugmentedAssignment", + "-=": "SubAugmentedAssignment", + "*=": "MulAugmentedAssignment", + "/=": "DivAugmentedAssignment", + "%=": "ModAugmentedAssignment", + } + + if expr.rel_op in charmap: + return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), + self._print(expr.rhs)) + + return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), + self._relationals.get(expr.rel_op) or expr.rel_op, + self.parenthesize(expr.rhs, precedence(expr))) + + def _print_ComplexRootOf(self, expr): + return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), + expr.index) + + def _print_RootSum(self, expr): + args = [self._print_Add(expr.expr, order='lex')] + + if expr.fun is not S.IdentityFunction: + args.append(self._print(expr.fun)) + + return "RootSum(%s)" % ", ".join(args) + + def _print_GroebnerBasis(self, basis): + cls = basis.__class__.__name__ + + exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] + exprs = "[%s]" % ", ".join(exprs) + + gens = [ self._print(gen) for gen in basis.gens ] + domain = "domain='%s'" % self._print(basis.domain) + order = "order='%s'" % self._print(basis.order) + + args = [exprs] + gens + [domain, order] + + return "%s(%s)" % (cls, ", ".join(args)) + + def _print_set(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if not args: + return "set()" + return '{%s}' % args + + def _print_FiniteSet(self, s): + from sympy.sets.sets import FiniteSet + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(item) for item in items) + if any(item.has(FiniteSet) for item in items): + return 'FiniteSet({})'.format(args) + return '{{{}}}'.format(args) + + def _print_Partition(self, s): + items = sorted(s, key=default_sort_key) + + args = ', '.join(self._print(arg) for arg in items) + return 'Partition({})'.format(args) + + def _print_frozenset(self, s): + if not s: + return "frozenset()" + return "frozenset(%s)" % self._print_set(s) + + def _print_Sum(self, expr): + def _xab_tostr(xab): + if len(xab) == 1: + return self._print(xab[0]) + else: + return self._print((xab[0],) + tuple(xab[1:])) + L = ', '.join([_xab_tostr(l) for l in expr.limits]) + return 'Sum(%s, %s)' % (self._print(expr.function), L) + + def _print_Symbol(self, expr): + return expr.name + _print_MatrixSymbol = _print_Symbol + _print_RandomSymbol = _print_Symbol + + def _print_Identity(self, expr): + return "I" + + def _print_ZeroMatrix(self, expr): + return "0" + + def _print_OneMatrix(self, expr): + return "1" + + def _print_Predicate(self, expr): + return "Q.%s" % expr.name + + def _print_str(self, expr): + return str(expr) + + def _print_tuple(self, expr): + if len(expr) == 1: + return "(%s,)" % self._print(expr[0]) + else: + return "(%s)" % self.stringify(expr, ", ") + + def _print_Tuple(self, expr): + return self._print_tuple(expr) + + def _print_Transpose(self, T): + return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) + + def _print_Uniform(self, expr): + return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) + + def _print_Quantity(self, expr): + if self._settings.get("abbrev", False): + return "%s" % expr.abbrev + return "%s" % expr.name + + def _print_Quaternion(self, expr): + s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] + a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] + return " + ".join(a) + + def _print_Dimension(self, expr): + return str(expr) + + def _print_Wild(self, expr): + return expr.name + '_' + + def _print_WildFunction(self, expr): + return expr.name + '_' + + def _print_WildDot(self, expr): + return expr.name + + def _print_WildPlus(self, expr): + return expr.name + + def _print_WildStar(self, expr): + return expr.name + + def _print_Zero(self, expr): + if self._settings.get("sympy_integers", False): + return "S(0)" + return self._print_Integer(Integer(0)) + + def _print_DMP(self, p): + cls = p.__class__.__name__ + rep = self._print(p.to_list()) + dom = self._print(p.dom) + + return "%s(%s, %s)" % (cls, rep, dom) + + def _print_DMF(self, expr): + cls = expr.__class__.__name__ + num = self._print(expr.num) + den = self._print(expr.den) + dom = self._print(expr.dom) + + return "%s(%s, %s, %s)" % (cls, num, den, dom) + + def _print_Object(self, obj): + return 'Object("%s")' % obj.name + + def _print_IdentityMorphism(self, morphism): + return 'IdentityMorphism(%s)' % morphism.domain + + def _print_NamedMorphism(self, morphism): + return 'NamedMorphism(%s, %s, "%s")' % \ + (morphism.domain, morphism.codomain, morphism.name) + + def _print_Category(self, category): + return 'Category("%s")' % category.name + + def _print_Manifold(self, manifold): + return manifold.name.name + + def _print_Patch(self, patch): + return patch.name.name + + def _print_CoordSystem(self, coords): + return coords.name.name + + def _print_BaseScalarField(self, field): + return field._coord_sys.symbols[field._index].name + + def _print_BaseVectorField(self, field): + return 'e_%s' % field._coord_sys.symbols[field._index].name + + def _print_Differential(self, diff): + field = diff._form_field + if hasattr(field, '_coord_sys'): + return 'd%s' % field._coord_sys.symbols[field._index].name + else: + return 'd(%s)' % self._print(field) + + def _print_Tr(self, expr): + #TODO : Handle indices + return "%s(%s)" % ("Tr", self._print(expr.args[0])) + + def _print_Str(self, s): + return self._print(s.name) + + def _print_AppliedBinaryRelation(self, expr): + rel = expr.function + return '%s(%s, %s)' % (self._print(rel), + self._print(expr.lhs), + self._print(expr.rhs)) + + +@print_function(StrPrinter) +def sstr(expr, **settings): + """Returns the expression as a string. + + For large expressions where speed is a concern, use the setting + order='none'. If abbrev=True setting is used then units are printed in + abbreviated form. + + Examples + ======== + + >>> from sympy import symbols, Eq, sstr + >>> a, b = symbols('a b') + >>> sstr(Eq(a + b, 0)) + 'Eq(a + b, 0)' + """ + + p = StrPrinter(settings) + s = p.doprint(expr) + + return s + + +class StrReprPrinter(StrPrinter): + """(internal) -- see sstrrepr""" + + def _print_str(self, s): + return repr(s) + + def _print_Str(self, s): + # Str does not to be printed same as str here + return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) + +@print_function(StrReprPrinter) +def sstrrepr(expr, **settings): + """return expr in mixed str/repr form + + i.e. strings are returned in repr form with quotes, and everything else + is returned in str form. + + This function could be useful for hooking into sys.displayhook + """ + + p = StrReprPrinter(settings) + s = p.doprint(expr) + + return s diff --git a/shared/package-files/75/7534c4681d4c3b44b70e7da3e914a4b1f51bf199f4ad75888e3c25f838bb93a5/pass_manager.h b/shared/package-files/75/7534c4681d4c3b44b70e7da3e914a4b1f51bf199f4ad75888e3c25f838bb93a5/pass_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..efb19de59b5306ad09d096c8ee332204865c59e9 --- /dev/null +++ b/shared/package-files/75/7534c4681d4c3b44b70e7da3e914a4b1f51bf199f4ad75888e3c25f838bb93a5/pass_manager.h @@ -0,0 +1,134 @@ +#pragma once + +#include + +/* `getCustomPrePasses()` returns a vector of passes that will be executed + * after differentiation but before any fusion. This is the de-facto location + * for compiler backends to insert passes. + * + * `getCustomPostPasses()` returns a vector of passes that will be + * executed after differentiation and after fusion (if any). This is the + * location for fusion cleanup passes if they are needed. + * + * Static registration of a pass can be done by creating a global + * `Register{Pre,Post}Pass r(Pass)` variable in a compilation unit. + * + * pass_manager.h uses a Meyer's singleton to store a vector of `Pass`es, which + * modify the IR graph in place. + */ + +namespace torch::jit { + +// A pass modifies a Graph in place. +using GraphPass = std::function&)>; + +// Since Passes are std::functions, we associate a UUID to each pass, this way +// if we want to deregister a pass, we have something to reference it by. +using GraphPassNameType = unsigned int; + +// Graph pass entries have a name associated with them +using GraphPassEntry = std::pair; + +// Return currently registered passes. Passes are stored in a static vector +TORCH_API std::vector>& +getCustomPostPasses(); +TORCH_API std::vector>& +getCustomPrePasses(); + +TORCH_API GraphPassNameType registerPostPass(GraphPass p); +TORCH_API GraphPassNameType registerPrePass(GraphPass p); + +// Look up pass by name passed in, remove it from registered passes +TORCH_API void clearPostPass(GraphPassNameType p); +TORCH_API void clearPrePass(GraphPassNameType p); + +// Remove all passes +TORCH_API void clearAllPostPasses(); +TORCH_API void clearAllPrePasses(); + +// LEGACY CALL +struct TORCH_API RegisterPostPass { + RegisterPostPass(GraphPass p); +}; + +using RegisterPass = RegisterPostPass; + +/* + * PassManager is a wrapper on the register/clear PostPass functions above. It + * will register the pass provided in "registerPass" and will hold on to its + * associated name that way clearPass can be later called and will delete the + * pass used to register when called. + * + * PassManager is templated because we want static variables based on a + * particular GraphPass. When deriving from PassManager, you should send as the + * template parameter your derived class as you would for the curiously + * recurring template pattern. This template parameter isn't actually used and + * is simply done to prevent static members from being shared across derived + * types. + */ +template +struct C10_EXPORT PassManager { + private: + // We want this class to be abstract because it's + virtual void abstract() = 0; + + protected: + /* + * isRegistered() will return if a pass has been registered + * isRegistered(true) will change the value of the internal static bool + * + * There's an internal static bool to this function to keep track of the + * state, this is so when functions are derived from this class, they don't + * have to worry about initializing the static members. + */ + static bool isRegistered(bool flip_bit = false) { + static bool val = false; + if (flip_bit) + val = !val; + return val; + } + + /* + * name() will return the name of the registered pass + * name(pass_name, true) will set the name of the pass + * Similarly to isRegistered we use an internal static variable to hold the + * name. + */ + static GraphPassNameType passID( + GraphPassNameType PassID = 0, + bool set = false) { + static GraphPassNameType pass_id = 0; + if (set) + pass_id = PassID; + return pass_id; + } + + public: + // registerPass(pass) will register the pass provided and set the + // name/isRegistered functions appropriately, it returns a bool value + // indicating whether the given pass is already registered previously. + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + // If we don't already have a registered pass, register pass + // hold on to its name, change isRegistered to true + passID(registerPostPass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // Calls ClearPostPass(passID()) + static void clearPass() { + // If the pass is registered, clear it and change isRegistered to false. + if (isRegistered()) { + clearPostPass(passID()); + isRegistered(true); + } + } + + // clang-tidy requires virtual destructor; + virtual ~PassManager() = default; +}; + +} // namespace torch::jit diff --git a/shared/package-files/75/7546f144cbf0b1c772189a8afd13434707049dd827fd18efb08e21c82e47bf3b/acero.py b/shared/package-files/75/7546f144cbf0b1c772189a8afd13434707049dd827fd18efb08e21c82e47bf3b/acero.py new file mode 100644 index 0000000000000000000000000000000000000000..706338bd8cdb88e1fa9a1d5f301701d7116bc0f3 --- /dev/null +++ b/shared/package-files/75/7546f144cbf0b1c772189a8afd13434707049dd827fd18efb08e21c82e47bf3b/acero.py @@ -0,0 +1,410 @@ +# 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. + +# --------------------------------------------------------------------- +# Implement Internal ExecPlan bindings + +# cython: profile=False +# distutils: language = c++ +# cython: language_level = 3 + +from pyarrow.lib import Table, RecordBatch +from pyarrow.compute import Expression, field + +try: + from pyarrow._acero import ( # noqa + Declaration, + ExecNodeOptions, + TableSourceNodeOptions, + FilterNodeOptions, + ProjectNodeOptions, + AggregateNodeOptions, + OrderByNodeOptions, + HashJoinNodeOptions, + AsofJoinNodeOptions, + ) +except ImportError as exc: + raise ImportError( + f"The pyarrow installation is not built with support for 'acero' ({str(exc)})" + ) from None + + +try: + import pyarrow.dataset as ds + from pyarrow._dataset import ScanNodeOptions +except ImportError: + class DatasetModuleStub: + class Dataset: + pass + + class InMemoryDataset: + pass + ds = DatasetModuleStub + + +def _dataset_to_decl(dataset, use_threads=True, require_sequenced_output=False): + decl = Declaration("scan", ScanNodeOptions( + dataset, use_threads=use_threads, + require_sequenced_output=require_sequenced_output)) + + # Get rid of special dataset columns + # "__fragment_index", "__batch_index", "__last_in_fragment", "__filename" + projections = [field(f) for f in dataset.schema.names] + decl = Declaration.from_sequence( + [decl, Declaration("project", ProjectNodeOptions(projections))] + ) + + filter_expr = dataset._scan_options.get("filter") + if filter_expr is not None: + # Filters applied in CScanNodeOptions are "best effort" for the scan node itself + # so we always need to inject an additional Filter node to apply them for real. + decl = Declaration.from_sequence( + [decl, Declaration("filter", FilterNodeOptions(filter_expr))] + ) + + return decl + + +def _perform_join(join_type, left_operand, left_keys, + right_operand, right_keys, + left_suffix=None, right_suffix=None, + use_threads=True, coalesce_keys=False, + output_type=Table): + """ + Perform join of two tables or datasets. + + The result will be an output table with the result of the join operation + + Parameters + ---------- + join_type : str + One of supported join types. + left_operand : Table or Dataset + The left operand for the join operation. + left_keys : str or list[str] + The left key (or keys) on which the join operation should be performed. + right_operand : Table or Dataset + The right operand for the join operation. + right_keys : str or list[str] + The right key (or keys) on which the join operation should be performed. + left_suffix : str, default None + Which suffix to add to left column names. This prevents confusion + when the columns in left and right operands have colliding names. + right_suffix : str, default None + Which suffix to add to the right column names. This prevents confusion + when the columns in left and right operands have colliding names. + use_threads : bool, default True + Whether to use multithreading or not. + coalesce_keys : bool, default False + If the duplicated keys should be omitted from one of the sides + in the join result. + output_type: Table or InMemoryDataset + The output type for the exec plan result. + + Returns + ------- + result_table : Table or InMemoryDataset + """ + if not isinstance(left_operand, (Table, ds.Dataset)): + raise TypeError(f"Expected Table or Dataset, got {type(left_operand)}") + if not isinstance(right_operand, (Table, ds.Dataset)): + raise TypeError(f"Expected Table or Dataset, got {type(right_operand)}") + + # Prepare left and right tables Keys to send them to the C++ function + left_keys_order = {} + if not isinstance(left_keys, (tuple, list)): + left_keys = [left_keys] + for idx, key in enumerate(left_keys): + left_keys_order[key] = idx + + right_keys_order = {} + if not isinstance(right_keys, (list, tuple)): + right_keys = [right_keys] + for idx, key in enumerate(right_keys): + right_keys_order[key] = idx + + # By default expose all columns on both left and right table + left_columns = left_operand.schema.names + right_columns = right_operand.schema.names + + # Pick the join type + if join_type == "left semi" or join_type == "left anti": + right_columns = [] + elif join_type == "right semi" or join_type == "right anti": + left_columns = [] + elif join_type == "inner" or join_type == "left outer": + right_columns = [ + col for col in right_columns if col not in right_keys_order + ] + elif join_type == "right outer": + left_columns = [ + col for col in left_columns if col not in left_keys_order + ] + + # Turn the columns to vectors of FieldRefs + # and set aside indices of keys. + left_column_keys_indices = {} + for idx, colname in enumerate(left_columns): + if colname in left_keys: + left_column_keys_indices[colname] = idx + right_column_keys_indices = {} + for idx, colname in enumerate(right_columns): + if colname in right_keys: + right_column_keys_indices[colname] = idx + + # Add the join node to the execplan + if isinstance(left_operand, ds.Dataset): + left_source = _dataset_to_decl(left_operand, use_threads=use_threads) + else: + left_source = Declaration("table_source", TableSourceNodeOptions(left_operand)) + if isinstance(right_operand, ds.Dataset): + right_source = _dataset_to_decl(right_operand, use_threads=use_threads) + else: + right_source = Declaration( + "table_source", TableSourceNodeOptions(right_operand) + ) + + if coalesce_keys: + join_opts = HashJoinNodeOptions( + join_type, left_keys, right_keys, left_columns, right_columns, + output_suffix_for_left=left_suffix or "", + output_suffix_for_right=right_suffix or "", + ) + else: + join_opts = HashJoinNodeOptions( + join_type, left_keys, right_keys, + output_suffix_for_left=left_suffix or "", + output_suffix_for_right=right_suffix or "", + ) + decl = Declaration( + "hashjoin", options=join_opts, inputs=[left_source, right_source] + ) + + if coalesce_keys and join_type == "full outer": + # In case of full outer joins, the join operation will output all columns + # so that we can coalesce the keys and exclude duplicates in a subsequent + # projection. + left_columns_set = set(left_columns) + right_columns_set = set(right_columns) + # Where the right table columns start. + right_operand_index = len(left_columns) + projected_col_names = [] + projections = [] + for idx, col in enumerate(left_columns + right_columns): + if idx < len(left_columns) and col in left_column_keys_indices: + # Include keys only once and coalesce left+right table keys. + projected_col_names.append(col) + # Get the index of the right key that is being paired + # with this left key. We do so by retrieving the name + # of the right key that is in the same position in the provided keys + # and then looking up the index for that name in the right table. + right_key_index = right_column_keys_indices[ + right_keys[left_keys_order[col]]] + projections.append( + Expression._call("coalesce", [ + Expression._field(idx), Expression._field( + right_operand_index+right_key_index) + ]) + ) + elif idx >= right_operand_index and col in right_column_keys_indices: + # Do not include right table keys. As they would lead to duplicated keys + continue + else: + # For all the other columns include them as they are. + # Just recompute the suffixes that the join produced as the projection + # would lose them otherwise. + if ( + left_suffix and idx < right_operand_index + and col in right_columns_set + ): + col += left_suffix + if ( + right_suffix and idx >= right_operand_index + and col in left_columns_set + ): + col += right_suffix + projected_col_names.append(col) + projections.append( + Expression._field(idx) + ) + projection = Declaration( + "project", ProjectNodeOptions(projections, projected_col_names) + ) + decl = Declaration.from_sequence([decl, projection]) + + result_table = decl.to_table(use_threads=use_threads) + + if output_type == Table: + return result_table + elif output_type == ds.InMemoryDataset: + return ds.InMemoryDataset(result_table) + else: + raise TypeError("Unsupported output type") + + +def _perform_join_asof(left_operand, left_on, left_by, + right_operand, right_on, right_by, + tolerance, use_threads=True, + output_type=Table): + """ + Perform asof join of two tables or datasets. + + The result will be an output table with the result of the join operation + + Parameters + ---------- + left_operand : Table or Dataset + The left operand for the join operation. + left_on : str + The left key (or keys) on which the join operation should be performed. + left_by: str or list[str] + The left key (or keys) on which the join operation should be performed. + right_operand : Table or Dataset + The right operand for the join operation. + right_on : str or list[str] + The right key (or keys) on which the join operation should be performed. + right_by: str or list[str] + The right key (or keys) on which the join operation should be performed. + tolerance : int + The tolerance to use for the asof join. The tolerance is interpreted in + the same units as the "on" key. + output_type: Table or InMemoryDataset + The output type for the exec plan result. + + Returns + ------- + result_table : Table or InMemoryDataset + """ + if not isinstance(left_operand, (Table, ds.Dataset)): + raise TypeError(f"Expected Table or Dataset, got {type(left_operand)}") + if not isinstance(right_operand, (Table, ds.Dataset)): + raise TypeError(f"Expected Table or Dataset, got {type(right_operand)}") + + if not isinstance(left_by, (tuple, list)): + left_by = [left_by] + if not isinstance(right_by, (tuple, list)): + right_by = [right_by] + + # AsofJoin does not return on or by columns for right_operand. + right_columns = [ + col for col in right_operand.schema.names + if col not in [right_on] + right_by + ] + columns_collisions = set(left_operand.schema.names) & set(right_columns) + if columns_collisions: + raise ValueError( + "Columns {} present in both tables. AsofJoin does not support " + "column collisions.".format(columns_collisions), + ) + + # Add the join node to the execplan + if isinstance(left_operand, ds.Dataset): + left_source = _dataset_to_decl( + left_operand, + use_threads=use_threads, + require_sequenced_output=True) + else: + left_source = Declaration( + "table_source", TableSourceNodeOptions(left_operand), + ) + if isinstance(right_operand, ds.Dataset): + right_source = _dataset_to_decl( + right_operand, use_threads=use_threads, + require_sequenced_output=True) + else: + right_source = Declaration( + "table_source", TableSourceNodeOptions(right_operand) + ) + + join_opts = AsofJoinNodeOptions( + left_on, left_by, right_on, right_by, tolerance + ) + decl = Declaration( + "asofjoin", options=join_opts, inputs=[left_source, right_source] + ) + + result_table = decl.to_table(use_threads=use_threads) + + if output_type == Table: + return result_table + elif output_type == ds.InMemoryDataset: + return ds.InMemoryDataset(result_table) + else: + raise TypeError("Unsupported output type") + + +def _filter_table(table, expression): + """Filter rows of a table based on the provided expression. + + The result will be an output table with only the rows matching + the provided expression. + + Parameters + ---------- + table : Table or RecordBatch + Table that should be filtered. + expression : Expression + The expression on which rows should be filtered. + + Returns + ------- + Table + """ + is_batch = False + if isinstance(table, RecordBatch): + table = Table.from_batches([table]) + is_batch = True + + decl = Declaration.from_sequence([ + Declaration("table_source", options=TableSourceNodeOptions(table)), + Declaration("filter", options=FilterNodeOptions(expression)) + ]) + result = decl.to_table(use_threads=True) + if is_batch: + result = result.combine_chunks().to_batches()[0] + return result + + +def _sort_source(table_or_dataset, sort_keys, output_type=Table, **kwargs): + + if isinstance(table_or_dataset, ds.Dataset): + data_source = _dataset_to_decl(table_or_dataset, use_threads=True) + else: + data_source = Declaration( + "table_source", TableSourceNodeOptions(table_or_dataset) + ) + + order_by = Declaration("order_by", OrderByNodeOptions(sort_keys, **kwargs)) + + decl = Declaration.from_sequence([data_source, order_by]) + result_table = decl.to_table(use_threads=True) + + if output_type == Table: + return result_table + elif output_type == ds.InMemoryDataset: + return ds.InMemoryDataset(result_table) + else: + raise TypeError("Unsupported output type") + + +def _group_by(table, aggregates, keys, use_threads=True): + + decl = Declaration.from_sequence([ + Declaration("table_source", TableSourceNodeOptions(table)), + Declaration("aggregate", AggregateNodeOptions(aggregates, keys=keys)) + ]) + return decl.to_table(use_threads=use_threads) diff --git a/shared/package-files/75/754de25f9288d65ec76e4ca3ce04e068efaeb90b762c70f074a344fe580c631b/bamtk.c b/shared/package-files/75/754de25f9288d65ec76e4ca3ce04e068efaeb90b762c70f074a344fe580c631b/bamtk.c new file mode 100644 index 0000000000000000000000000000000000000000..8c330bc2b869aaabc4a0ce7423251a27eccd8cc9 --- /dev/null +++ b/shared/package-files/75/754de25f9288d65ec76e4ca3ce04e068efaeb90b762c70f074a344fe580c631b/bamtk.c @@ -0,0 +1,316 @@ +/* bamtk.c -- main samtools command front-end. + + Copyright (C) 2008-2023 Genome Research Ltd. + + Author: Heng Li + +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. */ + +#include + +#include +#include +#include +#include + +#include "htslib/hts.h" +#include "htslib/hfile.h" +#include "samtools.h" +#include "version.h" + +int bam_taf2baf(int argc, char *argv[]); +int bam_mpileup(int argc, char *argv[]); +int bam_merge(int argc, char *argv[]); +int bam_index(int argc, char *argv[]); +int bam_sort(int argc, char *argv[]); +int bam_tview_main(int argc, char *argv[]); +int bam_mating(int argc, char *argv[]); +int bam_rmdup(int argc, char *argv[]); +int bam_flagstat(int argc, char *argv[]); +int bam_fillmd(int argc, char *argv[]); +int bam_idxstats(int argc, char *argv[]); +int bam_markdup(int argc, char *argv[]); +int main_samview(int argc, char *argv[]); +int main_head(int argc, char *argv[]); +int main_reheader(int argc, char *argv[]); +int main_cut_target(int argc, char *argv[]); +int main_phase(int argc, char *argv[]); +int main_cat(int argc, char *argv[]); +int main_depth(int argc, char *argv[]); +int main_coverage(int argc, char *argv[]); +int main_bam2fq(int argc, char *argv[]); +int main_pad2unpad(int argc, char *argv[]); +int main_bedcov(int argc, char *argv[]); +int main_bamshuf(int argc, char *argv[]); +int main_stats(int argc, char *argv[]); +int main_flags(int argc, char *argv[]); +int main_split(int argc, char *argv[]); +int main_quickcheck(int argc, char *argv[]); +int main_addreplacerg(int argc, char *argv[]); +int faidx_main(int argc, char *argv[]); +int dict_main(int argc, char *argv[]); +int fqidx_main(int argc, char *argv[]); +int amplicon_clip_main(int argc, char *argv[]); +int main_ampliconstats(int argc, char *argv[]); +int main_import(int argc, char *argv[]); +int main_samples(int argc, char *argv[]); +int main_consensus(int argc, char *argv[]); +int main_reference(int argc, char *argv[]); +int main_reset(int argc, char *argv[]); +int main_cram_size(int argc, char *argv[]); + +const char *samtools_version(void) +{ + return SAMTOOLS_VERSION; +} + +// These come out of the config.h file built by autoconf or Makefile +const char *samtools_feature_string(void) { + const char *fmt = + +#ifdef PACKAGE_URL + "build=configure " +#else + "build=Makefile " +#endif + +#ifdef HAVE_CURSES + "curses=yes " +#else + "curses=no " +#endif + ; + + return fmt; +} + +static void long_version(void) { + printf("samtools %s\n" + "Using htslib %s\n" + "Copyright (C) 2024 Genome Research Ltd.\n", + samtools_version(), hts_version()); + + printf("\nSamtools compilation details:\n"); + printf(" Features: %s\n", samtools_feature_string()); + printf(" CC: %s\n", SAMTOOLS_CC); + printf(" CPPFLAGS: %s\n", SAMTOOLS_CPPFLAGS); + printf(" CFLAGS: %s\n", SAMTOOLS_CFLAGS); + printf(" LDFLAGS: %s\n", SAMTOOLS_LDFLAGS); + printf(" HTSDIR: %s\n", SAMTOOLS_HTSDIR); + printf(" LIBS: %s\n", SAMTOOLS_LIBS); + printf(" CURSES_LIB: %s\n", SAMTOOLS_CURSES_LIB); + + printf("\nHTSlib compilation details:\n"); + printf(" Features: %s\n", hts_feature_string()); + printf(" CC: %s\n", hts_test_feature(HTS_FEATURE_CC)); + printf(" CPPFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CPPFLAGS)); + printf(" CFLAGS: %s\n", hts_test_feature(HTS_FEATURE_CFLAGS)); + printf(" LDFLAGS: %s\n", hts_test_feature(HTS_FEATURE_LDFLAGS)); + + // Plugins and schemes + printf("\nHTSlib URL scheme handlers present:\n"); + const char *plugins[100]; + int np = 100, i, j; + + if (hfile_list_plugins(plugins, &np) < 0) + return; + + for (i = 0; i < np; i++) { + const char *sc_list[100]; + int nschemes = 100; + if (hfile_list_schemes(plugins[i], sc_list, &nschemes) < 0) + return; + + printf(" %s:\t", plugins[i]); + for (j = 0; j < nschemes; j++) + printf(" %s%c", sc_list[j], ",\n"[j+1==nschemes]); + } +} + +static void usage(FILE *fp) +{ + /* Please improve the grouping */ + + fprintf(fp, +"\n" +"Program: samtools (Tools for alignments in the SAM format)\n" +"Version: %s (using htslib %s)\n\n", samtools_version(), hts_version()); + fprintf(fp, +"Usage: samtools [options]\n" +"\n" +"Commands:\n" +" -- Indexing\n" +" dict create a sequence dictionary file\n" +" faidx index/extract FASTA\n" +" fqidx index/extract FASTQ\n" +" index index alignment\n" +"\n" +" -- Editing\n" +" calmd recalculate MD/NM tags and '=' bases\n" +" fixmate fix mate information\n" +" reheader replace BAM header\n" +" targetcut cut fosmid regions (for fosmid pool only)\n" +" addreplacerg adds or replaces RG tags\n" +" markdup mark duplicates\n" +" ampliconclip clip oligos from the end of reads\n" +"\n" +" -- File operations\n" +" collate shuffle and group alignments by name\n" +" cat concatenate BAMs\n" +" consensus produce a consensus Pileup/FASTA/FASTQ\n" +" merge merge sorted alignments\n" +" mpileup multi-way pileup\n" +" sort sort alignment file\n" +" split splits a file by read group\n" +" quickcheck quickly check if SAM/BAM/CRAM file appears intact\n" +" fastq converts a BAM to a FASTQ\n" +" fasta converts a BAM to a FASTA\n" +" import Converts FASTA or FASTQ files to SAM/BAM/CRAM\n" +" reference Generates a reference from aligned data\n" +" reset Reverts aligner changes in reads\n" +"\n" +" -- Statistics\n" +" bedcov read depth per BED region\n" +" coverage alignment depth and percent coverage\n" +" depth compute the depth\n" +" flagstat simple stats\n" +" idxstats BAM index stats\n" +" cram-size list CRAM Content-ID and Data-Series sizes\n" +" phase phase heterozygotes\n" +" stats generate stats (former bamcheck)\n" +" ampliconstats generate amplicon specific stats\n" +"\n" +" -- Viewing\n" +" flags explain BAM flags\n" +" head header viewer\n" +" tview text alignment viewer\n" +" view SAM<->BAM<->CRAM conversion\n" +" depad convert padded BAM to unpadded BAM\n" +" samples list the samples in a set of SAM/BAM/CRAM files\n" +"\n" +" -- Misc\n" +" help [cmd] display this help message or help for [cmd]\n" +" version detailed version information\n" +"\n"); +} + +// This is a tricky one, but on Windows the filename wildcard expansion is done by +// the application and not by the shell, as traditionally it never had a "shell". +// Even now, DOS and Powershell do not do this expansion (but bash does). +// +// This means that Mingw/Msys implements code before main() that takes e.g. "*" and +// expands it up to a list of matching filenames. This in turn breaks things like +// specifying "*" as a region (all the unmapped reads). We take a hard line here - +// filename expansion is the task of the shell, not our application! +#ifdef _WIN32 +int _CRT_glob = 0; +#endif + +int main(int argc, char *argv[]) +{ +#ifdef _WIN32 + setmode(fileno(stdout), O_BINARY); + setmode(fileno(stdin), O_BINARY); +#endif + if (argc < 2) { usage(stderr); return 1; } + + if (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "--help") == 0) { + if (argc == 2) { usage(stdout); return 0; } + + // Otherwise change "samtools help COMMAND [...]" to "samtools COMMAND"; + // main_xyz() functions by convention display the subcommand's usage + // when invoked without any arguments. + argv++; + argc = 2; + } + + int ret = 0; + if (strcmp(argv[1], "view") == 0) ret = main_samview(argc-1, argv+1); + else if (strcmp(argv[1], "import") == 0) ret = main_import(argc-1, argv+1); + else if (strcmp(argv[1], "mpileup") == 0) ret = bam_mpileup(argc-1, argv+1); + else if (strcmp(argv[1], "merge") == 0) ret = bam_merge(argc-1, argv+1); + else if (strcmp(argv[1], "sort") == 0) ret = bam_sort(argc-1, argv+1); + else if (strcmp(argv[1], "index") == 0) ret = bam_index(argc-1, argv+1); + else if (strcmp(argv[1], "idxstat") == 0 || + strcmp(argv[1], "idxstats") == 0) ret = bam_idxstats(argc-1, argv+1); + else if (strcmp(argv[1], "faidx") == 0) ret = faidx_main(argc-1, argv+1); + else if (strcmp(argv[1], "fqidx") == 0) ret = fqidx_main(argc-1, argv+1); + else if (strcmp(argv[1], "dict") == 0) ret = dict_main(argc-1, argv+1); + else if (strcmp(argv[1], "head") == 0) ret = main_head(argc-1, argv+1); + else if (strcmp(argv[1], "fixmate") == 0) ret = bam_mating(argc-1, argv+1); + else if (strcmp(argv[1], "rmdup") == 0) ret = bam_rmdup(argc-1, argv+1); + else if (strcmp(argv[1], "markdup") == 0) ret = bam_markdup(argc-1, argv+1); + else if (strcmp(argv[1], "ampliconclip") == 0) ret = amplicon_clip_main(argc-1, argv+1); + else if (strcmp(argv[1], "flagstat") == 0 || + strcmp(argv[1], "flagstats") == 0) ret = bam_flagstat(argc-1, argv+1); + else if (strcmp(argv[1], "calmd") == 0) ret = bam_fillmd(argc-1, argv+1); + else if (strcmp(argv[1], "fillmd") == 0) ret = bam_fillmd(argc-1, argv+1); + else if (strcmp(argv[1], "reheader") == 0) ret = main_reheader(argc-1, argv+1); + else if (strcmp(argv[1], "cat") == 0) ret = main_cat(argc-1, argv+1); + else if (strcmp(argv[1], "targetcut") == 0) ret = main_cut_target(argc-1, argv+1); + else if (strcmp(argv[1], "phase") == 0) ret = main_phase(argc-1, argv+1); + else if (strcmp(argv[1], "depth") == 0) ret = main_depth(argc-1, argv+1); + else if (strcmp(argv[1], "coverage") == 0) ret = main_coverage(argc-1, argv+1); + else if (strcmp(argv[1], "bam2fq") == 0 || + strcmp(argv[1], "fastq") == 0 || + strcmp(argv[1], "fasta") == 0) ret = main_bam2fq(argc-1, argv+1); + else if (strcmp(argv[1], "pad2unpad") == 0) ret = main_pad2unpad(argc-1, argv+1); + else if (strcmp(argv[1], "depad") == 0) ret = main_pad2unpad(argc-1, argv+1); + else if (strcmp(argv[1], "bedcov") == 0) ret = main_bedcov(argc-1, argv+1); + else if (strcmp(argv[1], "bamshuf") == 0) ret = main_bamshuf(argc-1, argv+1); + else if (strcmp(argv[1], "collate") == 0) ret = main_bamshuf(argc-1, argv+1); + else if (strcmp(argv[1], "stat") == 0 || + strcmp(argv[1], "stats") == 0) ret = main_stats(argc-1, argv+1); + else if (strcmp(argv[1], "flag") == 0 || + strcmp(argv[1], "flags") == 0) ret = main_flags(argc-1, argv+1); + else if (strcmp(argv[1], "split") == 0) ret = main_split(argc-1, argv+1); + else if (strcmp(argv[1], "quickcheck") == 0) ret = main_quickcheck(argc-1, argv+1); + else if (strcmp(argv[1], "addreplacerg") == 0) ret = main_addreplacerg(argc-1, argv+1); + else if (strcmp(argv[1], "pileup") == 0) { + fprintf(stderr, "[main] The `pileup' command has been removed. Please use `mpileup' instead.\n"); + return 1; + } + else if (strcmp(argv[1], "tview") == 0) ret = bam_tview_main(argc-1, argv+1); + else if (strcmp(argv[1], "ampliconstats") == 0) ret = main_ampliconstats(argc-1, argv+1); + else if (strcmp(argv[1], "samples") == 0) ret = main_samples(argc-1, argv+1); + else if (strcmp(argv[1], "consensus") == 0) ret = main_consensus(argc-1, argv+1); + else if (strcmp(argv[1], "reference") == 0) ret = main_reference(argc-1, argv+1); + else if (strcmp(argv[1], "cram-size") == 0) ret = main_cram_size(argc-1, argv+1); + else if (strcmp(argv[1], "version") == 0 || \ + strcmp(argv[1], "--version") == 0) + long_version(); + else if (strcmp(argv[1], "--version-only") == 0) { + printf("%s+htslib-%s\n", samtools_version(), hts_version()); + } + else if (strcmp(argv[1], "reset") == 0) ret = main_reset(argc-1, argv+1); + else { + fprintf(stderr, "[main] unrecognized command '%s'\n", argv[1]); + return 1; + } + + // For subcommands that may have produced substantial output on stdout, + // make a final check for delayed I/O errors. Ignore EBADF as other code + // may have already closed stdout. + if (fclose(stdout) != 0 && errno != EBADF) { + print_error_errno(argv[1], "closing standard output failed"); + return 1; + } + + return ret; +} diff --git a/shared/package-files/75/7552403d18cac0ab4e7a81dea03de2667bb5d1490d5ed6063c5018a376e522d0/objects.cpython-311.pyc b/shared/package-files/75/7552403d18cac0ab4e7a81dea03de2667bb5d1490d5ed6063c5018a376e522d0/objects.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec116ee5233eb10f3d1e898fea2d60f0d6fd99ba Binary files /dev/null and b/shared/package-files/75/7552403d18cac0ab4e7a81dea03de2667bb5d1490d5ed6063c5018a376e522d0/objects.cpython-311.pyc differ diff --git a/shared/package-files/75/7556cffebb8160f1cb842ad608084d4a1b3e4b47b01f093cea24448abced2c01/_functools.cpython-311.pyc b/shared/package-files/75/7556cffebb8160f1cb842ad608084d4a1b3e4b47b01f093cea24448abced2c01/_functools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..001cf7bb97a2876f5fd8c2fda303ca74c6e971a6 Binary files /dev/null and b/shared/package-files/75/7556cffebb8160f1cb842ad608084d4a1b3e4b47b01f093cea24448abced2c01/_functools.cpython-311.pyc differ diff --git a/shared/package-files/75/7559e9149624757f3318dda8741da1b23967264a3ba012ab0a9100ae95d62574/degree_alg.cpython-311.pyc b/shared/package-files/75/7559e9149624757f3318dda8741da1b23967264a3ba012ab0a9100ae95d62574/degree_alg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f93b14586d99f2f684a105757224cbce1d599cec Binary files /dev/null and b/shared/package-files/75/7559e9149624757f3318dda8741da1b23967264a3ba012ab0a9100ae95d62574/degree_alg.cpython-311.pyc differ diff --git a/shared/package-files/75/756cd348a72a1a12b8cc78268096f28acda4cc1ebd387ef518ffd80830436e9d/pytree_hacks.py b/shared/package-files/75/756cd348a72a1a12b8cc78268096f28acda4cc1ebd387ef518ffd80830436e9d/pytree_hacks.py new file mode 100644 index 0000000000000000000000000000000000000000..96dea7ad100705ae53139aa5ae729fd2206182af --- /dev/null +++ b/shared/package-files/75/756cd348a72a1a12b8cc78268096f28acda4cc1ebd387ef518ffd80830436e9d/pytree_hacks.py @@ -0,0 +1,23 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import warnings + +# TODO: remove this file when the migration of the pytree utility is done +from torch.utils._pytree import tree_map_, treespec_pprint + + +__all__ = ["tree_map_", "treespec_pprint"] + + +with warnings.catch_warnings(): + warnings.simplefilter("always") + warnings.warn( + "`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. " + "Please `use torch.utils._pytree` instead.", + DeprecationWarning, + stacklevel=2, + ) diff --git a/shared/package-files/75/756d1a1ef2d1e543f2c97cc14beb602ab408a7e1fa56ef2c2a3950ac1420b59e/test_interface.py b/shared/package-files/75/756d1a1ef2d1e543f2c97cc14beb602ab408a7e1fa56ef2c2a3950ac1420b59e/test_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae2f78b50bea24c64079066076971e315660d69 --- /dev/null +++ b/shared/package-files/75/756d1a1ef2d1e543f2c97cc14beb602ab408a7e1fa56ef2c2a3950ac1420b59e/test_interface.py @@ -0,0 +1,82 @@ +# This test file tests the SymPy function interface, that people use to create +# their own new functions. It should be as easy as possible. +# +# We test that it works with both Function and DefinedFunction. New code should +# use DefinedFunction because it has better type inference. Old code still +# using Function should continue to work though. +from sympy.core.function import Function, DefinedFunction +from sympy.core.sympify import sympify +from sympy.functions.elementary.hyperbolic import tanh +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.series.limits import limit +from sympy.abc import x + + +def test_function_series1(): + """Create our new "sin" function.""" + + for F in [Function, DefinedFunction]: + + class my_function(F): + + def fdiff(self, argindex=1): + return cos(self.args[0]) + + @classmethod + def eval(cls, arg): + arg = sympify(arg) + if arg == 0: + return sympify(0) + + #Test that the taylor series is correct + assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10) + assert limit(my_function(x)/x, x, 0) == 1 + + +def test_function_series2(): + """Create our new "cos" function.""" + + for F in [Function, DefinedFunction]: + + class my_function2(F): + + def fdiff(self, argindex=1): + return -sin(self.args[0]) + + @classmethod + def eval(cls, arg): + arg = sympify(arg) + if arg == 0: + return sympify(1) + + #Test that the taylor series is correct + assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10) + + +def test_function_series3(): + """ + Test our easy "tanh" function. + + This test tests two things: + * that the Function interface works as expected and it's easy to use + * that the general algorithm for the series expansion works even when the + derivative is defined recursively in terms of the original function, + since tanh(x).diff(x) == 1-tanh(x)**2 + """ + + for F in [Function, DefinedFunction]: + + class mytanh(F): + + def fdiff(self, argindex=1): + return 1 - mytanh(self.args[0])**2 + + @classmethod + def eval(cls, arg): + arg = sympify(arg) + if arg == 0: + return sympify(0) + + e = tanh(x) + f = mytanh(x) + assert e.series(x, 0, 6) == f.series(x, 0, 6) diff --git a/shared/package-files/75/7575dc6910595c8b761deaef24b0b5802c432e5871bba30cfccde0c5c695d51c/test_pandas.py b/shared/package-files/75/7575dc6910595c8b761deaef24b0b5802c432e5871bba30cfccde0c5c695d51c/test_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea2f46873aef09e111122f7a6f48942b4d1b731 --- /dev/null +++ b/shared/package-files/75/7575dc6910595c8b761deaef24b0b5802c432e5871bba30cfccde0c5c695d51c/test_pandas.py @@ -0,0 +1,657 @@ +# 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 io +import json + +try: + import numpy as np +except ImportError: + np = None +import pytest + +import pyarrow as pa +from pyarrow.fs import LocalFileSystem, SubTreeFileSystem +from pyarrow.util import guid +from pyarrow.vendored.version import Version + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import (_read_table, _test_dataframe, + _write_table) +except ImportError: + pq = None + + +try: + import pandas as pd + import pandas.testing as tm + + from pyarrow.tests.parquet.common import (_roundtrip_pandas_dataframe, + alltypes_sample) +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = pytest.mark.parquet + + +@pytest.mark.pandas +def test_pandas_parquet_custom_metadata(tempdir): + df = alltypes_sample(size=10000) + + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df) + assert b'pandas' in arrow_table.schema.metadata + + _write_table(arrow_table, filename) + + metadata = pq.read_metadata(filename).metadata + assert b'pandas' in metadata + + js = json.loads(metadata[b'pandas'].decode('utf8')) + assert js['index_columns'] == [{'kind': 'range', + 'name': None, + 'start': 0, 'stop': 10000, + 'step': 1}] + + +@pytest.mark.pandas +def test_merging_parquet_tables_with_different_pandas_metadata(tempdir): + # ARROW-3728: Merging Parquet Files - Pandas Meta in Schema Mismatch + schema = pa.schema([ + pa.field('int', pa.int16()), + pa.field('float', pa.float32()), + pa.field('string', pa.string()) + ]) + df1 = pd.DataFrame({ + 'int': np.arange(3, dtype=np.uint8), + 'float': np.arange(3, dtype=np.float32), + 'string': ['ABBA', 'EDDA', 'ACDC'] + }) + df2 = pd.DataFrame({ + 'int': [4, 5], + 'float': [1.1, None], + 'string': [None, None] + }) + table1 = pa.Table.from_pandas(df1, schema=schema, preserve_index=False) + table2 = pa.Table.from_pandas(df2, schema=schema, preserve_index=False) + + assert not table1.schema.equals(table2.schema, check_metadata=True) + assert table1.schema.equals(table2.schema) + + writer = pq.ParquetWriter(tempdir / 'merged.parquet', schema=schema) + writer.write_table(table1) + writer.write_table(table2) + + +@pytest.mark.pandas +def test_pandas_parquet_column_multiindex(tempdir): + df = alltypes_sample(size=10) + df.columns = pd.MultiIndex.from_tuples( + list(zip(df.columns, df.columns[::-1])), + names=['level_1', 'level_2'] + ) + + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df) + assert arrow_table.schema.pandas_metadata is not None + + _write_table(arrow_table, filename) + + table_read = pq.read_pandas(filename) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +def test_pandas_parquet_2_0_roundtrip_read_pandas_no_index_written(tempdir): + df = alltypes_sample(size=10000) + + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + js = arrow_table.schema.pandas_metadata + assert not js['index_columns'] + # ARROW-2170 + # While index_columns should be empty, columns needs to be filled still. + assert js['columns'] + + _write_table(arrow_table, filename) + table_read = pq.read_pandas(filename) + + js = table_read.schema.pandas_metadata + assert not js['index_columns'] + + read_metadata = table_read.schema.metadata + assert arrow_table.schema.metadata == read_metadata + + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +def test_pandas_parquet_native_file_roundtrip(): + df = _test_dataframe(10000) + arrow_table = pa.Table.from_pandas(df) + imos = pa.BufferOutputStream() + _write_table(arrow_table, imos, version='2.6') + buf = imos.getvalue() + reader = pa.BufferReader(buf) + df_read = _read_table(reader).to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +def test_read_pandas_column_subset(): + df = _test_dataframe(10000) + arrow_table = pa.Table.from_pandas(df) + imos = pa.BufferOutputStream() + _write_table(arrow_table, imos, version='2.6') + buf = imos.getvalue() + reader = pa.BufferReader(buf) + df_read = pq.read_pandas( + reader, columns=['strings', 'uint8'], + ).to_pandas() + tm.assert_frame_equal(df[['strings', 'uint8']], df_read) + + +@pytest.mark.pandas +def test_pandas_parquet_empty_roundtrip(): + df = _test_dataframe(0) + arrow_table = pa.Table.from_pandas(df) + imos = pa.BufferOutputStream() + _write_table(arrow_table, imos, version='2.6') + buf = imos.getvalue() + reader = pa.BufferReader(buf) + df_read = _read_table(reader).to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +def test_pandas_can_write_nested_data(): + data = { + "agg_col": [ + {"page_type": 1}, + {"record_type": 1}, + {"non_consecutive_home": 0}, + ], + "uid_first": "1001" + } + df = pd.DataFrame(data=data) + arrow_table = pa.Table.from_pandas(df) + imos = pa.BufferOutputStream() + # This succeeds under V2 + _write_table(arrow_table, imos) + + +@pytest.mark.pandas +def test_pandas_parquet_pyfile_roundtrip(tempdir): + filename = tempdir / 'pandas_pyfile_roundtrip.parquet' + size = 5 + df = pd.DataFrame({ + 'int64': np.arange(size, dtype=np.int64), + 'float32': np.arange(size, dtype=np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0, + 'strings': ['foo', 'bar', None, 'baz', 'qux'] + }) + + arrow_table = pa.Table.from_pandas(df) + + with filename.open('wb') as f: + _write_table(arrow_table, f, version="2.6") + + data = io.BytesIO(filename.read_bytes()) + + table_read = _read_table(data) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +def test_pandas_parquet_configuration_options(tempdir): + size = 10000 + np.random.seed(0) + df = pd.DataFrame({ + 'uint8': np.arange(size, dtype=np.uint8), + 'uint16': np.arange(size, dtype=np.uint16), + 'uint32': np.arange(size, dtype=np.uint32), + 'uint64': np.arange(size, dtype=np.uint64), + 'int8': np.arange(size, dtype=np.int16), + 'int16': np.arange(size, dtype=np.int16), + 'int32': np.arange(size, dtype=np.int32), + 'int64': np.arange(size, dtype=np.int64), + 'float32': np.arange(size, dtype=np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0 + }) + filename = tempdir / 'pandas_roundtrip.parquet' + arrow_table = pa.Table.from_pandas(df) + + for use_dictionary in [True, False]: + _write_table(arrow_table, filename, version='2.6', + use_dictionary=use_dictionary) + table_read = _read_table(filename) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + for write_statistics in [True, False]: + _write_table(arrow_table, filename, version='2.6', + write_statistics=write_statistics) + table_read = _read_table(filename) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + for compression in ['NONE', 'SNAPPY', 'GZIP', 'LZ4', 'ZSTD']: + if (compression != 'NONE' and + not pa.lib.Codec.is_available(compression)): + continue + _write_table(arrow_table, filename, version='2.6', + compression=compression) + table_read = _read_table(filename) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + +@pytest.mark.pandas +@pytest.mark.filterwarnings("ignore:Parquet format '2.0':FutureWarning") +def test_spark_flavor_preserves_pandas_metadata(): + df = _test_dataframe(size=100) + df.index = np.arange(0, 10 * len(df), 10) + df.index.name = 'foo' + + result = _roundtrip_pandas_dataframe(df, {'version': '2.0', + 'flavor': 'spark'}) + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_index_column_name_duplicate(tempdir): + data = { + 'close': { + pd.Timestamp('2017-06-30 01:31:00'): 154.99958999999998, + pd.Timestamp('2017-06-30 01:32:00'): 154.99958999999998, + }, + 'time': { + pd.Timestamp('2017-06-30 01:31:00'): pd.Timestamp( + '2017-06-30 01:31:00' + ), + pd.Timestamp('2017-06-30 01:32:00'): pd.Timestamp( + '2017-06-30 01:32:00' + ), + } + } + path = str(tempdir / 'data.parquet') + + # Pandas v2 defaults to [ns], but Arrow defaults to [us] time units + # so we need to cast the pandas dtype. Pandas v1 will always silently + # coerce to [ns] due to lack of non-[ns] support. + dfx = pd.DataFrame(data, dtype='datetime64[us]').set_index('time', drop=False) + + tdfx = pa.Table.from_pandas(dfx) + _write_table(tdfx, path) + arrow_table = _read_table(path) + result_df = arrow_table.to_pandas() + tm.assert_frame_equal(result_df, dfx) + + +@pytest.mark.pandas +def test_multiindex_duplicate_values(tempdir): + num_rows = 3 + numbers = list(range(num_rows)) + index = pd.MultiIndex.from_arrays( + [['foo', 'foo', 'bar'], numbers], + names=['foobar', 'some_numbers'], + ) + + df = pd.DataFrame({'numbers': numbers}, index=index) + table = pa.Table.from_pandas(df) + + filename = tempdir / 'dup_multi_index_levels.parquet' + + _write_table(table, filename) + result_table = _read_table(filename) + assert table.equals(result_table) + + result_df = result_table.to_pandas() + tm.assert_frame_equal(result_df, df) + + +@pytest.mark.pandas +def test_backwards_compatible_index_naming(datadir): + expected_string = b"""\ +carat cut color clarity depth table price x y z + 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 + 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 + 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 + 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 + 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 + 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48 + 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47 + 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53 + 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49 + 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39""" + expected = pd.read_csv(io.BytesIO(expected_string), sep=r'\s{2,}', + index_col=None, header=0, engine='python') + table = _read_table(datadir / 'v0.7.1.parquet') + result = table.to_pandas() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.pandas +def test_backwards_compatible_index_multi_level_named(datadir): + expected_string = b"""\ +carat cut color clarity depth table price x y z + 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 + 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 + 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 + 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 + 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 + 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48 + 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47 + 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53 + 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49 + 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39""" + expected = pd.read_csv( + io.BytesIO(expected_string), sep=r'\s{2,}', + index_col=['cut', 'color', 'clarity'], + header=0, engine='python' + ).sort_index() + + table = _read_table(datadir / 'v0.7.1.all-named-index.parquet') + result = table.to_pandas() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.pandas +def test_backwards_compatible_index_multi_level_some_named(datadir): + expected_string = b"""\ +carat cut color clarity depth table price x y z + 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 + 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 + 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 + 0.29 Premium I VS2 62.4 58.0 334 4.20 4.23 2.63 + 0.31 Good J SI2 63.3 58.0 335 4.34 4.35 2.75 + 0.24 Very Good J VVS2 62.8 57.0 336 3.94 3.96 2.48 + 0.24 Very Good I VVS1 62.3 57.0 336 3.95 3.98 2.47 + 0.26 Very Good H SI1 61.9 55.0 337 4.07 4.11 2.53 + 0.22 Fair E VS2 65.1 61.0 337 3.87 3.78 2.49 + 0.23 Very Good H VS1 59.4 61.0 338 4.00 4.05 2.39""" + expected = pd.read_csv( + io.BytesIO(expected_string), + sep=r'\s{2,}', index_col=['cut', 'color', 'clarity'], + header=0, engine='python' + ).sort_index() + expected.index = expected.index.set_names(['cut', None, 'clarity']) + + table = _read_table(datadir / 'v0.7.1.some-named-index.parquet') + result = table.to_pandas() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.pandas +def test_backwards_compatible_column_metadata_handling(datadir): + if Version("2.2.0") <= Version(pd.__version__): + # TODO: regression in pandas + # https://github.com/pandas-dev/pandas/issues/56775 + pytest.skip("Regression in pandas 2.2.0") + expected = pd.DataFrame( + {'a': [1, 2, 3], 'b': [.1, .2, .3], + 'c': pd.date_range("2017-01-01", periods=3, tz='Europe/Brussels')}) + expected.index = pd.MultiIndex.from_arrays( + [['a', 'b', 'c'], + pd.date_range("2017-01-01", periods=3, tz='Europe/Brussels')], + names=['index', None]) + + path = datadir / 'v0.7.1.column-metadata-handling.parquet' + table = _read_table(path) + result = table.to_pandas() + tm.assert_frame_equal(result, expected) + + table = _read_table( + path, columns=['a']) + result = table.to_pandas() + tm.assert_frame_equal(result, expected[['a']].reset_index(drop=True)) + + +@pytest.mark.pandas +def test_categorical_index_survives_roundtrip(): + # ARROW-3652, addressed by ARROW-3246 + df = pd.DataFrame([['a', 'b'], ['c', 'd']], columns=['c1', 'c2']) + df['c1'] = df['c1'].astype('category') + df = df.set_index(['c1']) + + table = pa.Table.from_pandas(df) + bos = pa.BufferOutputStream() + pq.write_table(table, bos) + ref_df = pq.read_pandas(bos.getvalue()).to_pandas() + assert isinstance(ref_df.index, pd.CategoricalIndex) + assert ref_df.index.equals(df.index) + + +@pytest.mark.pandas +def test_categorical_order_survives_roundtrip(): + # ARROW-6302 + df = pd.DataFrame({"a": pd.Categorical( + ["a", "b", "c", "a"], categories=["b", "c", "d"], ordered=True)}) + + table = pa.Table.from_pandas(df) + bos = pa.BufferOutputStream() + pq.write_table(table, bos) + + contents = bos.getvalue() + result = pq.read_pandas(contents).to_pandas() + + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_pandas_categorical_na_type_row_groups(): + # ARROW-5085 + df = pd.DataFrame({"col": [None] * 100, "int": [1.0] * 100}) + df_category = df.astype({"col": "category", "int": "category"}) + table = pa.Table.from_pandas(df) + table_cat = pa.Table.from_pandas(df_category) + buf = pa.BufferOutputStream() + + # it works + pq.write_table(table_cat, buf, version='2.6', chunk_size=10) + result = pq.read_table(buf.getvalue()) + + # Result is non-categorical + assert result[0].equals(table[0]) + assert result[1].equals(table[1]) + + +@pytest.mark.pandas +def test_pandas_categorical_roundtrip(): + # ARROW-5480, this was enabled by ARROW-3246 + + # Have one of the categories unobserved and include a null (-1) + codes = np.array([2, 0, 0, 2, 0, -1, 2], dtype='int32') + categories = ['foo', 'bar', 'baz'] + df = pd.DataFrame({'x': pd.Categorical.from_codes( + codes, categories=categories)}) + + buf = pa.BufferOutputStream() + pq.write_table(pa.table(df), buf) + + result = pq.read_table(buf.getvalue()).to_pandas() + assert result.x.dtype == 'category' + assert (result.x.cat.categories == categories).all() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_categories_with_string_pyarrow_dtype(tempdir): + # gh-33727: writing to parquet should not fail + if Version(pd.__version__) < Version("1.3.0"): + pytest.skip("PyArrow backed string data type introduced in pandas 1.3.0") + + df1 = pd.DataFrame({"x": ["foo", "bar", "foo"]}, dtype="string[pyarrow]") + df1 = df1.astype("category") + + df2 = pd.DataFrame({"x": ["foo", "bar", "foo"]}) + df2 = df2.astype("category") + + # categories should be converted to pa.Array + assert pa.array(df1["x"]).to_pylist() == pa.array(df2["x"]).to_pylist() + assert pa.array(df1["x"].cat.categories.values).to_pylist() == pa.array( + df2["x"].cat.categories.values).to_pylist() + + path = str(tempdir / 'cat.parquet') + pq.write_table(pa.table(df1), path) + result = pq.read_table(path).to_pandas() + + tm.assert_frame_equal(result, df2) + + +@pytest.mark.pandas +def test_write_to_dataset_pandas_preserve_extensiondtypes(tempdir): + df = pd.DataFrame({'part': 'a', "col": [1, 2, 3]}) + df['col'] = df['col'].astype("Int64") + table = pa.table(df) + + pq.write_to_dataset( + table, str(tempdir / "case1"), partition_cols=['part'], + ) + result = pq.read_table(str(tempdir / "case1")).to_pandas() + tm.assert_frame_equal(result[["col"]], df[["col"]]) + + pq.write_to_dataset(table, str(tempdir / "case2")) + result = pq.read_table(str(tempdir / "case2")).to_pandas() + tm.assert_frame_equal(result[["col"]], df[["col"]]) + + pq.write_table(table, str(tempdir / "data.parquet")) + result = pq.read_table(str(tempdir / "data.parquet")).to_pandas() + tm.assert_frame_equal(result[["col"]], df[["col"]]) + + +@pytest.mark.pandas +def test_write_to_dataset_pandas_preserve_index(tempdir): + # ARROW-8251 - preserve pandas index in roundtrip + + df = pd.DataFrame({'part': ['a', 'a', 'b'], "col": [1, 2, 3]}) + df.index = pd.Index(['a', 'b', 'c'], name="idx") + table = pa.table(df) + df_cat = df[["col", "part"]].copy() + df_cat["part"] = df_cat["part"].astype("category") + + pq.write_to_dataset( + table, str(tempdir / "case1"), partition_cols=['part'], + ) + result = pq.read_table(str(tempdir / "case1")).to_pandas() + tm.assert_frame_equal(result, df_cat) + + pq.write_to_dataset(table, str(tempdir / "case2")) + result = pq.read_table(str(tempdir / "case2")).to_pandas() + tm.assert_frame_equal(result, df) + + pq.write_table(table, str(tempdir / "data.parquet")) + result = pq.read_table(str(tempdir / "data.parquet")).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +@pytest.mark.parametrize('preserve_index', [True, False, None]) +@pytest.mark.parametrize('metadata_fname', ["_metadata", "_common_metadata"]) +def test_dataset_read_pandas_common_metadata( + tempdir, preserve_index, metadata_fname +): + # ARROW-1103 + nfiles = 5 + size = 5 + + dirpath = tempdir / guid() + dirpath.mkdir() + + test_data = [] + frames = [] + paths = [] + for i in range(nfiles): + df = _test_dataframe(size, seed=i) + df.index = pd.Index( + np.arange(i * size, (i + 1) * size, dtype="int64"), name='index' + ) + + path = dirpath / '{}.parquet'.format(i) + + table = pa.Table.from_pandas(df, preserve_index=preserve_index) + + # Obliterate metadata + table = table.replace_schema_metadata(None) + assert table.schema.metadata is None + + _write_table(table, path) + test_data.append(table) + frames.append(df) + paths.append(path) + + # Write _metadata common file + table_for_metadata = pa.Table.from_pandas( + df, preserve_index=preserve_index + ) + pq.write_metadata(table_for_metadata.schema, dirpath / metadata_fname) + + dataset = pq.ParquetDataset(dirpath) + columns = ['uint8', 'strings'] + result = dataset.read_pandas(columns=columns).to_pandas() + expected = pd.concat([x[columns] for x in frames]) + expected.index.name = ( + df.index.name if preserve_index is not False else None) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.pandas +def test_read_pandas_passthrough_keywords(tempdir): + # ARROW-11464 - previously not all keywords were passed through (such as + # the filesystem keyword) + df = pd.DataFrame({'a': [1, 2, 3]}) + + filename = tempdir / 'data.parquet' + _write_table(df, filename) + + result = pq.read_pandas( + 'data.parquet', + filesystem=SubTreeFileSystem(str(tempdir), LocalFileSystem()) + ) + assert result.equals(pa.table(df)) + + +@pytest.mark.pandas +def test_read_pandas_map_fields(tempdir): + # ARROW-10140 - table created from Pandas with mapping fields + df = pd.DataFrame({ + 'col1': pd.Series([ + [('id', 'something'), ('value2', 'else')], + [('id', 'something2'), ('value', 'else2')], + ]), + 'col2': pd.Series(['foo', 'bar']) + }) + + filename = tempdir / 'data.parquet' + + udt = pa.map_(pa.string(), pa.string()) + schema = pa.schema([pa.field('col1', udt), pa.field('col2', pa.string())]) + arrow_table = pa.Table.from_pandas(df, schema) + + _write_table(arrow_table, filename) + + result = pq.read_pandas(filename).to_pandas() + tm.assert_frame_equal(result, df) diff --git a/shared/package-files/75/757b0e4832400720f17c6e7c9e467405cc5e5f0cebdd044e5a725c205407ad9d/special_scaled_modified_bessel_k1.h b/shared/package-files/75/757b0e4832400720f17c6e7c9e467405cc5e5f0cebdd044e5a725c205407ad9d/special_scaled_modified_bessel_k1.h new file mode 100644 index 0000000000000000000000000000000000000000..12b2e92dab862bc911eab6b9cfa4394f998498e8 --- /dev/null +++ b/shared/package-files/75/757b0e4832400720f17c6e7c9e467405cc5e5f0cebdd044e5a725c205407ad9d/special_scaled_modified_bessel_k1.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_scaled_modified_bessel_k1(Tensor x) -> Tensor +inline at::Tensor special_scaled_modified_bessel_k1(const at::Tensor & x) { + return at::_ops::special_scaled_modified_bessel_k1::call(x); +} + +// aten::special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_scaled_modified_bessel_k1_out(at::Tensor & out, const at::Tensor & x) { + return at::_ops::special_scaled_modified_bessel_k1_out::call(x, out); +} +// aten::special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_scaled_modified_bessel_k1_outf(const at::Tensor & x, at::Tensor & out) { + return at::_ops::special_scaled_modified_bessel_k1_out::call(x, out); +} + +} diff --git a/shared/package-files/75/757f922891dfc7d9bdd4d4a5b7ba50e46ba5d31edf8a0dd766c1c2b7692fb517/test_aesaracode.py b/shared/package-files/75/757f922891dfc7d9bdd4d4a5b7ba50e46ba5d31edf8a0dd766c1c2b7692fb517/test_aesaracode.py new file mode 100644 index 0000000000000000000000000000000000000000..13308af65b382e77de33302bcd75344d2b00adbf --- /dev/null +++ b/shared/package-files/75/757f922891dfc7d9bdd4d4a5b7ba50e46ba5d31edf8a0dd766c1c2b7692fb517/test_aesaracode.py @@ -0,0 +1,633 @@ +""" +Important note on tests in this module - the Aesara printing functions use a +global cache by default, which means that tests using it will modify global +state and thus not be independent from each other. Instead of using the "cache" +keyword argument each time, this module uses the aesara_code_ and +aesara_function_ functions defined below which default to using a new, empty +cache instead. +""" + +import logging + +from sympy.external import import_module +from sympy.testing.pytest import raises, SKIP, warns_deprecated_sympy + +from sympy.utilities.exceptions import ignore_warnings + + +aesaralogger = logging.getLogger('aesara.configdefaults') +aesaralogger.setLevel(logging.CRITICAL) +aesara = import_module('aesara') +aesaralogger.setLevel(logging.WARNING) + + +if aesara: + import numpy as np + aet = aesara.tensor + from aesara.scalar.basic import ScalarType + from aesara.graph.basic import Variable + from aesara.tensor.var import TensorVariable + from aesara.tensor.elemwise import Elemwise, DimShuffle + from aesara.tensor.math import Dot + + from sympy.printing.aesaracode import true_divide + + xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz'] + Xt, Yt, Zt = [aet.tensor('floatX', (False, False), name=n) for n in 'XYZ'] +else: + #bin/test will not execute any tests now + disabled = True + +import sympy as sy +from sympy.core.singleton import S +from sympy.abc import x, y, z, t +from sympy.printing.aesaracode import (aesara_code, dim_handling, + aesara_function) + + +# Default set of matrix symbols for testing - make square so we can both +# multiply and perform elementwise operations between them. +X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ'] + +# For testing AppliedUndef +f_t = sy.Function('f')(t) + + +def aesara_code_(expr, **kwargs): + """ Wrapper for aesara_code that uses a new, empty cache by default. """ + kwargs.setdefault('cache', {}) + with warns_deprecated_sympy(): + return aesara_code(expr, **kwargs) + +def aesara_function_(inputs, outputs, **kwargs): + """ Wrapper for aesara_function that uses a new, empty cache by default. """ + kwargs.setdefault('cache', {}) + with warns_deprecated_sympy(): + return aesara_function(inputs, outputs, **kwargs) + + +def fgraph_of(*exprs): + """ Transform SymPy expressions into Aesara Computation. + + Parameters + ========== + exprs + SymPy expressions + + Returns + ======= + aesara.graph.fg.FunctionGraph + """ + outs = list(map(aesara_code_, exprs)) + ins = list(aesara.graph.basic.graph_inputs(outs)) + ins, outs = aesara.graph.basic.clone(ins, outs) + return aesara.graph.fg.FunctionGraph(ins, outs) + + +def aesara_simplify(fgraph): + """ Simplify a Aesara Computation. + + Parameters + ========== + fgraph : aesara.graph.fg.FunctionGraph + + Returns + ======= + aesara.graph.fg.FunctionGraph + """ + mode = aesara.compile.get_default_mode().excluding("fusion") + fgraph = fgraph.clone() + mode.optimizer.rewrite(fgraph) + return fgraph + + +def theq(a, b): + """ Test two Aesara objects for equality. + + Also accepts numeric types and lists/tuples of supported types. + + Note - debugprint() has a bug where it will accept numeric types but does + not respect the "file" argument and in this case and instead prints the number + to stdout and returns an empty string. This can lead to tests passing where + they should fail because any two numbers will always compare as equal. To + prevent this we treat numbers as a separate case. + """ + numeric_types = (int, float, np.number) + a_is_num = isinstance(a, numeric_types) + b_is_num = isinstance(b, numeric_types) + + # Compare numeric types using regular equality + if a_is_num or b_is_num: + if not (a_is_num and b_is_num): + return False + + return a == b + + # Compare sequences element-wise + a_is_seq = isinstance(a, (tuple, list)) + b_is_seq = isinstance(b, (tuple, list)) + + if a_is_seq or b_is_seq: + if not (a_is_seq and b_is_seq) or type(a) != type(b): + return False + + return list(map(theq, a)) == list(map(theq, b)) + + # Otherwise, assume debugprint() can handle it + astr = aesara.printing.debugprint(a, file='str') + bstr = aesara.printing.debugprint(b, file='str') + + # Check for bug mentioned above + for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]: + if argstr == '': + raise TypeError( + 'aesara.printing.debugprint(%s) returned empty string ' + '(%s is instance of %r)' + % (argname, argname, type(argval)) + ) + + return astr == bstr + + +def test_example_symbols(): + """ + Check that the example symbols in this module print to their Aesara + equivalents, as many of the other tests depend on this. + """ + assert theq(xt, aesara_code_(x)) + assert theq(yt, aesara_code_(y)) + assert theq(zt, aesara_code_(z)) + assert theq(Xt, aesara_code_(X)) + assert theq(Yt, aesara_code_(Y)) + assert theq(Zt, aesara_code_(Z)) + + +def test_Symbol(): + """ Test printing a Symbol to a aesara variable. """ + xx = aesara_code_(x) + assert isinstance(xx, Variable) + assert xx.broadcastable == () + assert xx.name == x.name + + xx2 = aesara_code_(x, broadcastables={x: (False,)}) + assert xx2.broadcastable == (False,) + assert xx2.name == x.name + +def test_MatrixSymbol(): + """ Test printing a MatrixSymbol to a aesara variable. """ + XX = aesara_code_(X) + assert isinstance(XX, TensorVariable) + assert XX.broadcastable == (False, False) + +@SKIP # TODO - this is currently not checked but should be implemented +def test_MatrixSymbol_wrong_dims(): + """ Test MatrixSymbol with invalid broadcastable. """ + bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)] + for bc in bcs: + with raises(ValueError): + aesara_code_(X, broadcastables={X: bc}) + +def test_AppliedUndef(): + """ Test printing AppliedUndef instance, which works similarly to Symbol. """ + ftt = aesara_code_(f_t) + assert isinstance(ftt, TensorVariable) + assert ftt.broadcastable == () + assert ftt.name == 'f_t' + + +def test_add(): + expr = x + y + comp = aesara_code_(expr) + assert comp.owner.op == aesara.tensor.add + +def test_trig(): + assert theq(aesara_code_(sy.sin(x)), aet.sin(xt)) + assert theq(aesara_code_(sy.tan(x)), aet.tan(xt)) + +def test_many(): + """ Test printing a complex expression with multiple symbols. """ + expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z) + comp = aesara_code_(expr) + expected = aet.exp(xt**2 + aet.cos(yt)) * aet.log(2*zt) + assert theq(comp, expected) + + +def test_dtype(): + """ Test specifying specific data types through the dtype argument. """ + for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']: + assert aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype + + # "floatX" type + assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64') + + # Type promotion + assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32' + assert aesara_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64' + + +def test_broadcastables(): + """ Test the "broadcastables" argument when printing symbol-like objects. """ + + # No restrictions on shape + for s in [x, f_t]: + for bc in [(), (False,), (True,), (False, False), (True, False)]: + assert aesara_code_(s, broadcastables={s: bc}).broadcastable == bc + + # TODO - matrix broadcasting? + +def test_broadcasting(): + """ Test "broadcastable" attribute after applying element-wise binary op. """ + + expr = x + y + + cases = [ + [(), (), ()], + [(False,), (False,), (False,)], + [(True,), (False,), (False,)], + [(False, True), (False, False), (False, False)], + [(True, False), (False, False), (False, False)], + ] + + for bc1, bc2, bc3 in cases: + comp = aesara_code_(expr, broadcastables={x: bc1, y: bc2}) + assert comp.broadcastable == bc3 + + +def test_MatMul(): + expr = X*Y*Z + expr_t = aesara_code_(expr) + assert isinstance(expr_t.owner.op, Dot) + assert theq(expr_t, Xt.dot(Yt).dot(Zt)) + +def test_Transpose(): + assert isinstance(aesara_code_(X.T).owner.op, DimShuffle) + +def test_MatAdd(): + expr = X+Y+Z + assert isinstance(aesara_code_(expr).owner.op, Elemwise) + + +def test_Rationals(): + assert theq(aesara_code_(sy.Integer(2) / 3), true_divide(2, 3)) + assert theq(aesara_code_(S.Half), true_divide(1, 2)) + +def test_Integers(): + assert aesara_code_(sy.Integer(3)) == 3 + +def test_factorial(): + n = sy.Symbol('n') + assert aesara_code_(sy.factorial(n)) + +def test_Derivative(): + with ignore_warnings(UserWarning): + simp = lambda expr: aesara_simplify(fgraph_of(expr)) + assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))), + simp(aesara.grad(aet.sin(xt), xt))) + + +def test_aesara_function_simple(): + """ Test aesara_function() with single output. """ + f = aesara_function_([x, y], [x+y]) + assert f(2, 3) == 5 + +def test_aesara_function_multi(): + """ Test aesara_function() with multiple outputs. """ + f = aesara_function_([x, y], [x+y, x-y]) + o1, o2 = f(2, 3) + assert o1 == 5 + assert o2 == -1 + +def test_aesara_function_numpy(): + """ Test aesara_function() vs Numpy implementation. """ + f = aesara_function_([x, y], [x+y], dim=1, + dtypes={x: 'float64', y: 'float64'}) + assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9 + + f = aesara_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'}, + dim=1) + xx = np.arange(3).astype('float64') + yy = 2*np.arange(3).astype('float64') + assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9 + + +def test_aesara_function_matrix(): + m = sy.Matrix([[x, y], [z, x + y + z]]) + expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]]) + f = aesara_function_([x, y, z], [m]) + np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) + f = aesara_function_([x, y, z], [m], scalar=True) + np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) + f = aesara_function_([x, y, z], [m, m]) + assert isinstance(f(1.0, 2.0, 3.0), type([])) + np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected) + np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected) + +def test_dim_handling(): + assert dim_handling([x], dim=2) == {x: (False, False)} + assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True), + y: (False, False)} + assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)} + +def test_aesara_function_kwargs(): + """ + Test passing additional kwargs from aesara_function() to aesara.function(). + """ + import numpy as np + f = aesara_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore', + dtypes={x: 'float64', y: 'float64', z: 'float64'}) + assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9 + + f = aesara_function_([x, y, z], [x+y], + dtypes={x: 'float64', y: 'float64', z: 'float64'}, + dim=1, on_unused_input='ignore') + xx = np.arange(3).astype('float64') + yy = 2*np.arange(3).astype('float64') + zz = 2*np.arange(3).astype('float64') + assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9 + +def test_aesara_function_scalar(): + """ Test the "scalar" argument to aesara_function(). """ + from aesara.compile.function.types import Function + + args = [ + ([x, y], [x + y], None, [0]), # Single 0d output + ([X, Y], [X + Y], None, [2]), # Single 2d output + ([x, y], [x + y], {x: 0, y: 1}, [1]), # Single 1d output + ([x, y], [x + y, x - y], None, [0, 0]), # Two 0d outputs + ([x, y, X, Y], [x + y, X + Y], None, [0, 2]), # One 0d output, one 2d + ] + + # Create and test functions with and without the scalar setting + for inputs, outputs, in_dims, out_dims in args: + for scalar in [False, True]: + + f = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar) + + # Check the aesara_function attribute is set whether wrapped or not + assert isinstance(f.aesara_function, Function) + + # Feed in inputs of the appropriate size and get outputs + in_values = [ + np.ones([1 if bc else 5 for bc in i.type.broadcastable]) + for i in f.aesara_function.input_storage + ] + out_values = f(*in_values) + if not isinstance(out_values, list): + out_values = [out_values] + + # Check output types and shapes + assert len(out_dims) == len(out_values) + for d, value in zip(out_dims, out_values): + + if scalar and d == 0: + # Should have been converted to a scalar value + assert isinstance(value, np.number) + + else: + # Otherwise should be an array + assert isinstance(value, np.ndarray) + assert value.ndim == d + +def test_aesara_function_bad_kwarg(): + """ + Passing an unknown keyword argument to aesara_function() should raise an + exception. + """ + raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3)) + + +def test_slice(): + assert aesara_code_(slice(1, 2, 3)) == slice(1, 2, 3) + + def theq_slice(s1, s2): + for attr in ['start', 'stop', 'step']: + a1 = getattr(s1, attr) + a2 = getattr(s2, attr) + if a1 is None or a2 is None: + if not (a1 is None or a2 is None): + return False + elif not theq(a1, a2): + return False + return True + + dtypes = {x: 'int32', y: 'int32'} + assert theq_slice(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt)) + assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3)) + +def test_MatrixSlice(): + cache = {} + + n = sy.Symbol('n', integer=True) + X = sy.MatrixSymbol('X', n, n) + + Y = X[1:2:3, 4:5:6] + Yt = aesara_code_(Y, cache=cache) + + s = ScalarType('int64') + assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s)) + assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache) + # == doesn't work in Aesara like it does in SymPy. You have to use + # equals. + assert all(Yt.owner.inputs[i].data == i for i in range(1, 7)) + + k = sy.Symbol('k') + aesara_code_(k, dtypes={k: 'int32'}) + start, stop, step = 4, k, 2 + Y = X[start:stop:step] + Yt = aesara_code_(Y, dtypes={n: 'int32', k: 'int32'}) + # assert Yt.owner.op.idx_list[0].stop == kt + +def test_BlockMatrix(): + n = sy.Symbol('n', integer=True) + A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD'] + At, Bt, Ct, Dt = map(aesara_code_, (A, B, C, D)) + Block = sy.BlockMatrix([[A, B], [C, D]]) + Blockt = aesara_code_(Block) + solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)), + aet.join(1, aet.join(0, At, Ct), aet.join(0, Bt, Dt))] + assert any(theq(Blockt, solution) for solution in solutions) + +@SKIP +def test_BlockMatrix_Inverse_execution(): + k, n = 2, 4 + dtype = 'float32' + A = sy.MatrixSymbol('A', n, k) + B = sy.MatrixSymbol('B', n, n) + inputs = A, B + output = B.I*A + + cutsizes = {A: [(n//2, n//2), (k//2, k//2)], + B: [(n//2, n//2), (n//2, n//2)]} + cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs] + cutoutput = output.subs(dict(zip(inputs, cutinputs))) + + dtypes = dict(zip(inputs, [dtype]*len(inputs))) + f = aesara_function_(inputs, [output], dtypes=dtypes, cache={}) + fblocked = aesara_function_(inputs, [sy.block_collapse(cutoutput)], + dtypes=dtypes, cache={}) + + ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs] + ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype), + np.eye(n).astype(dtype)] + ninputs[1] += np.ones(B.shape)*1e-5 + + assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5) + +def test_DenseMatrix(): + from aesara.tensor.basic import Join + + t = sy.Symbol('theta') + for MatrixType in [sy.Matrix, sy.ImmutableMatrix]: + X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]]) + tX = aesara_code_(X) + assert isinstance(tX, TensorVariable) + assert isinstance(tX.owner.op, Join) + + +def test_cache_basic(): + """ Test single symbol-like objects are cached when printed by themselves. """ + + # Pairs of objects which should be considered equivalent with respect to caching + pairs = [ + (x, sy.Symbol('x')), + (X, sy.MatrixSymbol('X', *X.shape)), + (f_t, sy.Function('f')(sy.Symbol('t'))), + ] + + for s1, s2 in pairs: + cache = {} + st = aesara_code_(s1, cache=cache) + + # Test hit with same instance + assert aesara_code_(s1, cache=cache) is st + + # Test miss with same instance but new cache + assert aesara_code_(s1, cache={}) is not st + + # Test hit with different but equivalent instance + assert aesara_code_(s2, cache=cache) is st + +def test_global_cache(): + """ Test use of the global cache. """ + from sympy.printing.aesaracode import global_cache + + backup = dict(global_cache) + try: + # Temporarily empty global cache + global_cache.clear() + + for s in [x, X, f_t]: + with warns_deprecated_sympy(): + st = aesara_code(s) + assert aesara_code(s) is st + + finally: + # Restore global cache + global_cache.update(backup) + +def test_cache_types_distinct(): + """ + Test that symbol-like objects of different types (Symbol, MatrixSymbol, + AppliedUndef) are distinguished by the cache even if they have the same + name. + """ + symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t] + + cache = {} # Single shared cache + printed = {} + + for s in symbols: + st = aesara_code_(s, cache=cache) + assert st not in printed.values() + printed[s] = st + + # Check all printed objects are distinct + assert len(set(map(id, printed.values()))) == len(symbols) + + # Check retrieving + for s, st in printed.items(): + with warns_deprecated_sympy(): + assert aesara_code(s, cache=cache) is st + +def test_symbols_are_created_once(): + """ + Test that a symbol is cached and reused when it appears in an expression + more than once. + """ + expr = sy.Add(x, x, evaluate=False) + comp = aesara_code_(expr) + + assert theq(comp, xt + xt) + assert not theq(comp, xt + aesara_code_(x)) + +def test_cache_complex(): + """ + Test caching on a complicated expression with multiple symbols appearing + multiple times. + """ + expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y) + symbol_names = {s.name for s in expr.free_symbols} + expr_t = aesara_code_(expr) + + # Iterate through variables in the Aesara computational graph that the + # printed expression depends on + seen = set() + for v in aesara.graph.basic.ancestors([expr_t]): + # Owner-less, non-constant variables should be our symbols + if v.owner is None and not isinstance(v, aesara.graph.basic.Constant): + # Check it corresponds to a symbol and appears only once + assert v.name in symbol_names + assert v.name not in seen + seen.add(v.name) + + # Check all were present + assert seen == symbol_names + + +def test_Piecewise(): + # A piecewise linear + expr = sy.Piecewise((0, x<0), (x, x<2), (1, True)) # ___/III + result = aesara_code_(expr) + assert result.owner.op == aet.switch + + expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1)) + assert theq(result, expected) + + expr = sy.Piecewise((x, x < 0)) + result = aesara_code_(expr) + expected = aet.switch(xt < 0, xt, np.nan) + assert theq(result, expected) + + expr = sy.Piecewise((0, sy.And(x>0, x<2)), \ + (x, sy.Or(x>2, x<0))) + result = aesara_code_(expr) + expected = aet.switch(aet.and_(xt>0,xt<2), 0, \ + aet.switch(aet.or_(xt>2, xt<0), xt, np.nan)) + assert theq(result, expected) + + +def test_Relationals(): + assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt)) + # assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt)) # TODO - implement + assert theq(aesara_code_(x > y), xt > yt) + assert theq(aesara_code_(x < y), xt < yt) + assert theq(aesara_code_(x >= y), xt >= yt) + assert theq(aesara_code_(x <= y), xt <= yt) + + +def test_complexfunctions(): + dtypes = {x:'complex128', y:'complex128'} + with warns_deprecated_sympy(): + xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes) + from sympy.functions.elementary.complexes import conjugate + from aesara.tensor import as_tensor_variable as atv + from aesara.tensor import complex as cplx + with warns_deprecated_sympy(): + assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj())) + assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1))) + + +def test_constantfunctions(): + with warns_deprecated_sympy(): + tf = aesara_function([],[1+1j]) + assert(tf()==1+1j) diff --git a/shared/package-files/75/75860f66a0692d756147b77b1d8c814f7f2e4be716c17f9099bece182b063ac7/version.sh b/shared/package-files/75/75860f66a0692d756147b77b1d8c814f7f2e4be716c17f9099bece182b063ac7/version.sh new file mode 100644 index 0000000000000000000000000000000000000000..f35234c2d50c315460a5425ecc2bbd3ff5beda23 --- /dev/null +++ b/shared/package-files/75/75860f66a0692d756147b77b1d8c814f7f2e4be716c17f9099bece182b063ac7/version.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# version.sh -- Script to build the htslib version string +# +# Author : James Bonfield +# +# Copyright (C) 2017-2018, 2021 Genome Research Ltd. +# +# 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. + +# Master version, for use in tarballs or non-git source copies +VERSION=1.21 + +# If we have a git clone, then check against the current tag +srcdir=${0%/version.sh} +if [ -e $srcdir/.git ] +then + # If we ever get to 10.x this will need to be more liberal + v=`cd $srcdir && git describe --always --match '[0-9].[0-9]*' --dirty` + case $v in + [0-9]*.[0-9]*) VERSION="$v" ;; + [0-9a-f][0-9a-f]*) VERSION="$VERSION-1-g$v" ;; + esac +fi + +# Numeric version is for use in .dylib or .so libraries +# +# Follows the same logic from the Makefile commit c2e93911 +# as non-numeric versions get bumped to patch level 255 to indicate +# an unknown value. +if [ "$1" = "numeric" ] +then + v1=`expr "$VERSION" : '\([0-9]*\)'` + v2=`expr "$VERSION" : '[0-9]*.\([0-9]*\)'` + v3=`expr "$VERSION" : '[0-9]*.[0-9]*.\([0-9]*\)'` + if [ -z "`expr "$VERSION" : '\([0-9.]*\)$'`" ] + then + VERSION="$v1.$v2.255" + else + VERSION="$v1.$v2${v3:+.}$v3" + fi +fi + +echo $VERSION diff --git a/shared/package-files/75/7587f74c3748499c3a889291cde15e4dd463bda39d73795f5065155b8403045d/logdet_native.h b/shared/package-files/75/7587f74c3748499c3a889291cde15e4dd463bda39d73795f5065155b8403045d/logdet_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e6c13c00e0ca7c4c4c29cbaef7ab8ad198974055 --- /dev/null +++ b/shared/package-files/75/7587f74c3748499c3a889291cde15e4dd463bda39d73795f5065155b8403045d/logdet_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor logdet(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/758f26b0900991ce88ce7a0228b6ecf8f8819f4423cac7eabd924edb84c70186/test_case.cpython-311.pyc b/shared/package-files/75/758f26b0900991ce88ce7a0228b6ecf8f8819f4423cac7eabd924edb84c70186/test_case.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..624de80ffe10d07c2f2f490685a4d3c804843ce7 Binary files /dev/null and b/shared/package-files/75/758f26b0900991ce88ce7a0228b6ecf8f8819f4423cac7eabd924edb84c70186/test_case.cpython-311.pyc differ diff --git a/shared/package-files/75/759743d74ed8a587cef292c3359877460926b65a0b77268c7420def1ec669160/basic.cpython-311.pyc b/shared/package-files/75/759743d74ed8a587cef292c3359877460926b65a0b77268c7420def1ec669160/basic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e37cadf29c62744ea4a311ac239895316779c53 Binary files /dev/null and b/shared/package-files/75/759743d74ed8a587cef292c3359877460926b65a0b77268c7420def1ec669160/basic.cpython-311.pyc differ diff --git a/shared/package-files/75/7598b598c7b6ff1e23c4c77cd056b858540f3476e8433354f4f1d6de4963b8ed/test_debugobj.cpython-311.pyc b/shared/package-files/75/7598b598c7b6ff1e23c4c77cd056b858540f3476e8433354f4f1d6de4963b8ed/test_debugobj.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b93ad0ffa9a6277215d29a06c7942b2b5a0aca6 Binary files /dev/null and b/shared/package-files/75/7598b598c7b6ff1e23c4c77cd056b858540f3476e8433354f4f1d6de4963b8ed/test_debugobj.cpython-311.pyc differ diff --git a/shared/package-files/75/759d942c6377c91b2197a341a759536005f980d07c187af9f9356146e92fcf13/os_helper.py b/shared/package-files/75/759d942c6377c91b2197a341a759536005f980d07c187af9f9356146e92fcf13/os_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..c1b2995ef37a12c902c4ef874ff644ae9ab4eedf --- /dev/null +++ b/shared/package-files/75/759d942c6377c91b2197a341a759536005f980d07c187af9f9356146e92fcf13/os_helper.py @@ -0,0 +1,728 @@ +import collections.abc +import contextlib +import errno +import os +import re +import stat +import sys +import time +import unittest +import warnings + + +# Filename used for testing +if os.name == 'java': + # Jython disallows @ in module names + TESTFN_ASCII = '$test' +else: + TESTFN_ASCII = '@test' + +# Disambiguate TESTFN for parallel testing, while letting it remain a valid +# module name. +TESTFN_ASCII = "{}_{}_tmp".format(TESTFN_ASCII, os.getpid()) + +# TESTFN_UNICODE is a non-ascii filename +TESTFN_UNICODE = TESTFN_ASCII + "-\xe0\xf2\u0258\u0141\u011f" +if sys.platform == 'darwin': + # In Mac OS X's VFS API file names are, by definition, canonically + # decomposed Unicode, encoded using UTF-8. See QA1173: + # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html + import unicodedata + TESTFN_UNICODE = unicodedata.normalize('NFD', TESTFN_UNICODE) + +# TESTFN_UNENCODABLE is a filename (str type) that should *not* be able to be +# encoded by the filesystem encoding (in strict mode). It can be None if we +# cannot generate such filename. +TESTFN_UNENCODABLE = None +if os.name == 'nt': + # skip win32s (0) or Windows 9x/ME (1) + if sys.getwindowsversion().platform >= 2: + # Different kinds of characters from various languages to minimize the + # probability that the whole name is encodable to MBCS (issue #9819) + TESTFN_UNENCODABLE = TESTFN_ASCII + "-\u5171\u0141\u2661\u0363\uDC80" + try: + TESTFN_UNENCODABLE.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + pass + else: + print('WARNING: The filename %r CAN be encoded by the filesystem ' + 'encoding (%s). Unicode filename tests may not be effective' + % (TESTFN_UNENCODABLE, sys.getfilesystemencoding())) + TESTFN_UNENCODABLE = None +# macOS and Emscripten deny unencodable filenames (invalid utf-8) +elif sys.platform not in {'darwin', 'emscripten', 'wasi'}: + try: + # ascii and utf-8 cannot encode the byte 0xff + b'\xff'.decode(sys.getfilesystemencoding()) + except UnicodeDecodeError: + # 0xff will be encoded using the surrogate character u+DCFF + TESTFN_UNENCODABLE = TESTFN_ASCII \ + + b'-\xff'.decode(sys.getfilesystemencoding(), 'surrogateescape') + else: + # File system encoding (eg. ISO-8859-* encodings) can encode + # the byte 0xff. Skip some unicode filename tests. + pass + +# FS_NONASCII: non-ASCII character encodable by os.fsencode(), +# or an empty string if there is no such character. +FS_NONASCII = '' +for character in ( + # First try printable and common characters to have a readable filename. + # For each character, the encoding list are just example of encodings able + # to encode the character (the list is not exhaustive). + + # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1 + '\u00E6', + # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3 + '\u0130', + # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257 + '\u0141', + # U+03C6 (Greek Small Letter Phi): cp1253 + '\u03C6', + # U+041A (Cyrillic Capital Letter Ka): cp1251 + '\u041A', + # U+05D0 (Hebrew Letter Alef): Encodable to cp424 + '\u05D0', + # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic + '\u060C', + # U+062A (Arabic Letter Teh): cp720 + '\u062A', + # U+0E01 (Thai Character Ko Kai): cp874 + '\u0E01', + + # Then try more "special" characters. "special" because they may be + # interpreted or displayed differently depending on the exact locale + # encoding and the font. + + # U+00A0 (No-Break Space) + '\u00A0', + # U+20AC (Euro Sign) + '\u20AC', +): + try: + # If Python is set up to use the legacy 'mbcs' in Windows, + # 'replace' error mode is used, and encode() returns b'?' + # for characters missing in the ANSI codepage + if os.fsdecode(os.fsencode(character)) != character: + raise UnicodeError + except UnicodeError: + pass + else: + FS_NONASCII = character + break + +# Save the initial cwd +SAVEDCWD = os.getcwd() + +# TESTFN_UNDECODABLE is a filename (bytes type) that should *not* be able to be +# decoded from the filesystem encoding (in strict mode). It can be None if we +# cannot generate such filename (ex: the latin1 encoding can decode any byte +# sequence). On UNIX, TESTFN_UNDECODABLE can be decoded by os.fsdecode() thanks +# to the surrogateescape error handler (PEP 383), but not from the filesystem +# encoding in strict mode. +TESTFN_UNDECODABLE = None +for name in ( + # b'\xff' is not decodable by os.fsdecode() with code page 932. Windows + # accepts it to create a file or a directory, or don't accept to enter to + # such directory (when the bytes name is used). So test b'\xe7' first: + # it is not decodable from cp932. + b'\xe7w\xf0', + # undecodable from ASCII, UTF-8 + b'\xff', + # undecodable from iso8859-3, iso8859-6, iso8859-7, cp424, iso8859-8, cp856 + # and cp857 + b'\xae\xd5' + # undecodable from UTF-8 (UNIX and Mac OS X) + b'\xed\xb2\x80', b'\xed\xb4\x80', + # undecodable from shift_jis, cp869, cp874, cp932, cp1250, cp1251, cp1252, + # cp1253, cp1254, cp1255, cp1257, cp1258 + b'\x81\x98', +): + try: + name.decode(sys.getfilesystemencoding()) + except UnicodeDecodeError: + TESTFN_UNDECODABLE = os.fsencode(TESTFN_ASCII) + name + break + +if FS_NONASCII: + TESTFN_NONASCII = TESTFN_ASCII + FS_NONASCII +else: + TESTFN_NONASCII = None +TESTFN = TESTFN_NONASCII or TESTFN_ASCII + + +def make_bad_fd(): + """ + Create an invalid file descriptor by opening and closing a file and return + its fd. + """ + file = open(TESTFN, "wb") + try: + return file.fileno() + finally: + file.close() + unlink(TESTFN) + + +_can_symlink = None + + +def can_symlink(): + global _can_symlink + if _can_symlink is not None: + return _can_symlink + # WASI / wasmtime prevents symlinks with absolute paths, see man + # openat2(2) RESOLVE_BENEATH. Almost all symlink tests use absolute + # paths. Skip symlink tests on WASI for now. + src = os.path.abspath(TESTFN) + symlink_path = src + "can_symlink" + try: + os.symlink(src, symlink_path) + can = True + except (OSError, NotImplementedError, AttributeError): + can = False + else: + os.remove(symlink_path) + _can_symlink = can + return can + + +def skip_unless_symlink(test): + """Skip decorator for tests that require functional symlink""" + ok = can_symlink() + msg = "Requires functional symlink implementation" + return test if ok else unittest.skip(msg)(test) + + +_can_xattr = None + + +def can_xattr(): + import tempfile + global _can_xattr + if _can_xattr is not None: + return _can_xattr + if not hasattr(os, "setxattr"): + can = False + else: + import platform + tmp_dir = tempfile.mkdtemp() + tmp_fp, tmp_name = tempfile.mkstemp(dir=tmp_dir) + try: + with open(TESTFN, "wb") as fp: + try: + # TESTFN & tempfile may use different file systems with + # different capabilities + os.setxattr(tmp_fp, b"user.test", b"") + os.setxattr(tmp_name, b"trusted.foo", b"42") + os.setxattr(fp.fileno(), b"user.test", b"") + # Kernels < 2.6.39 don't respect setxattr flags. + kernel_version = platform.release() + m = re.match(r"2.6.(\d{1,2})", kernel_version) + can = m is None or int(m.group(1)) >= 39 + except OSError: + can = False + finally: + unlink(TESTFN) + unlink(tmp_name) + rmdir(tmp_dir) + _can_xattr = can + return can + + +def skip_unless_xattr(test): + """Skip decorator for tests that require functional extended attributes""" + ok = can_xattr() + msg = "no non-broken extended attribute support" + return test if ok else unittest.skip(msg)(test) + + +_can_chmod = None + +def can_chmod(): + global _can_chmod + if _can_chmod is not None: + return _can_chmod + if not hasattr(os, "chmod"): + _can_chmod = False + return _can_chmod + try: + with open(TESTFN, "wb") as f: + try: + os.chmod(TESTFN, 0o555) + mode1 = os.stat(TESTFN).st_mode + os.chmod(TESTFN, 0o777) + mode2 = os.stat(TESTFN).st_mode + except OSError as e: + can = False + else: + can = stat.S_IMODE(mode1) != stat.S_IMODE(mode2) + finally: + unlink(TESTFN) + _can_chmod = can + return can + + +def skip_unless_working_chmod(test): + """Skip tests that require working os.chmod() + + WASI SDK 15.0 cannot change file mode bits. + """ + ok = can_chmod() + msg = "requires working os.chmod()" + return test if ok else unittest.skip(msg)(test) + + +# Check whether the current effective user has the capability to override +# DAC (discretionary access control). Typically user root is able to +# bypass file read, write, and execute permission checks. The capability +# is independent of the effective user. See capabilities(7). +_can_dac_override = None + +def can_dac_override(): + global _can_dac_override + + if not can_chmod(): + _can_dac_override = False + if _can_dac_override is not None: + return _can_dac_override + + try: + with open(TESTFN, "wb") as f: + os.chmod(TESTFN, 0o400) + try: + with open(TESTFN, "wb"): + pass + except OSError: + _can_dac_override = False + else: + _can_dac_override = True + finally: + try: + os.chmod(TESTFN, 0o700) + except OSError: + pass + unlink(TESTFN) + + return _can_dac_override + + +def skip_if_dac_override(test): + ok = not can_dac_override() + msg = "incompatible with CAP_DAC_OVERRIDE" + return test if ok else unittest.skip(msg)(test) + + +def skip_unless_dac_override(test): + ok = can_dac_override() + msg = "requires CAP_DAC_OVERRIDE" + return test if ok else unittest.skip(msg)(test) + + +def unlink(filename): + try: + _unlink(filename) + except (FileNotFoundError, NotADirectoryError): + pass + + +if sys.platform.startswith("win"): + def _waitfor(func, pathname, waitall=False): + # Perform the operation + func(pathname) + # Now setup the wait loop + if waitall: + dirname = pathname + else: + dirname, name = os.path.split(pathname) + dirname = dirname or '.' + # Check for `pathname` to be removed from the filesystem. + # The exponential backoff of the timeout amounts to a total + # of ~1 second after which the deletion is probably an error + # anyway. + # Testing on an i7@4.3GHz shows that usually only 1 iteration is + # required when contention occurs. + timeout = 0.001 + while timeout < 1.0: + # Note we are only testing for the existence of the file(s) in + # the contents of the directory regardless of any security or + # access rights. If we have made it this far, we have sufficient + # permissions to do that much using Python's equivalent of the + # Windows API FindFirstFile. + # Other Windows APIs can fail or give incorrect results when + # dealing with files that are pending deletion. + L = os.listdir(dirname) + if not (L if waitall else name in L): + return + # Increase the timeout and try again + time.sleep(timeout) + timeout *= 2 + warnings.warn('tests may fail, delete still pending for ' + pathname, + RuntimeWarning, stacklevel=4) + + def _unlink(filename): + _waitfor(os.unlink, filename) + + def _rmdir(dirname): + _waitfor(os.rmdir, dirname) + + def _rmtree(path): + from test.support import _force_run + + def _rmtree_inner(path): + for name in _force_run(path, os.listdir, path): + fullname = os.path.join(path, name) + try: + mode = os.lstat(fullname).st_mode + except OSError as exc: + print("support.rmtree(): os.lstat(%r) failed with %s" + % (fullname, exc), + file=sys.__stderr__) + mode = 0 + if stat.S_ISDIR(mode): + _waitfor(_rmtree_inner, fullname, waitall=True) + _force_run(fullname, os.rmdir, fullname) + else: + _force_run(fullname, os.unlink, fullname) + _waitfor(_rmtree_inner, path, waitall=True) + _waitfor(lambda p: _force_run(p, os.rmdir, p), path) + + def _longpath(path): + try: + import ctypes + except ImportError: + # No ctypes means we can't expands paths. + pass + else: + buffer = ctypes.create_unicode_buffer(len(path) * 2) + length = ctypes.windll.kernel32.GetLongPathNameW(path, buffer, + len(buffer)) + if length: + return buffer[:length] + return path +else: + _unlink = os.unlink + _rmdir = os.rmdir + + def _rmtree(path): + import shutil + try: + shutil.rmtree(path) + return + except OSError: + pass + + def _rmtree_inner(path): + from test.support import _force_run + for name in _force_run(path, os.listdir, path): + fullname = os.path.join(path, name) + try: + mode = os.lstat(fullname).st_mode + except OSError: + mode = 0 + if stat.S_ISDIR(mode): + _rmtree_inner(fullname) + _force_run(path, os.rmdir, fullname) + else: + _force_run(path, os.unlink, fullname) + _rmtree_inner(path) + os.rmdir(path) + + def _longpath(path): + return path + + +def rmdir(dirname): + try: + _rmdir(dirname) + except FileNotFoundError: + pass + + +def rmtree(path): + try: + _rmtree(path) + except FileNotFoundError: + pass + + +@contextlib.contextmanager +def temp_dir(path=None, quiet=False): + """Return a context manager that creates a temporary directory. + + Arguments: + + path: the directory to create temporarily. If omitted or None, + defaults to creating a temporary directory using tempfile.mkdtemp. + + quiet: if False (the default), the context manager raises an exception + on error. Otherwise, if the path is specified and cannot be + created, only a warning is issued. + + """ + import tempfile + dir_created = False + if path is None: + path = tempfile.mkdtemp() + dir_created = True + path = os.path.realpath(path) + else: + try: + os.mkdir(path) + dir_created = True + except OSError as exc: + if not quiet: + raise + warnings.warn(f'tests may fail, unable to create ' + f'temporary directory {path!r}: {exc}', + RuntimeWarning, stacklevel=3) + if dir_created: + pid = os.getpid() + try: + yield path + finally: + # In case the process forks, let only the parent remove the + # directory. The child has a different process id. (bpo-30028) + if dir_created and pid == os.getpid(): + rmtree(path) + + +@contextlib.contextmanager +def change_cwd(path, quiet=False): + """Return a context manager that changes the current working directory. + + Arguments: + + path: the directory to use as the temporary current working directory. + + quiet: if False (the default), the context manager raises an exception + on error. Otherwise, it issues only a warning and keeps the current + working directory the same. + + """ + saved_dir = os.getcwd() + try: + os.chdir(os.path.realpath(path)) + except OSError as exc: + if not quiet: + raise + warnings.warn(f'tests may fail, unable to change the current working ' + f'directory to {path!r}: {exc}', + RuntimeWarning, stacklevel=3) + try: + yield os.getcwd() + finally: + os.chdir(saved_dir) + + +@contextlib.contextmanager +def temp_cwd(name='tempcwd', quiet=False): + """ + Context manager that temporarily creates and changes the CWD. + + The function temporarily changes the current working directory + after creating a temporary directory in the current directory with + name *name*. If *name* is None, the temporary directory is + created using tempfile.mkdtemp. + + If *quiet* is False (default) and it is not possible to + create or change the CWD, an error is raised. If *quiet* is True, + only a warning is raised and the original CWD is used. + + """ + with temp_dir(path=name, quiet=quiet) as temp_path: + with change_cwd(temp_path, quiet=quiet) as cwd_dir: + yield cwd_dir + + +def create_empty_file(filename): + """Create an empty file. If the file already exists, truncate it.""" + fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) + os.close(fd) + + +@contextlib.contextmanager +def open_dir_fd(path): + """Open a file descriptor to a directory.""" + assert os.path.isdir(path) + flags = os.O_RDONLY + if hasattr(os, "O_DIRECTORY"): + flags |= os.O_DIRECTORY + dir_fd = os.open(path, flags) + try: + yield dir_fd + finally: + os.close(dir_fd) + + +def fs_is_case_insensitive(directory): + """Detects if the file system for the specified directory + is case-insensitive.""" + import tempfile + with tempfile.NamedTemporaryFile(dir=directory) as base: + base_path = base.name + case_path = base_path.upper() + if case_path == base_path: + case_path = base_path.lower() + try: + return os.path.samefile(base_path, case_path) + except FileNotFoundError: + return False + + +class FakePath: + """Simple implementation of the path protocol. + """ + def __init__(self, path): + self.path = path + + def __repr__(self): + return f'' + + def __fspath__(self): + if (isinstance(self.path, BaseException) or + isinstance(self.path, type) and + issubclass(self.path, BaseException)): + raise self.path + else: + return self.path + + +def fd_count(): + """Count the number of open file descriptors. + """ + if sys.platform.startswith(('linux', 'freebsd', 'emscripten')): + fd_path = "/proc/self/fd" + elif sys.platform == "darwin": + fd_path = "/dev/fd" + else: + fd_path = None + + if fd_path is not None: + try: + names = os.listdir(fd_path) + # Subtract one because listdir() internally opens a file + # descriptor to list the content of the directory. + return len(names) - 1 + except FileNotFoundError: + pass + + MAXFD = 256 + if hasattr(os, 'sysconf'): + try: + MAXFD = os.sysconf("SC_OPEN_MAX") + except OSError: + pass + + old_modes = None + if sys.platform == 'win32': + # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process + # on invalid file descriptor if Python is compiled in debug mode + try: + import msvcrt + msvcrt.CrtSetReportMode + except (AttributeError, ImportError): + # no msvcrt or a release build + pass + else: + old_modes = {} + for report_type in (msvcrt.CRT_WARN, + msvcrt.CRT_ERROR, + msvcrt.CRT_ASSERT): + old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, + 0) + + try: + count = 0 + for fd in range(MAXFD): + try: + # Prefer dup() over fstat(). fstat() can require input/output + # whereas dup() doesn't. + fd2 = os.dup(fd) + except OSError as e: + if e.errno != errno.EBADF: + raise + else: + os.close(fd2) + count += 1 + finally: + if old_modes is not None: + for report_type in (msvcrt.CRT_WARN, + msvcrt.CRT_ERROR, + msvcrt.CRT_ASSERT): + msvcrt.CrtSetReportMode(report_type, old_modes[report_type]) + + return count + + +if hasattr(os, "umask"): + @contextlib.contextmanager + def temp_umask(umask): + """Context manager that temporarily sets the process umask.""" + oldmask = os.umask(umask) + try: + yield + finally: + os.umask(oldmask) +else: + @contextlib.contextmanager + def temp_umask(umask): + """no-op on platforms without umask()""" + yield + + +class EnvironmentVarGuard(collections.abc.MutableMapping): + + """Class to help protect the environment variable properly. Can be used as + a context manager.""" + + def __init__(self): + self._environ = os.environ + self._changed = {} + + def __getitem__(self, envvar): + return self._environ[envvar] + + def __setitem__(self, envvar, value): + # Remember the initial value on the first access + if envvar not in self._changed: + self._changed[envvar] = self._environ.get(envvar) + self._environ[envvar] = value + + def __delitem__(self, envvar): + # Remember the initial value on the first access + if envvar not in self._changed: + self._changed[envvar] = self._environ.get(envvar) + if envvar in self._environ: + del self._environ[envvar] + + def keys(self): + return self._environ.keys() + + def __iter__(self): + return iter(self._environ) + + def __len__(self): + return len(self._environ) + + def set(self, envvar, value): + self[envvar] = value + + def unset(self, envvar): + del self[envvar] + + def copy(self): + # We do what os.environ.copy() does. + return dict(self) + + def __enter__(self): + return self + + def __exit__(self, *ignore_exc): + for (k, v) in self._changed.items(): + if v is None: + if k in self._environ: + del self._environ[k] + else: + self._environ[k] = v + os.environ = self._environ diff --git a/shared/package-files/75/75abff02c286e3a64e8ac329c380aa998d1751ab8b12e44afad1b2d210d373a1/test_array_object.cpython-311.pyc b/shared/package-files/75/75abff02c286e3a64e8ac329c380aa998d1751ab8b12e44afad1b2d210d373a1/test_array_object.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f52888ab4cf2b00583f5342debd29077a9272390 Binary files /dev/null and b/shared/package-files/75/75abff02c286e3a64e8ac329c380aa998d1751ab8b12e44afad1b2d210d373a1/test_array_object.cpython-311.pyc differ diff --git a/shared/package-files/75/75b00504cb8e4d2a32efa08b37c981e3dc9e43c818d3c31b7f9b3dab0ea48917/test_map.cpython-311.pyc b/shared/package-files/75/75b00504cb8e4d2a32efa08b37c981e3dc9e43c818d3c31b7f9b3dab0ea48917/test_map.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..432447b900f6dc9ada4e26ae2814e979591dae1a Binary files /dev/null and b/shared/package-files/75/75b00504cb8e4d2a32efa08b37c981e3dc9e43c818d3c31b7f9b3dab0ea48917/test_map.cpython-311.pyc differ diff --git a/shared/package-files/75/75b2b00dccf5e1d8e50ee1b07d58bb1b8435c8029539c4bf3bc241b8d7a3dbe7/vcffilter.c b/shared/package-files/75/75b2b00dccf5e1d8e50ee1b07d58bb1b8435c8029539c4bf3bc241b8d7a3dbe7/vcffilter.c new file mode 100644 index 0000000000000000000000000000000000000000..52d4f9455567ba1f2e39b415bbc1dbd5820a1c77 --- /dev/null +++ b/shared/package-files/75/75b2b00dccf5e1d8e50ee1b07d58bb1b8435c8029539c4bf3bc241b8d7a3dbe7/vcffilter.c @@ -0,0 +1,741 @@ +/* vcffilter.c -- Apply fixed-threshold filters. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "filter.h" +#include "rbuf.h" +#include "regidx.h" + +// Logic of the filters: include or exclude sites which match the filters? +#define FLT_INCLUDE 1 +#define FLT_EXCLUDE 2 + +// FILTER columns annotation: replace or add to existing FILTERs; set FILTER to PASS at good sites? +#define ANNOT_ADD 1 +#define ANNOT_RESET 2 + +// Set genotypes of filtered samples +#define SET_GTS_MISSING 1 +#define SET_GTS_REF 2 + +typedef struct _args_t +{ + filter_t *filter; + char *filter_str; + int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE + const uint8_t *smpl_pass; + int set_gts; + char *soft_filter; // drop failed sites or annotate FILTER column? + int annot_mode; // add to existing FILTER annotation or replace? Otherwise reset FILTER to PASS or leave as it is? + int flt_fail, flt_pass; // BCF ids of fail and pass filters + int snp_gap, snp_gap_type, indel_gap, IndelGap_id, SnpGap_id; + char *snp_gap_str; + int32_t ntmpi, *tmpi, ntmp_ac, *tmp_ac; + rbuf_t rbuf; + bcf1_t **rbuf_lines; + + bcf_srs_t *files; + bcf_hdr_t *hdr; + htsFile *out_fh; + int output_type, n_threads, clevel; + + char **argv, *output_fname, *targets_list, *regions_list, *mask_list; + int argc, record_cmd_line, mask_is_file, mask_overlap, mask_negate; + regidx_t *mask; + char *index_fn; + int write_index; +} +args_t; + +static void init_data(args_t *args) +{ + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads); + + if ( args->mask_list ) + { + if ( args->mask_list[0]=='^' ) args->mask_negate = 1; + if ( args->mask_is_file ) + args->mask = regidx_init(args->mask_negate?args->mask_list+1:args->mask_list,NULL,NULL,0,NULL); + else + { + char *rmme = strdup(args->mask_negate?args->mask_list+1:args->mask_list), *tmp = rmme; + while ( *tmp ) + { + if ( *tmp==',' ) *tmp = '\n'; + tmp++; + } + args->mask = regidx_init_string(rmme, regidx_parse_reg, NULL, 0, NULL); + free(rmme); + } + if ( !args->mask ) + error("Could not initialize the mask: %s\n",args->mask_list); + } + + args->hdr = args->files->readers[0].header; + args->flt_pass = bcf_hdr_id2int(args->hdr,BCF_DT_ID,"PASS"); assert( !args->flt_pass ); // sanity check: required by BCF spec + + if ( args->soft_filter && (args->filter_logic || args->mask_list) ) + { + kstring_t flt_name = {0,0,0}; + if ( strcmp(args->soft_filter,"+") ) + kputs(args->soft_filter, &flt_name); + else + { + // Make up a filter name + int i = 0, id = -1; + do + { + ksprintf(&flt_name,"Filter%d", ++i); + id = bcf_hdr_id2int(args->hdr,BCF_DT_ID,flt_name.s); + } + while ( bcf_hdr_idinfo_exists(args->hdr,BCF_HL_FLT,id) ); + } + + kstring_t tmp = {0,0,0}; + if ( args->filter_logic ) + { + // -i or -e: append FILTER line + ksprintf(&tmp,"Set if %s: ",args->filter_logic & FLT_INCLUDE ? "not true" : "true"); + + // escape quotes + char *t = args->filter_str; + while ( *t ) + { + if ( *t=='"' ) kputc('\\',&tmp); + kputc(*t,&tmp); + t++; + } + } + else if ( args->mask_list ) + ksprintf(&tmp,"Record masked by region"); + + int ret = bcf_hdr_printf(args->hdr, "##FILTER=", flt_name.s,tmp.s); + if ( ret!=0 ) + error("Failed to append header line: ##FILTER=\n", flt_name.s,tmp.s); + args->flt_fail = bcf_hdr_id2int(args->hdr,BCF_DT_ID,flt_name.s); assert( args->flt_fail>=0 ); + free(flt_name.s); + free(tmp.s); + } + + if ( args->snp_gap || args->indel_gap ) + { + if ( !args->filter_logic && args->soft_filter && strcmp(args->soft_filter,"+") ) + { + kstring_t tmp = {0,0,0}; + if ( args->snp_gap ) kputs("\"SnpGap\"", &tmp); + if ( args->indel_gap ) + { + if ( tmp.s ) kputs(" and ", &tmp); + kputs("\"IndelGap\"", &tmp); + } + if ( strncmp(tmp.s+1,args->soft_filter,tmp.l-2) ) + fprintf(stderr,"Warning: using %s filter name instead of \"%s\"\n", tmp.s,args->soft_filter); + free(tmp.s); + } + + rbuf_init(&args->rbuf, 64); + args->rbuf_lines = (bcf1_t**) calloc(args->rbuf.m, sizeof(bcf1_t*)); + if ( args->snp_gap ) + { + bcf_hdr_printf(args->hdr, "##FILTER=", args->snp_gap,args->snp_gap_str); + args->SnpGap_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "SnpGap"); + assert( args->SnpGap_id>=0 ); + } + if ( args->indel_gap ) + { + bcf_hdr_printf(args->hdr, "##FILTER=", args->indel_gap); + args->IndelGap_id = bcf_hdr_id2int(args->hdr, BCF_DT_ID, "IndelGap"); + assert( args->IndelGap_id>=0 ); + } + } + + if (args->record_cmd_line) bcf_hdr_append_version(args->hdr, args->argc, args->argv, "bcftools_filter"); + + if ( args->filter_str ) + args->filter = filter_init(args->hdr, args->filter_str); +} + +static void destroy_data(args_t *args) +{ + if ( args->rbuf_lines ) + { + int i; + for (i=0; irbuf.m; i++) + if ( args->rbuf_lines[i] ) bcf_destroy1(args->rbuf_lines[i]); + free(args->rbuf_lines); + } + if ( args->filter ) + filter_destroy(args->filter); + free(args->tmpi); + free(args->tmp_ac); + if ( args->mask ) regidx_destroy(args->mask); +} + +static void flush_buffer(args_t *args, int n) +{ + int i, j; + for (i=0; irbuf); + bcf1_t *rec = args->rbuf_lines[k]; + + int pass = 1; + if ( !args->soft_filter ) + { + for (j=0; jd.n_flt; j++) + { + if ( args->indel_gap && rec->d.flt[j]==args->IndelGap_id ) { pass = 0; break; } + if ( args->snp_gap && rec->d.flt[j]==args->SnpGap_id ) { pass = 0; break; } + } + } + if ( pass && bcf_write1(args->out_fh, args->hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + } +} + +#define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; } +static void buffered_filters(args_t *args, bcf1_t *line) +{ + /** + * The logic of SnpGap=3. The SNPs at positions 1 and 7 are filtered, + * positions 0 and 8 are not: + * 0123456789 + * ref .G.GT..G.. + * del .A.G-..A.. + * Here the positions 1 and 6 are filtered, 0 and 7 are not: + * 0123-456789 + * ref .G.G-..G.. + * ins .A.GT..A.. + * + * The logic of IndelGap=2. The second indel is filtered: + * 012345678901 + * ref .GT.GT..GT.. + * del .G-.G-..G-.. + * And similarly here, the second is filtered: + * 01 23 456 78 + * ref .A-.A-..A-.. + * ins .AT.AT..AT.. + */ + + // To avoid additional data structure, we abuse bcf1_t's var and var_type records. + const int SnpGap_set = 1 << (8*sizeof(int)/2); + const int IndelGap_set = 1 << (8*sizeof(int)/2-1); + const int IndelGap_flush = 1 << (8*sizeof(int)/2-2); + + int var_type = 0, i; + if ( line ) + { + // Still on the same chromosome? + int ilast = rbuf_last(&args->rbuf); + if ( ilast>=0 && line->rid != args->rbuf_lines[ilast]->rid ) + flush_buffer(args, args->rbuf.n); // new chromosome, flush everything + + rbuf_expand0(&args->rbuf,bcf1_t*,args->rbuf.n,args->rbuf_lines); + + // Insert the new record in the buffer. The line would be overwritten in + // the next bcf_sr_next_line call, therefore we need to swap it with an + // unused one + ilast = rbuf_append(&args->rbuf); + if ( !args->rbuf_lines[ilast] ) args->rbuf_lines[ilast] = bcf_init1(); + SWAP(bcf1_t*, args->files->readers[0].buffer[0], args->rbuf_lines[ilast]); + + var_type = bcf_get_variant_types(line); + + // Find out the size of an indel. The indel boundaries are based on REF + // (POS+1,POS+rlen-1). This is not entirely correct: mpileup likes to + // output REF=CAGAGAGAGA, ALT=CAGAGAGAGAGA where REF=C,ALT=CGA could be + // used. This filter is therefore more strict and may remove some valid + // SNPs. + // Set the REF allele's length to max deletion length or to 1 if a SNP or an insertion. + line->d.var[0].n = line->rlen; + } + + int k_flush = 1; + if ( args->indel_gap ) + { + k_flush = 0; + // Find indels which are too close to each other + int last_to = -1; + for (i=-1; rbuf_next(&args->rbuf,&i); ) + { + bcf1_t *rec = args->rbuf_lines[i]; + int rec_from = rec->pos; + if ( last_to!=-1 && last_to < rec_from ) break; + + k_flush++; + if ( !(rec->d.var_type & VCF_INDEL) ) continue; + + rec->d.var_type |= IndelGap_set; + last_to = args->indel_gap + rec->pos + rec->d.var[0].n - 1; + } + if ( i==args->rbuf.f && line && last_to!=-1 ) k_flush = 0; + if ( k_flush || !line ) + { + // Select the best indel from the cluster of k_flush indels + int k = 0, max_ac = -1, imax_ac = -1, max_qual = -1, imax_qual = -1; + for (i=-1; rbuf_next(&args->rbuf,&i) && krbuf_lines[i]; + if ( !(rec->d.var_type & IndelGap_set) ) continue; + hts_expand(int, rec->n_allele, args->ntmpi, args->tmpi); + int ret = bcf_calc_ac(args->hdr, rec, args->tmpi, BCF_UN_ALL); + if ( imax_ac==-1 || (ret && max_ac < args->tmpi[1]) ) { max_ac = args->tmpi[1]; imax_ac = i; } + if ( imax_qual==-1 || max_qual < rec->qual ) { max_qual = rec->qual; imax_qual = i; } + } + + // Filter all but the best indel (with the best QUAL, bigger AC, or take the first if neither QUAL nor AC are available) + k = 0; + for (i=-1; rbuf_next(&args->rbuf,&i) && krbuf_lines[i]; + if ( !(rec->d.var_type & IndelGap_set) ) continue; + rec->d.var_type |= IndelGap_flush; + + int do_filter = 0; + if ( max_qual>0 ) + { + if ( i!=imax_qual ) do_filter = 1; + } + else if ( i!=imax_ac ) do_filter = 1; + if ( do_filter ) bcf_add_filter(args->hdr, args->rbuf_lines[i], args->IndelGap_id); + } + } + } + + if ( !line ) + { + // Finished: flush everything + flush_buffer(args, args->rbuf.n); + return; + } + + int j_flush = 1; + if ( args->snp_gap ) + { + j_flush = 0; + int last_from = line->pos; + for (i=-1; rbuf_next(&args->rbuf,&i); ) + { + bcf1_t *rec = args->rbuf_lines[i]; + int rec_to = rec->pos + rec->d.var[0].n - 1; // last position affected by the variant + if ( rec_to + args->snp_gap < last_from ) + j_flush++; + else if ( (var_type & args->snp_gap_type) && (rec->d.var_type & VCF_SNP) && !(rec->d.var_type & SnpGap_set) ) + { + // this SNP has not been SnpGap-filtered yet + rec->d.var_type |= SnpGap_set; + bcf_add_filter(args->hdr, rec, args->SnpGap_id); + } + else if ( (var_type & VCF_SNP) && (rec->d.var_type & args->snp_gap_type) ) + { + // the line which we are adding is a SNP and needs to be filtered + line->d.var_type |= SnpGap_set; + bcf_add_filter(args->hdr, line, args->SnpGap_id); + break; + } + } + } + flush_buffer(args, j_flush < k_flush ? j_flush : k_flush); +} + +static void set_genotypes(args_t *args, bcf1_t *line, int pass_site) +{ + int i,j; + if ( !bcf_hdr_nsamples(args->hdr) ) return; + if ( args->smpl_pass ) + { + int npass = 0; + for (i=0; ihdr); i++) npass += args->smpl_pass[i]; + + // return if all samples pass + if ( npass==bcf_hdr_nsamples(args->hdr) && (args->filter_logic & FLT_INCLUDE) ) return; + if ( npass==0 && (args->filter_logic & FLT_EXCLUDE) ) return; + } + else if ( pass_site ) return; + + int an = 0, has_an = bcf_get_info_int32(args->hdr, line, "AN", &args->tmp_ac, &args->ntmp_ac); + if ( has_an==1 ) an = args->tmp_ac[0]; + else has_an = 0; + + int has_ac = bcf_get_info_int32(args->hdr, line, "AC", &args->tmp_ac, &args->ntmp_ac); + has_ac = has_ac==line->n_allele-1 ? 1 : 0; + + int new_gt = 0, ngts = bcf_get_format_int32(args->hdr, line, "GT", &args->tmpi, &args->ntmpi); + ngts /= bcf_hdr_nsamples(args->hdr); + if ( args->set_gts==SET_GTS_MISSING ) new_gt = bcf_gt_missing; + else if ( args->set_gts==SET_GTS_REF ) new_gt = bcf_gt_unphased(0); + else error("todo: set_gts=%d\n", args->set_gts); + for (i=0; ihdr); i++) + { + if ( args->smpl_pass ) + { + int pass = args->smpl_pass[i]; + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( pass ) continue; + } + int32_t *gts = args->tmpi + ngts*i; + for (j=0; jset_gts==SET_GTS_MISSING && !bcf_gt_is_missing(gts[j]) ) + { + int ial = bcf_gt_allele(gts[j]); + if ( has_ac && ial>0 && ial<=line->n_allele ) args->tmp_ac[ ial-1 ]--; + an--; + } + else if ( args->set_gts==SET_GTS_REF ) + { + int ial = bcf_gt_allele(gts[j]); + if ( bcf_gt_is_missing(gts[j]) ) an++; + else if ( has_ac && ial>0 && ial<=line->n_allele ) args->tmp_ac[ ial-1 ]--; + } + gts[j] = new_gt; + } + } + bcf_update_genotypes(args->hdr,line,args->tmpi,ngts*bcf_hdr_nsamples(args->hdr)); + if ( has_an ) bcf_update_info_int32(args->hdr,line,"AN",&an,1); + if ( has_ac ) bcf_update_info_int32(args->hdr,line,"AC",args->tmp_ac,line->n_allele-1); +} + +static void _set_variant_boundaries(bcf1_t *rec, hts_pos_t *beg, hts_pos_t *end) +{ + hts_pos_t off; + if ( rec->n_allele ) + { + off = rec->rlen; + bcf_unpack(rec, BCF_UN_STR); + int i; + for (i=1; in_allele; i++) + { + // Make symbolic alleles start at POS, although this is not strictly true for + // , where POS should be the position BEFORE the deletion/insertion. + // However, since arbitrary symbolic alleles can be defined by the user, we + // will simplify the interpretation of --targets-overlap and --region-overlap. + int j = 0; + char *ref = rec->d.allele[0]; + char *alt = rec->d.allele[i]; + while ( ref[j] && alt[j] && ref[j]==alt[j] ) j++; + if ( off > j ) off = j; + if ( !off ) break; + } + } + else + off = 0; + + *beg = rec->pos + off; + *end = rec->pos + rec->rlen - 1; +} + +static void usage(args_t *args) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: Apply fixed-threshold filters.\n"); + fprintf(stderr, "Usage: bcftools filter [options] \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true (see man page for details)\n"); + fprintf(stderr, " -g, --SnpGap INT[:TYPE] Filter SNPs within base pairs of an indel (the default) or any combination of indel,mnp,bnd,other,overlap\n"); + fprintf(stderr, " -G, --IndelGap INT Filter clusters of indels separated by or fewer base pairs allowing only one to pass\n"); + fprintf(stderr, " -i, --include EXPR Include only sites for which the expression is true (see man page for details\n"); + fprintf(stderr, " --mask [^]REGION Soft filter regions, \"^\" to negate\n"); + fprintf(stderr, " -M, --mask-file [^]FILE Soft filter regions listed in a file, \"^\" to negate\n"); + fprintf(stderr, " --mask-overlap 0|1|2 Mask if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(stderr, " -m, --mode [+x] \"+\": do not replace but add to existing FILTER; \"x\": reset filters at sites which pass\n"); + fprintf(stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(stderr, " -s, --soft-filter STRING Annotate FILTER column with or unique filter name (\"Filter%%d\") made up by the program (\"+\")\n"); + fprintf(stderr, " -S, --set-GTs .|0 Set genotypes of failed samples to missing (.) or ref (0)\n"); + fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(stderr, " --threads INT Use multithreading with worker threads [0]\n"); + fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(stderr, "\n"); + exit(1); +} + +int main_vcffilter(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->files = bcf_sr_init(); + args->output_fname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->clevel = -1; + int regions_is_file = 0, targets_is_file = 0; + int regions_overlap = 1; + int targets_overlap = 0; + args->mask_overlap = 1; + + static struct option loptions[] = + { + {"set-GTs",required_argument,NULL,'S'}, + {"mode",required_argument,NULL,'m'}, + {"mask",required_argument,NULL,10}, + {"mask-file",required_argument,NULL,'M'}, + {"mask-overlap",required_argument,NULL,11}, + {"soft-filter",required_argument,NULL,'s'}, + {"exclude",required_argument,NULL,'e'}, + {"include",required_argument,NULL,'i'}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"targets-overlap",required_argument,NULL,4}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,3}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"SnpGap",required_argument,NULL,'g'}, + {"IndelGap",required_argument,NULL,'G'}, + {"no-version",no_argument,NULL,8}, + {"write-index",optional_argument,NULL,'W'}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "e:i:t:T:r:R:h?s:m:M:o:O:g:G:S:W::",loptions,NULL)) >= 0) { + switch (c) { + case 'g': + args->snp_gap = strtol(optarg,&tmp,10); + if ( *tmp && *tmp!=':' ) error("Could not parse argument: --SnpGap %s\n", optarg); + if ( *tmp==':' ) + { + args->snp_gap_str = tmp+1; + int i,n; + char **keys = hts_readlist(tmp+1,0,&n); + for(i=0; isnp_gap_type |= VCF_INDEL; + else if ( !strcasecmp(keys[i],"mnp") ) args->snp_gap_type |= VCF_MNP; + else if ( !strcasecmp(keys[i],"bnd") ) args->snp_gap_type |= VCF_BND; + else if ( !strcasecmp(keys[i],"other") ) args->snp_gap_type |= VCF_OTHER; + else if ( !strcasecmp(keys[i],"overlap") ) args->snp_gap_type |= VCF_OVERLAP; + else error("Could not parse \"%s\" in \"--SnpGap %s\"\n", keys[i], optarg); + free(keys[i]); + } + if ( n ) free(keys); + } + else + { + args->snp_gap_type = VCF_INDEL; + args->snp_gap_str = "indel"; + } + break; + case 'G': + args->indel_gap = strtol(optarg,&tmp,10); + if ( *tmp ) error("Could not parse argument: --IndelGap %s\n", optarg); + break; + case 'o': args->output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 's': args->soft_filter = optarg; break; + case 'm': + if ( strchr(optarg,'x') ) args->annot_mode |= ANNOT_RESET; + if ( strchr(optarg,'+') ) args->annot_mode |= ANNOT_ADD; + break; + case 't': args->targets_list = optarg; break; + case 'T': args->targets_list = optarg; targets_is_file = 1; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; regions_is_file = 1; break; + case 'e': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break; + case 'i': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break; + case 'S': + if ( !strcmp(".",optarg) ) args->set_gts = SET_GTS_MISSING; + else if ( !strcmp("0",optarg) ) args->set_gts = SET_GTS_REF; + else error("The argument to -S not recognised: %s\n", optarg); + break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 8 : args->record_cmd_line = 0; break; + case 3 : + regions_overlap = parse_overlap_option(optarg); + if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 4 : + targets_overlap = parse_overlap_option(optarg); + if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case 10 : args->mask_list = optarg; break; + case 'M' : args->mask_list = optarg; args->mask_is_file = 1; break; + case 11 : + if ( !strcasecmp(optarg,"0") ) args->mask_overlap = 0; + else if ( !strcasecmp(optarg,"1") ) args->mask_overlap = 1; + else if ( !strcasecmp(optarg,"2") ) args->mask_overlap = 2; + else error("Could not parse: --mask-overlap %s\n",optarg); + break; + case 'W': + if (!(args->write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + case 'h': + case '?': usage(args); break; + default: error("Unknown argument: %s\n", optarg); + } + } + + if ( args->filter_logic == (FLT_EXCLUDE|FLT_INCLUDE) ) error("Only one of -i or -e can be given.\n"); + char *fname = NULL; + if ( optind>=argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin + else usage(args); + } + else fname = argv[optind]; + + if ( args->mask_list && !args->soft_filter ) error("The option --soft-filter is required with --mask and --mask-file options\n"); + + // read in the regions from the command line + if ( args->regions_list ) + { + args->files->require_index = 1; + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + else if ( optind+1 < argc ) + { + int i; + kstring_t tmp = {0,0,0}; + kputs(argv[optind+1],&tmp); + for (i=optind+2; ifiles->require_index = 1; + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap); + if ( bcf_sr_set_regions(args->files, tmp.s, regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + free(tmp.s); + } + if ( args->targets_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap); + if ( bcf_sr_set_targets(args->files, args->targets_list,targets_is_file, 0)<0 ) + error("Failed to read the targets: %s\n", args->targets_list); + } + if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum)); + + init_data(args); + if ( bcf_hdr_write(args->out_fh, args->hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname); + if ( init_index2(args->out_fh,args->hdr,args->output_fname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->output_fname); + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files, 0); + int pass = 1; + if ( args->filter ) + { + pass = filter_test(args->filter, line, &args->smpl_pass); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + } + if ( args->mask ) + { + hts_pos_t beg, end; + if ( args->mask_overlap==0 ) beg = end = line->pos; + else if ( args->mask_overlap==1 ) beg = line->pos, end = line->pos + line->rlen - 1; + else _set_variant_boundaries(line,&beg,&end); + int mpass = regidx_overlap(args->mask,bcf_seqname(args->hdr,line),beg,end,NULL) ? 0 : 1; + if ( args->mask_negate ) mpass = mpass ? 0 : 1; + pass &= mpass; + } + if ( args->soft_filter || args->set_gts || pass ) + { + if ( pass ) + { + bcf_unpack(line,BCF_UN_FLT); + if ( args->annot_mode & ANNOT_RESET || !line->d.n_flt ) bcf_add_filter(args->hdr, line, args->flt_pass); + } + else if ( args->soft_filter ) + { + if ( (args->annot_mode & ANNOT_ADD) ) bcf_add_filter(args->hdr, line, args->flt_fail); + else bcf_update_filter(args->hdr, line, &args->flt_fail, 1); + } + if ( args->set_gts ) set_genotypes(args, line, pass); + if ( !args->rbuf_lines ) + { + if ( bcf_write1(args->out_fh, args->hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + } + else + buffered_filters(args, line); + } + } + buffered_filters(args, NULL); + if ( args->write_index ) + { + if ( bcf_idx_save(args->out_fh)<0 ) + { + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname); + destroy_data(args); + bcf_sr_destroy(args->files); + free(args); + return 0; +} diff --git a/shared/package-files/75/75bde4b9e3c7c1e51a62412c7f9ea611db74191b1b4f569c6b439dedc9b0a533/test_entrypoints.cpython-311.pyc b/shared/package-files/75/75bde4b9e3c7c1e51a62412c7f9ea611db74191b1b4f569c6b439dedc9b0a533/test_entrypoints.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67b6bfdacc756def8228538d9aae8dd2fcefc17b Binary files /dev/null and b/shared/package-files/75/75bde4b9e3c7c1e51a62412c7f9ea611db74191b1b4f569c6b439dedc9b0a533/test_entrypoints.cpython-311.pyc differ diff --git a/shared/package-files/75/75c100f9b8fa023d4da0ce686bae96f24b4d7a456bfefcb4e459e031d29e6bd0/_nested_tensor_storage_offsets_native.h b/shared/package-files/75/75c100f9b8fa023d4da0ce686bae96f24b4d7a456bfefcb4e459e031d29e6bd0/_nested_tensor_storage_offsets_native.h new file mode 100644 index 0000000000000000000000000000000000000000..d702cc8299be5f37e1d50dafb3232ea5b82170bc --- /dev/null +++ b/shared/package-files/75/75c100f9b8fa023d4da0ce686bae96f24b4d7a456bfefcb4e459e031d29e6bd0/_nested_tensor_storage_offsets_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & _nested_tensor_storage_offsets_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor _nested_tensor_storage_offsets(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/75/75c932f8fd87932ec4f4647bd2cf36160c62c1890d18b575da5fc8b0fefa4f39/_sfdp_pattern_15.py b/shared/package-files/75/75c932f8fd87932ec4f4647bd2cf36160c62c1890d18b575da5fc8b0fefa4f39/_sfdp_pattern_15.py new file mode 100644 index 0000000000000000000000000000000000000000..289585111a54bf37d1f017adbcf73afd7ae03f94 --- /dev/null +++ b/shared/package-files/75/75c932f8fd87932ec4f4647bd2cf36160c62c1890d18b575da5fc8b0fefa4f39/_sfdp_pattern_15.py @@ -0,0 +1,227 @@ +# mypy: ignore-errors + +# noqa: F401, E501 +# This is an auto-generated file. Please do not modify it by hand. +# To re-generate, run: +# cd ~/pytorch && python torchgen/fuse/gen_patterns.py + +import torch +import torch._inductor + +aten = torch.ops.aten +prims = torch.ops.prims + +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + CallFunctionVarArgs, + CallMethod, + CallMethodVarArgs, + CallModule, + CallModuleVarArgs, + ExclusiveKeywordArg, + Ignored, + KeywordArg, + ListOf, + MultiOutputPattern, + PatternExpr, + RepeatedExpr, + _TargetArgsExpr, + _TargetExpr, + _TargetExprVarArgs, +) +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +expand_default = CallFunction(aten.expand.default, eq_Scalar, Ignored(), _users=2) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3) +expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored()) +neg_default = CallFunction(aten.neg.default, div_Tensor_1) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, fma_default) +div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_15_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2) +amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_15_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +expand_default = CallFunction(aten.expand.default, eq_Scalar, Ignored(), _users=2) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2) +bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1) +view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_3 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4) +view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored()) +scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored()) +convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2) +neg_default = CallFunction(aten.neg.default, convert_element_type_default_2) +view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2) +permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored()) +bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4) +view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored()) +convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored()) +mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2) +sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True) +fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor) +convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored()) +where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, convert_element_type_default_4) +div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, KeywordArg('inv_scale')) +view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2) +permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored()) +bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5) +view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored()) +permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored()) +permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored()) +bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8) +view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored()) +permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored()) +permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored()) +permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored()) +bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6) +view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored()) +permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored()) +_sfdp_pattern_15_half_training = MultiOutputPattern([view_default_5, + permute_default_6, + permute_default_9, + permute_default_11, + None, + None +]) + + +eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored()) +view_default = CallFunction(aten.view.default, eq_Scalar, Ignored()) +expand_default = CallFunction(aten.expand.default, view_default, Ignored()) +full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False) +permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored()) +expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored()) +clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format) +view_default_1 = CallFunction(aten.view.default, clone_default, Ignored()) +permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored()) +permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored()) +expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored()) +clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format) +view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored()) +bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2) +view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored()) +div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale')) +where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor) +convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2) +amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True) +sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default) +exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2) +sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True) +div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList) +convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored()) +expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored()) +view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored()) +permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored()) +expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored()) +clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format) +view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored()) +bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5) +_sfdp_pattern_15_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0) diff --git a/shared/package-files/75/75cf01999116c38604ae0d13287b921beb889ad080f7d5492845042b08ab4d4f/v3.py b/shared/package-files/75/75cf01999116c38604ae0d13287b921beb889ad080f7d5492845042b08ab4d4f/v3.py new file mode 100644 index 0000000000000000000000000000000000000000..334788585ff796530a6487834f8639eb612c66be --- /dev/null +++ b/shared/package-files/75/75cf01999116c38604ae0d13287b921beb889ad080f7d5492845042b08ab4d4f/v3.py @@ -0,0 +1,628 @@ +import os +import shutil +from collections import OrderedDict +from collections.abc import MutableMapping +from threading import Lock +from typing import Union, Dict, Any, Optional + +from zarr.errors import ( + MetadataError, + ReadOnlyError, +) +from zarr.util import buffer_size, json_loads, normalize_storage_path +from zarr.types import DIMENSION_SEPARATOR + +from zarr._storage.absstore import ABSStoreV3 # noqa: F401 +from zarr._storage.store import ( # noqa: F401 + _get_hierarchy_metadata, + _get_metadata_suffix, + _listdir_from_keys, + _rename_from_keys, + _rename_metadata_v3, + _rmdir_from_keys, + _rmdir_from_keys_v3, + _path_to_prefix, + _prefix_to_array_key, + _prefix_to_group_key, + array_meta_key, + attrs_key, + data_root, + group_meta_key, + meta_root, + BaseStore, + Store, + StoreV3, +) +from zarr.storage import ( + DBMStore, + ConsolidatedMetadataStore, + DirectoryStore, + FSStore, + KVStore, + LMDBStore, + LRUStoreCache, + MemoryStore, + MongoDBStore, + RedisStore, + SQLiteStore, + ZipStore, + _getsize, +) + +__doctest_requires__ = { + ("RedisStore", "RedisStore.*"): ["redis"], + ("MongoDBStore", "MongoDBStore.*"): ["pymongo"], + ("LRUStoreCache", "LRUStoreCache.*"): ["s3fs"], +} + + +try: + # noinspection PyUnresolvedReferences + from zarr.codecs import Blosc + + default_compressor = Blosc() +except ImportError: # pragma: no cover + from zarr.codecs import Zlib + + default_compressor = Zlib() + + +Path = Union[str, bytes, None] +# allow MutableMapping for backwards compatibility +StoreLike = Union[BaseStore, MutableMapping] + + +class RmdirV3: + """Mixin class that can be used to ensure override of any existing v2 rmdir class.""" + + def rmdir(self, path: str = "") -> None: + path = normalize_storage_path(path) + _rmdir_from_keys_v3(self, path) # type: ignore + + +class KVStoreV3(RmdirV3, KVStore, StoreV3): + def list(self): + return list(self._mutable_mapping.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def __eq__(self, other): + return isinstance(other, KVStoreV3) and self._mutable_mapping == other._mutable_mapping + + +KVStoreV3.__doc__ = KVStore.__doc__ + + +def _get_files_and_dirs_from_path(store, path): + path = normalize_storage_path(path) + + files = [] + # add array metadata file if present + array_key = _prefix_to_array_key(store, path) + if array_key in store: + files.append(os.path.join(store.path, array_key)) + + # add group metadata file if present + group_key = _prefix_to_group_key(store, path) + if group_key in store: + files.append(os.path.join(store.path, group_key)) + + dirs = [] + # add array and group folders if present + for d in [data_root + path, meta_root + path]: + dir_path = os.path.join(store.path, d) + if os.path.exists(dir_path): + dirs.append(dir_path) + return files, dirs + + +class FSStoreV3(FSStore, StoreV3): + # FSStoreV3 doesn't use this (FSStore uses it within _normalize_key) + _META_KEYS = () + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def _default_key_separator(self): + if self.key_separator is None: + self.key_separator = "/" + + def list(self): + return list(self.keys()) + + def _normalize_key(self, key): + key = normalize_storage_path(key).lstrip("/") + return key.lower() if self.normalize_keys else key + + def getsize(self, path=None): + size = 0 + if path is None or path == "": + # size of both the data and meta subdirs + dirs = [] + for d in ["data/root", "meta/root"]: + dir_path = os.path.join(self.path, d) + if os.path.exists(dir_path): + dirs.append(dir_path) + elif path in self: + # access individual element by full path + return buffer_size(self[path]) + else: + files, dirs = _get_files_and_dirs_from_path(self, path) + for file in files: + size += os.path.getsize(file) + for d in dirs: + size += self.fs.du(d, total=True, maxdepth=None) + return size + + def setitems(self, values): + if self.mode == "r": + raise ReadOnlyError() + values = {self._normalize_key(key): val for key, val in values.items()} + + # initialize the /data/root/... folder corresponding to the array! + # Note: zarr.tests.test_core_v3.TestArrayWithFSStoreV3PartialRead fails + # without this explicit creation of directories + subdirectories = set(os.path.dirname(v) for v in values.keys()) + for subdirectory in subdirectories: + data_dir = os.path.join(self.path, subdirectory) + if not self.fs.exists(data_dir): + self.fs.mkdir(data_dir) + + self.map.setitems(values) + + def rmdir(self, path=None): + if self.mode == "r": + raise ReadOnlyError() + if path: + for base in [meta_root, data_root]: + store_path = self.dir_path(base + path) + if self.fs.isdir(store_path): + self.fs.rm(store_path, recursive=True) + + # remove any associated metadata files + sfx = _get_metadata_suffix(self) + meta_dir = (meta_root + path).rstrip("/") + array_meta_file = meta_dir + ".array" + sfx + self.pop(array_meta_file, None) + group_meta_file = meta_dir + ".group" + sfx + self.pop(group_meta_file, None) + else: + store_path = self.dir_path(path) + if self.fs.isdir(store_path): + self.fs.rm(store_path, recursive=True) + + @property + def supports_efficient_get_partial_values(self): + return True + + def get_partial_values(self, key_ranges): + """Get multiple partial values. + key_ranges can be an iterable of key, range pairs, + where a range specifies two integers range_start and range_length + as a tuple, (range_start, range_length). + range_length may be None to indicate to read until the end. + range_start may be negative to start reading range_start bytes + from the end of the file. + A key may occur multiple times with different ranges. + Inserts None for missing keys into the returned list.""" + results = [] + for key, (range_start, range_length) in key_ranges: + key = self._normalize_key(key) + path = self.dir_path(key) + try: + if range_start is None or range_length is None: + end = None + else: + end = range_start + range_length + result = self.fs.cat_file(path, start=range_start, end=end) + except self.map.missing_exceptions: + result = None + results.append(result) + return results + + +class MemoryStoreV3(MemoryStore, StoreV3): + def __init__( + self, root=None, cls=dict, dimension_separator: Optional[DIMENSION_SEPARATOR] = None + ): + if root is None: + self.root = cls() + else: + self.root = root + self.cls = cls + self.write_mutex = Lock() + self._dimension_separator = dimension_separator # TODO: modify for v3? + + def __eq__(self, other): + return ( + isinstance(other, MemoryStoreV3) and self.root == other.root and self.cls == other.cls + ) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def list(self): + return list(self.keys()) + + def getsize(self, path: Path = None): + return _getsize(self, path) + + def rename(self, src_path: Path, dst_path: Path): + src_path = normalize_storage_path(src_path) + dst_path = normalize_storage_path(dst_path) + + any_renamed = False + for base in [meta_root, data_root]: + if self.list_prefix(base + src_path): + src_parent, src_key = self._get_parent(base + src_path) + dst_parent, dst_key = self._require_parent(base + dst_path) + + if src_key in src_parent: + dst_parent[dst_key] = src_parent.pop(src_key) + + if base == meta_root: + # check for and move corresponding metadata + sfx = _get_metadata_suffix(self) + src_meta = src_key + ".array" + sfx + if src_meta in src_parent: + dst_meta = dst_key + ".array" + sfx + dst_parent[dst_meta] = src_parent.pop(src_meta) + src_meta = src_key + ".group" + sfx + if src_meta in src_parent: + dst_meta = dst_key + ".group" + sfx + dst_parent[dst_meta] = src_parent.pop(src_meta) + any_renamed = True + any_renamed = _rename_metadata_v3(self, src_path, dst_path) or any_renamed + if not any_renamed: + raise ValueError(f"no item {src_path} found to rename") + + def rmdir(self, path: Path = None): + path = normalize_storage_path(path) + if path: + for base in [meta_root, data_root]: + try: + parent, key = self._get_parent(base + path) + value = parent[key] + except KeyError: + continue + else: + if isinstance(value, self.cls): + del parent[key] + + # remove any associated metadata files + sfx = _get_metadata_suffix(self) + meta_dir = (meta_root + path).rstrip("/") + array_meta_file = meta_dir + ".array" + sfx + self.pop(array_meta_file, None) + group_meta_file = meta_dir + ".group" + sfx + self.pop(group_meta_file, None) + else: + # clear out root + self.root = self.cls() + + +MemoryStoreV3.__doc__ = MemoryStore.__doc__ + + +class DirectoryStoreV3(DirectoryStore, StoreV3): + def list(self): + return list(self.keys()) + + def __eq__(self, other): + return isinstance(other, DirectoryStoreV3) and self.path == other.path + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def getsize(self, path: Path = None): + return _getsize(self, path) + + def rename(self, src_path, dst_path, metadata_key_suffix=".json"): + store_src_path = normalize_storage_path(src_path) + store_dst_path = normalize_storage_path(dst_path) + + dir_path = self.path + any_existed = False + for root_prefix in ["meta", "data"]: + src_path = os.path.join(dir_path, root_prefix, "root", store_src_path) + if os.path.exists(src_path): + any_existed = True + dst_path = os.path.join(dir_path, root_prefix, "root", store_dst_path) + os.renames(src_path, dst_path) + + for suffix in [".array" + metadata_key_suffix, ".group" + metadata_key_suffix]: + src_meta = os.path.join(dir_path, "meta", "root", store_src_path + suffix) + if os.path.exists(src_meta): + any_existed = True + dst_meta = os.path.join(dir_path, "meta", "root", store_dst_path + suffix) + dst_dir = os.path.dirname(dst_meta) + if not os.path.exists(dst_dir): + os.makedirs(dst_dir) + os.rename(src_meta, dst_meta) + if not any_existed: + raise FileNotFoundError("nothing found at src_path") + + def rmdir(self, path=None): + store_path = normalize_storage_path(path) + dir_path = self.path + if store_path: + for base in [meta_root, data_root]: + dir_path = os.path.join(dir_path, base + store_path) + if os.path.isdir(dir_path): + shutil.rmtree(dir_path) + + # remove any associated metadata files + sfx = _get_metadata_suffix(self) + meta_dir = (meta_root + path).rstrip("/") + array_meta_file = meta_dir + ".array" + sfx + self.pop(array_meta_file, None) + group_meta_file = meta_dir + ".group" + sfx + self.pop(group_meta_file, None) + + elif os.path.isdir(dir_path): + shutil.rmtree(dir_path) + + +DirectoryStoreV3.__doc__ = DirectoryStore.__doc__ + + +class ZipStoreV3(ZipStore, StoreV3): + def list(self): + return list(self.keys()) + + def __eq__(self, other): + return ( + isinstance(other, ZipStore) + and self.path == other.path + and self.compression == other.compression + and self.allowZip64 == other.allowZip64 + ) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def getsize(self, path=None): + path = normalize_storage_path(path) + with self.mutex: + children = self.list_prefix(data_root + path) + children += self.list_prefix(meta_root + path) + print(f"path={path}, children={children}") + if children: + size = 0 + for name in children: + info = self.zf.getinfo(name) + size += info.compress_size + return size + elif path in self: + info = self.zf.getinfo(path) + return info.compress_size + else: + return 0 + + +ZipStoreV3.__doc__ = ZipStore.__doc__ + + +class RedisStoreV3(RmdirV3, RedisStore, StoreV3): + def list(self): + return list(self.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + +RedisStoreV3.__doc__ = RedisStore.__doc__ + + +class MongoDBStoreV3(RmdirV3, MongoDBStore, StoreV3): + def list(self): + return list(self.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + +MongoDBStoreV3.__doc__ = MongoDBStore.__doc__ + + +class DBMStoreV3(RmdirV3, DBMStore, StoreV3): + def list(self): + return list(self.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + +DBMStoreV3.__doc__ = DBMStore.__doc__ + + +class LMDBStoreV3(RmdirV3, LMDBStore, StoreV3): + def list(self): + return list(self.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + +LMDBStoreV3.__doc__ = LMDBStore.__doc__ + + +class SQLiteStoreV3(SQLiteStore, StoreV3): + def list(self): + return list(self.keys()) + + def getsize(self, path=None): + # TODO: why does the query below not work in this case? + # For now fall back to the default _getsize implementation + # size = 0 + # for _path in [data_root + path, meta_root + path]: + # c = self.cursor.execute( + # ''' + # SELECT COALESCE(SUM(LENGTH(v)), 0) FROM zarr + # WHERE k LIKE (? || "%") AND + # 0 == INSTR(LTRIM(SUBSTR(k, LENGTH(?) + 1), "/"), "/") + # ''', + # (_path, _path) + # ) + # for item_size, in c: + # size += item_size + # return size + + # fallback to default implementation for now + return _getsize(self, path) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + def rmdir(self, path=None): + path = normalize_storage_path(path) + if path: + for base in [meta_root, data_root]: + with self.lock: + self.cursor.execute("DELETE FROM zarr WHERE k LIKE (? || '/%')", (base + path,)) + # remove any associated metadata files + sfx = _get_metadata_suffix(self) + meta_dir = (meta_root + path).rstrip("/") + array_meta_file = meta_dir + ".array" + sfx + self.pop(array_meta_file, None) + group_meta_file = meta_dir + ".group" + sfx + self.pop(group_meta_file, None) + else: + self.clear() + + +SQLiteStoreV3.__doc__ = SQLiteStore.__doc__ + + +class LRUStoreCacheV3(RmdirV3, LRUStoreCache, StoreV3): + def __init__(self, store, max_size: int): + self._store = StoreV3._ensure_store(store) + self._max_size = max_size + self._current_size = 0 + self._keys_cache = None + self._contains_cache = {} + self._listdir_cache: Dict[Path, Any] = dict() + self._values_cache: Dict[Path, Any] = OrderedDict() + self._mutex = Lock() + self.hits = self.misses = 0 + + def list(self): + return list(self.keys()) + + def __setitem__(self, key, value): + self._validate_key(key) + super().__setitem__(key, value) + + +LRUStoreCacheV3.__doc__ = LRUStoreCache.__doc__ + + +class ConsolidatedMetadataStoreV3(ConsolidatedMetadataStore, StoreV3): + """A layer over other storage, where the metadata has been consolidated into + a single key. + + The purpose of this class, is to be able to get all of the metadata for + a given array in a single read operation from the underlying storage. + See :func:`zarr.convenience.consolidate_metadata` for how to create this + single metadata key. + + This class loads from the one key, and stores the data in a dict, so that + accessing the keys no longer requires operations on the backend store. + + This class is read-only, and attempts to change the array metadata will + fail, but changing the data is possible. If the backend storage is changed + directly, then the metadata stored here could become obsolete, and + :func:`zarr.convenience.consolidate_metadata` should be called again and the class + re-invoked. The use case is for write once, read many times. + + .. note:: This is an experimental feature. + + Parameters + ---------- + store: Store + Containing the zarr array. + metadata_key: str + The target in the store where all of the metadata are stored. We + assume JSON encoding. + + See Also + -------- + zarr.convenience.consolidate_metadata, zarr.convenience.open_consolidated + + """ + + def __init__(self, store: StoreLike, metadata_key=meta_root + "consolidated/.zmetadata"): + self.store = StoreV3._ensure_store(store) + + # retrieve consolidated metadata + meta = json_loads(self.store[metadata_key]) + + # check format of consolidated metadata + consolidated_format = meta.get("zarr_consolidated_format", None) + if consolidated_format != 1: + raise MetadataError( + f"unsupported zarr consolidated metadata format: {consolidated_format}" + ) + + # decode metadata + self.meta_store: Store = KVStoreV3(meta["metadata"]) + + def rmdir(self, key): + raise ReadOnlyError() + + +def _normalize_store_arg_v3(store: Any, storage_options=None, mode="r") -> BaseStore: + # default to v2 store for backward compatibility + zarr_version = getattr(store, "_store_version", 3) + if zarr_version != 3: + raise ValueError("store must be a version 3 store") + if store is None: + store = KVStoreV3(dict()) + # add default zarr.json metadata + store["zarr.json"] = store._metadata_class.encode_hierarchy_metadata(None) + return store + if isinstance(store, os.PathLike): + store = os.fspath(store) + if FSStore._fsspec_installed(): + import fsspec + + if isinstance(store, fsspec.FSMap): + return FSStoreV3( + store.root, + fs=store.fs, + mode=mode, + check=store.check, + create=store.create, + missing_exceptions=store.missing_exceptions, + **(storage_options or {}), + ) + if isinstance(store, str): + if "://" in store or "::" in store: + store = FSStoreV3(store, mode=mode, **(storage_options or {})) + elif storage_options: + raise ValueError("storage_options passed with non-fsspec path") + elif store.endswith(".zip"): + store = ZipStoreV3(store, mode=mode) + elif store.endswith(".n5"): + raise NotImplementedError("N5Store not yet implemented for V3") + # return N5StoreV3(store) + else: + store = DirectoryStoreV3(store) + else: + store = StoreV3._ensure_store(store) + + if "zarr.json" not in store: + # add default zarr.json metadata + store["zarr.json"] = store._metadata_class.encode_hierarchy_metadata(None) + return store diff --git a/shared/package-files/75/75d15f1f4b41ce8ba2917707875123df1ec80510768665928ad1e9af741e068e/test_digraph_historical.cpython-311.pyc b/shared/package-files/75/75d15f1f4b41ce8ba2917707875123df1ec80510768665928ad1e9af741e068e/test_digraph_historical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f0e4e4f9c3a7b1be6689b2322c573926002ce69 Binary files /dev/null and b/shared/package-files/75/75d15f1f4b41ce8ba2917707875123df1ec80510768665928ad1e9af741e068e/test_digraph_historical.cpython-311.pyc differ diff --git a/shared/package-files/75/75d409013ac5ec4eb73cc4305a65d075d6574a71e3e62c958230d4e9ab6346b0/_affine_quantization.cpython-311.pyc b/shared/package-files/75/75d409013ac5ec4eb73cc4305a65d075d6574a71e3e62c958230d4e9ab6346b0/_affine_quantization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fa0a0fd6d537ae594d964c03bb3eb055be1cbad Binary files /dev/null and b/shared/package-files/75/75d409013ac5ec4eb73cc4305a65d075d6574a71e3e62c958230d4e9ab6346b0/_affine_quantization.cpython-311.pyc differ diff --git a/shared/package-files/75/75de9e4260a37c29a623bea182c0b7ed1faa3c9d7520c85a7d56b14a8d97245b/sparse_tensor.h b/shared/package-files/75/75de9e4260a37c29a623bea182c0b7ed1faa3c9d7520c85a7d56b14a8d97245b/sparse_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..4ec824dfa7d8653fa83b949c193a0bd55ead3491 --- /dev/null +++ b/shared/package-files/75/75de9e4260a37c29a623bea182c0b7ed1faa3c9d7520c85a7d56b14a8d97245b/sparse_tensor.h @@ -0,0 +1,617 @@ +// 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. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/compare.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/tensor.h" // IWYU pragma: export +#include "arrow/type.h" +#include "arrow/util/checked_cast.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +namespace arrow { + +class MemoryPool; + +namespace internal { + +ARROW_EXPORT +Status CheckSparseIndexMaximumValue(const std::shared_ptr& index_value_type, + const std::vector& shape); + +} // namespace internal + +// ---------------------------------------------------------------------- +// SparseIndex class + +struct SparseTensorFormat { + /// EXPERIMENTAL: The index format type of SparseTensor + enum type { + /// Coordinate list (COO) format. + COO, + /// Compressed sparse row (CSR) format. + CSR, + /// Compressed sparse column (CSC) format. + CSC, + /// Compressed sparse fiber (CSF) format. + CSF + }; +}; + +/// \brief EXPERIMENTAL: The base class for the index of a sparse tensor +/// +/// SparseIndex describes where the non-zero elements are within a SparseTensor. +/// +/// There are several ways to represent this. The format_id is used to +/// distinguish what kind of representation is used. Each possible value of +/// format_id must have only one corresponding concrete subclass of SparseIndex. +class ARROW_EXPORT SparseIndex { + public: + explicit SparseIndex(SparseTensorFormat::type format_id) : format_id_(format_id) {} + + virtual ~SparseIndex() = default; + + /// \brief Return the identifier of the format type + SparseTensorFormat::type format_id() const { return format_id_; } + + /// \brief Return the number of non zero values in the sparse tensor related + /// to this sparse index + virtual int64_t non_zero_length() const = 0; + + /// \brief Return the string representation of the sparse index + virtual std::string ToString() const = 0; + + virtual Status ValidateShape(const std::vector& shape) const; + + protected: + const SparseTensorFormat::type format_id_; +}; + +namespace internal { +template +class SparseIndexBase : public SparseIndex { + public: + SparseIndexBase() : SparseIndex(SparseIndexType::format_id) {} +}; +} // namespace internal + +// ---------------------------------------------------------------------- +// SparseCOOIndex class + +/// \brief EXPERIMENTAL: The index data for a COO sparse tensor +/// +/// A COO sparse index manages the location of its non-zero values by their +/// coordinates. +class ARROW_EXPORT SparseCOOIndex : public internal::SparseIndexBase { + public: + static constexpr SparseTensorFormat::type format_id = SparseTensorFormat::COO; + + /// \brief Make SparseCOOIndex from a coords tensor and canonicality + static Result> Make( + const std::shared_ptr& coords, bool is_canonical); + + /// \brief Make SparseCOOIndex from a coords tensor with canonicality auto-detection + static Result> Make( + const std::shared_ptr& coords); + + /// \brief Make SparseCOOIndex from raw properties with canonicality auto-detection + static Result> Make( + const std::shared_ptr& indices_type, + const std::vector& indices_shape, + const std::vector& indices_strides, std::shared_ptr indices_data); + + /// \brief Make SparseCOOIndex from raw properties + static Result> Make( + const std::shared_ptr& indices_type, + const std::vector& indices_shape, + const std::vector& indices_strides, std::shared_ptr indices_data, + bool is_canonical); + + /// \brief Make SparseCOOIndex from sparse tensor's shape properties and data + /// with canonicality auto-detection + /// + /// The indices_data should be in row-major (C-like) order. If not, + /// use the raw properties constructor. + static Result> Make( + const std::shared_ptr& indices_type, const std::vector& shape, + int64_t non_zero_length, std::shared_ptr indices_data); + + /// \brief Make SparseCOOIndex from sparse tensor's shape properties and data + /// + /// The indices_data should be in row-major (C-like) order. If not, + /// use the raw properties constructor. + static Result> Make( + const std::shared_ptr& indices_type, const std::vector& shape, + int64_t non_zero_length, std::shared_ptr indices_data, bool is_canonical); + + /// \brief Construct SparseCOOIndex from column-major NumericTensor + explicit SparseCOOIndex(const std::shared_ptr& coords, bool is_canonical); + + /// \brief Return a tensor that has the coordinates of the non-zero values + /// + /// The returned tensor is a N x D tensor where N is the number of non-zero + /// values and D is the number of dimensions in the logical data. + /// The column at index `i` is a D-tuple of coordinates indicating that the + /// logical value at those coordinates should be found at physical index `i`. + const std::shared_ptr& indices() const { return coords_; } + + /// \brief Return the number of non zero values in the sparse tensor related + /// to this sparse index + int64_t non_zero_length() const override { return coords_->shape()[0]; } + + /// \brief Return whether a sparse tensor index is canonical, or not. + /// If a sparse tensor index is canonical, it is sorted in the lexicographical order, + /// and the corresponding sparse tensor doesn't have duplicated entries. + bool is_canonical() const { return is_canonical_; } + + /// \brief Return a string representation of the sparse index + std::string ToString() const override; + + /// \brief Return whether the COO indices are equal + bool Equals(const SparseCOOIndex& other) const { + return indices()->Equals(*other.indices()); + } + + inline Status ValidateShape(const std::vector& shape) const override { + ARROW_RETURN_NOT_OK(SparseIndex::ValidateShape(shape)); + + if (static_cast(coords_->shape()[1]) == shape.size()) { + return Status::OK(); + } + + return Status::Invalid( + "shape length is inconsistent with the coords matrix in COO index"); + } + + protected: + std::shared_ptr coords_; + bool is_canonical_; +}; + +namespace internal { + +/// EXPERIMENTAL: The axis to be compressed +enum class SparseMatrixCompressedAxis : char { + /// The value for CSR matrix + ROW, + /// The value for CSC matrix + COLUMN +}; + +ARROW_EXPORT +Status ValidateSparseCSXIndex(const std::shared_ptr& indptr_type, + const std::shared_ptr& indices_type, + const std::vector& indptr_shape, + const std::vector& indices_shape, + char const* type_name); + +ARROW_EXPORT +void CheckSparseCSXIndexValidity(const std::shared_ptr& indptr_type, + const std::shared_ptr& indices_type, + const std::vector& indptr_shape, + const std::vector& indices_shape, + char const* type_name); + +template +class SparseCSXIndex : public SparseIndexBase { + public: + static constexpr SparseMatrixCompressedAxis kCompressedAxis = COMPRESSED_AXIS; + + /// \brief Make a subclass of SparseCSXIndex from raw properties + static Result> Make( + const std::shared_ptr& indptr_type, + const std::shared_ptr& indices_type, + const std::vector& indptr_shape, const std::vector& indices_shape, + std::shared_ptr indptr_data, std::shared_ptr indices_data) { + ARROW_RETURN_NOT_OK(ValidateSparseCSXIndex(indptr_type, indices_type, indptr_shape, + indices_shape, + SparseIndexType::kTypeName)); + return std::make_shared( + std::make_shared(indptr_type, indptr_data, indptr_shape), + std::make_shared(indices_type, indices_data, indices_shape)); + } + + /// \brief Make a subclass of SparseCSXIndex from raw properties + static Result> Make( + const std::shared_ptr& indices_type, + const std::vector& indptr_shape, const std::vector& indices_shape, + std::shared_ptr indptr_data, std::shared_ptr indices_data) { + return Make(indices_type, indices_type, indptr_shape, indices_shape, indptr_data, + indices_data); + } + + /// \brief Make a subclass of SparseCSXIndex from sparse tensor's shape properties and + /// data + static Result> Make( + const std::shared_ptr& indptr_type, + const std::shared_ptr& indices_type, const std::vector& shape, + int64_t non_zero_length, std::shared_ptr indptr_data, + std::shared_ptr indices_data) { + std::vector indptr_shape({shape[0] + 1}); + std::vector indices_shape({non_zero_length}); + return Make(indptr_type, indices_type, indptr_shape, indices_shape, indptr_data, + indices_data); + } + + /// \brief Make a subclass of SparseCSXIndex from sparse tensor's shape properties and + /// data + static Result> Make( + const std::shared_ptr& indices_type, const std::vector& shape, + int64_t non_zero_length, std::shared_ptr indptr_data, + std::shared_ptr indices_data) { + return Make(indices_type, indices_type, shape, non_zero_length, indptr_data, + indices_data); + } + + /// \brief Construct SparseCSXIndex from two index vectors + explicit SparseCSXIndex(const std::shared_ptr& indptr, + const std::shared_ptr& indices) + : SparseIndexBase(), indptr_(indptr), indices_(indices) { + CheckSparseCSXIndexValidity(indptr_->type(), indices_->type(), indptr_->shape(), + indices_->shape(), SparseIndexType::kTypeName); + } + + /// \brief Return a 1D tensor of indptr vector + const std::shared_ptr& indptr() const { return indptr_; } + + /// \brief Return a 1D tensor of indices vector + const std::shared_ptr& indices() const { return indices_; } + + /// \brief Return the number of non zero values in the sparse tensor related + /// to this sparse index + int64_t non_zero_length() const override { return indices_->shape()[0]; } + + /// \brief Return a string representation of the sparse index + std::string ToString() const override { + return std::string(SparseIndexType::kTypeName); + } + + /// \brief Return whether the CSR indices are equal + bool Equals(const SparseIndexType& other) const { + return indptr()->Equals(*other.indptr()) && indices()->Equals(*other.indices()); + } + + inline Status ValidateShape(const std::vector& shape) const override { + ARROW_RETURN_NOT_OK(SparseIndex::ValidateShape(shape)); + + if (shape.size() < 2) { + return Status::Invalid("shape length is too short"); + } + + if (shape.size() > 2) { + return Status::Invalid("shape length is too long"); + } + + if (indptr_->shape()[0] == shape[static_cast(kCompressedAxis)] + 1) { + return Status::OK(); + } + + return Status::Invalid("shape length is inconsistent with the ", ToString()); + } + + protected: + std::shared_ptr indptr_; + std::shared_ptr indices_; +}; + +} // namespace internal + +// ---------------------------------------------------------------------- +// SparseCSRIndex class + +/// \brief EXPERIMENTAL: The index data for a CSR sparse matrix +/// +/// A CSR sparse index manages the location of its non-zero values by two +/// vectors. +/// +/// The first vector, called indptr, represents the range of the rows; the i-th +/// row spans from indptr[i] to indptr[i+1] in the corresponding value vector. +/// So the length of an indptr vector is the number of rows + 1. +/// +/// The other vector, called indices, represents the column indices of the +/// corresponding non-zero values. So the length of an indices vector is same +/// as the number of non-zero-values. +class ARROW_EXPORT SparseCSRIndex + : public internal::SparseCSXIndex { + public: + using BaseClass = + internal::SparseCSXIndex; + + static constexpr SparseTensorFormat::type format_id = SparseTensorFormat::CSR; + static constexpr char const* kTypeName = "SparseCSRIndex"; + + using SparseCSXIndex::kCompressedAxis; + using SparseCSXIndex::Make; + using SparseCSXIndex::SparseCSXIndex; +}; + +// ---------------------------------------------------------------------- +// SparseCSCIndex class + +/// \brief EXPERIMENTAL: The index data for a CSC sparse matrix +/// +/// A CSC sparse index manages the location of its non-zero values by two +/// vectors. +/// +/// The first vector, called indptr, represents the range of the column; the i-th +/// column spans from indptr[i] to indptr[i+1] in the corresponding value vector. +/// So the length of an indptr vector is the number of columns + 1. +/// +/// The other vector, called indices, represents the row indices of the +/// corresponding non-zero values. So the length of an indices vector is same +/// as the number of non-zero-values. +class ARROW_EXPORT SparseCSCIndex + : public internal::SparseCSXIndex { + public: + using BaseClass = + internal::SparseCSXIndex; + + static constexpr SparseTensorFormat::type format_id = SparseTensorFormat::CSC; + static constexpr char const* kTypeName = "SparseCSCIndex"; + + using SparseCSXIndex::kCompressedAxis; + using SparseCSXIndex::Make; + using SparseCSXIndex::SparseCSXIndex; +}; + +// ---------------------------------------------------------------------- +// SparseCSFIndex class + +/// \brief EXPERIMENTAL: The index data for a CSF sparse tensor +/// +/// A CSF sparse index manages the location of its non-zero values by set of +/// prefix trees. Each path from a root to leaf forms one tensor non-zero index. +/// CSF is implemented with three vectors. +/// +/// Vectors inptr and indices contain N-1 and N buffers respectively, where N is the +/// number of dimensions. Axis_order is a vector of integers of length N. Indptr and +/// indices describe the set of prefix trees. Trees traverse dimensions in order given by +/// axis_order. +class ARROW_EXPORT SparseCSFIndex : public internal::SparseIndexBase { + public: + static constexpr SparseTensorFormat::type format_id = SparseTensorFormat::CSF; + static constexpr char const* kTypeName = "SparseCSFIndex"; + + /// \brief Make SparseCSFIndex from raw properties + static Result> Make( + const std::shared_ptr& indptr_type, + const std::shared_ptr& indices_type, + const std::vector& indices_shapes, const std::vector& axis_order, + const std::vector>& indptr_data, + const std::vector>& indices_data); + + /// \brief Make SparseCSFIndex from raw properties + static Result> Make( + const std::shared_ptr& indices_type, + const std::vector& indices_shapes, const std::vector& axis_order, + const std::vector>& indptr_data, + const std::vector>& indices_data) { + return Make(indices_type, indices_type, indices_shapes, axis_order, indptr_data, + indices_data); + } + + /// \brief Construct SparseCSFIndex from two index vectors + explicit SparseCSFIndex(const std::vector>& indptr, + const std::vector>& indices, + const std::vector& axis_order); + + /// \brief Return a 1D vector of indptr tensors + const std::vector>& indptr() const { return indptr_; } + + /// \brief Return a 1D vector of indices tensors + const std::vector>& indices() const { return indices_; } + + /// \brief Return a 1D vector specifying the order of axes + const std::vector& axis_order() const { return axis_order_; } + + /// \brief Return the number of non zero values in the sparse tensor related + /// to this sparse index + int64_t non_zero_length() const override { return indices_.back()->shape()[0]; } + + /// \brief Return a string representation of the sparse index + std::string ToString() const override; + + /// \brief Return whether the CSF indices are equal + bool Equals(const SparseCSFIndex& other) const; + + protected: + std::vector> indptr_; + std::vector> indices_; + std::vector axis_order_; +}; + +// ---------------------------------------------------------------------- +// SparseTensor class + +/// \brief EXPERIMENTAL: The base class of sparse tensor container +class ARROW_EXPORT SparseTensor { + public: + virtual ~SparseTensor() = default; + + SparseTensorFormat::type format_id() const { return sparse_index_->format_id(); } + + /// \brief Return a value type of the sparse tensor + std::shared_ptr type() const { return type_; } + + /// \brief Return a buffer that contains the value vector of the sparse tensor + std::shared_ptr data() const { return data_; } + + /// \brief Return an immutable raw data pointer + const uint8_t* raw_data() const { return data_->data(); } + + /// \brief Return a mutable raw data pointer + uint8_t* raw_mutable_data() const { return data_->mutable_data(); } + + /// \brief Return a shape vector of the sparse tensor + const std::vector& shape() const { return shape_; } + + /// \brief Return a sparse index of the sparse tensor + const std::shared_ptr& sparse_index() const { return sparse_index_; } + + /// \brief Return a number of dimensions of the sparse tensor + int ndim() const { return static_cast(shape_.size()); } + + /// \brief Return a vector of dimension names + const std::vector& dim_names() const { return dim_names_; } + + /// \brief Return the name of the i-th dimension + const std::string& dim_name(int i) const; + + /// \brief Total number of value cells in the sparse tensor + int64_t size() const; + + /// \brief Return true if the underlying data buffer is mutable + bool is_mutable() const { return data_->is_mutable(); } + + /// \brief Total number of non-zero cells in the sparse tensor + int64_t non_zero_length() const { + return sparse_index_ ? sparse_index_->non_zero_length() : 0; + } + + /// \brief Return whether sparse tensors are equal + bool Equals(const SparseTensor& other, + const EqualOptions& = EqualOptions::Defaults()) const; + + /// \brief Return dense representation of sparse tensor as tensor + /// + /// The returned Tensor has row-major order (C-like). + Result> ToTensor(MemoryPool* pool) const; + Result> ToTensor() const { + return ToTensor(default_memory_pool()); + } + + protected: + // Constructor with all attributes + SparseTensor(const std::shared_ptr& type, const std::shared_ptr& data, + const std::vector& shape, + const std::shared_ptr& sparse_index, + const std::vector& dim_names); + + std::shared_ptr type_; + std::shared_ptr data_; + std::vector shape_; + std::shared_ptr sparse_index_; + + // These names are optional + std::vector dim_names_; +}; + +// ---------------------------------------------------------------------- +// SparseTensorImpl class + +namespace internal { + +ARROW_EXPORT +Status MakeSparseTensorFromTensor(const Tensor& tensor, + SparseTensorFormat::type sparse_format_id, + const std::shared_ptr& index_value_type, + MemoryPool* pool, + std::shared_ptr* out_sparse_index, + std::shared_ptr* out_data); + +} // namespace internal + +/// \brief EXPERIMENTAL: Concrete sparse tensor implementation classes with sparse index +/// type +template +class SparseTensorImpl : public SparseTensor { + public: + virtual ~SparseTensorImpl() = default; + + /// \brief Construct a sparse tensor from physical data buffer and logical index + SparseTensorImpl(const std::shared_ptr& sparse_index, + const std::shared_ptr& type, + const std::shared_ptr& data, const std::vector& shape, + const std::vector& dim_names) + : SparseTensor(type, data, shape, sparse_index, dim_names) {} + + /// \brief Construct an empty sparse tensor + SparseTensorImpl(const std::shared_ptr& type, + const std::vector& shape, + const std::vector& dim_names = {}) + : SparseTensorImpl(NULLPTR, type, NULLPTR, shape, dim_names) {} + + /// \brief Create a SparseTensor with full parameters + static inline Result>> Make( + const std::shared_ptr& sparse_index, + const std::shared_ptr& type, const std::shared_ptr& data, + const std::vector& shape, const std::vector& dim_names) { + if (!is_tensor_supported(type->id())) { + return Status::Invalid(type->ToString(), + " is not valid data type for a sparse tensor"); + } + ARROW_RETURN_NOT_OK(sparse_index->ValidateShape(shape)); + if (dim_names.size() > 0 && dim_names.size() != shape.size()) { + return Status::Invalid("dim_names length is inconsistent with shape"); + } + return std::make_shared>(sparse_index, type, data, + shape, dim_names); + } + + /// \brief Create a sparse tensor from a dense tensor + /// + /// The dense tensor is re-encoded as a sparse index and a physical + /// data buffer for the non-zero value. + static inline Result>> Make( + const Tensor& tensor, const std::shared_ptr& index_value_type, + MemoryPool* pool = default_memory_pool()) { + std::shared_ptr sparse_index; + std::shared_ptr data; + ARROW_RETURN_NOT_OK(internal::MakeSparseTensorFromTensor( + tensor, SparseIndexType::format_id, index_value_type, pool, &sparse_index, + &data)); + return std::make_shared>( + internal::checked_pointer_cast(sparse_index), tensor.type(), + data, tensor.shape(), tensor.dim_names_); + } + + static inline Result>> Make( + const Tensor& tensor, MemoryPool* pool = default_memory_pool()) { + return Make(tensor, int64(), pool); + } + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(SparseTensorImpl); +}; + +/// \brief EXPERIMENTAL: Type alias for COO sparse tensor +using SparseCOOTensor = SparseTensorImpl; + +/// \brief EXPERIMENTAL: Type alias for CSR sparse matrix +using SparseCSRMatrix = SparseTensorImpl; + +/// \brief EXPERIMENTAL: Type alias for CSC sparse matrix +using SparseCSCMatrix = SparseTensorImpl; + +/// \brief EXPERIMENTAL: Type alias for CSF sparse matrix +using SparseCSFTensor = SparseTensorImpl; + +} // namespace arrow diff --git a/shared/package-files/75/75e19c946d7794e39dff112429811f1540e07b4222b9da7d309c2ebfb622b3e3/test_update.py b/shared/package-files/75/75e19c946d7794e39dff112429811f1540e07b4222b9da7d309c2ebfb622b3e3/test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..3f18ae6c138807f7bd84f4bd88125508703d86e8 --- /dev/null +++ b/shared/package-files/75/75e19c946d7794e39dff112429811f1540e07b4222b9da7d309c2ebfb622b3e3/test_update.py @@ -0,0 +1,139 @@ +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas import ( + CategoricalDtype, + DataFrame, + NaT, + Series, + Timestamp, +) +import pandas._testing as tm + + +class TestUpdate: + def test_update(self, using_copy_on_write): + s = Series([1.5, np.nan, 3.0, 4.0, np.nan]) + s2 = Series([np.nan, 3.5, np.nan, 5.0]) + s.update(s2) + + expected = Series([1.5, 3.5, 3.0, 5.0, np.nan]) + tm.assert_series_equal(s, expected) + + # GH 3217 + df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) + df["c"] = np.nan + # Cast to object to avoid upcast when setting "foo" + df["c"] = df["c"].astype(object) + df_orig = df.copy() + + if using_copy_on_write: + with tm.raises_chained_assignment_error(): + df["c"].update(Series(["foo"], index=[0])) + expected = df_orig + else: + with tm.assert_produces_warning(FutureWarning, match="inplace method"): + df["c"].update(Series(["foo"], index=[0])) + expected = DataFrame( + [[1, np.nan, "foo"], [3, 2.0, np.nan]], columns=["a", "b", "c"] + ) + expected["c"] = expected["c"].astype(object) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize( + "other, dtype, expected, warn", + [ + # other is int + ([61, 63], "int32", Series([10, 61, 12], dtype="int32"), None), + ([61, 63], "int64", Series([10, 61, 12]), None), + ([61, 63], float, Series([10.0, 61.0, 12.0]), None), + ([61, 63], object, Series([10, 61, 12], dtype=object), None), + # other is float, but can be cast to int + ([61.0, 63.0], "int32", Series([10, 61, 12], dtype="int32"), None), + ([61.0, 63.0], "int64", Series([10, 61, 12]), None), + ([61.0, 63.0], float, Series([10.0, 61.0, 12.0]), None), + ([61.0, 63.0], object, Series([10, 61.0, 12], dtype=object), None), + # others is float, cannot be cast to int + ([61.1, 63.1], "int32", Series([10.0, 61.1, 12.0]), FutureWarning), + ([61.1, 63.1], "int64", Series([10.0, 61.1, 12.0]), FutureWarning), + ([61.1, 63.1], float, Series([10.0, 61.1, 12.0]), None), + ([61.1, 63.1], object, Series([10, 61.1, 12], dtype=object), None), + # other is object, cannot be cast + ([(61,), (63,)], "int32", Series([10, (61,), 12]), FutureWarning), + ([(61,), (63,)], "int64", Series([10, (61,), 12]), FutureWarning), + ([(61,), (63,)], float, Series([10.0, (61,), 12.0]), FutureWarning), + ([(61,), (63,)], object, Series([10, (61,), 12]), None), + ], + ) + def test_update_dtypes(self, other, dtype, expected, warn): + ser = Series([10, 11, 12], dtype=dtype) + other = Series(other, index=[1, 3]) + with tm.assert_produces_warning(warn, match="item of incompatible dtype"): + ser.update(other) + + tm.assert_series_equal(ser, expected) + + @pytest.mark.parametrize( + "series, other, expected", + [ + # update by key + ( + Series({"a": 1, "b": 2, "c": 3, "d": 4}), + {"b": 5, "c": np.nan}, + Series({"a": 1, "b": 5, "c": 3, "d": 4}), + ), + # update by position + (Series([1, 2, 3, 4]), [np.nan, 5, 1], Series([1, 5, 1, 4])), + ], + ) + def test_update_from_non_series(self, series, other, expected): + # GH 33215 + series.update(other) + tm.assert_series_equal(series, expected) + + @pytest.mark.parametrize( + "data, other, expected, dtype", + [ + (["a", None], [None, "b"], ["a", "b"], "string[python]"), + pytest.param( + ["a", None], + [None, "b"], + ["a", "b"], + "string[pyarrow]", + marks=td.skip_if_no("pyarrow"), + ), + ([1, None], [None, 2], [1, 2], "Int64"), + ([True, None], [None, False], [True, False], "boolean"), + ( + ["a", None], + [None, "b"], + ["a", "b"], + CategoricalDtype(categories=["a", "b"]), + ), + ( + [Timestamp(year=2020, month=1, day=1, tz="Europe/London"), NaT], + [NaT, Timestamp(year=2020, month=1, day=1, tz="Europe/London")], + [Timestamp(year=2020, month=1, day=1, tz="Europe/London")] * 2, + "datetime64[ns, Europe/London]", + ), + ], + ) + def test_update_extension_array_series(self, data, other, expected, dtype): + result = Series(data, dtype=dtype) + other = Series(other, dtype=dtype) + expected = Series(expected, dtype=dtype) + + result.update(other) + tm.assert_series_equal(result, expected) + + def test_update_with_categorical_type(self): + # GH 25744 + dtype = CategoricalDtype(["a", "b", "c", "d"]) + s1 = Series(["a", "b", "c"], index=[1, 2, 3], dtype=dtype) + s2 = Series(["b", "a"], index=[1, 2], dtype=dtype) + s1.update(s2) + result = s1 + expected = Series(["b", "a", "c"], index=[1, 2, 3], dtype=dtype) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/75/75e7f26abf62db5b6ba529f2537ae7b9e97697ce2bada661cd1175cb20718c0f/Loops.cuh b/shared/package-files/75/75e7f26abf62db5b6ba529f2537ae7b9e97697ce2bada661cd1175cb20718c0f/Loops.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bb8c6f1b37ac1b33f4cf64d44fa9ccb33a0f7f2b --- /dev/null +++ b/shared/package-files/75/75e7f26abf62db5b6ba529f2537ae7b9e97697ce2bada661cd1175cb20718c0f/Loops.cuh @@ -0,0 +1,328 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +namespace at::native { + +template +static OffsetCalculator make_input_offset_calculator(const TensorIteratorBase& iter) { + // array size can not be 0, this happens when N == 0 + constexpr int array_size = std::max(N, 1); + TORCH_INTERNAL_ASSERT(N == iter.ntensors() - iter.noutputs()); + std::array strides; + int64_t element_sizes[array_size]; + for (int i = 0; i < N; i++) { + strides[i] = iter.strides(i + iter.noutputs()).data(); + element_sizes[i] = iter.element_size(i + iter.noutputs()); + } + return OffsetCalculator(iter.ndim(), iter.shape().data(), strides.data(), element_sizes); +} + +template +static OffsetCalculator make_output_offset_calculator(const TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(num_outputs == iter.noutputs()); + std::array strides; + int64_t element_sizes[num_outputs]; + for (int i = 0; i < num_outputs; i++) { + strides[i] = iter.strides(i).data(); + element_sizes[i] = iter.element_size(i); + } + return OffsetCalculator(iter.ndim(), iter.shape().data(), strides.data(), element_sizes); +} + +template +__device__ inline void elementwise_kernel_helper(func_t f, policy_t policy) { + using traits = function_traits; + using return_t = typename traits::result_type; + using args_t = typename traits::ArgsTuple; + constexpr int elems_per_thread = policy_t::tws; + + int idx = blockIdx.x; + + return_t results[elems_per_thread]; + args_t args[elems_per_thread]; + + // load + policy.load(args, idx); + + // compute + #pragma unroll + for (int i = 0; i < elems_per_thread; i++) { + if (policy.check_inbounds(i)) { + results[i] = c10::guts::apply(f, args[i]); + } + } + + // store + policy.store(results, idx); +} + +} // namespace at::native + +#include + +namespace at:: native { + +template +void gpu_kernel_nocast(TensorIteratorBase& iter, const func_t& f) { + + for (int arg = 0; arg < iter.ntensors(); arg++) { + TORCH_INTERNAL_ASSERT( + iter.device(arg).is_cuda(), + "argument ", arg, ": expected a CUDA device but found ", iter.device(arg)); + } + + if (iter.numel() == 0) { + return; + } + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + gpu_kernel_nocast(sub_iter, f); + } + return; + } + + gpu_kernel_impl_nocast(iter, f); +} + +template +void gpu_kernel(TensorIteratorBase& iter, const func_t& f) { + + for (int arg = 0; arg < iter.ntensors(); arg++) { + TORCH_INTERNAL_ASSERT( + iter.device(arg).is_cuda(), + "argument ", arg, ": expected a CUDA device but found ", iter.device(arg)); + } + + if (iter.numel() == 0) { + return; + } + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + gpu_kernel(sub_iter, f); + } + return; + } + + gpu_kernel_impl(iter, f); +} + +template +struct AUnaryFunctor { + using traits = function_traits; + using opmath_arg1_t = typename traits::template arg<0>::type; + __device__ return_t operator()(arg2_t b) const { + return f(a, b); + } + // NB: scalar is stored in higher precision! + AUnaryFunctor(func_t f_, opmath_arg1_t a_): f(f_), a(a_) {} + private: + func_t f; + opmath_arg1_t a; +}; + +template +struct BUnaryFunctor { + using traits = function_traits; + using opmath_arg2_t = typename traits::template arg<1>::type; + __device__ return_t operator()(arg1_t a) const { + return f(a, b); + } + // NB: scalar is stored in higher precision! + BUnaryFunctor(func_t f_, opmath_arg2_t b_): f(f_), b(b_) {} + private: + func_t f; + opmath_arg2_t b; +}; + +// Though seemingly noop, this inserts casts from arg1_t to func_t's type +// (which may be higher precision), as well as casts to return_t +template +struct BinaryFunctor { + __device__ return_t operator()(arg1_t a, arg2_t b) const { + return f(a, b); + } + BinaryFunctor(func_t f_): f(f_) {} + private: + func_t f; +}; + +// Unlike gpu_kernel_with_scalars, this allows you to pass a func_t which +// accepts inputs at higher precision (typically opmath_t), but then +// ensure that we load from memory at the correct precision (scalar_t) +// to avoid expensive loads. For the whole sordid story see +// https://dev-discuss.pytorch.org/t/cuda-loops-case-study-code-generation-vs-templates/302 +template +void opmath_gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 3); + + using traits = function_traits; + using opmath_arg1_t = typename traits::template arg<0>::type; + using opmath_arg2_t = typename traits::template arg<1>::type; + static_assert( + traits::arity == 2, + "gpu_kernel_with_scalars only supports two input arguments"); + + if (iter.is_cpu_scalar(1)) { + AUnaryFunctor af(f, iter.scalar_value(1)); + iter.remove_operand(1); + // TODO: When all kernels that use gpu_kernel_with_scalars are + // ported to structured, this device guard can be deleted. This + // works around incorrect device guard generation for pre-structured + // kernels device guards, but structured kernels do it right and + // we can assume the device is already set correctly + const OptionalDeviceGuard device_guard(iter.device(1)); + gpu_kernel(iter, af); + } else if (iter.is_cpu_scalar(2)) { + BUnaryFunctor bf(f, iter.scalar_value(2)); + iter.remove_operand(2); + gpu_kernel(iter, bf); + } else { + gpu_kernel(iter, BinaryFunctor(f)); + } +} + +template +void opmath_symmetric_gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) { + // Use symmetric property of the functor to reduce number of kernels, + // requires f(a, b) == f(b, a) + TORCH_INTERNAL_ASSERT(iter.ntensors() == 3); + + using traits = function_traits; + using opmath_arg_t = typename traits::template arg<0>::type; + static_assert( + traits::arity == 2, + "gpu_kernel_with_scalars only supports two input arguments"); + static_assert(std::is_same_v::type>, + "f is not symmetric"); + + OptionalDeviceGuard device_guard; + opmath_arg_t scalar_val{}; + + if (iter.is_cpu_scalar(1)) { + scalar_val = iter.scalar_value(1); + iter.remove_operand(1); + + // TODO: When all kernels that use gpu_kernel_with_scalars are + // ported to structured, this device guard can be deleted. This + // works around incorrect device guard generation for pre-structured + // kernels device guards, but structured kernels do it right and + // we can assume the device is already set correctly + device_guard.reset_device(iter.device(1)); + } else if (iter.is_cpu_scalar(2)) { + scalar_val = iter.scalar_value(2); + iter.remove_operand(2); + } + + if (iter.ninputs() == 2) { + gpu_kernel(iter, BinaryFunctor(f)); + } else { + AUnaryFunctor unary_f(f, scalar_val); + gpu_kernel(iter, unary_f); + } +} + +// Legacy variant that assumes that func_t has the correct types +// that we expect to load from memory +template +void gpu_kernel_with_scalars(TensorIteratorBase& iter, const func_t& f) { + using traits = function_traits; + static_assert( + traits::arity == 2, + "gpu_kernel_with_scalars only supports two input arguments"); + using arg1_t = typename traits::template arg<0>::type; + using arg2_t = typename traits::template arg<1>::type; + using return_t = typename traits::result_type; + opmath_gpu_kernel_with_scalars(iter, f); +} + +namespace { // functions for `gpu_kernel_multiple_outputs`. + +// check the return type is `thrust::tuple`, not `std::tuple`. +template struct is_tuple: std::false_type {}; + +template struct is_tuple>: std::true_type {}; + +template +C10_LAUNCH_BOUNDS_1(num_threads()) +__global__ void unrolled_elementwise_kernel_for_multi_outputs(int N, func_t f, array_t data, inp_calc_t ic, out_calc_t oc) { + int remaining = N - block_work_size() * blockIdx.x; + elementwise_kernel_helper(f, memory::policies::multi_outputs_unroll(data, remaining, ic, oc)); +} + +template +static inline void launch_unrolled_kernel_for_multi_outputs(int64_t N, const func_t& f, array_t data, inp_calc_t ic, out_calc_t oc) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + int64_t grid = (N + block_work_size() - 1) / block_work_size(); + auto stream = at::cuda::getCurrentCUDAStream(); + unrolled_elementwise_kernel_for_multi_outputs<<>>(N, f, data, ic, oc); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +template +void gpu_kernel_multiple_outputs_impl(TensorIteratorBase& iter, const func_t& f) { + using traits = function_traits; + using output_t = typename traits::result_type; + static_assert(is_tuple::value, "f's return type must be `thrust::tuple`"); + constexpr int num_outputs = thrust::tuple_size::value; + constexpr int num_inputs = traits::arity; + constexpr int ntensors = num_outputs + num_inputs; + + TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing()); + TORCH_INTERNAL_ASSERT(iter.ntensors() == ntensors); + + std::array data; + for (int i = 0; i < ntensors; i++) { + data[i] = (char*)iter.data_ptr(i); + } + + int64_t numel = iter.numel(); + + if (iter.is_contiguous()) { + auto input_calc = TrivialOffsetCalculator(); + auto output_calc = TrivialOffsetCalculator(); + launch_unrolled_kernel_for_multi_outputs(numel, f, data, input_calc, output_calc); + } else { + auto input_calc = make_input_offset_calculator(iter); + auto output_calc = make_output_offset_calculator(iter); + launch_unrolled_kernel_for_multi_outputs(numel, f, data, input_calc, output_calc); + } +} +} // namespace + +template +void gpu_kernel_multiple_outputs(TensorIteratorBase& iter, const func_t& f) { + ASSERT_HOST_DEVICE_LAMBDA(func_t); + + for (int arg = 0; arg < iter.ntensors(); arg++) { + TORCH_INTERNAL_ASSERT(iter.device(arg).is_cuda()); + } + + if (iter.numel() == 0) { + return; + } + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + gpu_kernel_multiple_outputs(sub_iter, f); + } + return; + } + + gpu_kernel_multiple_outputs_impl(iter, f); +} + +} //namespace at::native diff --git a/shared/package-files/75/75efb2a53599123bc592af5180fab782118ebc539f3e66fd25f50300f290a179/beta_functions.py b/shared/package-files/75/75efb2a53599123bc592af5180fab782118ebc539f3e66fd25f50300f290a179/beta_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..337ae6c71fe5a38cc0fcd819e9d489ebbbd1946b --- /dev/null +++ b/shared/package-files/75/75efb2a53599123bc592af5180fab782118ebc539f3e66fd25f50300f290a179/beta_functions.py @@ -0,0 +1,389 @@ +from sympy.core import S +from sympy.core.function import DefinedFunction, ArgumentIndexError +from sympy.core.symbol import Dummy, uniquely_named_symbol +from sympy.functions.special.gamma_functions import gamma, digamma +from sympy.functions.combinatorial.numbers import catalan +from sympy.functions.elementary.complexes import conjugate + +# See mpmath #569 and SymPy #20569 +def betainc_mpmath_fix(a, b, x1, x2, reg=0): + from mpmath import betainc, mpf + if x1 == x2: + return mpf(0) + else: + return betainc(a, b, x1, x2, reg) + +############################################################################### +############################ COMPLETE BETA FUNCTION ########################## +############################################################################### + +class beta(DefinedFunction): + r""" + The beta integral is called the Eulerian integral of the first kind by + Legendre: + + .. math:: + \mathrm{B}(x,y) \int^{1}_{0} t^{x-1} (1-t)^{y-1} \mathrm{d}t. + + Explanation + =========== + + The Beta function or Euler's first integral is closely associated + with the gamma function. The Beta function is often used in probability + theory and mathematical statistics. It satisfies properties like: + + .. math:: + \mathrm{B}(a,1) = \frac{1}{a} \\ + \mathrm{B}(a,b) = \mathrm{B}(b,a) \\ + \mathrm{B}(a,b) = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)} + + Therefore for integral values of $a$ and $b$: + + .. math:: + \mathrm{B} = \frac{(a-1)! (b-1)!}{(a+b-1)!} + + A special case of the Beta function when `x = y` is the + Central Beta function. It satisfies properties like: + + .. math:: + \mathrm{B}(x) = 2^{1 - 2x}\mathrm{B}(x, \frac{1}{2}) + \mathrm{B}(x) = 2^{1 - 2x} cos(\pi x) \mathrm{B}(\frac{1}{2} - x, x) + \mathrm{B}(x) = \int_{0}^{1} \frac{t^x}{(1 + t)^{2x}} dt + \mathrm{B}(x) = \frac{2}{x} \prod_{n = 1}^{\infty} \frac{n(n + 2x)}{(n + x)^2} + + Examples + ======== + + >>> from sympy import I, pi + >>> from sympy.abc import x, y + + The Beta function obeys the mirror symmetry: + + >>> from sympy import beta, conjugate + >>> conjugate(beta(x, y)) + beta(conjugate(x), conjugate(y)) + + Differentiation with respect to both $x$ and $y$ is supported: + + >>> from sympy import beta, diff + >>> diff(beta(x, y), x) + (polygamma(0, x) - polygamma(0, x + y))*beta(x, y) + + >>> diff(beta(x, y), y) + (polygamma(0, y) - polygamma(0, x + y))*beta(x, y) + + >>> diff(beta(x), x) + 2*(polygamma(0, x) - polygamma(0, 2*x))*beta(x, x) + + We can numerically evaluate the Beta function to + arbitrary precision for any complex numbers x and y: + + >>> from sympy import beta + >>> beta(pi).evalf(40) + 0.02671848900111377452242355235388489324562 + + >>> beta(1 + I).evalf(20) + -0.2112723729365330143 - 0.7655283165378005676*I + + See Also + ======== + + gamma: Gamma function. + uppergamma: Upper incomplete gamma function. + lowergamma: Lower incomplete gamma function. + polygamma: Polygamma function. + loggamma: Log Gamma function. + digamma: Digamma function. + trigamma: Trigamma function. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function + .. [2] https://mathworld.wolfram.com/BetaFunction.html + .. [3] https://dlmf.nist.gov/5.12 + + """ + unbranched = True + + def fdiff(self, argindex): + x, y = self.args + if argindex == 1: + # Diff wrt x + return beta(x, y)*(digamma(x) - digamma(x + y)) + elif argindex == 2: + # Diff wrt y + return beta(x, y)*(digamma(y) - digamma(x + y)) + else: + raise ArgumentIndexError(self, argindex) + + @classmethod + def eval(cls, x, y=None): + if y is None: + return beta(x, x) + if x.is_Number and y.is_Number: + return beta(x, y, evaluate=False).doit() + + def doit(self, **hints): + x = xold = self.args[0] + # Deal with unevaluated single argument beta + single_argument = len(self.args) == 1 + y = yold = self.args[0] if single_argument else self.args[1] + if hints.get('deep', True): + x = x.doit(**hints) + y = y.doit(**hints) + if y.is_zero or x.is_zero: + return S.ComplexInfinity + if y is S.One: + return 1/x + if x is S.One: + return 1/y + if y == x + 1: + return 1/(x*y*catalan(x)) + s = x + y + if (s.is_integer and s.is_negative and x.is_integer is False and + y.is_integer is False): + return S.Zero + if x == xold and y == yold and not single_argument: + return self + return beta(x, y) + + def _eval_expand_func(self, **hints): + x, y = self.args + return gamma(x)*gamma(y) / gamma(x + y) + + def _eval_is_real(self): + return self.args[0].is_real and self.args[1].is_real + + def _eval_conjugate(self): + return self.func(self.args[0].conjugate(), self.args[1].conjugate()) + + def _eval_rewrite_as_gamma(self, x, y, piecewise=True, **kwargs): + return self._eval_expand_func(**kwargs) + + def _eval_rewrite_as_Integral(self, x, y, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy(uniquely_named_symbol('t', [x, y]).name) + return Integral(t**(x - 1)*(1 - t)**(y - 1), (t, 0, 1)) + +############################################################################### +########################## INCOMPLETE BETA FUNCTION ########################### +############################################################################### + +class betainc(DefinedFunction): + r""" + The Generalized Incomplete Beta function is defined as + + .. math:: + \mathrm{B}_{(x_1, x_2)}(a, b) = \int_{x_1}^{x_2} t^{a - 1} (1 - t)^{b - 1} dt + + The Incomplete Beta function is a special case + of the Generalized Incomplete Beta function : + + .. math:: \mathrm{B}_z (a, b) = \mathrm{B}_{(0, z)}(a, b) + + The Incomplete Beta function satisfies : + + .. math:: \mathrm{B}_z (a, b) = (-1)^a \mathrm{B}_{\frac{z}{z - 1}} (a, 1 - a - b) + + The Beta function is a special case of the Incomplete Beta function : + + .. math:: \mathrm{B}(a, b) = \mathrm{B}_{1}(a, b) + + Examples + ======== + + >>> from sympy import betainc, symbols, conjugate + >>> a, b, x, x1, x2 = symbols('a b x x1 x2') + + The Generalized Incomplete Beta function is given by: + + >>> betainc(a, b, x1, x2) + betainc(a, b, x1, x2) + + The Incomplete Beta function can be obtained as follows: + + >>> betainc(a, b, 0, x) + betainc(a, b, 0, x) + + The Incomplete Beta function obeys the mirror symmetry: + + >>> conjugate(betainc(a, b, x1, x2)) + betainc(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) + + We can numerically evaluate the Incomplete Beta function to + arbitrary precision for any complex numbers a, b, x1 and x2: + + >>> from sympy import betainc, I + >>> betainc(2, 3, 4, 5).evalf(10) + 56.08333333 + >>> betainc(0.75, 1 - 4*I, 0, 2 + 3*I).evalf(25) + 0.2241657956955709603655887 + 0.3619619242700451992411724*I + + The Generalized Incomplete Beta function can be expressed + in terms of the Generalized Hypergeometric function. + + >>> from sympy import hyper + >>> betainc(a, b, x1, x2).rewrite(hyper) + (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/a + + See Also + ======== + + beta: Beta function + hyper: Generalized Hypergeometric function + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function + .. [2] https://dlmf.nist.gov/8.17 + .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ + .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ + + """ + nargs = 4 + unbranched = True + + def fdiff(self, argindex): + a, b, x1, x2 = self.args + if argindex == 3: + # Diff wrt x1 + return -(1 - x1)**(b - 1)*x1**(a - 1) + elif argindex == 4: + # Diff wrt x2 + return (1 - x2)**(b - 1)*x2**(a - 1) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_mpmath(self): + return betainc_mpmath_fix, self.args + + def _eval_is_real(self): + if all(arg.is_real for arg in self.args): + return True + + def _eval_conjugate(self): + return self.func(*map(conjugate, self.args)) + + def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy(uniquely_named_symbol('t', [a, b, x1, x2]).name) + return Integral(t**(a - 1)*(1 - t)**(b - 1), (t, x1, x2)) + + def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): + from sympy.functions.special.hyper import hyper + return (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a + +############################################################################### +#################### REGULARIZED INCOMPLETE BETA FUNCTION ##################### +############################################################################### + +class betainc_regularized(DefinedFunction): + r""" + The Generalized Regularized Incomplete Beta function is given by + + .. math:: + \mathrm{I}_{(x_1, x_2)}(a, b) = \frac{\mathrm{B}_{(x_1, x_2)}(a, b)}{\mathrm{B}(a, b)} + + The Regularized Incomplete Beta function is a special case + of the Generalized Regularized Incomplete Beta function : + + .. math:: \mathrm{I}_z (a, b) = \mathrm{I}_{(0, z)}(a, b) + + The Regularized Incomplete Beta function is the cumulative distribution + function of the beta distribution. + + Examples + ======== + + >>> from sympy import betainc_regularized, symbols, conjugate + >>> a, b, x, x1, x2 = symbols('a b x x1 x2') + + The Generalized Regularized Incomplete Beta + function is given by: + + >>> betainc_regularized(a, b, x1, x2) + betainc_regularized(a, b, x1, x2) + + The Regularized Incomplete Beta function + can be obtained as follows: + + >>> betainc_regularized(a, b, 0, x) + betainc_regularized(a, b, 0, x) + + The Regularized Incomplete Beta function + obeys the mirror symmetry: + + >>> conjugate(betainc_regularized(a, b, x1, x2)) + betainc_regularized(conjugate(a), conjugate(b), conjugate(x1), conjugate(x2)) + + We can numerically evaluate the Regularized Incomplete Beta function + to arbitrary precision for any complex numbers a, b, x1 and x2: + + >>> from sympy import betainc_regularized, pi, E + >>> betainc_regularized(1, 2, 0, 0.25).evalf(10) + 0.4375000000 + >>> betainc_regularized(pi, E, 0, 1).evalf(5) + 1.00000 + + The Generalized Regularized Incomplete Beta function can be + expressed in terms of the Generalized Hypergeometric function. + + >>> from sympy import hyper + >>> betainc_regularized(a, b, x1, x2).rewrite(hyper) + (-x1**a*hyper((a, 1 - b), (a + 1,), x1) + x2**a*hyper((a, 1 - b), (a + 1,), x2))/(a*beta(a, b)) + + See Also + ======== + + beta: Beta function + hyper: Generalized Hypergeometric function + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function + .. [2] https://dlmf.nist.gov/8.17 + .. [3] https://functions.wolfram.com/GammaBetaErf/Beta4/ + .. [4] https://functions.wolfram.com/GammaBetaErf/BetaRegularized4/02/ + + """ + nargs = 4 + unbranched = True + + def __new__(cls, a, b, x1, x2): + return super().__new__(cls, a, b, x1, x2) + + def _eval_mpmath(self): + return betainc_mpmath_fix, (*self.args, S(1)) + + def fdiff(self, argindex): + a, b, x1, x2 = self.args + if argindex == 3: + # Diff wrt x1 + return -(1 - x1)**(b - 1)*x1**(a - 1) / beta(a, b) + elif argindex == 4: + # Diff wrt x2 + return (1 - x2)**(b - 1)*x2**(a - 1) / beta(a, b) + else: + raise ArgumentIndexError(self, argindex) + + def _eval_is_real(self): + if all(arg.is_real for arg in self.args): + return True + + def _eval_conjugate(self): + return self.func(*map(conjugate, self.args)) + + def _eval_rewrite_as_Integral(self, a, b, x1, x2, **kwargs): + from sympy.integrals.integrals import Integral + t = Dummy(uniquely_named_symbol('t', [a, b, x1, x2]).name) + integrand = t**(a - 1)*(1 - t)**(b - 1) + expr = Integral(integrand, (t, x1, x2)) + return expr / Integral(integrand, (t, 0, 1)) + + def _eval_rewrite_as_hyper(self, a, b, x1, x2, **kwargs): + from sympy.functions.special.hyper import hyper + expr = (x2**a * hyper((a, 1 - b), (a + 1,), x2) - x1**a * hyper((a, 1 - b), (a + 1,), x1)) / a + return expr / beta(a, b) diff --git a/shared/package-files/75/75f1a058bd727c1f983f05338650d0b5f4ee3738827aaea6f4fbd1f97f8a9614/zarr3.py b/shared/package-files/75/75f1a058bd727c1f983f05338650d0b5f4ee3738827aaea6f4fbd1f97f8a9614/zarr3.py new file mode 100644 index 0000000000000000000000000000000000000000..f1743ffbc24355c86e5fd849aa46f95c9fc0315e --- /dev/null +++ b/shared/package-files/75/75f1a058bd727c1f983f05338650d0b5f4ee3738827aaea6f4fbd1f97f8a9614/zarr3.py @@ -0,0 +1,401 @@ +""" +This module provides the compatibility for :py:mod:`numcodecs` in Zarr version 3. + +A compatibility module is required because the codec handling in Zarr version 3 is different from Zarr version 2. + +You can use codecs from :py:mod:`numcodecs` by constructing codecs from :py:mod:`numcodecs.zarr3` using the same parameters as the original codecs. + +>>> import zarr +>>> import numcodecs.zarr3 +>>> +>>> array = zarr.create_array( +... store="data.zarr", +... shape=(1024, 1024), +... chunks=(64, 64), +... dtype="uint32", +... filters=[numcodecs.zarr3.Delta()], +... compressors=[numcodecs.zarr3.BZ2(level=5)]) +>>> array[:] = np.arange(*array.shape).astype(array.dtype) + +.. note:: + + Please note that the codecs in :py:mod:`numcodecs.zarr3` are not part of the Zarr version 3 specification. + Using these codecs might cause interoperability issues with other Zarr implementations. +""" + +from __future__ import annotations + +import asyncio +import math +from dataclasses import dataclass, replace +from functools import cached_property, partial +from typing import Any, Self, TypeVar +from warnings import warn + +import numpy as np + +import numcodecs + +try: + import zarr + + if zarr.__version__ < "3.0.0": # pragma: no cover + raise ImportError("zarr 3.0.0 or later is required to use the numcodecs zarr integration.") +except ImportError as e: # pragma: no cover + raise ImportError( + "zarr 3.0.0 or later is required to use the numcodecs zarr integration." + ) from e + +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec +from zarr.abc.metadata import Metadata +from zarr.core.array_spec import ArraySpec +from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer +from zarr.core.buffer.cpu import as_numpy_array_wrapper +from zarr.core.common import JSON, parse_named_configuration, product + +CODEC_PREFIX = "numcodecs." + + +def _expect_name_prefix(codec_name: str) -> str: + if not codec_name.startswith(CODEC_PREFIX): + raise ValueError( + f"Expected name to start with '{CODEC_PREFIX}'. Got {codec_name} instead." + ) # pragma: no cover + return codec_name.removeprefix(CODEC_PREFIX) + + +def _parse_codec_configuration(data: dict[str, JSON]) -> dict[str, JSON]: + parsed_name, parsed_configuration = parse_named_configuration(data) + if not parsed_name.startswith(CODEC_PREFIX): + raise ValueError( + f"Expected name to start with '{CODEC_PREFIX}'. Got {parsed_name} instead." + ) # pragma: no cover + id = _expect_name_prefix(parsed_name) + return {"id": id, **parsed_configuration} + + +@dataclass(frozen=True) +class _NumcodecsCodec(Metadata): + codec_name: str + codec_config: dict[str, JSON] + + def __init__(self, **codec_config: JSON) -> None: + if not self.codec_name: + raise ValueError( + "The codec name needs to be supplied through the `codec_name` attribute." + ) # pragma: no cover + unprefixed_codec_name = _expect_name_prefix(self.codec_name) + + if "id" not in codec_config: + codec_config = {"id": unprefixed_codec_name, **codec_config} + elif codec_config["id"] != unprefixed_codec_name: + raise ValueError( + f"Codec id does not match {unprefixed_codec_name}. Got: {codec_config['id']}." + ) # pragma: no cover + + object.__setattr__(self, "codec_config", codec_config) + warn( + "Numcodecs codecs are not in the Zarr version 3 specification and " + "may not be supported by other zarr implementations.", + category=UserWarning, + stacklevel=2, + ) + + @cached_property + def _codec(self) -> numcodecs.abc.Codec: + return numcodecs.get_codec(self.codec_config) + + @classmethod + def from_dict(cls, data: dict[str, JSON]) -> Self: + codec_config = _parse_codec_configuration(data) + return cls(**codec_config) + + def to_dict(self) -> dict[str, JSON]: + codec_config = self.codec_config.copy() + codec_config.pop("id", None) + return { + "name": self.codec_name, + "configuration": codec_config, + } + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + raise NotImplementedError # pragma: no cover + + # Override __repr__ because dynamically constructed classes don't seem to work otherwise + def __repr__(self) -> str: + codec_config = self.codec_config.copy() + codec_config.pop("id", None) + return f"{self.__class__.__name__}(codec_name={self.codec_name!r}, codec_config={codec_config!r})" + + +class _NumcodecsBytesBytesCodec(_NumcodecsCodec, BytesBytesCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread( + as_numpy_array_wrapper, + self._codec.decode, + chunk_bytes, + chunk_spec.prototype, + ) + + def _encode(self, chunk_bytes: Buffer, prototype: BufferPrototype) -> Buffer: + encoded = self._codec.encode(chunk_bytes.as_array_like()) + if isinstance(encoded, np.ndarray): # Required for checksum codecs + return prototype.buffer.from_bytes(encoded.tobytes()) + return prototype.buffer.from_bytes(encoded) + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return await asyncio.to_thread(self._encode, chunk_bytes, chunk_spec.prototype) + + +class _NumcodecsArrayArrayCodec(_NumcodecsCodec, ArrayArrayCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + chunk_ndarray = chunk_array.as_ndarray_like() + out = await asyncio.to_thread(self._codec.decode, chunk_ndarray) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + chunk_ndarray = chunk_array.as_ndarray_like() + out = await asyncio.to_thread(self._codec.encode, chunk_ndarray) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out) + + +class _NumcodecsArrayBytesCodec(_NumcodecsCodec, ArrayBytesCodec): + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + async def _decode_single(self, chunk_buffer: Buffer, chunk_spec: ArraySpec) -> NDBuffer: + chunk_bytes = chunk_buffer.to_bytes() + out = await asyncio.to_thread(self._codec.decode, chunk_bytes) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(out.reshape(chunk_spec.shape)) + + async def _encode_single(self, chunk_ndbuffer: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + chunk_ndarray = chunk_ndbuffer.as_ndarray_like() + out = await asyncio.to_thread(self._codec.encode, chunk_ndarray) + return chunk_spec.prototype.buffer.from_bytes(out) + + +T = TypeVar("T", bound=_NumcodecsCodec) + + +def _add_docstring(cls: type[T], ref_class_name: str) -> type[T]: + cls.__doc__ = f""" + See :class:`{ref_class_name}` for more details and parameters. + """ + return cls + + +def _add_docstring_wrapper(ref_class_name: str) -> partial: + return partial(_add_docstring, ref_class_name=ref_class_name) + + +def _make_bytes_bytes_codec(codec_name: str, cls_name: str) -> type[_NumcodecsBytesBytesCodec]: + # rename for class scope + _codec_name = CODEC_PREFIX + codec_name + + class _Codec(_NumcodecsBytesBytesCodec): + codec_name = _codec_name + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + _Codec.__name__ = cls_name + return _Codec + + +def _make_array_array_codec(codec_name: str, cls_name: str) -> type[_NumcodecsArrayArrayCodec]: + # rename for class scope + _codec_name = CODEC_PREFIX + codec_name + + class _Codec(_NumcodecsArrayArrayCodec): + codec_name = _codec_name + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + _Codec.__name__ = cls_name + return _Codec + + +def _make_array_bytes_codec(codec_name: str, cls_name: str) -> type[_NumcodecsArrayBytesCodec]: + # rename for class scope + _codec_name = CODEC_PREFIX + codec_name + + class _Codec(_NumcodecsArrayBytesCodec): + codec_name = _codec_name + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + _Codec.__name__ = cls_name + return _Codec + + +def _make_checksum_codec(codec_name: str, cls_name: str) -> type[_NumcodecsBytesBytesCodec]: + # rename for class scope + _codec_name = CODEC_PREFIX + codec_name + + class _ChecksumCodec(_NumcodecsBytesBytesCodec): + codec_name = _codec_name + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def compute_encoded_size(self, input_byte_length: int, chunk_spec: ArraySpec) -> int: + return input_byte_length + 4 # pragma: no cover + + _ChecksumCodec.__name__ = cls_name + return _ChecksumCodec + + +# bytes-to-bytes codecs +Blosc = _add_docstring(_make_bytes_bytes_codec("blosc", "Blosc"), "numcodecs.blosc.Blosc") +LZ4 = _add_docstring(_make_bytes_bytes_codec("lz4", "LZ4"), "numcodecs.lz4.LZ4") +Zstd = _add_docstring(_make_bytes_bytes_codec("zstd", "Zstd"), "numcodecs.zstd.Zstd") +Zlib = _add_docstring(_make_bytes_bytes_codec("zlib", "Zlib"), "numcodecs.zlib.Zlib") +GZip = _add_docstring(_make_bytes_bytes_codec("gzip", "GZip"), "numcodecs.gzip.GZip") +BZ2 = _add_docstring(_make_bytes_bytes_codec("bz2", "BZ2"), "numcodecs.bz2.BZ2") +LZMA = _add_docstring(_make_bytes_bytes_codec("lzma", "LZMA"), "numcodecs.lzma.LZMA") + + +@_add_docstring_wrapper("numcodecs.shuffle.Shuffle") +class Shuffle(_NumcodecsBytesBytesCodec): + codec_name = f"{CODEC_PREFIX}shuffle" + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Shuffle: + if self.codec_config.get("elementsize", None) is None: + return Shuffle(**{**self.codec_config, "elementsize": array_spec.dtype.itemsize}) + return self # pragma: no cover + + +# array-to-array codecs ("filters") +@_add_docstring_wrapper("numcodecs.delta.Delta") +class Delta(_NumcodecsArrayArrayCodec): + codec_name = f"{CODEC_PREFIX}delta" + + def __init__(self, **codec_config: dict[str, JSON]) -> None: + super().__init__(**codec_config) + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + if astype := self.codec_config.get("astype"): + return replace(chunk_spec, dtype=np.dtype(astype)) # type: ignore[arg-type] + return chunk_spec + + +BitRound = _add_docstring( + _make_array_array_codec("bitround", "BitRound"), "numcodecs.bitround.BitRound" +) + + +@_add_docstring_wrapper("numcodecs.fixedscaleoffset.FixedScaleOffset") +class FixedScaleOffset(_NumcodecsArrayArrayCodec): + codec_name = f"{CODEC_PREFIX}fixedscaleoffset" + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + if astype := self.codec_config.get("astype"): + return replace(chunk_spec, dtype=np.dtype(astype)) # type: ignore[arg-type] + return chunk_spec + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> FixedScaleOffset: + if self.codec_config.get("dtype", None) is None: + return FixedScaleOffset(**{**self.codec_config, "dtype": str(array_spec.dtype)}) + return self + + +@_add_docstring_wrapper("numcodecs.quantize.Quantize") +class Quantize(_NumcodecsArrayArrayCodec): + codec_name = f"{CODEC_PREFIX}quantize" + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> Quantize: + if self.codec_config.get("dtype", None) is None: + return Quantize(**{**self.codec_config, "dtype": str(array_spec.dtype)}) + return self + + +@_add_docstring_wrapper("numcodecs.packbits.PackBits") +class PackBits(_NumcodecsArrayArrayCodec): + codec_name = f"{CODEC_PREFIX}packbits" + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace( + chunk_spec, + shape=(1 + math.ceil(product(chunk_spec.shape) / 8),), + dtype=np.dtype("uint8"), + ) + + def validate(self, *, dtype: np.dtype[Any], **_kwargs) -> None: + if dtype != np.dtype("bool"): + raise ValueError(f"Packbits filter requires bool dtype. Got {dtype}.") + + +@_add_docstring_wrapper("numcodecs.astype.AsType") +class AsType(_NumcodecsArrayArrayCodec): + codec_name = f"{CODEC_PREFIX}astype" + + def __init__(self, **codec_config: JSON) -> None: + super().__init__(**codec_config) + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace(chunk_spec, dtype=np.dtype(self.codec_config["encode_dtype"])) # type: ignore[arg-type] + + def evolve_from_array_spec(self, array_spec: ArraySpec) -> AsType: + if self.codec_config.get("decode_dtype", None) is None: + return AsType(**{**self.codec_config, "decode_dtype": str(array_spec.dtype)}) + return self + + +# bytes-to-bytes checksum codecs +CRC32 = _add_docstring(_make_checksum_codec("crc32", "CRC32"), "numcodecs.checksum32.CRC32") +CRC32C = _add_docstring(_make_checksum_codec("crc32c", "CRC32C"), "numcodecs.checksum32.CRC32C") +Adler32 = _add_docstring(_make_checksum_codec("adler32", "Adler32"), "numcodecs.checksum32.Adler32") +Fletcher32 = _add_docstring( + _make_checksum_codec("fletcher32", "Fletcher32"), "numcodecs.fletcher32.Fletcher32" +) +JenkinsLookup3 = _add_docstring( + _make_checksum_codec("jenkins_lookup3", "JenkinsLookup3"), "numcodecs.checksum32.JenkinsLookup3" +) + +# array-to-bytes codecs +PCodec = _add_docstring(_make_array_bytes_codec("pcodec", "PCodec"), "numcodecs.pcodec.PCodec") +ZFPY = _add_docstring(_make_array_bytes_codec("zfpy", "ZFPY"), "numcodecs.zfpy.ZFPY") + +__all__ = [ + "BZ2", + "CRC32", + "CRC32C", + "LZ4", + "LZMA", + "ZFPY", + "Adler32", + "AsType", + "BitRound", + "Blosc", + "Delta", + "FixedScaleOffset", + "Fletcher32", + "GZip", + "JenkinsLookup3", + "PCodec", + "PackBits", + "Quantize", + "Shuffle", + "Zlib", + "Zstd", +] diff --git a/shared/package-files/75/75f7a8bf6caf1c8798ee1ecdaa2ad262ca0995e420af1b9ce967def3c67867cf/popen_spawn_posix.cpython-311.pyc b/shared/package-files/75/75f7a8bf6caf1c8798ee1ecdaa2ad262ca0995e420af1b9ce967def3c67867cf/popen_spawn_posix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff1df3df318ba2816ad1dfe5d6a70a2211d1f8d Binary files /dev/null and b/shared/package-files/75/75f7a8bf6caf1c8798ee1ecdaa2ad262ca0995e420af1b9ce967def3c67867cf/popen_spawn_posix.cpython-311.pyc differ diff --git a/shared/package-files/75/75fbaced2e2db4c4599039a4a6959aa7d3923050a0d7277a35d6194f0a0ec284/_ctc_loss_ops.h b/shared/package-files/75/75fbaced2e2db4c4599039a4a6959aa7d3923050a0d7277a35d6194f0a0ec284/_ctc_loss_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8dc434fe35e6dd6a2c1deba54bf7003dcdb99479 --- /dev/null +++ b/shared/package-files/75/75fbaced2e2db4c4599039a4a6959aa7d3923050a0d7277a35d6194f0a0ec284/_ctc_loss_ops.h @@ -0,0 +1,62 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _ctc_loss { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_ctc_loss"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool zero_infinity); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool zero_infinity); +}; + +struct TORCH_API _ctc_loss_Tensor { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_ctc_loss"; + static constexpr const char* overload_name = "Tensor"; + static constexpr const char* schema_str = "_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, int64_t blank, bool zero_infinity); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, int64_t blank, bool zero_infinity); +}; + +struct TORCH_API _ctc_loss_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, int64_t, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_ctc_loss"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_ctc_loss.out(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))"; + static ::std::tuple call(const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool zero_infinity, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank, bool zero_infinity, at::Tensor & out0, at::Tensor & out1); +}; + +struct TORCH_API _ctc_loss_Tensor_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, bool, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_ctc_loss"; + static constexpr const char* overload_name = "Tensor_out"; + static constexpr const char* schema_str = "_ctc_loss.Tensor_out(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))"; + static ::std::tuple call(const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, int64_t blank, bool zero_infinity, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, int64_t blank, bool zero_infinity, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7c014eb161d9c2a7e7ea17b1836ec96372f36715d2df924674a1e8db5fb0f6e2/METADATA b/shared/package-files/7c/7c014eb161d9c2a7e7ea17b1836ec96372f36715d2df924674a1e8db5fb0f6e2/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5e4b68868ddc136e1e9093b03bfe06c10f1e50e4 --- /dev/null +++ b/shared/package-files/7c/7c014eb161d9c2a7e7ea17b1836ec96372f36715d2df924674a1e8db5fb0f6e2/METADATA @@ -0,0 +1,36 @@ +Metadata-Version: 2.1 +Name: nvidia-cusparse-cu12 +Version: 12.5.4.2 +Summary: CUSPARSE native runtime libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: compute_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt +Requires-Dist: nvidia-nvjitlink-cu12 + +CUSPARSE native runtime libraries diff --git a/shared/package-files/7c/7c0353b29c1c12593f227f5b895f0cb4a57c2efd7ffcbd93976b463a8e696912/common_state_dict.py b/shared/package-files/7c/7c0353b29c1c12593f227f5b895f0cb4a57c2efd7ffcbd93976b463a8e696912/common_state_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..148a1749c433e74ad0439a54b50fcd9ac26f31e3 --- /dev/null +++ b/shared/package-files/7c/7c0353b29c1c12593f227f5b895f0cb4a57c2efd7ffcbd93976b463a8e696912/common_state_dict.py @@ -0,0 +1,170 @@ +# mypy: allow-untyped-defs + +# Owner(s): ["oncall: distributed"] + +import copy +from itertools import chain +from typing import Any + +import torch +import torch.nn as nn +from torch.distributed._sharded_tensor import ShardedTensor +from torch.distributed._state_dict_utils import _gather_state_dict +from torch.distributed._tensor import DTensor +from torch.distributed.checkpoint.state_dict import ( + _PG, + _STATE, + set_state_dict, + StateDictOptions, +) + + +class VerifyStateDictMixin: + def _compare_tensor(self, orig_tensor, dist_tensor, offload_to_cpu=False): + if isinstance(dist_tensor, (DTensor, ShardedTensor)): + dist_tensor = _gather_state_dict({"mykey": dist_tensor}).pop("mykey") + + if offload_to_cpu: + orig_tensor = orig_tensor.cpu() + dist_tensor = dist_tensor.cpu() + self.assertTrue(isinstance(dist_tensor, torch.Tensor)) + self.assertTrue(torch.allclose(orig_tensor, dist_tensor)) + + def _verify_msd( + self, + msd: dict[str, Any], + dist_msd: dict[str, Any], + options: StateDictOptions = StateDictOptions(), + offload_to_cpu=False, + ) -> None: + if not options.ignore_frozen_params: + self.assertEqual(len(msd), len(dist_msd)) + for fqn, param in msd.items(): + dist_param = dist_msd.get(fqn, None) + if not options.ignore_frozen_params: + self.assertIsNotNone(dist_param, f"{fqn=}") + try: + self._compare_tensor(param, dist_param, offload_to_cpu) + except AssertionError as e: + raise AssertionError( + f"{fqn} has mismatched value {param} {dist_param}" + ) from e + elif dist_param is None: + self.assertFalse(param.requires_grad, f"{fqn=}") + + def _verify_osd( + self, + model: nn.Module, + optim: torch.optim.Optimizer, + osd: dict[str, Any], + dist_osd: dict[str, Any], + ) -> None: + params = list(chain.from_iterable(g["params"] for g in optim.param_groups)) + param_pid_mapping = dict(zip(params, range(len(params)))) + fqn_pid_mapping = {} + for fqn, param in model.named_parameters(): + pid = param_pid_mapping[param] + fqn_pid_mapping[fqn] = pid + fqn_pid_mapping[pid] = fqn + # Check optimizer_state_dict state + + self.assertEqual(len(osd[_STATE]), len(dist_osd[_STATE])) + for pid, states in osd[_STATE].items(): + fqn = fqn_pid_mapping[pid] + dist_states = dist_osd[_STATE].get(fqn, None) + self.assertIsNotNone(dist_states, fqn) + self.assertEqual(len(states), len(dist_states)) + for key, state in states.items(): + dist_state = states.get(key, None) + self.assertIsNotNone(dist_state) + self._compare_tensor(state, dist_state) + + # Check optimizer_state_dict param_group + old_dist_osd_pg = dist_osd[_PG] + if len(osd[_PG]) != len(dist_osd[_PG]): + self.assertTrue(len(dist_osd[_PG]) > len(osd[_PG])) + new_pg = copy.deepcopy(dist_osd[_PG][0]) + new_pg["params"] = [] + for dist_group in dist_osd[_PG]: + new_pg["params"].extend(dist_group["params"]) + dist_osd[_PG] = [new_pg] + + self.assertEqual(len(osd[_PG]), len(dist_osd[_PG])) + for group, dist_group in zip(osd[_PG], dist_osd[_PG]): + self.assertEqual(len(group), len(dist_group)) + for key, value in group.items(): + # Below doesn't work because param_groups can have None + # values. + # dist_value = dist_group.get(key, None) + # self.assertIsNotNone(dist_value, (dist_group, group)) + dist_value = dist_group[key] + if key == "params": + fqns = [fqn_pid_mapping[pid] for pid in value] + self.assertEqual(sorted(fqns), sorted(dist_value)) + else: + self.assertEqual(value, dist_value) + dist_osd[_PG] = old_dist_osd_pg + + def _verify_osd_by_load( + self, + model: nn.Module, + optim: torch.optim.Optimizer, + new_optim: torch.optim.Optimizer, + dist_osd: dict[str, Any], + ) -> None: + new_dist_osd = _gather_state_dict(dist_osd) + set_state_dict( + model, + optimizers=new_optim, + model_state_dict={}, + optim_state_dict=new_dist_osd, + ) + self.assertEqual(optim.state_dict(), new_optim.state_dict()) + + +class FusionEmbedding(nn.Module): + def __init__(self, vocab_size: int, fusion_vocab_size: int, embed_dim: int) -> None: + super().__init__() + self.embedding = nn.Embedding(vocab_size, embed_dim) + self.fusion_embedding = nn.Embedding(fusion_vocab_size, embed_dim) + + +class FusionEmbeddingWithHook(nn.Module): + def __init__(self, vocab_size: int, fusion_vocab_size: int, embed_dim: int) -> None: + super().__init__() + self.embedding = nn.Embedding(vocab_size, embed_dim) + self.fusion_embedding = nn.Embedding(fusion_vocab_size, embed_dim) + self._register_state_dict_hook(FusionEmbeddingWithHook._state_dict_hook) + self._register_load_state_dict_pre_hook( + FusionEmbeddingWithHook._load_state_dict_hook, with_module=True + ) + + def _state_dict_hook(self, destination, prefix, keep_vars): + """Remove "embedding" from the original embedding in the state_dict + name. This keeps the orginal state dict name for the embedding + from before fusing with the FusionEmbedding. + """ + key = prefix + "embedding.weight" + new_key = prefix + "weight" + destination[new_key] = destination[key] + del destination[key] + + def _load_state_dict_hook(self, state_dict, prefix, *args, **kwargs): + """Apply extra "embedding" prefix to the state_dict key to + account for the FusionEmbedding wrapping. + """ + if state_dict: + key = prefix + "weight" + new_key = prefix + "embedding.weight" + state_dict[new_key] = state_dict[key] + del state_dict[key] + + +class FusionEmbeddingWithModifier(FusionEmbeddingWithHook): + # _fqn_modifiers is a private function as a contract between DSD. When users change the state_dict + # keys, they need to provide a mapping from the new key to the original key. This is used to ensure + # consistency between the state_dict keys and fqn. + def _fqn_modifiers(self) -> dict[str, str]: + return { + "weight": "embedding", + } diff --git a/shared/package-files/7c/7c079db28431694de12000290160ce2ac6bd92072e430e2d7727fc9252e6fb79/generated_cudaVDPAU_meta.h b/shared/package-files/7c/7c079db28431694de12000290160ce2ac6bd92072e430e2d7727fc9252e6fb79/generated_cudaVDPAU_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..abc603c8d9be21e012a9b1641330c2e203d623b2 --- /dev/null +++ b/shared/package-files/7c/7c079db28431694de12000290160ce2ac6bd92072e430e2d7727fc9252e6fb79/generated_cudaVDPAU_meta.h @@ -0,0 +1,46 @@ +// This file is generated. Any changes you make will be lost during the next clean build. + +// Dependent includes +#include + +// CUDA public interface, for type definitions and cu* function prototypes +#include "cudaVDPAU.h" + + +// ************************************************************************* +// Definitions of structs to hold parameters for each function +// ************************************************************************* + +typedef struct cuVDPAUGetDevice_params_st { + CUdevice *pDevice; + VdpDevice vdpDevice; + VdpGetProcAddress *vdpGetProcAddress; +} cuVDPAUGetDevice_params; + +typedef struct cuVDPAUCtxCreate_v2_params_st { + CUcontext *pCtx; + unsigned int flags; + CUdevice device; + VdpDevice vdpDevice; + VdpGetProcAddress *vdpGetProcAddress; +} cuVDPAUCtxCreate_v2_params; + +typedef struct cuGraphicsVDPAURegisterVideoSurface_params_st { + CUgraphicsResource *pCudaResource; + VdpVideoSurface vdpSurface; + unsigned int flags; +} cuGraphicsVDPAURegisterVideoSurface_params; + +typedef struct cuGraphicsVDPAURegisterOutputSurface_params_st { + CUgraphicsResource *pCudaResource; + VdpOutputSurface vdpSurface; + unsigned int flags; +} cuGraphicsVDPAURegisterOutputSurface_params; + +typedef struct cuVDPAUCtxCreate_params_st { + CUcontext *pCtx; + unsigned int flags; + CUdevice device; + VdpDevice vdpDevice; + VdpGetProcAddress *vdpGetProcAddress; +} cuVDPAUCtxCreate_params; diff --git a/shared/package-files/7c/7c14ddf49cc3913a8d433ec6050092f654a15353f7956450ecbf84e568527650/test_planar_drawing.py b/shared/package-files/7c/7c14ddf49cc3913a8d433ec6050092f654a15353f7956450ecbf84e568527650/test_planar_drawing.py new file mode 100644 index 0000000000000000000000000000000000000000..b59d5c17331d6aac71e688b3dfde46991ea2ef97 --- /dev/null +++ b/shared/package-files/7c/7c14ddf49cc3913a8d433ec6050092f654a15353f7956450ecbf84e568527650/test_planar_drawing.py @@ -0,0 +1,274 @@ +import math + +import pytest + +import networkx as nx +from networkx.algorithms.planar_drawing import triangulate_embedding + + +def test_graph1(): + embedding_data = {0: [1, 2, 3], 1: [2, 0], 2: [3, 0, 1], 3: [2, 0]} + check_embedding_data(embedding_data) + + +def test_graph2(): + embedding_data = { + 0: [8, 6], + 1: [2, 6, 9], + 2: [8, 1, 7, 9, 6, 4], + 3: [9], + 4: [2], + 5: [6, 8], + 6: [9, 1, 0, 5, 2], + 7: [9, 2], + 8: [0, 2, 5], + 9: [1, 6, 2, 7, 3], + } + check_embedding_data(embedding_data) + + +def test_circle_graph(): + embedding_data = { + 0: [1, 9], + 1: [0, 2], + 2: [1, 3], + 3: [2, 4], + 4: [3, 5], + 5: [4, 6], + 6: [5, 7], + 7: [6, 8], + 8: [7, 9], + 9: [8, 0], + } + check_embedding_data(embedding_data) + + +def test_grid_graph(): + embedding_data = { + (0, 1): [(0, 0), (1, 1), (0, 2)], + (1, 2): [(1, 1), (2, 2), (0, 2)], + (0, 0): [(0, 1), (1, 0)], + (2, 1): [(2, 0), (2, 2), (1, 1)], + (1, 1): [(2, 1), (1, 2), (0, 1), (1, 0)], + (2, 0): [(1, 0), (2, 1)], + (2, 2): [(1, 2), (2, 1)], + (1, 0): [(0, 0), (2, 0), (1, 1)], + (0, 2): [(1, 2), (0, 1)], + } + check_embedding_data(embedding_data) + + +def test_one_node_graph(): + embedding_data = {0: []} + check_embedding_data(embedding_data) + + +def test_two_node_graph(): + embedding_data = {0: [1], 1: [0]} + check_embedding_data(embedding_data) + + +def test_three_node_graph(): + embedding_data = {0: [1, 2], 1: [0, 2], 2: [0, 1]} + check_embedding_data(embedding_data) + + +def test_multiple_component_graph1(): + embedding_data = {0: [], 1: []} + check_embedding_data(embedding_data) + + +def test_multiple_component_graph2(): + embedding_data = {0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4, 5], 4: [3, 5], 5: [3, 4]} + check_embedding_data(embedding_data) + + +def test_invalid_half_edge(): + with pytest.raises(nx.NetworkXException): + embedding_data = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3]} + embedding = nx.PlanarEmbedding() + embedding.set_data(embedding_data) + nx.combinatorial_embedding_to_pos(embedding) + + +def test_triangulate_embedding1(): + embedding = nx.PlanarEmbedding() + embedding.add_node(1) + expected_embedding = {1: []} + check_triangulation(embedding, expected_embedding) + + +def test_triangulate_embedding2(): + embedding = nx.PlanarEmbedding() + embedding.connect_components(1, 2) + expected_embedding = {1: [2], 2: [1]} + check_triangulation(embedding, expected_embedding) + + +def check_triangulation(embedding, expected_embedding): + res_embedding, _ = triangulate_embedding(embedding, True) + assert res_embedding.get_data() == expected_embedding, ( + "Expected embedding incorrect" + ) + res_embedding, _ = triangulate_embedding(embedding, False) + assert res_embedding.get_data() == expected_embedding, ( + "Expected embedding incorrect" + ) + + +def check_embedding_data(embedding_data): + """Checks that the planar embedding of the input is correct""" + embedding = nx.PlanarEmbedding() + embedding.set_data(embedding_data) + pos_fully = nx.combinatorial_embedding_to_pos(embedding, False) + msg = "Planar drawing does not conform to the embedding (fully triangulation)" + assert planar_drawing_conforms_to_embedding(embedding, pos_fully), msg + check_edge_intersections(embedding, pos_fully) + pos_internally = nx.combinatorial_embedding_to_pos(embedding, True) + msg = "Planar drawing does not conform to the embedding (internal triangulation)" + assert planar_drawing_conforms_to_embedding(embedding, pos_internally), msg + check_edge_intersections(embedding, pos_internally) + + +def is_close(a, b, rel_tol=1e-09, abs_tol=0.0): + # Check if float numbers are basically equal, for python >=3.5 there is + # function for that in the standard library + return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) + + +def point_in_between(a, b, p): + # checks if p is on the line between a and b + x1, y1 = a + x2, y2 = b + px, py = p + dist_1_2 = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) + dist_1_p = math.sqrt((x1 - px) ** 2 + (y1 - py) ** 2) + dist_2_p = math.sqrt((x2 - px) ** 2 + (y2 - py) ** 2) + return is_close(dist_1_p + dist_2_p, dist_1_2) + + +def check_edge_intersections(G, pos): + """Check all edges in G for intersections. + + Raises an exception if an intersection is found. + + Parameters + ---------- + G : NetworkX graph + pos : dict + Maps every node to a tuple (x, y) representing its position + + """ + for a, b in G.edges(): + for c, d in G.edges(): + # Check if end points are different + if a != c and b != d and b != c and a != d: + x1, y1 = pos[a] + x2, y2 = pos[b] + x3, y3 = pos[c] + x4, y4 = pos[d] + determinant = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) + if determinant != 0: # the lines are not parallel + # calculate intersection point, see: + # https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection + px = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * ( + x3 * y4 - y3 * x4 + ) / determinant + py = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * ( + x3 * y4 - y3 * x4 + ) / determinant + + # Check if intersection lies between the points + if point_in_between(pos[a], pos[b], (px, py)) and point_in_between( + pos[c], pos[d], (px, py) + ): + msg = f"There is an intersection at {px},{py}" + raise nx.NetworkXException(msg) + + # Check overlap + msg = "A node lies on a edge connecting two other nodes" + if ( + point_in_between(pos[a], pos[b], pos[c]) + or point_in_between(pos[a], pos[b], pos[d]) + or point_in_between(pos[c], pos[d], pos[a]) + or point_in_between(pos[c], pos[d], pos[b]) + ): + raise nx.NetworkXException(msg) + # No edge intersection found + + +class Vector: + """Compare vectors by their angle without loss of precision + + All vectors in direction [0, 1] are the smallest. + The vectors grow in clockwise direction. + """ + + __slots__ = ["x", "y", "node", "quadrant"] + + def __init__(self, x, y, node): + self.x = x + self.y = y + self.node = node + if self.x >= 0 and self.y > 0: + self.quadrant = 1 + elif self.x > 0 and self.y <= 0: + self.quadrant = 2 + elif self.x <= 0 and self.y < 0: + self.quadrant = 3 + else: + self.quadrant = 4 + + def __eq__(self, other): + return self.quadrant == other.quadrant and self.x * other.y == self.y * other.x + + def __lt__(self, other): + if self.quadrant < other.quadrant: + return True + elif self.quadrant > other.quadrant: + return False + else: + return self.x * other.y < self.y * other.x + + def __ne__(self, other): + return self != other + + def __le__(self, other): + return not other < self + + def __gt__(self, other): + return other < self + + def __ge__(self, other): + return not self < other + + +def planar_drawing_conforms_to_embedding(embedding, pos): + """Checks if pos conforms to the planar embedding + + Returns true iff the neighbors are actually oriented in the orientation + specified of the embedding + """ + for v in embedding: + nbr_vectors = [] + v_pos = pos[v] + for nbr in embedding[v]: + new_vector = Vector(pos[nbr][0] - v_pos[0], pos[nbr][1] - v_pos[1], nbr) + nbr_vectors.append(new_vector) + # Sort neighbors according to their phi angle + nbr_vectors.sort() + for idx, nbr_vector in enumerate(nbr_vectors): + cw_vector = nbr_vectors[(idx + 1) % len(nbr_vectors)] + ccw_vector = nbr_vectors[idx - 1] + if ( + embedding[v][nbr_vector.node]["cw"] != cw_vector.node + or embedding[v][nbr_vector.node]["ccw"] != ccw_vector.node + ): + return False + if cw_vector.node != nbr_vector.node and cw_vector == nbr_vector: + # Lines overlap + return False + if ccw_vector.node != nbr_vector.node and ccw_vector == nbr_vector: + # Lines overlap + return False + return True diff --git a/shared/package-files/7c/7c1874ae4306f9c181df810de828522afb4d6d9bc26887e7e04cf3bf9274de3d/sections.h b/shared/package-files/7c/7c1874ae4306f9c181df810de828522afb4d6d9bc26887e7e04cf3bf9274de3d/sections.h new file mode 100644 index 0000000000000000000000000000000000000000..85abc72305bed478386edccd29db2b196e6b1fc1 --- /dev/null +++ b/shared/package-files/7c/7c1874ae4306f9c181df810de828522afb4d6d9bc26887e7e04cf3bf9274de3d/sections.h @@ -0,0 +1,120 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +static std::string demangle(const std::string& mangled_name) { + int status = 0; + char* realname = + abi::__cxa_demangle(mangled_name.c_str(), nullptr, nullptr, &status); + if (status == 0) { + std::string demangled_name(realname); + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + free(realname); + return demangled_name; + } else { + return mangled_name; + } +} + +struct Sections { + Sections() = default; + void parse(const char* name) { + library_ = std::make_unique(name); + strtab = library_->getSection(".strtab", false); + + symtab = library_->getSection(".symtab", true); + debug_info = library_->getSection(".debug_info", true); + if (debug_info.size > 0) { + debug_abbrev = library_->getSection(".debug_abbrev", false); + debug_str = library_->getSection(".debug_str", false); + debug_line = library_->getSection(".debug_line", false); + // dwarf 5 + debug_line_str = library_->getSection(".debug_line_str", true); + debug_rnglists = library_->getSection(".debug_rnglists", true); + debug_addr = library_->getSection(".debug_addr", true); + // dwarf 4 + debug_ranges = library_->getSection(".debug_ranges", true); + } + parseSymtab(); + } + + Section debug_info; + Section debug_abbrev; + Section debug_str; + Section debug_line; + Section debug_line_str; + Section debug_rnglists; + Section debug_ranges; + Section debug_addr; + Section symtab; + Section strtab; + + const char* readString(CheckedLexer& data, uint64_t encoding, bool is_64bit) { + switch (encoding) { + case DW_FORM_string: { + return data.readCString(); + } + case DW_FORM_strp: { + return debug_str.string(readSegmentOffset(data, is_64bit)); + } + case DW_FORM_line_strp: { + return debug_line_str.string(readSegmentOffset(data, is_64bit)); + } + default: + UNWIND_CHECK(false, "unsupported string encoding {:x}", encoding); + } + } + + uint64_t readSegmentOffset(CheckedLexer& data, bool is_64bit) { + return is_64bit ? data.read() : data.read(); + } + + std::optional findDebugInfoOffset(uint64_t address) { + return debug_info_offsets_.find(address); + } + size_t compilationUnitCount() { + return debug_info_offsets_.size() / 2; + } + void addDebugInfoRange( + uint64_t start, + uint64_t end, + uint64_t debug_info_offset) { + debug_info_offsets_.add(start, debug_info_offset, false); + debug_info_offsets_.add(end, std::nullopt, false); + } + std::optional findSubprogramName(uint64_t address) { + if (auto e = symbol_table_.find(address)) { + return demangle(strtab.string(*e)); + } + return std::nullopt; + } + + private: + void parseSymtab() { + auto L = symtab.lexer(0); + char* end = symtab.data + symtab.size; + while (L.loc() < end) { + auto symbol = L.read(); + if (symbol.st_shndx == SHN_UNDEF || + ELF64_ST_TYPE(symbol.st_info) != STT_FUNC) { + continue; + } + symbol_table_.add(symbol.st_value, symbol.st_name, false); + symbol_table_.add(symbol.st_value + symbol.st_size, std::nullopt, false); + } + } + + std::unique_ptr library_; + RangeTable debug_info_offsets_; + RangeTable symbol_table_; +}; + +} // namespace torch::unwind diff --git a/shared/package-files/7c/7c19febea7bb3e8861309f0ad2a8c72f4272d1cbee013ef8726b810ce83880a7/check_alias_annotation.h b/shared/package-files/7c/7c19febea7bb3e8861309f0ad2a8c72f4272d1cbee013ef8726b810ce83880a7/check_alias_annotation.h new file mode 100644 index 0000000000000000000000000000000000000000..e227c3bb456027f1593dd24ff27d7064d1900b8c --- /dev/null +++ b/shared/package-files/7c/7c19febea7bb3e8861309f0ad2a8c72f4272d1cbee013ef8726b810ce83880a7/check_alias_annotation.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// Verify that alias annotations are correct. See impl for definition of +// "correct". +// +// This function expects a graph with a single op with `unqualifiedOpName`, plus +// the inputs that you would otherwise have passed to the graph executor. +TORCH_API void checkAliasAnnotation( + const std::shared_ptr& graph, + std::vector pythonInputs, + const std::string& unqualifiedOpName); +} // namespace torch::jit diff --git a/shared/package-files/7c/7c1ec80c64a9bd32fe79fffa52d3413a754ac4b74a08ba95c06244b93e5ae062/quantized_rnn_relu_cell_native.h b/shared/package-files/7c/7c1ec80c64a9bd32fe79fffa52d3413a754ac4b74a08ba95c06244b93e5ae062/quantized_rnn_relu_cell_native.h new file mode 100644 index 0000000000000000000000000000000000000000..13b4aecbd7741cb9cd079a1d68ba7c123bced5c2 --- /dev/null +++ b/shared/package-files/7c/7c1ec80c64a9bd32fe79fffa52d3413a754ac4b74a08ba95c06244b93e5ae062/quantized_rnn_relu_cell_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor quantized_rnn_relu_cell(const at::Tensor & input, const at::Tensor & hx, const at::Tensor & w_ih, const at::Tensor & w_hh, const at::Tensor & b_ih, const at::Tensor & b_hh, const at::Tensor & packed_ih, const at::Tensor & packed_hh, const at::Tensor & col_offsets_ih, const at::Tensor & col_offsets_hh, const at::Scalar & scale_ih, const at::Scalar & scale_hh, const at::Scalar & zero_point_ih, const at::Scalar & zero_point_hh); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c20290c82a8e9ff6b6730a22066caa36985c4814c7437e0215c28977a2008e5/__init__.cpython-311.pyc b/shared/package-files/7c/7c20290c82a8e9ff6b6730a22066caa36985c4814c7437e0215c28977a2008e5/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a9a83a2aec24568d74c5335d5b357c047a442ae Binary files /dev/null and b/shared/package-files/7c/7c20290c82a8e9ff6b6730a22066caa36985c4814c7437e0215c28977a2008e5/__init__.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c248b7b5e92b93c7bf99eab23fbbacfc6cf298d45e28c2644c72cb31337723a/test_expand.cpython-311.pyc b/shared/package-files/7c/7c248b7b5e92b93c7bf99eab23fbbacfc6cf298d45e28c2644c72cb31337723a/test_expand.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6311827277962c5a20176d1eb7755aafb39240f9 Binary files /dev/null and b/shared/package-files/7c/7c248b7b5e92b93c7bf99eab23fbbacfc6cf298d45e28c2644c72cb31337723a/test_expand.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c25f5b7f3572ba848effc652f9f35286f2d392e88bbb6f78c6d52dd0135ed27/proxy_value.py b/shared/package-files/7c/7c25f5b7f3572ba848effc652f9f35286f2d392e88bbb6f78c6d52dd0135ed27/proxy_value.py new file mode 100644 index 0000000000000000000000000000000000000000..df62c9d0ffe5631e6823c56e728a30af6bce3c14 --- /dev/null +++ b/shared/package-files/7c/7c25f5b7f3572ba848effc652f9f35286f2d392e88bbb6f78c6d52dd0135ed27/proxy_value.py @@ -0,0 +1,44 @@ +# pyre-strict +from typing import Union, Generic +from collections.abc import Iterator, Iterable +import torch + +from typing import TypeVar + +_T = TypeVar("_T") + +class ProxyValue(Generic[_T]): + # pyre-ignore + def __init__(self, data: Iterable[_T], proxy: Union[torch.fx.Proxy, torch.fx.Node]): + # pyre-ignore + self.data = data + self.proxy_or_node = proxy + + @property + def node(self) -> torch.fx.Node: + if isinstance(self.proxy_or_node, torch.fx.Node): + return self.proxy_or_node + assert isinstance(self.proxy_or_node, torch.fx.Proxy) + return self.proxy_or_node.node + + @property + def proxy(self) -> torch.fx.Proxy: + if not isinstance(self.proxy_or_node, torch.fx.Proxy): + raise RuntimeError( + f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}" + ) + return self.proxy_or_node + + def to_tensor(self) -> torch.Tensor: + assert isinstance(self.data, torch.Tensor) + return self.data + + def is_tensor(self) -> bool: + return isinstance(self.data, torch.Tensor) + + # pyre-ignore + def __iter__(self) -> Iterator[_T]: + yield from self.data + + def __bool__(self) -> bool: + return bool(self.data) diff --git a/shared/package-files/7c/7c2a8fe500d338b12fa94d55a246cce97cc255081d32ed1b911e2dfd387d6da2/test_mrecords.cpython-311.pyc b/shared/package-files/7c/7c2a8fe500d338b12fa94d55a246cce97cc255081d32ed1b911e2dfd387d6da2/test_mrecords.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26234b4dbce1af46b54784840c8910b05902465d Binary files /dev/null and b/shared/package-files/7c/7c2a8fe500d338b12fa94d55a246cce97cc255081d32ed1b911e2dfd387d6da2/test_mrecords.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c2efc8c6c767227f25c5c14b7e1e6ff0237b78879ba8d6587d44ed1c360ed30/constants.py b/shared/package-files/7c/7c2efc8c6c767227f25c5c14b7e1e6ff0237b78879ba8d6587d44ed1c360ed30/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0ad997a9215fdcf7e34fe7d925ab8d6386d63395 --- /dev/null +++ b/shared/package-files/7c/7c2efc8c6c767227f25c5c14b7e1e6ff0237b78879ba8d6587d44ed1c360ed30/constants.py @@ -0,0 +1,38 @@ +# Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0 +# SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0) +# SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io + +import enum + +# After the connection is lost, log warnings after this many write()s. +LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5 + +# Seconds to wait before retrying accept(). +ACCEPT_RETRY_DELAY = 1 + +# Number of stack entries to capture in debug mode. +# The larger the number, the slower the operation in debug mode +# (see extract_stack() in format_helpers.py). +DEBUG_STACK_DEPTH = 10 + +# Number of seconds to wait for SSL handshake to complete +# The default timeout matches that of Nginx. +SSL_HANDSHAKE_TIMEOUT = 60.0 + +# Number of seconds to wait for SSL shutdown to complete +# The default timeout mimics lingering_time +SSL_SHUTDOWN_TIMEOUT = 30.0 + +# Used in sendfile fallback code. We use fallback for platforms +# that don't support sendfile, or for TLS connections. +SENDFILE_FALLBACK_READBUFFER_SIZE = 1024 * 256 + +FLOW_CONTROL_HIGH_WATER_SSL_READ = 256 # KiB +FLOW_CONTROL_HIGH_WATER_SSL_WRITE = 512 # KiB + +# The enum should be here to break circular dependencies between +# base_events and sslproto +class _SendfileMode(enum.Enum): + UNSUPPORTED = enum.auto() + TRY_NATIVE = enum.auto() + FALLBACK = enum.auto() diff --git a/shared/package-files/7c/7c33ea52389051d3a9df278265607c7179f1cd37dde90f43e72052a529ba88f8/new_empty_ops.h b/shared/package-files/7c/7c33ea52389051d3a9df278265607c7179f1cd37dde90f43e72052a529ba88f8/new_empty_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6e124e57badd4eeb7b3809630b41f052cec67e37 --- /dev/null +++ b/shared/package-files/7c/7c33ea52389051d3a9df278265607c7179f1cd37dde90f43e72052a529ba88f8/new_empty_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API new_empty { + using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, ::std::optional, ::std::optional, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::new_empty"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +}; + +struct TORCH_API new_empty_out { + using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::new_empty"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "new_empty.out(Tensor self, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7c34bff25a743f4ca5e6ae1534a36883cdab68243a68ffb4f249f208ee8b7686/_to_sparse_semi_structured.h b/shared/package-files/7c/7c34bff25a743f4ca5e6ae1534a36883cdab68243a68ffb4f249f208ee8b7686/_to_sparse_semi_structured.h new file mode 100644 index 0000000000000000000000000000000000000000..08fb0160a4cfd78fb1226a1f31745a029f0a8bb1 --- /dev/null +++ b/shared/package-files/7c/7c34bff25a743f4ca5e6ae1534a36883cdab68243a68ffb4f249f208ee8b7686/_to_sparse_semi_structured.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_to_sparse_semi_structured(Tensor dense) -> (Tensor, Tensor) +inline ::std::tuple _to_sparse_semi_structured(const at::Tensor & dense) { + return at::_ops::_to_sparse_semi_structured::call(dense); +} + +} diff --git a/shared/package-files/7c/7c353fd1c41db48bc474cd33645298d0e6e83003443201cb6e589f3da94f18b9/host_defines.h b/shared/package-files/7c/7c353fd1c41db48bc474cd33645298d0e6e83003443201cb6e589f3da94f18b9/host_defines.h new file mode 100644 index 0000000000000000000000000000000000000000..b58cb3cc1086bdc6e0376f042c86b2755ef2ff00 --- /dev/null +++ b/shared/package-files/7c/7c353fd1c41db48bc474cd33645298d0e6e83003443201cb6e589f3da94f18b9/host_defines.h @@ -0,0 +1,283 @@ +/* + * Copyright 1993-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/host_defines.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/host_defines.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__ +#endif + +#if !defined(__HOST_DEFINES_H__) +#define __HOST_DEFINES_H__ + +#if defined(__CUDACC__) && !defined(__CUDACC_RTC__) && !defined(__CUDADEVRT_INTERNAL__) && !defined(_ALLOW_UNSUPPORTED_LIBCPP) +#include +#if ((defined(_MSC_VER ) && (defined(_M_X64) || defined(_M_AMD64))) ||\ + (defined(__x86_64__) || defined(__amd64__))) && defined(_LIBCPP_VERSION) && !(defined(__HORIZON__) || defined(__ANDROID__) || defined(__QNX__)) +#error "libc++ is not supported on x86 system" +#endif +#endif + +/* CUDA JIT mode (__CUDACC_RTC__) also uses GNU style attributes */ +#if defined(__GNUC__) || (defined(__PGIC__) && defined(__linux__)) || defined(__CUDA_LIBDEVICE__) || defined(__CUDACC_RTC__) + +#if defined(__CUDACC_RTC__) +#define __volatile__ volatile +#endif /* __CUDACC_RTC__ */ + +#define __no_return__ \ + __attribute__((noreturn)) + +#if defined(__CUDACC__) || defined(__CUDA_ARCH__) || defined(__CUDA_LIBDEVICE__) +/* gcc allows users to define attributes with underscores, + e.g., __attribute__((__noinline__)). + Consider a non-CUDA source file (e.g. .cpp) that has the + above attribute specification, and includes this header file. In that case, + defining __noinline__ as below would cause a gcc compilation error. + Hence, only define __noinline__ when the code is being processed + by a CUDA compiler component. +*/ +#define __noinline__ \ + __attribute__((noinline)) +#endif /* __CUDACC__ || __CUDA_ARCH__ || __CUDA_LIBDEVICE__ */ + +#undef __forceinline__ +#define __forceinline__ \ + __inline__ __attribute__((always_inline)) +#define __inline_hint__ \ + __attribute__((nv_inline_hint)) +#define __align__(n) \ + __attribute__((aligned(n))) +#define __maxnreg__(a) \ + __attribute__((maxnreg(a))) +#define __thread__ \ + __thread +#define __import__ +#define __export__ +#define __cdecl +#define __annotate__(a) \ + __attribute__((a)) +#define __location__(a) \ + __annotate__(a) +#define CUDARTAPI +#define CUDARTAPI_CDECL + +#elif defined(_MSC_VER) + +#if _MSC_VER >= 1400 + +#define __restrict__ \ + __restrict + +#else /* _MSC_VER >= 1400 */ + +#define __restrict__ + +#endif /* _MSC_VER >= 1400 */ + +#define __inline__ \ + __inline +#define __no_return__ \ + __declspec(noreturn) +#define __noinline__ \ + __declspec(noinline) +#define __forceinline__ \ + __forceinline +#define __inline_hint__ \ + __declspec(nv_inline_hint) +#define __align__(n) \ + __declspec(align(n)) +#define __maxnreg__(n) \ + __declspec(maxnreg(n)) +#define __thread__ \ + __declspec(thread) +#define __import__ \ + __declspec(dllimport) +#define __export__ \ + __declspec(dllexport) +#define __annotate__(a) \ + __declspec(a) +#define __location__(a) \ + __annotate__(__##a##__) +#define CUDARTAPI \ + __stdcall +#define CUDARTAPI_CDECL \ + __cdecl + +#else /* __GNUC__ || __CUDA_LIBDEVICE__ || __CUDACC_RTC__ */ + +#define __inline__ + +#if !defined(__align__) + +#error --- !!! UNKNOWN COMPILER: please provide a CUDA compatible definition for '__align__' !!! --- + +#endif /* !__align__ */ + +#if !defined(CUDARTAPI) + +#error --- !!! UNKNOWN COMPILER: please provide a CUDA compatible definition for 'CUDARTAPI' !!! --- + +#endif /* !CUDARTAPI */ + +#endif /* __GNUC__ || __CUDA_LIBDEVICE__ || __CUDACC_RTC__ */ + +#if (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !defined(__clang__)))) || \ + (defined(_MSC_VER) && _MSC_VER < 1900) || \ + (!defined(__GNUC__) && !defined(_MSC_VER)) + +#define __specialization_static \ + static + +#else /* (__GNUC__ && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !__clang__))) || + (_MSC_VER && _MSC_VER < 1900) || + (!__GNUC__ && !_MSC_VER) */ + +#define __specialization_static + +#endif /* (__GNUC__ && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !__clang__))) || + (_MSC_VER && _MSC_VER < 1900) || + (!__GNUC__ && !_MSC_VER) */ + +#if !defined(__CUDACC__) && !defined(__CUDA_LIBDEVICE__) + +#undef __annotate__ +#define __annotate__(a) + +#else /* !__CUDACC__ && !__CUDA_LIBDEVICE__ */ + +#define __launch_bounds__(...) \ + __annotate__(launch_bounds(__VA_ARGS__)) + +#endif /* !__CUDACC__ && !__CUDA_LIBDEVICE__ */ + +#if defined(__CUDACC__) || defined(__CUDA_LIBDEVICE__) || \ + defined(__GNUC__) || defined(_WIN64) + +#define __builtin_align__(a) \ + __align__(a) + +#else /* __CUDACC__ || __CUDA_LIBDEVICE__ || __GNUC__ || _WIN64 */ + +#define __builtin_align__(a) + +#endif /* __CUDACC__ || __CUDA_LIBDEVICE__ || __GNUC__ || _WIN64 */ + +#if defined(__CUDACC__) || !defined(__grid_constant__) +#define __grid_constant__ \ + __location__(grid_constant) +#endif /* defined(__CUDACC__) || !defined(__grid_constant__) */ + +#if defined(__CUDACC__) || !defined(__host__) +#define __host__ \ + __location__(host) +#endif /* defined(__CUDACC__) || !defined(__host__) */ +#if defined(__CUDACC__) || !defined(__device__) +#define __device__ \ + __location__(device) +#endif /* defined(__CUDACC__) || !defined(__device__) */ +#if defined(__CUDACC__) || !defined(__global__) +#define __global__ \ + __location__(global) +#endif /* defined(__CUDACC__) || !defined(__global__) */ +#if defined(__CUDACC__) || !defined(__shared__) +#define __shared__ \ + __location__(shared) +#endif /* defined(__CUDACC__) || !defined(__shared__) */ +#if defined(__CUDACC__) || !defined(__constant__) +#define __constant__ \ + __location__(constant) +#endif /* defined(__CUDACC__) || !defined(__constant__) */ +#if defined(__CUDACC__) || !defined(__managed__) +#define __managed__ \ + __location__(managed) +#endif /* defined(__CUDACC__) || !defined(__managed__) */ +#if defined(__CUDACC__) || !defined(__nv_pure__) +#define __nv_pure__ \ + __location__(nv_pure) +#endif /* defined(__CUDACC__) || !defined(__nv_pure__) */ +#if !defined(__CUDACC__) +#define __device_builtin__ +#define __device_builtin_texture_type__ +#define __device_builtin_surface_type__ +#define __cudart_builtin__ +#else /* defined(__CUDACC__) */ +#define __device_builtin__ \ + __location__(device_builtin) +#define __device_builtin_texture_type__ \ + __location__(device_builtin_texture_type) +#define __device_builtin_surface_type__ \ + __location__(device_builtin_surface_type) +#define __cudart_builtin__ \ + __location__(cudart_builtin) +#endif /* !defined(__CUDACC__) */ + +#if defined(__CUDACC__) || !defined(__cluster_dims__) +#if defined(_MSC_VER) +#define __cluster_dims__(...) \ + __declspec(__cluster_dims__(__VA_ARGS__)) + +#else /* !defined(_MSC_VER) */ +#define __cluster_dims__(...) \ + __attribute__((cluster_dims(__VA_ARGS__))) +#endif /* defined(_MSC_VER) */ +#endif /* defined(__CUDACC__) || !defined(__cluster_dims__) */ + +#define __CUDA_ARCH_HAS_FEATURE__(_FEAT) __CUDA_ARCH_FEAT_##_FEAT + +#endif /* !__HOST_DEFINES_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__ +#endif diff --git a/shared/package-files/7c/7c3927b20970a0cadde64592aaba3f6489d6fb886840a695fc186da87a6527b5/scimath.cpython-311.pyc b/shared/package-files/7c/7c3927b20970a0cadde64592aaba3f6489d6fb886840a695fc186da87a6527b5/scimath.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..525cbaf70d011bc2ef2a7a818f475cbf72e31096 Binary files /dev/null and b/shared/package-files/7c/7c3927b20970a0cadde64592aaba3f6489d6fb886840a695fc186da87a6527b5/scimath.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c3c5f7eb91a9b1af52b7e4c8882df12c33b60eef865b3475e40560b51ffd5ee/pattern_utils.py b/shared/package-files/7c/7c3c5f7eb91a9b1af52b7e4c8882df12c33b60eef865b3475e40560b51ffd5ee/pattern_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..551f68be424f2717a213be2df9811f00859f5ae8 --- /dev/null +++ b/shared/package-files/7c/7c3c5f7eb91a9b1af52b7e4c8882df12c33b60eef865b3475e40560b51ffd5ee/pattern_utils.py @@ -0,0 +1,112 @@ +# mypy: allow-untyped-defs +import copy +from collections import OrderedDict +from typing import Any + +from torch.ao.quantization.fake_quantize import FixedQParamsFakeQuantize +from torch.ao.quantization.observer import ObserverBase +from torch.ao.quantization.utils import Pattern + + +__all__ = [ + "get_default_fusion_patterns", + "get_default_quant_patterns", + "get_default_output_activation_post_process_map", +] + +# TODO(future PR): fix the typing on QuantizeHandler (currently a circular dependency) +QuantizeHandler = Any + +# pattern for conv bn fusion +_DEFAULT_FUSION_PATTERNS: dict[Pattern, QuantizeHandler] = OrderedDict() + + +def _register_fusion_pattern(pattern): + def insert(fn): + _DEFAULT_FUSION_PATTERNS[pattern] = fn + return fn + + return insert + + +def get_default_fusion_patterns() -> dict[Pattern, QuantizeHandler]: + return copy.copy(_DEFAULT_FUSION_PATTERNS) + + +_DEFAULT_QUANTIZATION_PATTERNS: dict[Pattern, QuantizeHandler] = OrderedDict() + +# Mapping from pattern to activation_post_process(observer/fake_quant) constructor for output activation +# e.g. pattern: torch.sigmoid, +# output_activation_post_process: default_fixed_qparams_range_0to1_fake_quant +_DEFAULT_OUTPUT_FAKE_QUANTIZE_MAP: dict[Pattern, QuantizeHandler] = {} +_DEFAULT_OUTPUT_OBSERVER_MAP: dict[Pattern, QuantizeHandler] = {} + + +# Register pattern for both static quantization and qat +def _register_quant_pattern(pattern, fixed_qparams_observer=None): + def insert(fn): + _DEFAULT_QUANTIZATION_PATTERNS[pattern] = fn + if fixed_qparams_observer is not None: + _DEFAULT_OUTPUT_FAKE_QUANTIZE_MAP[ + pattern + ] = FixedQParamsFakeQuantize.with_args(observer=fixed_qparams_observer) + _DEFAULT_OUTPUT_OBSERVER_MAP[pattern] = fixed_qparams_observer + return fn + + return insert + + +# Get patterns for both static quantization and qat +def get_default_quant_patterns() -> dict[Pattern, QuantizeHandler]: + return copy.copy(_DEFAULT_QUANTIZATION_PATTERNS) + + +# a map from pattern to output activation post process constructor +# e.g. torch.sigmoid -> default_affine_fixed_qparam_fake_quant +def get_default_output_activation_post_process_map( + is_training, +) -> dict[Pattern, ObserverBase]: + if is_training: + return copy.copy(_DEFAULT_OUTPUT_FAKE_QUANTIZE_MAP) + else: + return copy.copy(_DEFAULT_OUTPUT_OBSERVER_MAP) + + +# Example use of register pattern function: +# @_register_fusion_pattern(torch.nn.ReLU, (torch.nn.BatchNorm2d, torch.nn.Conv2d))) +# class ConvOrLinearBNReLUFusion(): +# def __init__(...): +# ... +# + + +def _sorted_patterns_dict( + patterns_dict: dict[Pattern, QuantizeHandler] +) -> dict[Pattern, QuantizeHandler]: + """ + Return a sorted version of the patterns dictionary such that longer patterns are matched first, + e.g. match (F.relu, F.linear) before F.relu. + This works for current use cases, but we may need to have a more clever way to sort + things to address more complex patterns + """ + + def get_len(pattern): + """this will calculate the length of the pattern by counting all the entries + in the pattern. + this will make sure (nn.ReLU, (nn.BatchNorm, nn.Conv2d)) comes before + (nn.BatchNorm, nn.Conv2d) so that we can match the former first + """ + len = 0 + if isinstance(pattern, tuple): + for item in pattern: + len += get_len(item) + else: + len += 1 + return len + + return OrderedDict( + sorted( + patterns_dict.items(), + key=lambda kv: -get_len(kv[0]) if isinstance(kv[0], tuple) else 1, + ) + ) diff --git a/shared/package-files/7c/7c3db77cc051ab65a26b495568a0541224829bd0f1fdba6f39babb022ec21088/adaptive_max_pool2d_backward_native.h b/shared/package-files/7c/7c3db77cc051ab65a26b495568a0541224829bd0f1fdba6f39babb022ec21088/adaptive_max_pool2d_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..0bcd2ce028a1d2fc743eb2d1c1ff1eb1c10f7c03 --- /dev/null +++ b/shared/package-files/7c/7c3db77cc051ab65a26b495568a0541224829bd0f1fdba6f39babb022ec21088/adaptive_max_pool2d_backward_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_adaptive_max_pool2d_backward_out_cpu : public at::meta::structured_adaptive_max_pool2d_backward { +void impl(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, const at::Tensor & grad_input); +}; +struct TORCH_API structured_adaptive_max_pool2d_backward_out_cuda : public at::meta::structured_adaptive_max_pool2d_backward { +void impl(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, const at::Tensor & grad_input); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c3e4fd0142b1d847c1bce3a315e0e3c41b37f9ca869334a1e2ad0397628c95a/_thread_flow.cpython-311.pyc b/shared/package-files/7c/7c3e4fd0142b1d847c1bce3a315e0e3c41b37f9ca869334a1e2ad0397628c95a/_thread_flow.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bb3c389839ad30dd95c9177672a7043b616995b Binary files /dev/null and b/shared/package-files/7c/7c3e4fd0142b1d847c1bce3a315e0e3c41b37f9ca869334a1e2ad0397628c95a/_thread_flow.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c3ecec9aa416a03a1b9132a4de488c98ba2a7e254b3499fbeb95c417bc701a3/test_spawn.cpython-311.pyc b/shared/package-files/7c/7c3ecec9aa416a03a1b9132a4de488c98ba2a7e254b3499fbeb95c417bc701a3/test_spawn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4b0a6842a1380d27d658d8283b6b3173020c707 Binary files /dev/null and b/shared/package-files/7c/7c3ecec9aa416a03a1b9132a4de488c98ba2a7e254b3499fbeb95c417bc701a3/test_spawn.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c3fc7eb991f7180e0aa63eee673f862ba9999d51468fe83d3cb940cd539f4bb/__init__.py b/shared/package-files/7c/7c3fc7eb991f7180e0aa63eee673f862ba9999d51468fe83d3cb940cd539f4bb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..494a8e14141f055b6f4a5b5a18195c5b10eeecf5 --- /dev/null +++ b/shared/package-files/7c/7c3fc7eb991f7180e0aa63eee673f862ba9999d51468fe83d3cb940cd539f4bb/__init__.py @@ -0,0 +1,28 @@ +"""Functions for computing and measuring community structure. + +The ``community`` subpackage can be accessed by using :mod:`networkx.community`, then accessing the +functions as attributes of ``community``. For example:: + + >>> import networkx as nx + >>> G = nx.barbell_graph(5, 1) + >>> communities_generator = nx.community.girvan_newman(G) + >>> top_level_communities = next(communities_generator) + >>> next_level_communities = next(communities_generator) + >>> sorted(map(sorted, next_level_communities)) + [[0, 1, 2, 3, 4], [5], [6, 7, 8, 9, 10]] + +""" + +from networkx.algorithms.community.asyn_fluid import * +from networkx.algorithms.community.centrality import * +from networkx.algorithms.community.divisive import * +from networkx.algorithms.community.kclique import * +from networkx.algorithms.community.kernighan_lin import * +from networkx.algorithms.community.label_propagation import * +from networkx.algorithms.community.lukes import * +from networkx.algorithms.community.modularity_max import * +from networkx.algorithms.community.quality import * +from networkx.algorithms.community.community_utils import * +from networkx.algorithms.community.louvain import * +from networkx.algorithms.community.leiden import * +from networkx.algorithms.community.local import * diff --git a/shared/package-files/7c/7c43459f0071b53676d1313993f053bf72cb3af5f2d2026754f0667e0df09173/embedding_dense_backward_native.h b/shared/package-files/7c/7c43459f0071b53676d1313993f053bf72cb3af5f2d2026754f0667e0df09173/embedding_dense_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..006d55e1c83b386b0901635cdd103063595eef60 --- /dev/null +++ b/shared/package-files/7c/7c43459f0071b53676d1313993f053bf72cb3af5f2d2026754f0667e0df09173/embedding_dense_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & embedding_dense_backward_out_symint(const at::Tensor & grad_output, const at::Tensor & indices, c10::SymInt num_weights, c10::SymInt padding_idx, bool scale_grad_by_freq, at::Tensor & out); +TORCH_API at::Tensor embedding_dense_backward_cpu(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +TORCH_API at::Tensor embedding_dense_backward_cuda(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c43bbe4fece48cee8c6830400e03ac1e08678a88a89a17c2768b01ad2ee4ff5/io.cpython-311.pyc b/shared/package-files/7c/7c43bbe4fece48cee8c6830400e03ac1e08678a88a89a17c2768b01ad2ee4ff5/io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5744590bd456f06fdbb04b567deeb00f6cb90fb Binary files /dev/null and b/shared/package-files/7c/7c43bbe4fece48cee8c6830400e03ac1e08678a88a89a17c2768b01ad2ee4ff5/io.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c46e938be26782638f6f222144d4a7493513e36eee74d89ec02bab045152586/streams.py b/shared/package-files/7c/7c46e938be26782638f6f222144d4a7493513e36eee74d89ec02bab045152586/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..15095868bbad3f0c07b93ef8b731ac176f37b11a --- /dev/null +++ b/shared/package-files/7c/7c46e938be26782638f6f222144d4a7493513e36eee74d89ec02bab045152586/streams.py @@ -0,0 +1,244 @@ +# mypy: allow-untyped-defs +import ctypes + +import torch +from torch._utils import _dummy_type + + +if not hasattr(torch._C, "_CudaStreamBase"): + # Define dummy base classes + torch._C.__dict__["_CudaStreamBase"] = _dummy_type("_CudaStreamBase") + torch._C.__dict__["_CudaEventBase"] = _dummy_type("_CudaEventBase") + + +class Stream(torch._C._CudaStreamBase): + r"""Wrapper around a CUDA stream. + + A CUDA stream is a linear sequence of execution that belongs to a specific + device, independent from other streams. It supports with statement as a + context manager to ensure the operators within the with block are running + on the corresponding stream. See :ref:`cuda-semantics` for details. + + Args: + device(torch.device or int, optional): a device on which to allocate + the stream. If :attr:`device` is ``None`` (default) or a negative + integer, this will use the current device. + priority(int, optional): priority of the stream, which can be positive, 0, or negative. + A lower number indicates a higher priority. By default, the priority is set to 0. + If the value falls outside of the allowed priority range, it will automatically be + mapped to the nearest valid priority (lowest for large positive numbers or + highest for large negative numbers). + + """ + + def __new__(cls, device=None, priority=0, **kwargs): + # setting device manager is expensive, so we avoid it unless necessary + if device is None or ("stream_id" in kwargs and "device_index" in kwargs): + return super().__new__(cls, priority=priority, **kwargs) + else: + with torch.cuda.device(device): + return super().__new__(cls, priority=priority, **kwargs) + + def wait_event(self, event) -> None: + r"""Make all future work submitted to the stream wait for an event. + + Args: + event (torch.cuda.Event): an event to wait for. + + .. note:: This is a wrapper around ``cudaStreamWaitEvent()``: see + `CUDA Stream documentation`_ for more info. + + This function returns without waiting for :attr:`event`: only future + operations are affected. + + .. _CUDA Stream documentation: + https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html + """ + event.wait(self) + + def wait_stream(self, stream) -> None: + r"""Synchronize with another stream. + + All future work submitted to this stream will wait until all kernels + submitted to a given stream at the time of call complete. + + Args: + stream (Stream): a stream to synchronize. + + .. note:: This function returns without waiting for currently enqueued + kernels in :attr:`stream`: only future operations are affected. + """ + self.wait_event(stream.record_event()) + + def record_event(self, event=None): + r"""Record an event. + + Args: + event (torch.cuda.Event, optional): event to record. If not given, a new one + will be allocated. + + Returns: + Recorded event. + """ + if event is None: + event = Event() + event.record(self) + return event + + def query(self) -> bool: + r"""Check if all the work submitted has been completed. + + Returns: + A boolean indicating if all kernels in this stream are completed. + """ + return super().query() + + def synchronize(self) -> None: + r"""Wait for all the kernels in this stream to complete. + + .. note:: This is a wrapper around ``cudaStreamSynchronize()``: see + `CUDA Stream documentation`_ for more info. + """ + super().synchronize() + + @property + def _as_parameter_(self): + return ctypes.c_void_p(self.cuda_stream) + + def __eq__(self, o) -> bool: + if isinstance(o, Stream): + return super().__eq__(o) + return False + + def __hash__(self): + return hash((self.cuda_stream, self.device)) + + def __repr__(self): + return f"" + + +class ExternalStream(Stream): + r"""Wrapper around an externally allocated CUDA stream. + + This class is used to wrap streams allocated in other libraries in order + to facilitate data exchange and multi-library interactions. + + .. note:: This class doesn't manage the stream life-cycle, it is the user + responsibility to keep the referenced stream alive while this class is + being used. + + Args: + stream_ptr(int): Integer representation of the `cudaStream_t` value. + allocated externally. + device(torch.device or int, optional): the device where the stream + was originally allocated. If device is specified incorrectly, + subsequent launches using this stream may fail. + """ + + def __new__(cls, stream_ptr, device=None, **kwargs): + with torch.cuda.device(device): + return super().__new__(cls, stream_ptr=stream_ptr, **kwargs) + + +class Event(torch._C._CudaEventBase): + r"""Wrapper around a CUDA event. + + CUDA events are synchronization markers that can be used to monitor the + device's progress, to accurately measure timing, and to synchronize CUDA + streams. + + The underlying CUDA events are lazily initialized when the event is first + recorded or exported to another process. After creation, only streams on the + same device may record the event. However, streams on any device can wait on + the event. + + Args: + enable_timing (bool, optional): indicates if the event should measure time + (default: ``False``) + blocking (bool, optional): if ``True``, :meth:`wait` will be blocking (default: ``False``) + interprocess (bool): if ``True``, the event can be shared between processes + (default: ``False``) + + .. _CUDA Event Documentation: + https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EVENT.html + """ + + def __new__(cls, enable_timing=False, blocking=False, interprocess=False): + return super().__new__( + cls, + enable_timing=enable_timing, + blocking=blocking, + interprocess=interprocess, + ) + + @classmethod + def from_ipc_handle(cls, device, handle): + r"""Reconstruct an event from an IPC handle on the given device.""" + return super().from_ipc_handle(device, handle) + + def record(self, stream=None): + r"""Record the event in a given stream. + + Uses ``torch.cuda.current_stream()`` if no stream is specified. The + stream's device must match the event's device. + """ + if stream is None: + stream = torch.cuda.current_stream() + super().record(stream) + + def wait(self, stream=None) -> None: + r"""Make all future work submitted to the given stream wait for this event. + + Use ``torch.cuda.current_stream()`` if no stream is specified. + + .. note:: This is a wrapper around ``cudaStreamWaitEvent()``: see + `CUDA Event documentation`_ for more info. + """ + if stream is None: + stream = torch.cuda.current_stream() + super().wait(stream) + + def query(self): + r"""Check if all work currently captured by event has completed. + + Returns: + A boolean indicating if all work currently captured by event has + completed. + """ + return super().query() + + def elapsed_time(self, end_event): + r"""Return the time elapsed. + + Time reported in milliseconds after the event was recorded and + before the end_event was recorded. + """ + return super().elapsed_time(end_event) + + def synchronize(self) -> None: + r"""Wait for the event to complete. + + Waits until the completion of all work currently captured in this event. + This prevents the CPU thread from proceeding until the event completes. + + .. note:: This is a wrapper around ``cudaEventSynchronize()``: see + `CUDA Event documentation`_ for more info. + """ + super().synchronize() + + def ipc_handle(self): + r"""Return an IPC handle of this event. + + If not recorded yet, the event will use the current device. + """ + return super().ipc_handle() + + @property + def _as_parameter_(self): + return ctypes.c_void_p(self.cuda_event) + + def __repr__(self) -> str: + if self.cuda_event: + return f"" + else: + return "" diff --git a/shared/package-files/7c/7c47338023ffa074810efb0067a80bb732ecccaa2fdfb316b8089a0fe61f41ef/_deprecation_warning.cpython-311.pyc b/shared/package-files/7c/7c47338023ffa074810efb0067a80bb732ecccaa2fdfb316b8089a0fe61f41ef/_deprecation_warning.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80cbacb222039b9e98bc37353eff6a28aa168ea5 Binary files /dev/null and b/shared/package-files/7c/7c47338023ffa074810efb0067a80bb732ecccaa2fdfb316b8089a0fe61f41ef/_deprecation_warning.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c47650c89cce095fef37e1bb638e0f56ba224444ba5ba33f5f4f91aaf10a1c9/decomposition.cpython-311.pyc b/shared/package-files/7c/7c47650c89cce095fef37e1bb638e0f56ba224444ba5ba33f5f4f91aaf10a1c9/decomposition.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bedadb818e46824b9debdb6dfc8c3485a64b405 Binary files /dev/null and b/shared/package-files/7c/7c47650c89cce095fef37e1bb638e0f56ba224444ba5ba33f5f4f91aaf10a1c9/decomposition.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c48813abfd5750b1ec253fefc99887343ee2036cc40d0d847fe8bb55090dc2b/arange_native.h b/shared/package-files/7c/7c48813abfd5750b1ec253fefc99887343ee2036cc40d0d847fe8bb55090dc2b/arange_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2fd77bd375a1e92635396492cf02d80c62bd67f3 --- /dev/null +++ b/shared/package-files/7c/7c48813abfd5750b1ec253fefc99887343ee2036cc40d0d847fe8bb55090dc2b/arange_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor arange(const at::Scalar & end, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor & arange_out(const at::Scalar & end, at::Tensor & out); +TORCH_API at::Tensor arange(const at::Scalar & start, const at::Scalar & end, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor arange(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step=1, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor & arange_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out); +TORCH_API at::Tensor & arange_cuda_out(const at::Scalar & start, const at::Scalar & end, const at::Scalar & step, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c499de6cb6114455b78f5aab91f993b76a6b8e0c8a82c3b61a13c342fba94c5/__init__.cpython-311.pyc b/shared/package-files/7c/7c499de6cb6114455b78f5aab91f993b76a6b8e0c8a82c3b61a13c342fba94c5/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c816cd20ed719e6d7c027e82b295f0dcf26162b3 Binary files /dev/null and b/shared/package-files/7c/7c499de6cb6114455b78f5aab91f993b76a6b8e0c8a82c3b61a13c342fba94c5/__init__.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c49dda4637ffc3e39eaf8773406a6a0ad4a766b44caf980b16d20641d13131a/fn_with_kwargs.py b/shared/package-files/7c/7c49dda4637ffc3e39eaf8773406a6a0ad4a766b44caf980b16d20641d13131a/fn_with_kwargs.py new file mode 100644 index 0000000000000000000000000000000000000000..46b2637b398c21bf9399d0a3fa2a964354beea3e --- /dev/null +++ b/shared/package-files/7c/7c49dda4637ffc3e39eaf8773406a6a0ad4a766b44caf980b16d20641d13131a/fn_with_kwargs.py @@ -0,0 +1,30 @@ +# mypy: allow-untyped-defs +import torch + +class FnWithKwargs(torch.nn.Module): + """ + Keyword arguments are not supported at the moment. + """ + + def forward(self, pos0, tuple0, *myargs, mykw0, **mykwargs): + out = pos0 + for arg in tuple0: + out = out * arg + for arg in myargs: + out = out * arg + out = out * mykw0 + out = out * mykwargs["input0"] * mykwargs["input1"] + return out + +example_args = ( + torch.randn(4), + (torch.randn(4), torch.randn(4)), + *[torch.randn(4), torch.randn(4)] +) +example_kwargs = { + "mykw0": torch.randn(4), + "input0": torch.randn(4), + "input1": torch.randn(4), +} +tags = {"python.data-structure"} +model = FnWithKwargs() diff --git a/shared/package-files/7c/7c4b924d046086d258f157018bbab08994d05f077dbb1f1dd4f441630e9077a1/dynamic_shape_view.py b/shared/package-files/7c/7c4b924d046086d258f157018bbab08994d05f077dbb1f1dd4f441630e9077a1/dynamic_shape_view.py new file mode 100644 index 0000000000000000000000000000000000000000..c45d4aeebb0282a0f56c58a587b4bfe1655f50e3 --- /dev/null +++ b/shared/package-files/7c/7c4b924d046086d258f157018bbab08994d05f077dbb1f1dd4f441630e9077a1/dynamic_shape_view.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeView(torch.nn.Module): + """ + Dynamic shapes should be propagated to view arguments instead of being + baked into the exported graph. + """ + + def forward(self, x): + new_x_shape = x.size()[:-1] + (2, 5) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1) + +example_args = (torch.randn(10, 10),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeView() diff --git a/shared/package-files/7c/7c4efbbe179dade6d4b2854b1d404308b0b13fb737dac9f5b608b2791ab608c8/special_log1p_native.h b/shared/package-files/7c/7c4efbbe179dade6d4b2854b1d404308b0b13fb737dac9f5b608b2791ab608c8/special_log1p_native.h new file mode 100644 index 0000000000000000000000000000000000000000..52e6ab859521a5b259df3eb49dde948a3188c2d5 --- /dev/null +++ b/shared/package-files/7c/7c4efbbe179dade6d4b2854b1d404308b0b13fb737dac9f5b608b2791ab608c8/special_log1p_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor special_log1p(const at::Tensor & self); +TORCH_API at::Tensor & special_log1p_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c4f7ae8433b9f922d2c2103f07a21599867d735c617cbbd8ac491689a7fc634/_scaled_dot_product_flash_attention_cuda_dispatch.h b/shared/package-files/7c/7c4f7ae8433b9f922d2c2103f07a21599867d735c617cbbd8ac491689a7fc634/_scaled_dot_product_flash_attention_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9cdf00823e0902d3667b0ab0061af593207e96a7 --- /dev/null +++ b/shared/package-files/7c/7c4f7ae8433b9f922d2c2103f07a21599867d735c617cbbd8ac491689a7fc634/_scaled_dot_product_flash_attention_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _scaled_dot_product_flash_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, ::std::optional scale=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7c/7c509ff364e5f62cecdfcf08f184764bfbc88bf5e1c9d5feb8c4f201593a4e6f/relaxed_categorical.cpython-311.pyc b/shared/package-files/7c/7c509ff364e5f62cecdfcf08f184764bfbc88bf5e1c9d5feb8c4f201593a4e6f/relaxed_categorical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ace364e5f5cc0f428aad4d74ca3b67d41f12234 Binary files /dev/null and b/shared/package-files/7c/7c509ff364e5f62cecdfcf08f184764bfbc88bf5e1c9d5feb8c4f201593a4e6f/relaxed_categorical.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c5a9bf47a9a261f794b5ab044de33e424bb0ec72efc776ea8706867b0f86120/cuda_kernel.cpython-311.pyc b/shared/package-files/7c/7c5a9bf47a9a261f794b5ab044de33e424bb0ec72efc776ea8706867b0f86120/cuda_kernel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f8135a6e61391001d03b04d394dc657362e9a57 Binary files /dev/null and b/shared/package-files/7c/7c5a9bf47a9a261f794b5ab044de33e424bb0ec72efc776ea8706867b0f86120/cuda_kernel.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c5f6326c895d4ee93445a209c818e0777fae8623adf2c5924a54ad61a601c97/test_distance_regular.cpython-311.pyc b/shared/package-files/7c/7c5f6326c895d4ee93445a209c818e0777fae8623adf2c5924a54ad61a601c97/test_distance_regular.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea2045e1c56df342ddfdaa315d2d7e97b47d32f2 Binary files /dev/null and b/shared/package-files/7c/7c5f6326c895d4ee93445a209c818e0777fae8623adf2c5924a54ad61a601c97/test_distance_regular.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c5f650fbd4e790e479527d1fbe2338cd31eeecebbfcdf53e59d50be11ac6b9b/node_metadata.py b/shared/package-files/7c/7c5f650fbd4e790e479527d1fbe2338cd31eeecebbfcdf53e59d50be11ac6b9b/node_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9874dc1520fdbd6f4adc061dd7bccee031710797 --- /dev/null +++ b/shared/package-files/7c/7c5f650fbd4e790e479527d1fbe2338cd31eeecebbfcdf53e59d50be11ac6b9b/node_metadata.py @@ -0,0 +1,32 @@ +from typing import Any + + +NodeMetadataValue = Any + + +PROTECTED_KEYS: set[str] = { + "val", + "stack_trace", + "nn_module_stack", + "debug_handle", + "tensor_meta", +} + + +class NodeMetadata: + def __init__(self, data: dict[str, Any]) -> None: + self.data: dict[str, Any] = data.copy() + + def __getitem__(self, key: str) -> NodeMetadataValue: + return self.data[key] + + def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue: + if key in PROTECTED_KEYS: + raise RuntimeError(f"Could not override node key: {key}") + self.data[key] = value + + def __contains__(self, key: str) -> bool: + return key in self.data + + def copy(self) -> "NodeMetadata": + return NodeMetadata(self.data.copy()) diff --git a/shared/package-files/7c/7c626ce80cabb8a1a002d7c580e114d2759c429b47004d442f87bdd670916d9a/__init__.cpython-311.pyc b/shared/package-files/7c/7c626ce80cabb8a1a002d7c580e114d2759c429b47004d442f87bdd670916d9a/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34b39f4389f403ed064c1804c6c1225a4dc04d1e Binary files /dev/null and b/shared/package-files/7c/7c626ce80cabb8a1a002d7c580e114d2759c429b47004d442f87bdd670916d9a/__init__.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c6459ff0e650004d3fbc2f97d4f5be804e36ae228768c32418703c4284c7b3a/multigraph.cpython-311.pyc b/shared/package-files/7c/7c6459ff0e650004d3fbc2f97d4f5be804e36ae228768c32418703c4284c7b3a/multigraph.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cdf147eb55826fddc4b9c9e38f49dcab37f2d20 Binary files /dev/null and b/shared/package-files/7c/7c6459ff0e650004d3fbc2f97d4f5be804e36ae228768c32418703c4284c7b3a/multigraph.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c6b69143f0632143fb3bf8001eda948ecc659d7f6cf6c8b8534413d370515b8/configure.ac b/shared/package-files/7c/7c6b69143f0632143fb3bf8001eda948ecc659d7f6cf6c8b8534413d370515b8/configure.ac new file mode 100644 index 0000000000000000000000000000000000000000..cdb8391ff81f6e22f31dec572cab2bdf2c6e8fff --- /dev/null +++ b/shared/package-files/7c/7c6b69143f0632143fb3bf8001eda948ecc659d7f6cf6c8b8534413d370515b8/configure.ac @@ -0,0 +1,684 @@ +# Configure script for htslib, a C library for high-throughput sequencing data. +# +# Copyright (C) 2015-2024 Genome Research Ltd. +# +# Author: John Marshall +# +# 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. + +dnl Process this file with autoconf to produce a configure script +AC_INIT([HTSlib], m4_esyscmd_s([./version.sh 2>/dev/null]), + [samtools-help@lists.sourceforge.net], [], [http://www.htslib.org/]) +AC_PREREQ(2.63) dnl This version introduced 4-argument AC_CHECK_HEADER +AC_CONFIG_SRCDIR(hts.c) +AC_CONFIG_HEADERS(config.h) + +m4_include([m4/hts_prog_cc_warnings.m4]) +m4_include([m4/hts_check_compile_flags_needed.m4]) +m4_include([m4/hts_hide_dynamic_syms.m4]) +m4_include([m4/pkg.m4]) + +dnl Copyright notice to be copied into the generated configure script +AC_COPYRIGHT([Portions copyright (C) 2020-2024 Genome Research Ltd. + +This configure script is free software: you are free to change and +redistribute it. There is NO WARRANTY, to the extent permitted by law.]) + +dnl Notes to be copied (by autoheader) into the generated config.h.in +AH_TOP([/* If you use configure, this file provides @%:@defines reflecting your + configuration choices. If you have not run configure, suitable + conservative defaults will be used. + + Autoheader adds a number of items to this template file that are not + used by HTSlib: STDC_HEADERS and most HAVE_*_H header file defines + are immaterial, as we assume standard ISO C headers and facilities; + the PACKAGE_* defines are unused and are overridden by the more + accurate PACKAGE_VERSION as computed by the Makefile. */]) + +dnl Variant of AC_MSG_ERROR that ensures subsequent make(1) invocations fail +dnl until the configuration error is resolved and configure is run again. +AC_DEFUN([MSG_ERROR], + [cat > config.mk <<'EOF' +ifneq ($(MAKECMDGOALS),distclean) +$(error Resolve configure error first) +endif +EOF + AC_MSG_ERROR([$1], [$2])]) + +AC_PROG_CC +AC_PROG_RANLIB + +dnl Turn on compiler warnings, if possible +HTS_PROG_CC_WARNINGS +dnl Flags to treat warnings as errors. These need to be applied to CFLAGS +dnl later as they can interfere with some of the tests (notably AC_SEARCH_LIBS) +HTS_PROG_CC_WERROR(hts_late_cflags) + +# HTSlib uses X/Open-only facilities (M_SQRT2 etc, drand48() etc), and +# various POSIX functions that are provided by various _POSIX_C_SOURCE values +# or by _XOPEN_SOURCE >= 500. It also uses usleep(), which is removed when +# _XOPEN_SOURCE >= 700. Additionally, some definitions may require +# _XOPEN_SOURCE >= 600 on some platforms (snprintf on MinGW, +# PTHREAD_MUTEX_RECURSIVE on some Linux distributions). Hence we set it to 600. + +# Define _XOPEN_SOURCE unless the user has already done so via $CPPFLAGS etc. +AC_CHECK_DECL([_XOPEN_SOURCE], [], + [AC_DEFINE([_XOPEN_SOURCE], [600], [Specify X/Open requirements])], + []) + +dnl Check that we have cpuid, and if so run the x86 SIMD checks +AC_CHECK_DECLS([__get_cpuid_max, __cpuid_count], [ + hts_have_cpuid=yes +], [ + hts_have_cpuid=no +], [[#include ]]) + +AS_IF(test "x$hts_have_cpuid" = "xyes", [ +dnl Options for rANS32x16 sse4.1 version - sse4.1 +HTS_CHECK_COMPILE_FLAGS_NEEDED([sse4.1], [-msse4.1 -mssse3 -mpopcnt], + [AC_LANG_PROGRAM([[ + #ifdef __x86_64__ + #include "x86intrin.h" + #endif + ]],[[ + #ifdef __x86_64__ + __m128i a = _mm_set_epi32(1, 2, 3, 4), b = _mm_set_epi32(4, 3, 2, 1); + __m128i c = _mm_shuffle_epi8(_mm_max_epu32(a, b), b); + return _mm_popcnt_u32(*((char *) &c)); + #endif + ]])], [ + hts_cflags_sse4="$flags_needed" + AC_DEFINE([HAVE_SSSE3],1,[Defined to 1 if rANS source using SSSE3 can be compiled.]) + AC_DEFINE([HAVE_POPCNT],1,[Defined to 1 if rANS source using popcnt can be compiled.]) + AC_DEFINE([HAVE_SSE4_1],1,[Defined to 1 if rANS source using SSE4.1 can be compiled. +]) + +dnl Propagate HTSlib's unaligned access preference to htscodecs + AH_VERBATIM([UBSAN],[ +/* Prevent unaligned access in htscodecs SSE4 rANS codec */ +#if defined(HTS_ALLOW_UNALIGNED) && HTS_ALLOW_UNALIGNED == 0 +#undef UBSAN +#endif]) + AC_DEFINE([UBSAN],1,[]) +]) +AC_SUBST([hts_cflags_sse4]) + +dnl Options for rANS32x16 avx2 version +HTS_CHECK_COMPILE_FLAGS_NEEDED([avx2], [-mavx2 -mpopcnt], [AC_LANG_PROGRAM([[ + #ifdef __x86_64__ + #include "x86intrin.h" + #endif + ]],[[ + #ifdef __x86_64__ + __m256i a = _mm256_set_epi32(1, 2, 3, 4, 5, 6, 7, 8); + __m256i b = _mm256_add_epi32(a, a); + long long c = _mm256_extract_epi64(b, 0); + return _mm_popcnt_u32((int) c); + #endif + ]])], [ + hts_cflags_avx2="$flags_needed" + AC_SUBST([hts_cflags_avx2]) + AC_DEFINE([HAVE_POPCNT],1,[Defined to 1 if rANS source using popcnt can be compiled.]) + AC_DEFINE([HAVE_AVX2],1,[Defined to 1 if rANS source using AVX2 can be compiled.]) +]) + +dnl Options for rANS32x16 avx512 version +HTS_CHECK_COMPILE_FLAGS_NEEDED([avx512f], [-mavx512f -mpopcnt], + [AC_LANG_PROGRAM([[ + #ifdef __x86_64__ + #include "x86intrin.h" + #endif + ]],[[ + #ifdef __x86_64__ + __m512i a = _mm512_set1_epi32(1); + __m512i b = _mm512_add_epi32(a, a); + __m256i c = _mm512_castsi512_si256(b); + __m256i d = _mm512_extracti64x4_epi64(a, 1); + return _mm_popcnt_u32(*((char *) &c)) + (*(char *) &d); + #endif + ]])], [ + hts_cflags_avx512="$flags_needed" + AC_SUBST([hts_cflags_avx512]) + AC_DEFINE([HAVE_POPCNT],1,[Defined to 1 if rANS source using popcnt can be compiled.]) + AC_DEFINE([HAVE_AVX512],1,[Defined to 1 if rANS source using AVX512F can be compiled.]) +]) + +dnl Check for working __builtin_cpu_supports (ssse3 is broken on some clangs) +AC_MSG_CHECKING([for working __builtin_cpu_supports("ssse3")]) +AC_LINK_IFELSE([AC_LANG_PROGRAM([],[ + if (__builtin_cpu_supports("ssse3")) { + return 0; + } +])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE([HAVE_BUILTIN_CPU_SUPPORT_SSSE3], 1, + [Defined to 1 if __builtin_cpu_supports("ssse3") works]) +], [ + AC_MSG_RESULT([no]) +]) + +dnl Check for function attribute used in conjunction with __builtin_cpu_supports +dnl and that it does enable the corresponding intrinsics (which is broken on ancient GCCs) +AC_MSG_CHECKING([for working __attribute__((target("ssse3")))]) +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ + #ifdef __x86_64__ + #include "x86intrin.h" + + __attribute__((target("ssse3"))) + void shuffle(char *aptr, char *bptr) { + __m128i a = _mm_lddqu_si128((__m128i *)aptr); + __m128i b = _mm_shuffle_epi8(a, a); + _mm_storeu_si128((__m128i *)bptr, b); + } + #else + void shuffle(char *aptr, char *bptr) { } + #endif +]], [[shuffle(0, 0);]])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE([HAVE_ATTRIBUTE_TARGET_SSSE3], 1, + [Define if __attribute__((target("ssse3"))) works.]) +], [ + AC_MSG_RESULT([no]) +]) + +]) dnl End of AS_IF(hts_have_cpuid) + +dnl Avoid chicken-and-egg problem where pkg-config supplies the +dnl PKG_PROG_PKG_CONFIG macro, but we want to use it to check +dnl for pkg-config... +m4_ifdef([PKG_PROG_PKG_CONFIG], [PKG_PROG_PKG_CONFIG], [PKG_CONFIG=""]) + +need_crypto=no +pc_requires= +static_LDFLAGS=$LDFLAGS +static_LIBS='-lpthread -lz -lm' +private_LIBS=$LDFLAGS + +AC_ARG_ENABLE([versioned-symbols], + [AS_HELP_STRING([--disable-versioned-symbols], + [disable versioned symbols in shared library])], + [], [enable_versioned_symbols=yes]) + +AC_ARG_ENABLE([bz2], + [AS_HELP_STRING([--disable-bz2], + [omit support for BZ2-compressed CRAM files])], + [], [enable_bz2=yes]) + +AC_ARG_ENABLE([gcs], + [AS_HELP_STRING([--enable-gcs], + [support Google Cloud Storage URLs])], + [], [enable_gcs=check]) + +AC_SYS_LARGEFILE + +AC_ARG_ENABLE([libcurl], + [AS_HELP_STRING([--enable-libcurl], + [enable libcurl-based support for http/https/etc URLs])], + [], [enable_libcurl=check]) + +AC_ARG_ENABLE([lzma], + [AS_HELP_STRING([--disable-lzma], + [omit support for LZMA-compressed CRAM files])], + [], [enable_lzma=yes]) + +AC_ARG_ENABLE([plugins], + [AS_HELP_STRING([--enable-plugins], + [enable separately-compiled plugins for file access])], + [], [enable_plugins=no]) +AC_SUBST(enable_plugins) + +AC_ARG_WITH([external-htscodecs], + [AS_HELP_STRING([--with-external-htscodecs], + [get htscodecs functions from a shared library])], + [], [with_external_htscodecs=no]) +AC_SUBST(with_external_htscodecs) + +AC_ARG_WITH([libdeflate], + [AS_HELP_STRING([--with-libdeflate], + [use libdeflate for faster crc and deflate algorithms])], + [], [with_libdeflate=check]) + +AC_ARG_WITH([plugin-dir], + [AS_HELP_STRING([--with-plugin-dir=DIR], + [plugin installation location [LIBEXECDIR/htslib]])], + [case $withval in + yes|no) MSG_ERROR([no directory specified for --with-plugin-dir]) ;; + esac], + [with_plugin_dir='$(libexecdir)/htslib']) +AC_SUBST([plugindir], $with_plugin_dir) + +AC_ARG_WITH([plugin-path], + [AS_HELP_STRING([--with-plugin-path=PATH], + [default HTS_PATH plugin search path [PLUGINDIR]])], + [case $withval in + yes) MSG_ERROR([no path specified for --with-plugin-path]) ;; + no) with_plugin_path= ;; + esac], + [with_plugin_path=$with_plugin_dir]) +AC_SUBST([pluginpath], $with_plugin_path) + +AC_ARG_ENABLE([s3], + [AS_HELP_STRING([--enable-s3], + [support Amazon AWS S3 URLs])], + [], [enable_s3=check]) + +basic_host=${host_alias:-unknown-`uname -s`} +AC_MSG_CHECKING([shared library type for $basic_host]) +case $basic_host in + *-cygwin* | *-CYGWIN*) + host_result="Cygwin DLL" + PLATFORM=CYGWIN + PLUGIN_EXT=.cygdll + ;; + *-darwin* | *-Darwin*) + host_result="Darwin dylib" + PLATFORM=Darwin + PLUGIN_EXT=.bundle + ;; + *-msys* | *-MSYS* | *-mingw* | *-MINGW*) + host_result="MSYS dll" + PLATFORM=MSYS + PLUGIN_EXT=.dll + # This also sets __USE_MINGW_ANSI_STDIO which in turn makes PRId64, + # %lld and %z printf formats work. It also enforces the snprintf to + # be C99 compliant so it returns the correct values (in kstring.c). + + # Now set by default, so no need to do it here. + # CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600" + ;; + *) + host_result="plain .so" + PLATFORM=default + PLUGIN_EXT=.so + ;; +esac +AC_MSG_RESULT([$host_result]) +AC_SUBST([PLATFORM]) + +dnl Check for versioned symbol support +dnl Only try for .so shared libraries as other types won't work +AS_IF([test x"$PLATFORM" = xdefault && test x"$enable_versioned_symbols" = xyes], + [AC_CACHE_CHECK([whether the linker supports versioned symbols], + [hts_cv_have_versioned_symbols], [ + save_LDFLAGS=$LDFLAGS + LDFLAGS="-Wl,-version-script,$srcdir/htslib.map $LDFLAGS" + AC_LINK_IFELSE([AC_LANG_PROGRAM()], + [hts_cv_have_versioned_symbols=yes], + [hts_cv_have_versioned_symbols=no]) + LDFLAGS=$save_LDFLAGS + ]) + AS_IF([test "x$hts_cv_have_versioned_symbols" = xyes],[ + VERSION_SCRIPT_LDFLAGS='-Wl,-version-script,$(srcprefix)htslib.map' + AC_SUBST([VERSION_SCRIPT_LDFLAGS]) + ]) +]) + +dnl Try to get more control over which symbols are exported in the shared +dnl library. +HTS_HIDE_DYNAMIC_SYMBOLS + +dnl FIXME This pulls in dozens of standard header checks +AC_FUNC_MMAP +AC_CHECK_FUNCS([gmtime_r fsync drand48 srand48_deterministic]) + +# Darwin has a dubious fdatasync() symbol, but no declaration in +AC_CHECK_DECL([fdatasync(int)], [AC_CHECK_FUNCS(fdatasync)]) + +AC_MSG_CHECKING([for __attribute__((constructor))]) +AC_LINK_IFELSE([AC_LANG_PROGRAM([[ + static __attribute__((constructor)) void noop(void) {} +]], [])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE([HAVE_ATTRIBUTE_CONSTRUCTOR], 1, + [Define if __attribute__((constructor)) is available.]) +], [AC_MSG_RESULT([no])]) + +AC_MSG_CHECKING([for clock_gettime with CLOCK_PROCESS_CPUTIME_ID]) +AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ + struct timespec ts; + clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts); +]])], [ + AC_MSG_RESULT([yes]) + AC_DEFINE([HAVE_CLOCK_GETTIME_CPUTIME], 1, + [Define if clock_gettime exists and accepts CLOCK_PROCESS_CPUTIME_ID.]) +], [AC_MSG_RESULT([no])]) + +if test $enable_plugins != no; then + AC_SEARCH_LIBS([dlsym], [dl], [], + [MSG_ERROR([dlsym() not found + +Plugin support requires dynamic linking facilities from the operating system. +Either configure with --disable-plugins or resolve this error to build HTSlib.])]) + # Check if the compiler understands -rdynamic + # TODO Test whether this is required and/or needs tweaking per-platform + HTS_TEST_CC_C_LD_FLAG([-rdynamic],[rdynamic_flag]) + AS_IF([test x"$rdynamic_flag" != "xno"], + [LDFLAGS="$LDFLAGS $rdynamic_flag" + static_LDFLAGS="$static_LDFLAGS $rdynamic_flag"]) + case "$ac_cv_search_dlsym" in + -l*) static_LIBS="$static_LIBS $ac_cv_search_dlsym" ;; + esac + AC_DEFINE([ENABLE_PLUGINS], 1, [Define if HTSlib should enable plugins.]) + AC_SUBST([PLUGIN_EXT]) + AC_DEFINE_UNQUOTED([PLUGIN_EXT], ["$PLUGIN_EXT"], + [Platform-dependent plugin filename extension.]) +fi + +AC_SEARCH_LIBS([log], [m], [], + [MSG_ERROR([log() not found + +HTSLIB requires a working floating-point math library. +FAILED. This error must be resolved in order to build HTSlib successfully.])]) + +zlib_devel=ok +dnl Set a trivial non-empty INCLUDES to avoid excess default includes tests +AC_CHECK_HEADER([zlib.h], [], [zlib_devel=missing], [;]) +AC_CHECK_LIB(z, inflate, [], [zlib_devel=missing]) + +if test $zlib_devel != ok; then + MSG_ERROR([zlib development files not found + +HTSlib uses compression routines from the zlib library . +Building HTSlib requires zlib development files to be installed on the build +machine; you may need to ensure a package such as zlib1g-dev (on Debian or +Ubuntu Linux) or zlib-devel (on RPM-based Linux distributions or Cygwin) +is installed. + +FAILED. This error must be resolved in order to build HTSlib successfully.]) +fi + +dnl connect() etc. fns are in libc on linux, but libsocket on illumos/Solaris +AC_SEARCH_LIBS([recv], [socket ws2_32], [ +if test "$ac_cv_search_recv" != "none required" +then + static_LIBS="$static_LIBS $ac_cv_search_recv" +fi], + dnl on MinGW-i686, checking recv() linking requires an annotated declaration + [AC_MSG_CHECKING([for library containing recv using declaration]) + LIBS="-lws2_32 $LIBS" + AC_LINK_IFELSE( + [AC_LANG_PROGRAM([[#include ]], [[recv(0, 0, 0, 0);]])], + [AC_MSG_RESULT([-lws2_32]) + static_LIBS="$static_LIBS -lws2_32"], + [AC_MSG_RESULT([no]) + MSG_ERROR([unable to find the recv() function])])]) + +if test "$enable_bz2" != no; then + bz2_devel=ok + AC_CHECK_HEADER([bzlib.h], [], [bz2_devel=missing], [;]) + AC_CHECK_LIB([bz2], [BZ2_bzBuffToBuffCompress], [], [bz2_devel=missing]) + if test $bz2_devel != ok; then + MSG_ERROR([libbzip2 development files not found + +The CRAM format may use bzip2 compression, which is implemented in HTSlib +by using compression routines from libbzip2 . + +Building HTSlib requires libbzip2 development files to be installed on the +build machine; you may need to ensure a package such as libbz2-dev (on Debian +or Ubuntu Linux) or bzip2-devel (on RPM-based Linux distributions or Cygwin) +is installed. + +Either configure with --disable-bz2 (which will make some CRAM files +produced elsewhere unreadable) or resolve this error to build HTSlib.]) + fi +dnl Unfortunately the 'bzip2' package-cfg module is not standard. +dnl Redhat/Fedora has it; Debian/Ubuntu does not. + if test -n "$PKG_CONFIG" && "$PKG_CONFIG" --exists bzip2; then + pc_requires="$pc_requires bzip2" + else + private_LIBS="$private_LIBS -lbz2" + fi + static_LIBS="$static_LIBS -lbz2" +fi + +if test "$enable_lzma" != no; then + lzma_devel=ok + AC_CHECK_HEADERS([lzma.h], [], [lzma_devel=header-missing], [;]) + AC_CHECK_LIB([lzma], [lzma_easy_buffer_encode], [], [lzma_devel=missing]) + if test $lzma_devel = missing; then + MSG_ERROR([liblzma development files not found + +The CRAM format may use LZMA2 compression, which is implemented in HTSlib +by using compression routines from liblzma . + +Building HTSlib requires liblzma development files to be installed on the +build machine; you may need to ensure a package such as liblzma-dev (on Debian +or Ubuntu Linux), xz-devel (on RPM-based Linux distributions or Cygwin), or +xz (via Homebrew on macOS) is installed; or build XZ Utils from source. + +Either configure with --disable-lzma (which will make some CRAM files +produced elsewhere unreadable) or resolve this error to build HTSlib.]) + fi + pc_requires="$pc_requires liblzma" + static_LIBS="$static_LIBS -llzma" +fi + +AS_IF([test "x$with_external_htscodecs" != "xno"], + [libhtscodecs=ok + AC_CHECK_HEADER([htscodecs/rANS_static4x16.h],[], + [libhtscodecs='missing header'],[;]) + AC_CHECK_LIB([htscodecs],[rans_compress_bound_4x16], + [:],[libhtscodecs='missing library']) + AS_IF([test "$libhtscodecs" = "ok"], + [AC_DEFINE([HAVE_EXTERNAL_LIBHTSCODECS], 1, [Define if using an external libhtscodecs]) + LIBS="-lhtscodecs $LIBS" + private_LIBS="-lhtscodecs $private_LIBS" + static_LIBS="-lhtscodecs $static_LIBS" + selected_htscodecs_mk="htscodecs_external.mk"], + [MSG_ERROR([libhtscodecs development files not found: $libhtscodecs + +You asked to use an external htscodecs library, but do not have the +required header / library files. You either need to supply these and +if necessary set CPPFLAGS and LDFLAGS so the compiler can find them; +or configure using --without-external-htscodecs to build the required +functions from the htscodecs submodule. +])])], + [AC_MSG_CHECKING([whether htscodecs files are present]) + AS_IF([test -e "$srcdir/htscodecs/htscodecs/rANS_static4x16.h"], + [AC_MSG_RESULT([yes]) + selected_htscodecs_mk="htscodecs_bundled.mk"], + [AC_MSG_RESULT([no]) + AS_IF([test -e "$srcdir/.git"], + [MSG_ERROR([htscodecs submodule files not present. + +HTSlib uses some functions from the htscodecs project, which is normally +included as a submodule. Try running: + + git submodule update --init --recursive + +in the top-level htslib directory to update it, and then re-run configure. +])], + [MSG_ERROR([htscodecs submodule files not present. + +You have an incomplete distribution. Please try downloading one of the +official releases from https://www.htslib.org +])])])]) + +AS_IF([test "x$with_libdeflate" != "xno"], + [libdeflate=ok + AC_CHECK_HEADER([libdeflate.h],[],[libdeflate='missing header'],[;]) + AC_CHECK_LIB([deflate], [libdeflate_deflate_compress],[:],[libdeflate='missing library']) + AS_IF([test "$libdeflate" = "ok"], + [AC_DEFINE([HAVE_LIBDEFLATE], 1, [Define if libdeflate is available.]) + LIBS="-ldeflate $LIBS" + private_LIBS="$private_LIBS -ldeflate" + static_LIBS="$static_LIBS -ldeflate"], + [AS_IF([test "x$with_libdeflate" != "xcheck"], + [MSG_ERROR([libdeflate development files not found: $libdeflate + +You requested libdeflate, but do not have the required header / library +files. The source for libdeflate is available from +. You may have to adjust +search paths in CPPFLAGS and/or LDFLAGS if the header and library +are not currently on them. + +Either configure with --without-libdeflate or resolve this error to build +HTSlib.])])])]) + +libcurl=disabled +if test "$enable_libcurl" != no; then + libcurl_devel=ok + AC_CHECK_HEADER([curl/curl.h], [], [libcurl_devel="headers not found"], [;]) + AC_CHECK_LIB([curl], [curl_easy_pause], [:], + [AC_CHECK_LIB([curl], [curl_easy_init], + [libcurl_devel="library is too old (7.18+ required)"], + [libcurl_devel="library not found"])]) + + if test "$libcurl_devel" = ok; then + AC_DEFINE([HAVE_LIBCURL], 1, [Define if libcurl file access is enabled.]) + libcurl=enabled + elif test "$enable_libcurl" = check; then + AC_MSG_WARN([libcurl not enabled: $libcurl_devel]) + else + MSG_ERROR([libcurl $libcurl_devel + +Support for HTTPS and other SSL-based URLs requires routines from the libcurl +library . Building HTSlib with libcurl enabled +requires libcurl development files to be installed on the build machine; you +may need to ensure a package such as libcurl4-{gnutls,nss,openssl}-dev (on +Debian or Ubuntu Linux) or libcurl-devel (on RPM-based Linux distributions +or Cygwin) is installed. + +Either configure with --disable-libcurl or resolve this error to build HTSlib.]) + fi + +dnl -lcurl is only needed for static linking if hfile_libcurl is not a plugin + if test "$libcurl" = enabled ; then + if test "$enable_plugins" != yes ; then + static_LIBS="$static_LIBS -lcurl" + fi + fi +fi +AC_SUBST([libcurl]) + +gcs=disabled +if test "$enable_gcs" != no; then + if test $libcurl = enabled; then + AC_DEFINE([ENABLE_GCS], 1, [Define if HTSlib should enable GCS support.]) + gcs=enabled + else + case "$enable_gcs" in + check) AC_MSG_WARN([GCS support not enabled: requires libcurl support]) ;; + *) MSG_ERROR([GCS support not enabled + +Support for Google Cloud Storage URLs requires libcurl support to be enabled +in HTSlib. Configure with --enable-libcurl in order to use GCS URLs.]) + ;; + esac + fi +fi +AC_SUBST([gcs]) + +s3=disabled +if test "$enable_s3" != no; then + if test $libcurl = enabled; then + s3=enabled + need_crypto="$enable_s3" + else + case "$enable_s3" in + check) AC_MSG_WARN([S3 support not enabled: requires libcurl support]) ;; + *) MSG_ERROR([S3 support not enabled + +Support for Amazon AWS S3 URLs requires libcurl support to be enabled +in HTSlib. Configure with --enable-libcurl in order to use S3 URLs.]) + ;; + esac + fi +fi + +CRYPTO_LIBS= +if test $need_crypto != no; then + AC_CHECK_FUNC([CCHmac], + [AC_DEFINE([HAVE_COMMONCRYPTO], 1, + [Define if you have the Common Crypto library.])], + [save_LIBS=$LIBS + AC_SEARCH_LIBS([HMAC], [crypto], + [AC_DEFINE([HAVE_HMAC], 1, [Define if you have libcrypto-style HMAC().]) + case "$ac_cv_search_HMAC" in + -l*) CRYPTO_LIBS=$ac_cv_search_HMAC ;; + esac], + [case "$need_crypto" in + check) AC_MSG_WARN([S3 support not enabled: requires SSL development files]) + s3=disabled ;; + *) MSG_ERROR([SSL development files not found + +Support for AWS S3 URLs requires routines from an SSL library. Building +HTSlib with libcurl enabled requires SSL development files to be installed +on the build machine; you may need to ensure a package such as libgnutls-dev, +libnss3-dev, or libssl-dev (on Debian or Ubuntu Linux, corresponding to the +libcurl4-*-dev package installed), or openssl-devel (on RPM-based Linux +distributions or Cygwin) is installed. + +Either configure with --disable-s3 or resolve this error to build HTSlib.]) ;; + esac]) + LIBS=$save_LIBS]) +dnl Only need to add to static_LIBS if not building as a plugin + if test "$enable_plugins" != yes ; then + static_LIBS="$static_LIBS $CRYPTO_LIBS" + fi +fi + +dnl Look for regcomp in various libraries (needed on windows/mingw). +AC_SEARCH_LIBS(regcomp, regex, [libregex=needed], []) + +dnl Look for PTHREAD_MUTEX_RECURSIVE. +dnl This is normally in pthread.h except on some broken glibc implementations. +dnl Now set by default +dnl AC_CHECK_DECL(PTHREAD_MUTEX_RECURSIVE, [], [AC_DEFINE([_XOPEN_SOURCE],[600], [Needed for PTHREAD_MUTEX_RECURSIVE])], [[#include ]]) + +if test "$s3" = enabled ; then + AC_DEFINE([ENABLE_S3], 1, [Define if HTSlib should enable S3 support.]) +fi + +dnl Apply value from HTS_PROG_CC_WERROR (if set) +AS_IF([test "x$hts_late_cflags" != x],[CFLAGS="$CFLAGS $hts_late_cflags"]) + +AC_SUBST([s3]) +AC_SUBST([CRYPTO_LIBS]) + +AC_SUBST([pc_requires]) +AC_SUBST([private_LIBS]) +AC_SUBST([static_LDFLAGS]) +AC_SUBST([static_LIBS]) + +AC_CONFIG_FILES([config.mk htslib.pc.tmp:htslib.pc.in]) +AC_CONFIG_LINKS([htscodecs.mk:$selected_htscodecs_mk]) + +if test "$srcdir" != .; then + # Set up for a separate build directory. As HTSlib uses a non-recursive + # makefile, we need to create additional build subdirectories explicitly. + AC_CONFIG_LINKS([Makefile:Makefile htslib.mk:htslib.mk]) + AC_CONFIG_FILES([htslib_vars.mk:builddir_vars.mk.in]) + AC_CONFIG_COMMANDS([mkdir], + [AS_MKDIR_P([cram]) + AS_MKDIR_P([htscodecs/htscodecs]) + AS_MKDIR_P([htscodecs/tests]) + AS_MKDIR_P([test/fuzz]) + AS_MKDIR_P([test/longrefs]) + AS_MKDIR_P([test/tabix])]) +fi + +# @HTSDIRslash_if_relsrcdir@ will be empty when $srcdir is absolute +case "$srcdir" in + /*) HTSDIRslash_if_relsrcdir= ;; + *) HTSDIRslash_if_relsrcdir='$(HTSDIR)/' ;; +esac +AC_SUBST([HTSDIRslash_if_relsrcdir]) + +AC_OUTPUT diff --git a/shared/package-files/7c/7c6c3bd30555f3c61c2e41126aa53b4a63e9a0484159d4e397bea093b5751e13/test_dense.cpython-311.pyc b/shared/package-files/7c/7c6c3bd30555f3c61c2e41126aa53b4a63e9a0484159d4e397bea093b5751e13/test_dense.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7266b606cb1ea5027094ed3c6705dc0745a599c5 Binary files /dev/null and b/shared/package-files/7c/7c6c3bd30555f3c61c2e41126aa53b4a63e9a0484159d4e397bea093b5751e13/test_dense.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c74c58675cd57fb023103a449cafd2292e71859ca633fa892edc91e0a379849/promote_types.h b/shared/package-files/7c/7c74c58675cd57fb023103a449cafd2292e71859ca633fa892edc91e0a379849/promote_types.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea289cf449feb7c4b00cf737b4bd061731f5cf6 --- /dev/null +++ b/shared/package-files/7c/7c74c58675cd57fb023103a449cafd2292e71859ca633fa892edc91e0a379849/promote_types.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::promote_types(ScalarType type1, ScalarType type2) -> ScalarType +inline at::ScalarType promote_types(at::ScalarType type1, at::ScalarType type2) { + return at::_ops::promote_types::call(type1, type2); +} + +} diff --git a/shared/package-files/7c/7c7ddc066329aa2157fe9ac4b58c8256f037b9b0eeb00aea31b035a1009bce6e/__init__.cpython-311.pyc b/shared/package-files/7c/7c7ddc066329aa2157fe9ac4b58c8256f037b9b0eeb00aea31b035a1009bce6e/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c4b894aac45b49f36b8198792b71d5ed26f2a9d Binary files /dev/null and b/shared/package-files/7c/7c7ddc066329aa2157fe9ac4b58c8256f037b9b0eeb00aea31b035a1009bce6e/__init__.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c7e297a29f3e6510ae7c9a6d0d91f91f70a2f3388584bc1783e409539e18bb9/common.cpython-311.pyc b/shared/package-files/7c/7c7e297a29f3e6510ae7c9a6d0d91f91f70a2f3388584bc1783e409539e18bb9/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a01ce0276bac282f4ac3fe6e03892140d6329114 Binary files /dev/null and b/shared/package-files/7c/7c7e297a29f3e6510ae7c9a6d0d91f91f70a2f3388584bc1783e409539e18bb9/common.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c829bdddb03d10a4b4849e78c7d6a84e6807548d7ee9b18c6080832ed7eb4ed/_to_sparse_bsc_cuda_dispatch.h b/shared/package-files/7c/7c829bdddb03d10a4b4849e78c7d6a84e6807548d7ee9b18c6080832ed7eb4ed/_to_sparse_bsc_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..40f9394addfc35d1b57565072b10a2382bfe103d --- /dev/null +++ b/shared/package-files/7c/7c829bdddb03d10a4b4849e78c7d6a84e6807548d7ee9b18c6080832ed7eb4ed/_to_sparse_bsc_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _to_sparse_bsc(const at::Tensor & self, at::IntArrayRef blocksize, ::std::optional dense_dim=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7c/7c8bf3e9827b54e76494dbc304ba3a308e14be3bace3689f6047b3242e9906dd/XPUGuardImpl.h b/shared/package-files/7c/7c8bf3e9827b54e76494dbc304ba3a308e14be3bace3689f6047b3242e9906dd/XPUGuardImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..e7a6b3de9e1ba957fa74f31c013b96ad8a954ee4 --- /dev/null +++ b/shared/package-files/7c/7c8bf3e9827b54e76494dbc304ba3a308e14be3bace3689f6047b3242e9906dd/XPUGuardImpl.h @@ -0,0 +1,217 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace c10::xpu::impl { + +struct XPUGuardImpl final : public c10::impl::DeviceGuardImplInterface { + static constexpr DeviceType static_type = kXPU; + + XPUGuardImpl() = default; + + explicit XPUGuardImpl(DeviceType t) { + TORCH_INTERNAL_ASSERT(t == kXPU); + } + + DeviceType type() const override { + return kXPU; + } + + Device exchangeDevice(Device d) const override { + TORCH_INTERNAL_ASSERT(d.is_xpu()); + const auto old_device_index = c10::xpu::exchange_device(d.index()); + return Device(kXPU, old_device_index); + } + + Device getDevice() const override { + const auto device = c10::xpu::current_device(); + return Device(kXPU, device); + } + + void setDevice(Device d) const override { + TORCH_INTERNAL_ASSERT(d.is_xpu()); + c10::xpu::set_device(d.index()); + } + + void uncheckedSetDevice(Device d) const noexcept override { + c10::xpu::set_device(d.index()); + } + + Stream getStream(Device d) const override { + return getCurrentXPUStream(d.index()).unwrap(); + } + + Stream getNewStream(Device d, int priority = 0) const override { + return getStreamFromPool(priority, d.index()); + } + + Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false) + const override { + return getStreamFromPool(isHighPriority, d.index()); + } + + // NB: These do NOT set the current device + Stream exchangeStream(Stream s) const override { + const XPUStream stream(s); + const auto old_stream = getCurrentXPUStream(s.device().index()); + setCurrentXPUStream(stream); + return old_stream.unwrap(); + } + + DeviceIndex deviceCount() const noexcept override { + return c10::xpu::device_count(); + } + + // Event-related functions + void destroyEvent(void* event, const DeviceIndex device_index) + const noexcept override { + if (!event) + return; + + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_deletion( + c10::kXPU, reinterpret_cast(event)); + } + + delete reinterpret_cast(event); + } + + void record( + void** event, + const Stream& stream, + const DeviceIndex device_index, + const EventFlag flag) const override { + TORCH_CHECK( + device_index == -1 || device_index == stream.device_index(), + "Event device index ", + device_index, + " does not match recording stream's device index ", + stream.device_index(), + "."); + + auto* xpu_event = reinterpret_cast(*event); + const XPUStream xpu_stream{stream}; + + // Delete the event previously recorded. + if (xpu_event) + delete xpu_event; +#if SYCL_COMPILER_VERSION >= 20250000 + if (flag == EventFlag::BACKEND_DEFAULT) { + // Use the profiling tag to record the event to enable timing feature. + xpu_event = + new sycl::event(sycl::ext::oneapi::experimental::submit_profiling_tag( + xpu_stream.queue())); + } else { + xpu_event = + new sycl::event(xpu_stream.queue().ext_oneapi_submit_barrier()); + } +#else + xpu_event = new sycl::event(xpu_stream.queue().ext_oneapi_submit_barrier()); +#endif + *event = reinterpret_cast(xpu_event); + + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_record( + c10::kXPU, + reinterpret_cast(xpu_event), + reinterpret_cast(&xpu_stream.queue())); + } + } + + void block(void* event, const Stream& stream) const override { + if (!event) + return; + auto* xpu_event = reinterpret_cast(event); + std::vector event_list{*xpu_event}; + const XPUStream xpu_stream(stream); + xpu_stream.queue().ext_oneapi_submit_barrier(event_list); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_wait( + c10::kXPU, + reinterpret_cast(xpu_event), + reinterpret_cast(&xpu_stream.queue())); + } + } + + bool queryEvent(void* event) const override { + using namespace sycl::info; + if (!event) + return true; + auto* xpu_event = reinterpret_cast(event); + return xpu_event->get_info() == + event_command_status::complete; + } + + double elapsedTime( + void* start_event, + void* end_event, + const DeviceIndex device_index) const override { +#if SYCL_COMPILER_VERSION < 20250000 + TORCH_CHECK_NOT_IMPLEMENTED( + false, + "elapsedTime requires PyTorch to be built with SYCL compiler version 2025.0.0 or newer."); +#endif + TORCH_CHECK( + start_event && end_event, + "Both events must be recorded before calculating elapsed time."); + auto* xpu_start_event = reinterpret_cast(start_event); + auto* xpu_end_event = reinterpret_cast(end_event); + + using namespace sycl::info::event_profiling; + // Block until both of the recorded events are completed. + uint64_t end_time_ns = xpu_end_event->get_profiling_info(); + uint64_t start_time_ns = xpu_start_event->get_profiling_info(); + // Return the eplased time in milliseconds. + return 1e-6 * + (static_cast(end_time_ns) - static_cast(start_time_ns)); + } + + // Stream-related functions + bool queryStream(const Stream& stream) const override { + const XPUStream xpu_stream{stream}; + return xpu_stream.query(); + } + + void synchronizeStream(const Stream& stream) const override { + const XPUStream xpu_stream{stream}; + xpu_stream.synchronize(); + } + + void synchronizeEvent(void* event) const override { + if (!event) + return; + auto* xpu_event = reinterpret_cast(event); + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_event_synchronization( + c10::kXPU, reinterpret_cast(xpu_event)); + } + xpu_event->wait_and_throw(); + } + + void synchronizeDevice(const c10::DeviceIndex device_index) const override { + const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace(); + if (C10_UNLIKELY(interp)) { + (*interp)->trace_gpu_device_synchronization(c10::kXPU); + } + c10::xpu::syncStreamsOnDevice(device_index); + } + + void recordDataPtrOnStream(const c10::DataPtr& data_ptr, const Stream& stream) + const override { + const XPUStream xpu_stream{stream}; + XPUCachingAllocator::recordStream(data_ptr, xpu_stream); + } +}; + +} // namespace c10::xpu::impl diff --git a/shared/package-files/7c/7c92d1346e95fd3d72794b39d5da9472988766ba05d1a2acbc7d9c6864701167/api.cpython-311.pyc b/shared/package-files/7c/7c92d1346e95fd3d72794b39d5da9472988766ba05d1a2acbc7d9c6864701167/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3859730b09ec60b692704de43a5bfea8e001c1ca Binary files /dev/null and b/shared/package-files/7c/7c92d1346e95fd3d72794b39d5da9472988766ba05d1a2acbc7d9c6864701167/api.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c93ec0587c8881aa499fdf9fab01907a339092edf11b7f1b719cdea50b505c5/test_distributedmodules.cpython-311.pyc b/shared/package-files/7c/7c93ec0587c8881aa499fdf9fab01907a339092edf11b7f1b719cdea50b505c5/test_distributedmodules.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..080306240cf46e7dd6ce8fb577645176c976a157 Binary files /dev/null and b/shared/package-files/7c/7c93ec0587c8881aa499fdf9fab01907a339092edf11b7f1b719cdea50b505c5/test_distributedmodules.cpython-311.pyc differ diff --git a/shared/package-files/7c/7c9761c0afdbc26562daa0be11548fe7553c70c50221c72f721283b2ed709a81/stft_native.h b/shared/package-files/7c/7c9761c0afdbc26562daa0be11548fe7553c70c50221c72f721283b2ed709a81/stft_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c37d7cf688db25c2d1740350dbfec802ac28cec2 --- /dev/null +++ b/shared/package-files/7c/7c9761c0afdbc26562daa0be11548fe7553c70c50221c72f721283b2ed709a81/stft_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor stft(const at::Tensor & self, int64_t n_fft, ::std::optional hop_length=::std::nullopt, ::std::optional win_length=::std::nullopt, const ::std::optional & window={}, bool normalized=false, ::std::optional onesided=::std::nullopt, ::std::optional return_complex=::std::nullopt, ::std::optional align_to_window=::std::nullopt); +TORCH_API at::Tensor stft(const at::Tensor & self, int64_t n_fft, ::std::optional hop_length=::std::nullopt, ::std::optional win_length=::std::nullopt, const ::std::optional & window={}, bool center=true, c10::string_view pad_mode="reflect", bool normalized=false, ::std::optional onesided=::std::nullopt, ::std::optional return_complex=::std::nullopt, ::std::optional align_to_window=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7c98974437b841bf952cb8268f85c9f20e9bf621272ade033ea14a0ff21ee0ff/syslog.cpython-311-x86_64-linux-gnu.so b/shared/package-files/7c/7c98974437b841bf952cb8268f85c9f20e9bf621272ade033ea14a0ff21ee0ff/syslog.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..091a18f2b376de491c6d04d4bca7bb305fed82a1 Binary files /dev/null and b/shared/package-files/7c/7c98974437b841bf952cb8268f85c9f20e9bf621272ade033ea14a0ff21ee0ff/syslog.cpython-311-x86_64-linux-gnu.so differ diff --git a/shared/package-files/7c/7c989d597686a35a54946da76770c678d2ded15693de5f008fd73e3e9f312492/micro_pipeline_tp.py b/shared/package-files/7c/7c989d597686a35a54946da76770c678d2ded15693de5f008fd73e3e9f312492/micro_pipeline_tp.py new file mode 100644 index 0000000000000000000000000000000000000000..ef42a0153692e532c72ebfa820165283182e948f --- /dev/null +++ b/shared/package-files/7c/7c989d597686a35a54946da76770c678d2ded15693de5f008fd73e3e9f312492/micro_pipeline_tp.py @@ -0,0 +1,955 @@ +# mypy: allow-untyped-defs +import operator +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any, cast, Optional + +import torch +from torch.utils._ordered_set import OrderedSet + +from .. import config, inductor_prims +from ..pattern_matcher import ( + CallFunction, + Ignored, + KeywordArg, + ListOf, + Match, + MULTIPLE, + PatternExpr, + PatternMatcherPass, +) + + +aten = torch.ops.aten +patterns = PatternMatcherPass() + + +def _is_backward(graph: torch.fx.Graph) -> bool: + placeholders = [] + for node in graph.nodes: + if node.op != "placeholder": + break + placeholders.append(node) + return not all(node.name.startswith("primal") for node in placeholders) + + +def _compute_mm_arithmetic_intensity(M: int, N: int, K: int) -> float: + return M * N * K / (M * K + N * K + M * N) + + +def _filter_nodes_by_target(nodes: list[torch.fx.Node], target) -> list[torch.fx.Node]: + return [x for x in nodes if x.target == target] + + +def _find_ancestors(node: torch.fx.Node) -> OrderedSet[torch.fx.Node]: + ancestors = OrderedSet[torch.fx.Node]() + ancestors.add(node) + cur_nodes = [node] + while len(cur_nodes) > 0: + new_nodes = [] + for node in cur_nodes: + for inp in node.all_input_nodes: + if inp not in ancestors: + ancestors.add(inp) + new_nodes.append(inp) + cur_nodes = new_nodes + return OrderedSet(node for node in ancestors if node.op != "placeholder") + + +def _get_tensor(node: torch.fx.Node) -> torch.Tensor: + val = node.meta["val"] + assert isinstance(val, torch.Tensor) + return val + + +@dataclass +class _AllGatherMatch: + match: Match + shard_node: torch.fx.Node + ag_node: torch.fx.Node + res_node: torch.fx.Node + gather_dim: int + group_name: str + + def replace_with(self, new_node: torch.fx.Node) -> None: + self.res_node.replace_all_uses_with(new_node) + + def erase(self) -> None: + for node in reversed(self.match.nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + +def find_all_gather_patterns(graph: torch.fx.Graph): + c10d = torch.ops._c10d_functional + + def make_zero_dim_all_gather_pattern(shard): + return CallFunction( + c10d.wait_tensor.default, + CallFunction( + c10d.all_gather_into_tensor.default, + shard, + Ignored(), + KeywordArg("group_name"), + ), + ) + + # Matches funcol.all_gather_tensor with gather_dim == 0 + zero_dim_all_gather_pattern = make_zero_dim_all_gather_pattern(KeywordArg("shard")) + + def make_all_gather_split_pattern(shard): + return CallFunction( + operator.getitem, + CallFunction( + aten.split.Tensor, + make_zero_dim_all_gather_pattern(shard), + Ignored(), + _users=MULTIPLE, + ), + Ignored(), + ) + + def make_cat_pattern(splits): + return CallFunction( + aten.cat.default, + ListOf(splits), + KeywordArg("gather_dim"), + ) + + # Matches funcol.all_gather_tensor with gather_dim > 0 + non_zero_dim_all_gather_pattern = make_cat_pattern( + make_all_gather_split_pattern(KeywordArg("shard")), + ) + + # Match a zero-dim all-gather in which the data is transferred as uint8 and + # viewed back as the original dtype. + zero_dim_type_erased_all_gather_pattern = CallFunction( + aten.view.dtype, + make_zero_dim_all_gather_pattern( + KeywordArg("shard"), + ), + Ignored(), + ) + + # Match a non-zero dim all-gather in which the data is transferred as uint8 + # and viewed back as the original dtype. + non_zero_dim_type_erased_all_gather_pattern = CallFunction( + aten.view.dtype, + make_cat_pattern( + CallFunction( + aten.view.dtype, + make_all_gather_split_pattern( + KeywordArg("shard"), + ), + Ignored(), + ), + ), + Ignored(), + ) + + # If two patterns with the same res_node_target have the same suffix, the + # longer pattern should appear first in the list. + # e.g. supposed we have (1) A -> B -> C -> D and (2) B -> C -> D, (1) + # should appear before (2) in the list. + res_node_target_to_patterns = { + aten.cat.default: [ + (non_zero_dim_all_gather_pattern, 0), + ], + aten.view.dtype: [ + (non_zero_dim_type_erased_all_gather_pattern, 0), + (zero_dim_type_erased_all_gather_pattern, 0), + ], + c10d.wait_tensor.default: [ + (zero_dim_all_gather_pattern, 0), + ], + } + + # Match in reverse to ensure longer patterns is prioritized + all_gathers = [] + visited_ag_nodes = OrderedSet[torch.fx.Node]() + for node in reversed(graph.nodes): + for target, patterns in res_node_target_to_patterns.items(): + if node.target != target: + continue + for pattern, ag_node_idx in patterns: + match = pattern.match(node) + if not match: + continue + + assert isinstance(match, Match) + ag_node = match.nodes[ag_node_idx] + assert ag_node.target == c10d.all_gather_into_tensor.default + + if ag_node in visited_ag_nodes: + continue + visited_ag_nodes.add(ag_node) + + ag_match = _AllGatherMatch( + match=match, + shard_node=match.kwargs["shard"], + ag_node=ag_node, + res_node=node, + gather_dim=match.kwargs.get("gather_dim", 0), + group_name=match.kwargs["group_name"], + ) + all_gathers.append(ag_match) + + return list(reversed(all_gathers)) + + +@dataclass +class _ReduceScatterMatch: + match: Match + input_node: torch.fx.Node + rs_node: torch.fx.Node + res_node: torch.fx.Node + reduce_op: str + scatter_dim: int + group_name: str + + def replace_with(self, new_node: torch.fx.Node) -> None: + self.res_node.replace_all_uses_with(new_node) + + def erase(self) -> None: + for node in reversed(self.match.nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + +def find_reduce_scatter_patterns(graph: torch.fx.Graph): + c10d = torch.ops._c10d_functional + + def reduce_scatter_template(inp: PatternExpr): + return CallFunction( + c10d.wait_tensor.default, + CallFunction( + c10d.reduce_scatter_tensor.default, + inp, + KeywordArg("reduce_op"), + Ignored(), + KeywordArg("group_name"), + ), + ) + + # Matches funcol.reduce_scatter_tensor with scatter_dim == 0 + zero_dim_reduce_scatter_pattern = reduce_scatter_template(KeywordArg("input")) + + # Matches funcol.reduce_scatter_tensor with scatter_dim > 0 + non_zero_dim_reduce_scatter_pattern = reduce_scatter_template( + CallFunction( + aten.cat.default, + ListOf( + CallFunction( + operator.getitem, + CallFunction( + aten.split.Tensor, + KeywordArg("input"), + Ignored(), + KeywordArg("scatter_dim"), + _users=MULTIPLE, + ), + Ignored(), + ) + ), + ), + ) + + reduce_scatters = [] + for node in reversed(graph.nodes): + if node.target == c10d.wait_tensor.default: + if match := non_zero_dim_reduce_scatter_pattern.match(node): + assert isinstance(match, Match) + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + rs_node=match.nodes[-2], + res_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=match.kwargs["scatter_dim"], + group_name=match.kwargs["group_name"], + ) + ) + elif match := zero_dim_reduce_scatter_pattern.match(node): + assert isinstance(match, Match) + reduce_scatters.append( + _ReduceScatterMatch( + match=match, + input_node=match.kwargs["input"], + rs_node=match.nodes[0], + res_node=node, + reduce_op=match.kwargs["reduce_op"], + scatter_dim=0, + group_name=match.kwargs["group_name"], + ) + ) + return list(reversed(reduce_scatters)) + + +@dataclass +class _Matmul: + nodes: list[torch.fx.Node] + arg_ancestor_nodes: OrderedSet[torch.fx.Node] = field(init=False) + A_node: torch.fx.Node + B_node: torch.fx.Node + + def __post_init__(self): + assert len(self.nodes) in (1, 3) + if len(self.nodes) == 1: + assert self.nodes[0].target in (aten.mm.default, aten._scaled_mm.default) + else: + assert self.nodes[0].target == aten.reshape.default + assert self.nodes[1].target in (aten.mm.default, aten._scaled_mm.default) + assert self.nodes[2].target == aten.reshape.default + self.arg_ancestor_nodes = _find_ancestors(self.B_node) + + def replace_with(self, new_node: torch.fx.Node) -> None: + """ + Replace the matmul with the new node. + """ + graph = new_node.graph + + # For 2D-matmuls, we simply replace the mm node with `new_node`. + if len(self.nodes) == 1: + mm_node = self.nodes[0] + assert mm_node.target in (aten.mm.default, aten._scaled_mm.default) + mm_node.replace_all_uses_with(new_node) + graph.erase_node(mm_node) + return + + # An ND-matmul is reshape -> mm -> reshape sequence. We first replace + # the second reshape node with `new_node`. Then, we ensure that the + # original mm node in the sequence ends up with zero users by replacing + # it with a reverse reshape of `new_node`. + graph = new_node.graph + assert len(self.nodes) == 3 + mm_node = self.nodes[1] + output_reshape_node = self.nodes[2] + + assert mm_node.target in (aten.mm.default, aten._scaled_mm.default) + assert output_reshape_node.target == aten.reshape.default + + output_reshape_node.replace_all_uses_with(new_node) + if len(mm_node.users) > 1: + with graph.inserting_after(new_node): + new_mm_node = graph.call_function( + aten.reshape.default, + args=(new_node, list(_get_tensor(mm_node).shape)), + ) + mm_node.replace_all_uses_with(new_mm_node) + + def erase(self) -> None: + for node in reversed(self.nodes): + if len(node.users) == 0: + node.graph.erase_node(node) + + @classmethod + def from_match(cls, match: list[torch.fx.Node]) -> "_Matmul": + assert len(match) in (1, 3) + assert match[0].target in ( + aten.mm.default, + aten.reshape.default, + ) + mm_node = match[0] if len(match) == 1 else match[1] + return _Matmul( + nodes=match, + A_node=cast(torch.fx.Node, match[0].args[0]), + B_node=cast(torch.fx.Node, mm_node.args[1]), + ) + + +@dataclass +class _ScaledMatmul(_Matmul): + A_scale_node: torch.fx.Node + B_scale_node: torch.fx.Node + bias_node: Optional[torch.fx.Node] + result_scale_node: Optional[torch.fx.Node] + out_dtype: Optional[torch.dtype] + use_fast_accum: bool + + def __post_init__(self): + super().__post_init__() + self.arg_ancestor_nodes |= _find_ancestors(self.A_scale_node) + self.arg_ancestor_nodes |= _find_ancestors(self.B_scale_node) + + @classmethod + def from_match(cls, match: list[torch.fx.Node]) -> "_ScaledMatmul": + assert len(match) in (1, 3) + assert match[0].target in ( + aten._scaled_mm.default, + aten.reshape.default, + ) + mm_node = match[0] if len(match) == 1 else match[1] + + def get_arg(node: torch.fx.Node, idx: int, default: Any) -> Any: + if idx >= len(node.args): + return default + return node.args[idx] + + def insert_reshape_op(node: torch.fx.Node): + """ + Given a reciprocal node with a parent reshape node, + insert a reshape node after the reciprocal node which reshapes + the reciprocal output back to the original shape before the first reshape. + + Before: + reshape (a,bc,) to (a*b,c) -> reciprocal + + After: + reshape (a,bc,) to (a*b,c) -> reciprocal -> reshape (a*b,c) to (a,b,c) + + Returns the new reshape node. + """ + # ensure the given node matches the pattern described in the docstring + assert node.target == aten.reciprocal.default, ( + "Node must be a aten.reciprocal.default op" + ) + assert len(node.all_input_nodes) == 1, "Node must have exactly one parent" + + parent_node = node.all_input_nodes[0] + assert parent_node.target == aten.reshape.default, ( + "Parent node must be a aten.reshape.default op" + ) + assert len(parent_node.all_input_nodes) == 1, ( + "Parent node must have exactly one input node" + ) + + parent_input_node = parent_node.all_input_nodes[0] + parent_input_shape = list(_get_tensor(parent_input_node).shape) + + # insert reshape back to shape from before the parent reshape op + graph = node.graph + with graph.inserting_after(node): + reshape_node = graph.call_function( + aten.reshape.default, (node, parent_input_shape) + ) + + # ensure all users of original node (except the reshape node) now use the reshaped node instead + node_users = list(node.users) + for user in node_users: + if user != reshape_node: + user.replace_input_with(node, reshape_node) + + return reshape_node + + is_reshape_mm_reshape_pattern = match[0].target == aten.reshape.default + mm_node = match[1] if is_reshape_mm_reshape_pattern else match[0] + + # `A_node` is pulled directly from match rather than `mm_node` because it needs to handle + # both of the following cases: + # + # Case 1: single node match (mm): + # - match[0].args[0] will be the "A tensor" node of scaled_mm + # - Has 2D shape + # + # Case 2: 3 node match (reshape -> mm -> reshape) + # - match[0].args[0] will be the "A tensor" input to the reshape op + # - Has 3D+ shape + A_node = cast(torch.fx.Node, match[0].args[0]) + B_node = cast(torch.fx.Node, mm_node.args[1]) + A_scale_node = cast(torch.fx.Node, mm_node.args[2]) + B_scale_node = cast(torch.fx.Node, mm_node.args[3]) + + A_ndim = _get_tensor(A_node).ndim + A_scale_ndim = _get_tensor(A_scale_node).ndim + is_reciprocal_with_reshape_parent = ( + A_scale_node.target == aten.reciprocal.default + and len(A_scale_node.all_input_nodes) == 1 + and A_scale_node.all_input_nodes[0].target == aten.reshape.default + ) + is_tensorwise_scaling = A_scale_ndim <= 1 + + # This is a temporary workaround to handle the reshape -> scaled_mm -> reshape + # pattern when scales are row-wise, and have been reshaped along with the target + # tensor. See https://github.com/pytorch/pytorch/pull/148001 for details. + # + # If tensor dim does not match scale dim, check if the scale node follows + # the "reshape -> reciprocal" pattern. If so, we can insert a reshape op after + # the reciprocal, to reshape the reciprocal back to the original shape before + # the first reshape op. + # + # TODO: remove this workaround once torch._scaled_matmul exists and can be used + # to implement a more robust long-term support for 3D+ scaled matmuls. + if ( + is_reshape_mm_reshape_pattern + and A_ndim != A_scale_ndim + and not is_tensorwise_scaling + and is_reciprocal_with_reshape_parent + ): + A_scale_node = insert_reshape_op(A_scale_node) + + return _ScaledMatmul( + nodes=match, + A_node=A_node, + B_node=B_node, + A_scale_node=A_scale_node, + B_scale_node=B_scale_node, + bias_node=get_arg(mm_node, 4, None), + result_scale_node=get_arg(mm_node, 5, None), + out_dtype=get_arg(mm_node, 6, None), + use_fast_accum=get_arg(mm_node, 7, False), + ) + + +def _find_reshape_mm_reshape(node: torch.fx.Node) -> list[_Matmul]: + if node.target != aten.reshape.default: + return [] + + matches = [] + for mm_node in node.users: + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + continue + for reshape_node in mm_node.users: + if reshape_node.target != aten.reshape.default: + continue + + # Since the reshape -> mm -> reshape pattern would be subsumed into + # the fused op, we only match the patterns where the shape of the + # second reshape is matches the mm result produced by the fused op. + matmul_input_node = cast(torch.fx.Node, node.args[0]) + B_node = cast(torch.fx.Node, mm_node.args[1]) + matmul_out_shape = torch.Size( + [ + *_get_tensor(matmul_input_node).shape[:-1], + _get_tensor(B_node).shape[-1], + ] + ) + if _get_tensor(reshape_node).shape != matmul_out_shape: + continue + matches.append([node, mm_node, reshape_node]) + # If for some rare reason mm_node is being reshaped by two + # different reshape nodes, we only include mm_node once in the + # parsing result. + break + + matmuls = [] + for match in matches: + mm_node = match[1] + if mm_node.target == aten.mm.default: + matmul = _Matmul.from_match(match) + matmuls.append(matmul) + elif mm_node.target == aten._scaled_mm.default: + matmul = _ScaledMatmul.from_match(match) + matmuls.append(matmul) + else: + raise AssertionError( + "Expect the node's target to be either aten.mm.default or " + f"aten._scaled_mm.default. Got {mm_node.target}." + ) + return matmuls + + +def _find_consumer_matmuls(node: torch.fx.Node) -> list[_Matmul]: + """ + Find the matmuls that use `node` as the lhs argument. + """ + matmuls = [] + for user in node.users: + # ND matmuls + if user.target == aten.reshape.default: + matmuls.extend(_find_reshape_mm_reshape(user)) + # 2D matmuls + elif user.target == aten.mm.default: + matmul = _Matmul.from_match(match=[user]) + matmuls.append(matmul) + elif user.target == aten._scaled_mm.default: + matmul = _ScaledMatmul.from_match([user]) + matmuls.append(matmul) + return matmuls + + +def _insert_fused_all_gather_matmul( + graph: torch.fx.Graph, + matmuls: list[_Matmul], + shard_node: torch.fx.Node, + gather_dim: int, + group_name: str, +) -> torch.fx.Node: + mm_types = OrderedSet(map(type, matmuls)) + assert len(mm_types) == 1 + mm_type = next(iter(mm_types)) + if mm_type == _Matmul: + B_nodes = [matmul.B_node for matmul in matmuls] + return graph.call_function( + torch.ops.symm_mem.fused_all_gather_matmul.default, + args=(shard_node, B_nodes, gather_dim, group_name), + kwargs={"return_A": True}, + ) + elif mm_type == _ScaledMatmul: + scaled_matmuls = cast(list[_ScaledMatmul], matmuls) + return graph.call_function( + torch.ops.symm_mem.fused_all_gather_scaled_matmul.default, + args=( + shard_node, + [matmul.B_node for matmul in scaled_matmuls], + scaled_matmuls[0].A_scale_node, + [matmul.B_scale_node for matmul in scaled_matmuls], + gather_dim, + group_name, + [matmul.bias_node for matmul in scaled_matmuls], + [matmul.result_scale_node for matmul in scaled_matmuls], + [matmul.out_dtype for matmul in scaled_matmuls], + [matmul.use_fast_accum for matmul in scaled_matmuls], + ), + ) + else: + raise AssertionError(f"Unexpected matmul match type: {mm_type}") + + +def fuse_all_gather_matmul(all_gather: _AllGatherMatch) -> None: + """ + Fused the pattern + + A = all_gather_tensor(A_shard, gather_dim, group_name) + C_0 = torch.matmul(A, B_0) + C_1 = torch.matmul(A, B_1) + C_2 = torch.matmul(A, B_2) + ... + + into + + A, Cs = torch.ops.symm_mem.fused_all_gather_matmul( + A_shard, [B_0, B_1, B_2, ...], gather_dim, group_name, + ) + """ + if ( + not torch.distributed.is_available() + or not torch.distributed.is_nccl_available() + ): + return + + from torch.distributed._symmetric_memory import ( + is_symm_mem_enabled_for_group, + restride_A_shard_for_fused_all_gather_matmul, + ) + + shard_node, ag_node, ag_res_node, gather_dim, group_name = ( + all_gather.shard_node, + all_gather.ag_node, + all_gather.res_node, + all_gather.gather_dim, + all_gather.group_name, + ) + + if not is_symm_mem_enabled_for_group(group_name): + return + + if gather_dim >= len(_get_tensor(shard_node).shape) - 1: + # Decomposing the matmul on the K dimension is not supported + return + + # Find consumer matmuls + matmuls = _find_consumer_matmuls(ag_res_node) + + # The matmuls are only fusible if non-A args don't depend on the all-gather + # result node + matmuls = [ + matmul + for matmul in matmuls + if all_gather.res_node not in matmul.arg_ancestor_nodes + ] + + if len(matmuls) == 0 or len(OrderedSet(map(type, matmuls))) != 1: + return + + # Fuse the all_gather_tensor with the eligible matmuls + graph = ag_node.graph + with graph.inserting_before(ag_node): + if "val" in shard_node.meta: + restrided = restride_A_shard_for_fused_all_gather_matmul( + _get_tensor(shard_node), + gather_dim, + ) + shard_node = graph.call_function( + inductor_prims.force_stride_order, + args=(shard_node, restrided.stride()), + ) + + fused_node = _insert_fused_all_gather_matmul( + graph, matmuls, shard_node, gather_dim, group_name + ) + new_ag_node = graph.call_function( + operator.getitem, + args=(fused_node, 0), + ) + new_out_nodes = graph.call_function( + operator.getitem, + args=(fused_node, 1), + ) + for idx, matmul in enumerate(matmuls): + new_out_node = graph.call_function( + operator.getitem, + args=(new_out_nodes, idx), + ) + matmul.replace_with(new_out_node) + matmul.erase() + all_gather.replace_with(new_ag_node) + all_gather.erase() + + # If the new_ag_node has no users, we tell the fused op to not return + # it. This creates more optimization opportunities. + if len(new_ag_node.users) == 0: + graph.erase_node(new_ag_node) + kwargs = dict(fused_node.kwargs) + if "return_A" in kwargs: + kwargs["return_A"] = False + fused_node.kwargs = kwargs + + # Raise ancestors of non-A args that are topologically ordered between + # ag_res_node and the matmul above fused_node. + order = {node: idx for idx, node in enumerate(graph.nodes)} + nodes_to_raise = sorted( + OrderedSet(x for matmul in matmuls for x in matmul.arg_ancestor_nodes), + key=lambda x: order[x], + ) + for node in nodes_to_raise: + if order[node] > order[fused_node]: + fused_node.prepend(node) + + +def _find_producer_matmul(node: torch.fx.Node) -> Optional[_Matmul]: + if node.target == aten.mm.default: + return _Matmul.from_match(match=[node]) + elif node.target == aten._scaled_mm.default: + return _ScaledMatmul.from_match(match=[node]) + elif node.target == aten.reshape.default: + reshape_node_1 = node + + mm_node = reshape_node_1.args[0] + assert isinstance(mm_node, torch.fx.Node) + if mm_node.target not in (aten.mm.default, aten._scaled_mm.default): + return None + + reshape_node_0 = mm_node.args[0] + assert isinstance(reshape_node_0, torch.fx.Node) + if reshape_node_0.target != aten.reshape.default: + return None + + if mm_node.target == aten.mm.default: + return _Matmul.from_match(match=[reshape_node_0, mm_node, reshape_node_1]) + elif mm_node.target == aten._scaled_mm.default: + return _ScaledMatmul.from_match( + match=[reshape_node_0, mm_node, reshape_node_1] + ) + return None + + +def _insert_fused_matmul_reduce_scatter( + graph: torch.fx.Graph, + matmul: _Matmul, + reduce_op: str, + scatter_dim: int, + group_name: str, +) -> torch.fx.Node: + if type(matmul) == _Matmul: + return graph.call_function( + torch.ops.symm_mem.fused_matmul_reduce_scatter.default, + args=(matmul.A_node, matmul.B_node, reduce_op, scatter_dim, group_name), + ) + elif type(matmul) == _ScaledMatmul: + return graph.call_function( + torch.ops.symm_mem.fused_scaled_matmul_reduce_scatter.default, + args=( + matmul.A_node, + matmul.B_node, + matmul.A_scale_node, + matmul.B_scale_node, + reduce_op, + scatter_dim, + group_name, + matmul.bias_node, + matmul.result_scale_node, + matmul.out_dtype, + matmul.use_fast_accum, + ), + ) + else: + raise AssertionError(f"Unexpected matmul match type: {type(matmul)}") + + +def fuse_matmul_reduce_scatter(reduce_scatter: _ReduceScatterMatch) -> None: + """ + Fused the pattern + + reduce_scatter_tensor(A @ B, scatter_dim, group_name) + + into + + torch.ops.symm_mem.fused_matmul_reduce_scatter( + A, B, scatter_dim, group_name, + ) + """ + if ( + not torch.distributed.is_available() + or not torch.distributed.is_nccl_available() + ): + return + + from torch.distributed._symmetric_memory import ( + is_symm_mem_enabled_for_group, + restride_A_for_fused_matmul_reduce_scatter, + ) + + input_node, _rs_node, rs_res_node, reduce_op, scatter_dim, group_name = ( + reduce_scatter.input_node, + reduce_scatter.rs_node, + reduce_scatter.res_node, + reduce_scatter.reduce_op, + reduce_scatter.scatter_dim, + reduce_scatter.group_name, + ) + + if not is_symm_mem_enabled_for_group(group_name): + return + + # Currently fused_matmul_reduce_scatter doesn't return the matmul result, + # so we can't apply the fusion if the matmul result is used by multiple + # users. This is not a fundamental limitation of the fused op and can be + # addressed if needed. + if len(input_node.users) != 1: + return + + matmul = _find_producer_matmul(input_node) + if matmul is None: + return + + if rs_res_node in matmul.arg_ancestor_nodes: + return + + graph = rs_res_node.graph + with graph.inserting_before(rs_res_node): + if "val" in matmul.A_node.meta: + restrided = restride_A_for_fused_matmul_reduce_scatter( + _get_tensor(matmul.A_node), + scatter_dim, + ) + matmul.A_node = graph.call_function( + inductor_prims.force_stride_order, + args=(matmul.A_node, restrided.stride()), + ) + + fused_node = _insert_fused_matmul_reduce_scatter( + graph, + matmul, + reduce_op, + scatter_dim, + group_name, + ) + reduce_scatter.replace_with(fused_node) + reduce_scatter.erase() + matmul.erase() + + order = {node: idx for idx, node in enumerate(graph.nodes)} + nodes_to_raise = sorted( + matmul.arg_ancestor_nodes, + key=lambda x: order[x], + ) + for node in nodes_to_raise: + if order[node] > order[fused_node]: + fused_node.prepend(node) + + +def _get_node_to_ancestors( + graph: torch.fx.Graph, +) -> dict[torch.fx.Node, OrderedSet[torch.fx.Node]]: + """ + Compute the ancestors for all nodes in a graph. + """ + node_to_ancestors = defaultdict(OrderedSet[torch.fx.Node]) # type: ignore[var-annotated] + for node in graph.nodes: + node_to_ancestors[node] = OrderedSet(node.all_input_nodes) + for dep in node.all_input_nodes: + node_to_ancestors[node] |= node_to_ancestors[dep] + + return node_to_ancestors + + +def _get_collective_to_overlappable_nodes( + graph: torch.fx.Graph, +) -> dict[torch.fx.Node, list[torch.fx.Node]]: + """ + For each collective in the graph, find nodes that are neither ancestors nor + descendants of the collective. + """ + + def is_collective(node) -> bool: + # Only consider all-gather and reduce-scatter in the context of + # micro-pipeline TP. + return node.target in [ + torch.ops._c10d_functional.all_gather_into_tensor.default, + torch.ops._c10d_functional.reduce_scatter_tensor.default, + ] + + node_to_ancestors = _get_node_to_ancestors(graph) + collective_to_overlappable_nodes = defaultdict(list) + for node in graph.nodes: + if not is_collective(node): + continue + for x in graph.nodes: + if ( + node not in node_to_ancestors[x] + and x not in node_to_ancestors[node] + and x.op == "call_function" + ): + collective_to_overlappable_nodes[node].append(x) + + return collective_to_overlappable_nodes + + +def _get_unexposed_collectives(graph: torch.fx.Graph) -> list[torch.fx.Node]: + """ + Find all unexposed collectives in the graph. + + Because we don't have the runtime estimate, this function is a rough + estimation using the following strong/hand-wavy assumptions: + + - Only a predefined set of "compute intensive" operation can hide a collective. + - Any "compute intensive" operation can hide exactly one collective. + """ + + def _is_compute_intensive(node: torch.fx.Node) -> bool: + return node.target in [torch.ops.aten.mm.default] + + collective_to_overlapping_candidates = defaultdict(list) + available_nodes = OrderedSet[torch.fx.Node]() + collective_to_overlappable_nodes = _get_collective_to_overlappable_nodes(graph) + for collective, overlappable_nodes in collective_to_overlappable_nodes.items(): + candidates = [x for x in overlappable_nodes if _is_compute_intensive(x)] + collective_to_overlapping_candidates[collective] = candidates + available_nodes.update(candidates) + + unexposed_collectives = [] + for ( + collective, + overlapping_candidates, + ) in collective_to_overlapping_candidates.items(): + # Each collective consumes exactly one overlapping candidate + for x in overlapping_candidates: + if x in available_nodes: + unexposed_collectives.append(collective) + available_nodes.remove(x) + break + return unexposed_collectives + + +def micro_pipeline_tp_pass(graph: torch.fx.Graph): + all_gathers = find_all_gather_patterns(graph) + reduce_scatters = find_reduce_scatter_patterns(graph) + + # When a collective can be hidden through either simple overlapping or + # micro-pipeline TP, we prefer simple overlapping to avoid the overhead + # associated with decomposition. If reorder_for_compute_comm_overlap is + # enabled, we identify collectives that can be hidden through simple + # overlapping and exclude them from micro-pipeline TP candidates. + if config.reorder_for_compute_comm_overlap: + unexposed_collectives = _get_unexposed_collectives(graph) + all_gathers = [x for x in all_gathers if x.ag_node not in unexposed_collectives] + reduce_scatters = [ + x for x in reduce_scatters if x.rs_node not in unexposed_collectives + ] + + for all_gather in all_gathers: + fuse_all_gather_matmul(all_gather) + + for reduce_scatter in reduce_scatters: + fuse_matmul_reduce_scatter(reduce_scatter) diff --git a/shared/package-files/7c/7c9a59da1b351a226a092b1e1671cf9935255f2c22d593a138c8938dec7e399e/_bootstrap_external.py b/shared/package-files/7c/7c9a59da1b351a226a092b1e1671cf9935255f2c22d593a138c8938dec7e399e/_bootstrap_external.py new file mode 100644 index 0000000000000000000000000000000000000000..e53f6acf38fc642f79a744f46d70b8b289ca7be0 --- /dev/null +++ b/shared/package-files/7c/7c9a59da1b351a226a092b1e1671cf9935255f2c22d593a138c8938dec7e399e/_bootstrap_external.py @@ -0,0 +1,1757 @@ +"""Core implementation of path-based import. + +This module is NOT meant to be directly imported! It has been designed such +that it can be bootstrapped into Python as the implementation of import. As +such it requires the injection of specific modules and attributes in order to +work. One should use importlib as the public-facing version of this module. + +""" +# IMPORTANT: Whenever making changes to this module, be sure to run a top-level +# `make regen-importlib` followed by `make` in order to get the frozen version +# of the module updated. Not doing so will result in the Makefile to fail for +# all others who don't have a ./python around to freeze the module in the early +# stages of compilation. +# + +# See importlib._setup() for what is injected into the global namespace. + +# When editing this code be aware that code executed at import time CANNOT +# reference any injected objects! This includes not only global code but also +# anything specified at the class level. + +# Module injected manually by _set_bootstrap_module() +_bootstrap = None + +# Import builtin modules +import _imp +import _io +import sys +import _warnings +import marshal + + +_MS_WINDOWS = (sys.platform == 'win32') +if _MS_WINDOWS: + import nt as _os + import winreg +else: + import posix as _os + + +if _MS_WINDOWS: + path_separators = ['\\', '/'] +else: + path_separators = ['/'] +# Assumption made in _path_join() +assert all(len(sep) == 1 for sep in path_separators) +path_sep = path_separators[0] +path_sep_tuple = tuple(path_separators) +path_separators = ''.join(path_separators) +_pathseps_with_colon = {f':{s}' for s in path_separators} + + +# Bootstrap-related code ###################################################### +_CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win', +_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin' +_CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY + + _CASE_INSENSITIVE_PLATFORMS_STR_KEY) + + +def _make_relax_case(): + if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS): + if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY): + key = 'PYTHONCASEOK' + else: + key = b'PYTHONCASEOK' + + def _relax_case(): + """True if filenames must be checked case-insensitively and ignore environment flags are not set.""" + return not sys.flags.ignore_environment and key in _os.environ + else: + def _relax_case(): + """True if filenames must be checked case-insensitively.""" + return False + return _relax_case + +_relax_case = _make_relax_case() + + +def _pack_uint32(x): + """Convert a 32-bit integer to little-endian.""" + return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little') + + +def _unpack_uint32(data): + """Convert 4 bytes in little-endian to an integer.""" + assert len(data) == 4 + return int.from_bytes(data, 'little') + +def _unpack_uint16(data): + """Convert 2 bytes in little-endian to an integer.""" + assert len(data) == 2 + return int.from_bytes(data, 'little') + + +if _MS_WINDOWS: + def _path_join(*path_parts): + """Replacement for os.path.join().""" + if not path_parts: + return "" + if len(path_parts) == 1: + return path_parts[0] + root = "" + path = [] + for new_root, tail in map(_os._path_splitroot, path_parts): + if new_root.startswith(path_sep_tuple) or new_root.endswith(path_sep_tuple): + root = new_root.rstrip(path_separators) or root + path = [path_sep + tail] + elif new_root.endswith(':'): + if root.casefold() != new_root.casefold(): + # Drive relative paths have to be resolved by the OS, so we reset the + # tail but do not add a path_sep prefix. + root = new_root + path = [tail] + else: + path.append(tail) + else: + root = new_root or root + path.append(tail) + path = [p.rstrip(path_separators) for p in path if p] + if len(path) == 1 and not path[0]: + # Avoid losing the root's trailing separator when joining with nothing + return root + path_sep + return root + path_sep.join(path) + +else: + def _path_join(*path_parts): + """Replacement for os.path.join().""" + return path_sep.join([part.rstrip(path_separators) + for part in path_parts if part]) + + +def _path_split(path): + """Replacement for os.path.split().""" + i = max(path.rfind(p) for p in path_separators) + if i < 0: + return '', path + return path[:i], path[i + 1:] + + +def _path_stat(path): + """Stat the path. + + Made a separate function to make it easier to override in experiments + (e.g. cache stat results). + + """ + return _os.stat(path) + + +def _path_is_mode_type(path, mode): + """Test whether the path is the specified mode type.""" + try: + stat_info = _path_stat(path) + except OSError: + return False + return (stat_info.st_mode & 0o170000) == mode + + +def _path_isfile(path): + """Replacement for os.path.isfile.""" + return _path_is_mode_type(path, 0o100000) + + +def _path_isdir(path): + """Replacement for os.path.isdir.""" + if not path: + path = _os.getcwd() + return _path_is_mode_type(path, 0o040000) + + +if _MS_WINDOWS: + def _path_isabs(path): + """Replacement for os.path.isabs.""" + if not path: + return False + root = _os._path_splitroot(path)[0].replace('/', '\\') + return len(root) > 1 and (root.startswith('\\\\') or root.endswith('\\')) + +else: + def _path_isabs(path): + """Replacement for os.path.isabs.""" + return path.startswith(path_separators) + + +def _write_atomic(path, data, mode=0o666): + """Best-effort function to write data to a path atomically. + Be prepared to handle a FileExistsError if concurrent writing of the + temporary file is attempted.""" + # id() is used to generate a pseudo-random filename. + path_tmp = '{}.{}'.format(path, id(path)) + fd = _os.open(path_tmp, + _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666) + try: + # We first write data to a temporary file, and then use os.replace() to + # perform an atomic rename. + with _io.FileIO(fd, 'wb') as file: + file.write(data) + _os.replace(path_tmp, path) + except OSError: + try: + _os.unlink(path_tmp) + except OSError: + pass + raise + + +_code_type = type(_write_atomic.__code__) + + +# Finder/loader utility code ############################################### + +# Magic word to reject .pyc files generated by other Python versions. +# It should change for each incompatible change to the bytecode. +# +# The value of CR and LF is incorporated so if you ever read or write +# a .pyc file in text mode the magic number will be wrong; also, the +# Apple MPW compiler swaps their values, botching string constants. +# +# There were a variety of old schemes for setting the magic number. +# The current working scheme is to increment the previous value by +# 10. +# +# Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic +# number also includes a new "magic tag", i.e. a human readable string used +# to represent the magic number in __pycache__ directories. When you change +# the magic number, you must also set a new unique magic tag. Generally this +# can be named after the Python major version of the magic number bump, but +# it can really be anything, as long as it's different than anything else +# that's come before. The tags are included in the following table, starting +# with Python 3.2a0. +# +# Known values: +# Python 1.5: 20121 +# Python 1.5.1: 20121 +# Python 1.5.2: 20121 +# Python 1.6: 50428 +# Python 2.0: 50823 +# Python 2.0.1: 50823 +# Python 2.1: 60202 +# Python 2.1.1: 60202 +# Python 2.1.2: 60202 +# Python 2.2: 60717 +# Python 2.3a0: 62011 +# Python 2.3a0: 62021 +# Python 2.3a0: 62011 (!) +# Python 2.4a0: 62041 +# Python 2.4a3: 62051 +# Python 2.4b1: 62061 +# Python 2.5a0: 62071 +# Python 2.5a0: 62081 (ast-branch) +# Python 2.5a0: 62091 (with) +# Python 2.5a0: 62092 (changed WITH_CLEANUP opcode) +# Python 2.5b3: 62101 (fix wrong code: for x, in ...) +# Python 2.5b3: 62111 (fix wrong code: x += yield) +# Python 2.5c1: 62121 (fix wrong lnotab with for loops and +# storing constants that should have been removed) +# Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp) +# Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode) +# Python 2.6a1: 62161 (WITH_CLEANUP optimization) +# Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND) +# Python 2.7a0: 62181 (optimize conditional branches: +# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE) +# Python 2.7a0 62191 (introduce SETUP_WITH) +# Python 2.7a0 62201 (introduce BUILD_SET) +# Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD) +# Python 3000: 3000 +# 3010 (removed UNARY_CONVERT) +# 3020 (added BUILD_SET) +# 3030 (added keyword-only parameters) +# 3040 (added signature annotations) +# 3050 (print becomes a function) +# 3060 (PEP 3115 metaclass syntax) +# 3061 (string literals become unicode) +# 3071 (PEP 3109 raise changes) +# 3081 (PEP 3137 make __file__ and __name__ unicode) +# 3091 (kill str8 interning) +# 3101 (merge from 2.6a0, see 62151) +# 3103 (__file__ points to source file) +# Python 3.0a4: 3111 (WITH_CLEANUP optimization). +# Python 3.0b1: 3131 (lexical exception stacking, including POP_EXCEPT + #3021) +# Python 3.1a1: 3141 (optimize list, set and dict comprehensions: +# change LIST_APPEND and SET_ADD, add MAP_ADD #2183) +# Python 3.1a1: 3151 (optimize conditional branches: +# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE + #4715) +# Python 3.2a1: 3160 (add SETUP_WITH #6101) +# tag: cpython-32 +# Python 3.2a2: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR #9225) +# tag: cpython-32 +# Python 3.2a3 3180 (add DELETE_DEREF #4617) +# Python 3.3a1 3190 (__class__ super closure changed) +# Python 3.3a1 3200 (PEP 3155 __qualname__ added #13448) +# Python 3.3a1 3210 (added size modulo 2**32 to the pyc header #13645) +# Python 3.3a2 3220 (changed PEP 380 implementation #14230) +# Python 3.3a4 3230 (revert changes to implicit __class__ closure #14857) +# Python 3.4a1 3250 (evaluate positional default arguments before +# keyword-only defaults #16967) +# Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override +# free vars #17853) +# Python 3.4a1 3270 (various tweaks to the __class__ closure #12370) +# Python 3.4a1 3280 (remove implicit class argument) +# Python 3.4a4 3290 (changes to __qualname__ computation #19301) +# Python 3.4a4 3300 (more changes to __qualname__ computation #19301) +# Python 3.4rc2 3310 (alter __qualname__ computation #20625) +# Python 3.5a1 3320 (PEP 465: Matrix multiplication operator #21176) +# Python 3.5b1 3330 (PEP 448: Additional Unpacking Generalizations #2292) +# Python 3.5b2 3340 (fix dictionary display evaluation order #11205) +# Python 3.5b3 3350 (add GET_YIELD_FROM_ITER opcode #24400) +# Python 3.5.2 3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286) +# Python 3.6a0 3360 (add FORMAT_VALUE opcode #25483) +# Python 3.6a1 3361 (lineno delta of code.co_lnotab becomes signed #26107) +# Python 3.6a2 3370 (16 bit wordcode #26647) +# Python 3.6a2 3371 (add BUILD_CONST_KEY_MAP opcode #27140) +# Python 3.6a2 3372 (MAKE_FUNCTION simplification, remove MAKE_CLOSURE +# #27095) +# Python 3.6b1 3373 (add BUILD_STRING opcode #27078) +# Python 3.6b1 3375 (add SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes +# #27985) +# Python 3.6b1 3376 (simplify CALL_FUNCTIONs & BUILD_MAP_UNPACK_WITH_CALL + #27213) +# Python 3.6b1 3377 (set __class__ cell from type.__new__ #23722) +# Python 3.6b2 3378 (add BUILD_TUPLE_UNPACK_WITH_CALL #28257) +# Python 3.6rc1 3379 (more thorough __class__ validation #23722) +# Python 3.7a1 3390 (add LOAD_METHOD and CALL_METHOD opcodes #26110) +# Python 3.7a2 3391 (update GET_AITER #31709) +# Python 3.7a4 3392 (PEP 552: Deterministic pycs #31650) +# Python 3.7b1 3393 (remove STORE_ANNOTATION opcode #32550) +# Python 3.7b5 3394 (restored docstring as the first stmt in the body; +# this might affected the first line number #32911) +# Python 3.8a1 3400 (move frame block handling to compiler #17611) +# Python 3.8a1 3401 (add END_ASYNC_FOR #33041) +# Python 3.8a1 3410 (PEP570 Python Positional-Only Parameters #36540) +# Python 3.8b2 3411 (Reverse evaluation order of key: value in dict +# comprehensions #35224) +# Python 3.8b2 3412 (Swap the position of positional args and positional +# only args in ast.arguments #37593) +# Python 3.8b4 3413 (Fix "break" and "continue" in "finally" #37830) +# Python 3.9a0 3420 (add LOAD_ASSERTION_ERROR #34880) +# Python 3.9a0 3421 (simplified bytecode for with blocks #32949) +# Python 3.9a0 3422 (remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY, POP_FINALLY bytecodes #33387) +# Python 3.9a2 3423 (add IS_OP, CONTAINS_OP and JUMP_IF_NOT_EXC_MATCH bytecodes #39156) +# Python 3.9a2 3424 (simplify bytecodes for *value unpacking) +# Python 3.9a2 3425 (simplify bytecodes for **value unpacking) +# Python 3.10a1 3430 (Make 'annotations' future by default) +# Python 3.10a1 3431 (New line number table format -- PEP 626) +# Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202) +# Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0) +# Python 3.10a6 3434 (PEP 634: Structural Pattern Matching) +# Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets). +# Python 3.10b1 3436 (Add GEN_START bytecode #43683) +# Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!) +# Python 3.10b1 3438 Safer line number table handling. +# Python 3.10b1 3439 (Add ROT_N) +# Python 3.11a1 3450 Use exception table for unwinding ("zero cost" exception handling) +# Python 3.11a1 3451 (Add CALL_METHOD_KW) +# Python 3.11a1 3452 (drop nlocals from marshaled code objects) +# Python 3.11a1 3453 (add co_fastlocalnames and co_fastlocalkinds) +# Python 3.11a1 3454 (compute cell offsets relative to locals bpo-43693) +# Python 3.11a1 3455 (add MAKE_CELL bpo-43693) +# Python 3.11a1 3456 (interleave cell args bpo-43693) +# Python 3.11a1 3457 (Change localsplus to a bytes object bpo-43693) +# Python 3.11a1 3458 (imported objects now don't use LOAD_METHOD/CALL_METHOD) +# Python 3.11a1 3459 (PEP 657: add end line numbers and column offsets for instructions) +# Python 3.11a1 3460 (Add co_qualname field to PyCodeObject bpo-44530) +# Python 3.11a1 3461 (JUMP_ABSOLUTE must jump backwards) +# Python 3.11a2 3462 (bpo-44511: remove COPY_DICT_WITHOUT_KEYS, change +# MATCH_CLASS and MATCH_KEYS, and add COPY) +# Python 3.11a3 3463 (bpo-45711: JUMP_IF_NOT_EXC_MATCH no longer pops the +# active exception) +# Python 3.11a3 3464 (bpo-45636: Merge numeric BINARY_*/INPLACE_* into +# BINARY_OP) +# Python 3.11a3 3465 (Add COPY_FREE_VARS opcode) +# Python 3.11a4 3466 (bpo-45292: PEP-654 except*) +# Python 3.11a4 3467 (Change CALL_xxx opcodes) +# Python 3.11a4 3468 (Add SEND opcode) +# Python 3.11a4 3469 (bpo-45711: remove type, traceback from exc_info) +# Python 3.11a4 3470 (bpo-46221: PREP_RERAISE_STAR no longer pushes lasti) +# Python 3.11a4 3471 (bpo-46202: remove pop POP_EXCEPT_AND_RERAISE) +# Python 3.11a4 3472 (bpo-46009: replace GEN_START with POP_TOP) +# Python 3.11a4 3473 (Add POP_JUMP_IF_NOT_NONE/POP_JUMP_IF_NONE opcodes) +# Python 3.11a4 3474 (Add RESUME opcode) +# Python 3.11a5 3475 (Add RETURN_GENERATOR opcode) +# Python 3.11a5 3476 (Add ASYNC_GEN_WRAP opcode) +# Python 3.11a5 3477 (Replace DUP_TOP/DUP_TOP_TWO with COPY and +# ROT_TWO/ROT_THREE/ROT_FOUR/ROT_N with SWAP) +# Python 3.11a5 3478 (New CALL opcodes) +# Python 3.11a5 3479 (Add PUSH_NULL opcode) +# Python 3.11a5 3480 (New CALL opcodes, second iteration) +# Python 3.11a5 3481 (Use inline cache for BINARY_OP) +# Python 3.11a5 3482 (Use inline caching for UNPACK_SEQUENCE and LOAD_GLOBAL) +# Python 3.11a5 3483 (Use inline caching for COMPARE_OP and BINARY_SUBSCR) +# Python 3.11a5 3484 (Use inline caching for LOAD_ATTR, LOAD_METHOD, and +# STORE_ATTR) +# Python 3.11a5 3485 (Add an oparg to GET_AWAITABLE) +# Python 3.11a6 3486 (Use inline caching for PRECALL and CALL) +# Python 3.11a6 3487 (Remove the adaptive "oparg counter" mechanism) +# Python 3.11a6 3488 (LOAD_GLOBAL can push additional NULL) +# Python 3.11a6 3489 (Add JUMP_BACKWARD, remove JUMP_ABSOLUTE) +# Python 3.11a6 3490 (remove JUMP_IF_NOT_EXC_MATCH, add CHECK_EXC_MATCH) +# Python 3.11a6 3491 (remove JUMP_IF_NOT_EG_MATCH, add CHECK_EG_MATCH, +# add JUMP_BACKWARD_NO_INTERRUPT, make JUMP_NO_INTERRUPT virtual) +# Python 3.11a7 3492 (make POP_JUMP_IF_NONE/NOT_NONE/TRUE/FALSE relative) +# Python 3.11a7 3493 (Make JUMP_IF_TRUE_OR_POP/JUMP_IF_FALSE_OR_POP relative) +# Python 3.11a7 3494 (New location info table) +# Python 3.11b4 3495 (Set line number of module's RESUME instr to 0 per PEP 626) +# Python 3.12 will start with magic number 3500 + + +# +# MAGIC must change whenever the bytecode emitted by the compiler may no +# longer be understood by older implementations of the eval loop (usually +# due to the addition of new opcodes). +# +# Starting with Python 3.11, Python 3.n starts with magic number 2900+50n. +# +# Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array +# in PC/launcher.c must also be updated. + +MAGIC_NUMBER = (3495).to_bytes(2, 'little') + b'\r\n' + +_RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c + +_PYCACHE = '__pycache__' +_OPT = 'opt-' + +SOURCE_SUFFIXES = ['.py'] +if _MS_WINDOWS: + SOURCE_SUFFIXES.append('.pyw') + +EXTENSION_SUFFIXES = _imp.extension_suffixes() + +BYTECODE_SUFFIXES = ['.pyc'] +# Deprecated. +DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES + +def cache_from_source(path, debug_override=None, *, optimization=None): + """Given the path to a .py file, return the path to its .pyc file. + + The .py file does not need to exist; this simply returns the path to the + .pyc file calculated as if the .py file were imported. + + The 'optimization' parameter controls the presumed optimization level of + the bytecode file. If 'optimization' is not None, the string representation + of the argument is taken and verified to be alphanumeric (else ValueError + is raised). + + The debug_override parameter is deprecated. If debug_override is not None, + a True value is the same as setting 'optimization' to the empty string + while a False value is equivalent to setting 'optimization' to '1'. + + If sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + if debug_override is not None: + _warnings.warn('the debug_override parameter is deprecated; use ' + "'optimization' instead", DeprecationWarning) + if optimization is not None: + message = 'debug_override or optimization must be set to None' + raise TypeError(message) + optimization = '' if debug_override else 1 + path = _os.fspath(path) + head, tail = _path_split(path) + base, sep, rest = tail.rpartition('.') + tag = sys.implementation.cache_tag + if tag is None: + raise NotImplementedError('sys.implementation.cache_tag is None') + almost_filename = ''.join([(base if base else rest), sep, tag]) + if optimization is None: + if sys.flags.optimize == 0: + optimization = '' + else: + optimization = sys.flags.optimize + optimization = str(optimization) + if optimization != '': + if not optimization.isalnum(): + raise ValueError('{!r} is not alphanumeric'.format(optimization)) + almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization) + filename = almost_filename + BYTECODE_SUFFIXES[0] + if sys.pycache_prefix is not None: + # We need an absolute path to the py file to avoid the possibility of + # collisions within sys.pycache_prefix, if someone has two different + # `foo/bar.py` on their system and they import both of them using the + # same sys.pycache_prefix. Let's say sys.pycache_prefix is + # `C:\Bytecode`; the idea here is that if we get `Foo\Bar`, we first + # make it absolute (`C:\Somewhere\Foo\Bar`), then make it root-relative + # (`Somewhere\Foo\Bar`), so we end up placing the bytecode file in an + # unambiguous `C:\Bytecode\Somewhere\Foo\Bar\`. + if not _path_isabs(head): + head = _path_join(_os.getcwd(), head) + + # Strip initial drive from a Windows path. We know we have an absolute + # path here, so the second part of the check rules out a POSIX path that + # happens to contain a colon at the second character. + if head[1] == ':' and head[0] not in path_separators: + head = head[2:] + + # Strip initial path separator from `head` to complete the conversion + # back to a root-relative path before joining. + return _path_join( + sys.pycache_prefix, + head.lstrip(path_separators), + filename, + ) + return _path_join(head, _PYCACHE, filename) + + +def source_from_cache(path): + """Given the path to a .pyc. file, return the path to its .py file. + + The .pyc file does not need to exist; this simply returns the path to + the .py file calculated to correspond to the .pyc file. If path does + not conform to PEP 3147/488 format, ValueError will be raised. If + sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + if sys.implementation.cache_tag is None: + raise NotImplementedError('sys.implementation.cache_tag is None') + path = _os.fspath(path) + head, pycache_filename = _path_split(path) + found_in_pycache_prefix = False + if sys.pycache_prefix is not None: + stripped_path = sys.pycache_prefix.rstrip(path_separators) + if head.startswith(stripped_path + path_sep): + head = head[len(stripped_path):] + found_in_pycache_prefix = True + if not found_in_pycache_prefix: + head, pycache = _path_split(head) + if pycache != _PYCACHE: + raise ValueError(f'{_PYCACHE} not bottom-level directory in ' + f'{path!r}') + dot_count = pycache_filename.count('.') + if dot_count not in {2, 3}: + raise ValueError(f'expected only 2 or 3 dots in {pycache_filename!r}') + elif dot_count == 3: + optimization = pycache_filename.rsplit('.', 2)[-2] + if not optimization.startswith(_OPT): + raise ValueError("optimization portion of filename does not start " + f"with {_OPT!r}") + opt_level = optimization[len(_OPT):] + if not opt_level.isalnum(): + raise ValueError(f"optimization level {optimization!r} is not an " + "alphanumeric value") + base_filename = pycache_filename.partition('.')[0] + return _path_join(head, base_filename + SOURCE_SUFFIXES[0]) + + +def _get_sourcefile(bytecode_path): + """Convert a bytecode file path to a source path (if possible). + + This function exists purely for backwards-compatibility for + PyImport_ExecCodeModuleWithFilenames() in the C API. + + """ + if len(bytecode_path) == 0: + return None + rest, _, extension = bytecode_path.rpartition('.') + if not rest or extension.lower()[-3:-1] != 'py': + return bytecode_path + try: + source_path = source_from_cache(bytecode_path) + except (NotImplementedError, ValueError): + source_path = bytecode_path[:-1] + return source_path if _path_isfile(source_path) else bytecode_path + + +def _get_cached(filename): + if filename.endswith(tuple(SOURCE_SUFFIXES)): + try: + return cache_from_source(filename) + except NotImplementedError: + pass + elif filename.endswith(tuple(BYTECODE_SUFFIXES)): + return filename + else: + return None + + +def _calc_mode(path): + """Calculate the mode permissions for a bytecode file.""" + try: + mode = _path_stat(path).st_mode + except OSError: + mode = 0o666 + # We always ensure write access so we can update cached files + # later even when the source files are read-only on Windows (#6074) + mode |= 0o200 + return mode + + +def _check_name(method): + """Decorator to verify that the module being requested matches the one the + loader can handle. + + The first argument (self) must define _name which the second argument is + compared against. If the comparison fails then ImportError is raised. + + """ + def _check_name_wrapper(self, name=None, *args, **kwargs): + if name is None: + name = self.name + elif self.name != name: + raise ImportError('loader for %s cannot handle %s' % + (self.name, name), name=name) + return method(self, name, *args, **kwargs) + + # FIXME: @_check_name is used to define class methods before the + # _bootstrap module is set by _set_bootstrap_module(). + if _bootstrap is not None: + _wrap = _bootstrap._wrap + else: + def _wrap(new, old): + for replace in ['__module__', '__name__', '__qualname__', '__doc__']: + if hasattr(old, replace): + setattr(new, replace, getattr(old, replace)) + new.__dict__.update(old.__dict__) + + _wrap(_check_name_wrapper, method) + return _check_name_wrapper + + +def _find_module_shim(self, fullname): + """Try to find a loader for the specified module by delegating to + self.find_loader(). + + This method is deprecated in favor of finder.find_spec(). + + """ + _warnings.warn("find_module() is deprecated and " + "slated for removal in Python 3.12; use find_spec() instead", + DeprecationWarning) + # Call find_loader(). If it returns a string (indicating this + # is a namespace package portion), generate a warning and + # return None. + loader, portions = self.find_loader(fullname) + if loader is None and len(portions): + msg = 'Not importing directory {}: missing __init__' + _warnings.warn(msg.format(portions[0]), ImportWarning) + return loader + + +def _classify_pyc(data, name, exc_details): + """Perform basic validity checking of a pyc header and return the flags field, + which determines how the pyc should be further validated against the source. + + *data* is the contents of the pyc file. (Only the first 16 bytes are + required, though.) + + *name* is the name of the module being imported. It is used for logging. + + *exc_details* is a dictionary passed to ImportError if it raised for + improved debugging. + + ImportError is raised when the magic number is incorrect or when the flags + field is invalid. EOFError is raised when the data is found to be truncated. + + """ + magic = data[:4] + if magic != MAGIC_NUMBER: + message = f'bad magic number in {name!r}: {magic!r}' + _bootstrap._verbose_message('{}', message) + raise ImportError(message, **exc_details) + if len(data) < 16: + message = f'reached EOF while reading pyc header of {name!r}' + _bootstrap._verbose_message('{}', message) + raise EOFError(message) + flags = _unpack_uint32(data[4:8]) + # Only the first two flags are defined. + if flags & ~0b11: + message = f'invalid flags {flags!r} in {name!r}' + raise ImportError(message, **exc_details) + return flags + + +def _validate_timestamp_pyc(data, source_mtime, source_size, name, + exc_details): + """Validate a pyc against the source last-modified time. + + *data* is the contents of the pyc file. (Only the first 16 bytes are + required.) + + *source_mtime* is the last modified timestamp of the source file. + + *source_size* is None or the size of the source file in bytes. + + *name* is the name of the module being imported. It is used for logging. + + *exc_details* is a dictionary passed to ImportError if it raised for + improved debugging. + + An ImportError is raised if the bytecode is stale. + + """ + if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF): + message = f'bytecode is stale for {name!r}' + _bootstrap._verbose_message('{}', message) + raise ImportError(message, **exc_details) + if (source_size is not None and + _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)): + raise ImportError(f'bytecode is stale for {name!r}', **exc_details) + + +def _validate_hash_pyc(data, source_hash, name, exc_details): + """Validate a hash-based pyc by checking the real source hash against the one in + the pyc header. + + *data* is the contents of the pyc file. (Only the first 16 bytes are + required.) + + *source_hash* is the importlib.util.source_hash() of the source file. + + *name* is the name of the module being imported. It is used for logging. + + *exc_details* is a dictionary passed to ImportError if it raised for + improved debugging. + + An ImportError is raised if the bytecode is stale. + + """ + if data[8:16] != source_hash: + raise ImportError( + f'hash in bytecode doesn\'t match hash of source {name!r}', + **exc_details, + ) + + +def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None): + """Compile bytecode as found in a pyc.""" + code = marshal.loads(data) + if isinstance(code, _code_type): + _bootstrap._verbose_message('code object from {!r}', bytecode_path) + if source_path is not None: + _imp._fix_co_filename(code, source_path) + return code + else: + raise ImportError('Non-code object in {!r}'.format(bytecode_path), + name=name, path=bytecode_path) + + +def _code_to_timestamp_pyc(code, mtime=0, source_size=0): + "Produce the data for a timestamp-based pyc." + data = bytearray(MAGIC_NUMBER) + data.extend(_pack_uint32(0)) + data.extend(_pack_uint32(mtime)) + data.extend(_pack_uint32(source_size)) + data.extend(marshal.dumps(code)) + return data + + +def _code_to_hash_pyc(code, source_hash, checked=True): + "Produce the data for a hash-based pyc." + data = bytearray(MAGIC_NUMBER) + flags = 0b1 | checked << 1 + data.extend(_pack_uint32(flags)) + assert len(source_hash) == 8 + data.extend(source_hash) + data.extend(marshal.dumps(code)) + return data + + +def decode_source(source_bytes): + """Decode bytes representing source code and return the string. + + Universal newline support is used in the decoding. + """ + import tokenize # To avoid bootstrap issues. + source_bytes_readline = _io.BytesIO(source_bytes).readline + encoding = tokenize.detect_encoding(source_bytes_readline) + newline_decoder = _io.IncrementalNewlineDecoder(None, True) + return newline_decoder.decode(source_bytes.decode(encoding[0])) + + +# Module specifications ####################################################### + +_POPULATE = object() + + +def spec_from_file_location(name, location=None, *, loader=None, + submodule_search_locations=_POPULATE): + """Return a module spec based on a file location. + + To indicate that the module is a package, set + submodule_search_locations to a list of directory paths. An + empty list is sufficient, though its not otherwise useful to the + import system. + + The loader must take a spec as its only __init__() arg. + + """ + if location is None: + # The caller may simply want a partially populated location- + # oriented spec. So we set the location to a bogus value and + # fill in as much as we can. + location = '' + if hasattr(loader, 'get_filename'): + # ExecutionLoader + try: + location = loader.get_filename(name) + except ImportError: + pass + else: + location = _os.fspath(location) + if not _path_isabs(location): + try: + location = _path_join(_os.getcwd(), location) + except OSError: + pass + + # If the location is on the filesystem, but doesn't actually exist, + # we could return None here, indicating that the location is not + # valid. However, we don't have a good way of testing since an + # indirect location (e.g. a zip file or URL) will look like a + # non-existent file relative to the filesystem. + + spec = _bootstrap.ModuleSpec(name, loader, origin=location) + spec._set_fileattr = True + + # Pick a loader if one wasn't provided. + if loader is None: + for loader_class, suffixes in _get_supported_file_loaders(): + if location.endswith(tuple(suffixes)): + loader = loader_class(name, location) + spec.loader = loader + break + else: + return None + + # Set submodule_search_paths appropriately. + if submodule_search_locations is _POPULATE: + # Check the loader. + if hasattr(loader, 'is_package'): + try: + is_package = loader.is_package(name) + except ImportError: + pass + else: + if is_package: + spec.submodule_search_locations = [] + else: + spec.submodule_search_locations = submodule_search_locations + if spec.submodule_search_locations == []: + if location: + dirname = _path_split(location)[0] + spec.submodule_search_locations.append(dirname) + + return spec + + +# Loaders ##################################################################### + +class WindowsRegistryFinder: + + """Meta path finder for modules declared in the Windows registry.""" + + REGISTRY_KEY = ( + 'Software\\Python\\PythonCore\\{sys_version}' + '\\Modules\\{fullname}') + REGISTRY_KEY_DEBUG = ( + 'Software\\Python\\PythonCore\\{sys_version}' + '\\Modules\\{fullname}\\Debug') + DEBUG_BUILD = (_MS_WINDOWS and '_d.pyd' in EXTENSION_SUFFIXES) + + @staticmethod + def _open_registry(key): + try: + return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) + except OSError: + return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key) + + @classmethod + def _search_registry(cls, fullname): + if cls.DEBUG_BUILD: + registry_key = cls.REGISTRY_KEY_DEBUG + else: + registry_key = cls.REGISTRY_KEY + key = registry_key.format(fullname=fullname, + sys_version='%d.%d' % sys.version_info[:2]) + try: + with cls._open_registry(key) as hkey: + filepath = winreg.QueryValue(hkey, '') + except OSError: + return None + return filepath + + @classmethod + def find_spec(cls, fullname, path=None, target=None): + filepath = cls._search_registry(fullname) + if filepath is None: + return None + try: + _path_stat(filepath) + except OSError: + return None + for loader, suffixes in _get_supported_file_loaders(): + if filepath.endswith(tuple(suffixes)): + spec = _bootstrap.spec_from_loader(fullname, + loader(fullname, filepath), + origin=filepath) + return spec + + @classmethod + def find_module(cls, fullname, path=None): + """Find module named in the registry. + + This method is deprecated. Use find_spec() instead. + + """ + _warnings.warn("WindowsRegistryFinder.find_module() is deprecated and " + "slated for removal in Python 3.12; use find_spec() instead", + DeprecationWarning) + spec = cls.find_spec(fullname, path) + if spec is not None: + return spec.loader + else: + return None + + +class _LoaderBasics: + + """Base class of common code needed by both SourceLoader and + SourcelessFileLoader.""" + + def is_package(self, fullname): + """Concrete implementation of InspectLoader.is_package by checking if + the path returned by get_filename has a filename of '__init__.py'.""" + filename = _path_split(self.get_filename(fullname))[1] + filename_base = filename.rsplit('.', 1)[0] + tail_name = fullname.rpartition('.')[2] + return filename_base == '__init__' and tail_name != '__init__' + + def create_module(self, spec): + """Use default semantics for module creation.""" + + def exec_module(self, module): + """Execute the module.""" + code = self.get_code(module.__name__) + if code is None: + raise ImportError('cannot load module {!r} when get_code() ' + 'returns None'.format(module.__name__)) + _bootstrap._call_with_frames_removed(exec, code, module.__dict__) + + def load_module(self, fullname): + """This method is deprecated.""" + # Warning implemented in _load_module_shim(). + return _bootstrap._load_module_shim(self, fullname) + + +class SourceLoader(_LoaderBasics): + + def path_mtime(self, path): + """Optional method that returns the modification time (an int) for the + specified path (a str). + + Raises OSError when the path cannot be handled. + """ + raise OSError + + def path_stats(self, path): + """Optional method returning a metadata dict for the specified + path (a str). + + Possible keys: + - 'mtime' (mandatory) is the numeric timestamp of last source + code modification; + - 'size' (optional) is the size in bytes of the source code. + + Implementing this method allows the loader to read bytecode files. + Raises OSError when the path cannot be handled. + """ + return {'mtime': self.path_mtime(path)} + + def _cache_bytecode(self, source_path, cache_path, data): + """Optional method which writes data (bytes) to a file path (a str). + + Implementing this method allows for the writing of bytecode files. + + The source path is needed in order to correctly transfer permissions + """ + # For backwards compatibility, we delegate to set_data() + return self.set_data(cache_path, data) + + def set_data(self, path, data): + """Optional method which writes data (bytes) to a file path (a str). + + Implementing this method allows for the writing of bytecode files. + """ + + + def get_source(self, fullname): + """Concrete implementation of InspectLoader.get_source.""" + path = self.get_filename(fullname) + try: + source_bytes = self.get_data(path) + except OSError as exc: + raise ImportError('source not available through get_data()', + name=fullname) from exc + return decode_source(source_bytes) + + def source_to_code(self, data, path, *, _optimize=-1): + """Return the code object compiled from source. + + The 'data' argument can be any object type that compile() supports. + """ + return _bootstrap._call_with_frames_removed(compile, data, path, 'exec', + dont_inherit=True, optimize=_optimize) + + def get_code(self, fullname): + """Concrete implementation of InspectLoader.get_code. + + Reading of bytecode requires path_stats to be implemented. To write + bytecode, set_data must also be implemented. + + """ + source_path = self.get_filename(fullname) + source_mtime = None + source_bytes = None + source_hash = None + hash_based = False + check_source = True + try: + bytecode_path = cache_from_source(source_path) + except NotImplementedError: + bytecode_path = None + else: + try: + st = self.path_stats(source_path) + except OSError: + pass + else: + source_mtime = int(st['mtime']) + try: + data = self.get_data(bytecode_path) + except OSError: + pass + else: + exc_details = { + 'name': fullname, + 'path': bytecode_path, + } + try: + flags = _classify_pyc(data, fullname, exc_details) + bytes_data = memoryview(data)[16:] + hash_based = flags & 0b1 != 0 + if hash_based: + check_source = flags & 0b10 != 0 + if (_imp.check_hash_based_pycs != 'never' and + (check_source or + _imp.check_hash_based_pycs == 'always')): + source_bytes = self.get_data(source_path) + source_hash = _imp.source_hash( + _RAW_MAGIC_NUMBER, + source_bytes, + ) + _validate_hash_pyc(data, source_hash, fullname, + exc_details) + else: + _validate_timestamp_pyc( + data, + source_mtime, + st['size'], + fullname, + exc_details, + ) + except (ImportError, EOFError): + pass + else: + _bootstrap._verbose_message('{} matches {}', bytecode_path, + source_path) + return _compile_bytecode(bytes_data, name=fullname, + bytecode_path=bytecode_path, + source_path=source_path) + if source_bytes is None: + source_bytes = self.get_data(source_path) + code_object = self.source_to_code(source_bytes, source_path) + _bootstrap._verbose_message('code object from {}', source_path) + if (not sys.dont_write_bytecode and bytecode_path is not None and + source_mtime is not None): + if hash_based: + if source_hash is None: + source_hash = _imp.source_hash(source_bytes) + data = _code_to_hash_pyc(code_object, source_hash, check_source) + else: + data = _code_to_timestamp_pyc(code_object, source_mtime, + len(source_bytes)) + try: + self._cache_bytecode(source_path, bytecode_path, data) + except NotImplementedError: + pass + return code_object + + +class FileLoader: + + """Base file loader class which implements the loader protocol methods that + require file system usage.""" + + def __init__(self, fullname, path): + """Cache the module name and the path to the file found by the + finder.""" + self.name = fullname + self.path = path + + def __eq__(self, other): + return (self.__class__ == other.__class__ and + self.__dict__ == other.__dict__) + + def __hash__(self): + return hash(self.name) ^ hash(self.path) + + @_check_name + def load_module(self, fullname): + """Load a module from a file. + + This method is deprecated. Use exec_module() instead. + + """ + # The only reason for this method is for the name check. + # Issue #14857: Avoid the zero-argument form of super so the implementation + # of that form can be updated without breaking the frozen module. + return super(FileLoader, self).load_module(fullname) + + @_check_name + def get_filename(self, fullname): + """Return the path to the source file as found by the finder.""" + return self.path + + def get_data(self, path): + """Return the data from path as raw bytes.""" + if isinstance(self, (SourceLoader, ExtensionFileLoader)): + with _io.open_code(str(path)) as file: + return file.read() + else: + with _io.FileIO(path, 'r') as file: + return file.read() + + @_check_name + def get_resource_reader(self, module): + from importlib.readers import FileReader + return FileReader(self) + + +class SourceFileLoader(FileLoader, SourceLoader): + + """Concrete implementation of SourceLoader using the file system.""" + + def path_stats(self, path): + """Return the metadata for the path.""" + st = _path_stat(path) + return {'mtime': st.st_mtime, 'size': st.st_size} + + def _cache_bytecode(self, source_path, bytecode_path, data): + # Adapt between the two APIs + mode = _calc_mode(source_path) + return self.set_data(bytecode_path, data, _mode=mode) + + def set_data(self, path, data, *, _mode=0o666): + """Write bytes data to a file.""" + parent, filename = _path_split(path) + path_parts = [] + # Figure out what directories are missing. + while parent and not _path_isdir(parent): + parent, part = _path_split(parent) + path_parts.append(part) + # Create needed directories. + for part in reversed(path_parts): + parent = _path_join(parent, part) + try: + _os.mkdir(parent) + except FileExistsError: + # Probably another Python process already created the dir. + continue + except OSError as exc: + # Could be a permission error, read-only filesystem: just forget + # about writing the data. + _bootstrap._verbose_message('could not create {!r}: {!r}', + parent, exc) + return + try: + _write_atomic(path, data, _mode) + _bootstrap._verbose_message('created {!r}', path) + except OSError as exc: + # Same as above: just don't write the bytecode. + _bootstrap._verbose_message('could not create {!r}: {!r}', path, + exc) + + +class SourcelessFileLoader(FileLoader, _LoaderBasics): + + """Loader which handles sourceless file imports.""" + + def get_code(self, fullname): + path = self.get_filename(fullname) + data = self.get_data(path) + # Call _classify_pyc to do basic validation of the pyc but ignore the + # result. There's no source to check against. + exc_details = { + 'name': fullname, + 'path': path, + } + _classify_pyc(data, fullname, exc_details) + return _compile_bytecode( + memoryview(data)[16:], + name=fullname, + bytecode_path=path, + ) + + def get_source(self, fullname): + """Return None as there is no source code.""" + return None + + +class ExtensionFileLoader(FileLoader, _LoaderBasics): + + """Loader for extension modules. + + The constructor is designed to work with FileFinder. + + """ + + def __init__(self, name, path): + self.name = name + self.path = path + + def __eq__(self, other): + return (self.__class__ == other.__class__ and + self.__dict__ == other.__dict__) + + def __hash__(self): + return hash(self.name) ^ hash(self.path) + + def create_module(self, spec): + """Create an uninitialized extension module""" + module = _bootstrap._call_with_frames_removed( + _imp.create_dynamic, spec) + _bootstrap._verbose_message('extension module {!r} loaded from {!r}', + spec.name, self.path) + return module + + def exec_module(self, module): + """Initialize an extension module""" + _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module) + _bootstrap._verbose_message('extension module {!r} executed from {!r}', + self.name, self.path) + + def is_package(self, fullname): + """Return True if the extension module is a package.""" + file_name = _path_split(self.path)[1] + return any(file_name == '__init__' + suffix + for suffix in EXTENSION_SUFFIXES) + + def get_code(self, fullname): + """Return None as an extension module cannot create a code object.""" + return None + + def get_source(self, fullname): + """Return None as extension modules have no source code.""" + return None + + @_check_name + def get_filename(self, fullname): + """Return the path to the source file as found by the finder.""" + return self.path + + +class _NamespacePath: + """Represents a namespace package's path. It uses the module name + to find its parent module, and from there it looks up the parent's + __path__. When this changes, the module's own path is recomputed, + using path_finder. For top-level modules, the parent module's path + is sys.path.""" + + # When invalidate_caches() is called, this epoch is incremented + # https://bugs.python.org/issue45703 + _epoch = 0 + + def __init__(self, name, path, path_finder): + self._name = name + self._path = path + self._last_parent_path = tuple(self._get_parent_path()) + self._last_epoch = self._epoch + self._path_finder = path_finder + + def _find_parent_path_names(self): + """Returns a tuple of (parent-module-name, parent-path-attr-name)""" + parent, dot, me = self._name.rpartition('.') + if dot == '': + # This is a top-level module. sys.path contains the parent path. + return 'sys', 'path' + # Not a top-level module. parent-module.__path__ contains the + # parent path. + return parent, '__path__' + + def _get_parent_path(self): + parent_module_name, path_attr_name = self._find_parent_path_names() + return getattr(sys.modules[parent_module_name], path_attr_name) + + def _recalculate(self): + # If the parent's path has changed, recalculate _path + parent_path = tuple(self._get_parent_path()) # Make a copy + if parent_path != self._last_parent_path or self._epoch != self._last_epoch: + spec = self._path_finder(self._name, parent_path) + # Note that no changes are made if a loader is returned, but we + # do remember the new parent path + if spec is not None and spec.loader is None: + if spec.submodule_search_locations: + self._path = spec.submodule_search_locations + self._last_parent_path = parent_path # Save the copy + self._last_epoch = self._epoch + return self._path + + def __iter__(self): + return iter(self._recalculate()) + + def __getitem__(self, index): + return self._recalculate()[index] + + def __setitem__(self, index, path): + self._path[index] = path + + def __len__(self): + return len(self._recalculate()) + + def __repr__(self): + return '_NamespacePath({!r})'.format(self._path) + + def __contains__(self, item): + return item in self._recalculate() + + def append(self, item): + self._path.append(item) + + +# This class is actually exposed publicly in a namespace package's __loader__ +# attribute, so it should be available through a non-private name. +# https://bugs.python.org/issue35673 +class NamespaceLoader: + def __init__(self, name, path, path_finder): + self._path = _NamespacePath(name, path, path_finder) + + @staticmethod + def module_repr(module): + """Return repr for the module. + + The method is deprecated. The import machinery does the job itself. + + """ + _warnings.warn("NamespaceLoader.module_repr() is deprecated and " + "slated for removal in Python 3.12", DeprecationWarning) + return ''.format(module.__name__) + + def is_package(self, fullname): + return True + + def get_source(self, fullname): + return '' + + def get_code(self, fullname): + return compile('', '', 'exec', dont_inherit=True) + + def create_module(self, spec): + """Use default semantics for module creation.""" + + def exec_module(self, module): + pass + + def load_module(self, fullname): + """Load a namespace module. + + This method is deprecated. Use exec_module() instead. + + """ + # The import system never calls this method. + _bootstrap._verbose_message('namespace module loaded with path {!r}', + self._path) + # Warning implemented in _load_module_shim(). + return _bootstrap._load_module_shim(self, fullname) + + def get_resource_reader(self, module): + from importlib.readers import NamespaceReader + return NamespaceReader(self._path) + + +# We use this exclusively in module_from_spec() for backward-compatibility. +_NamespaceLoader = NamespaceLoader + + +# Finders ##################################################################### + +class PathFinder: + + """Meta path finder for sys.path and package __path__ attributes.""" + + @staticmethod + def invalidate_caches(): + """Call the invalidate_caches() method on all path entry finders + stored in sys.path_importer_caches (where implemented).""" + for name, finder in list(sys.path_importer_cache.items()): + # Drop entry if finder name is a relative path. The current + # working directory may have changed. + if finder is None or not _path_isabs(name): + del sys.path_importer_cache[name] + elif hasattr(finder, 'invalidate_caches'): + finder.invalidate_caches() + # Also invalidate the caches of _NamespacePaths + # https://bugs.python.org/issue45703 + _NamespacePath._epoch += 1 + + from importlib.metadata import MetadataPathFinder + MetadataPathFinder.invalidate_caches() + + @staticmethod + def _path_hooks(path): + """Search sys.path_hooks for a finder for 'path'.""" + if sys.path_hooks is not None and not sys.path_hooks: + _warnings.warn('sys.path_hooks is empty', ImportWarning) + for hook in sys.path_hooks: + try: + return hook(path) + except ImportError: + continue + else: + return None + + @classmethod + def _path_importer_cache(cls, path): + """Get the finder for the path entry from sys.path_importer_cache. + + If the path entry is not in the cache, find the appropriate finder + and cache it. If no finder is available, store None. + + """ + if path == '': + try: + path = _os.getcwd() + except FileNotFoundError: + # Don't cache the failure as the cwd can easily change to + # a valid directory later on. + return None + try: + finder = sys.path_importer_cache[path] + except KeyError: + finder = cls._path_hooks(path) + sys.path_importer_cache[path] = finder + return finder + + @classmethod + def _legacy_get_spec(cls, fullname, finder): + # This would be a good place for a DeprecationWarning if + # we ended up going that route. + if hasattr(finder, 'find_loader'): + msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; " + "falling back to find_loader()") + _warnings.warn(msg, ImportWarning) + loader, portions = finder.find_loader(fullname) + else: + msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; " + "falling back to find_module()") + _warnings.warn(msg, ImportWarning) + loader = finder.find_module(fullname) + portions = [] + if loader is not None: + return _bootstrap.spec_from_loader(fullname, loader) + spec = _bootstrap.ModuleSpec(fullname, None) + spec.submodule_search_locations = portions + return spec + + @classmethod + def _get_spec(cls, fullname, path, target=None): + """Find the loader or namespace_path for this module/package name.""" + # If this ends up being a namespace package, namespace_path is + # the list of paths that will become its __path__ + namespace_path = [] + for entry in path: + if not isinstance(entry, str): + continue + finder = cls._path_importer_cache(entry) + if finder is not None: + if hasattr(finder, 'find_spec'): + spec = finder.find_spec(fullname, target) + else: + spec = cls._legacy_get_spec(fullname, finder) + if spec is None: + continue + if spec.loader is not None: + return spec + portions = spec.submodule_search_locations + if portions is None: + raise ImportError('spec missing loader') + # This is possibly part of a namespace package. + # Remember these path entries (if any) for when we + # create a namespace package, and continue iterating + # on path. + namespace_path.extend(portions) + else: + spec = _bootstrap.ModuleSpec(fullname, None) + spec.submodule_search_locations = namespace_path + return spec + + @classmethod + def find_spec(cls, fullname, path=None, target=None): + """Try to find a spec for 'fullname' on sys.path or 'path'. + + The search is based on sys.path_hooks and sys.path_importer_cache. + """ + if path is None: + path = sys.path + spec = cls._get_spec(fullname, path, target) + if spec is None: + return None + elif spec.loader is None: + namespace_path = spec.submodule_search_locations + if namespace_path: + # We found at least one namespace path. Return a spec which + # can create the namespace package. + spec.origin = None + spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec) + return spec + else: + return None + else: + return spec + + @classmethod + def find_module(cls, fullname, path=None): + """find the module on sys.path or 'path' based on sys.path_hooks and + sys.path_importer_cache. + + This method is deprecated. Use find_spec() instead. + + """ + _warnings.warn("PathFinder.find_module() is deprecated and " + "slated for removal in Python 3.12; use find_spec() instead", + DeprecationWarning) + spec = cls.find_spec(fullname, path) + if spec is None: + return None + return spec.loader + + @staticmethod + def find_distributions(*args, **kwargs): + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + from importlib.metadata import MetadataPathFinder + return MetadataPathFinder.find_distributions(*args, **kwargs) + + +class FileFinder: + + """File-based finder. + + Interactions with the file system are cached for performance, being + refreshed when the directory the finder is handling has been modified. + + """ + + def __init__(self, path, *loader_details): + """Initialize with the path to search on and a variable number of + 2-tuples containing the loader and the file suffixes the loader + recognizes.""" + loaders = [] + for loader, suffixes in loader_details: + loaders.extend((suffix, loader) for suffix in suffixes) + self._loaders = loaders + # Base (directory) path + if not path or path == '.': + self.path = _os.getcwd() + elif not _path_isabs(path): + self.path = _path_join(_os.getcwd(), path) + else: + self.path = path + self._path_mtime = -1 + self._path_cache = set() + self._relaxed_path_cache = set() + + def invalidate_caches(self): + """Invalidate the directory mtime.""" + self._path_mtime = -1 + + find_module = _find_module_shim + + def find_loader(self, fullname): + """Try to find a loader for the specified module, or the namespace + package portions. Returns (loader, list-of-portions). + + This method is deprecated. Use find_spec() instead. + + """ + _warnings.warn("FileFinder.find_loader() is deprecated and " + "slated for removal in Python 3.12; use find_spec() instead", + DeprecationWarning) + spec = self.find_spec(fullname) + if spec is None: + return None, [] + return spec.loader, spec.submodule_search_locations or [] + + def _get_spec(self, loader_class, fullname, path, smsl, target): + loader = loader_class(fullname, path) + return spec_from_file_location(fullname, path, loader=loader, + submodule_search_locations=smsl) + + def find_spec(self, fullname, target=None): + """Try to find a spec for the specified module. + + Returns the matching spec, or None if not found. + """ + is_namespace = False + tail_module = fullname.rpartition('.')[2] + try: + mtime = _path_stat(self.path or _os.getcwd()).st_mtime + except OSError: + mtime = -1 + if mtime != self._path_mtime: + self._fill_cache() + self._path_mtime = mtime + # tail_module keeps the original casing, for __file__ and friends + if _relax_case(): + cache = self._relaxed_path_cache + cache_module = tail_module.lower() + else: + cache = self._path_cache + cache_module = tail_module + # Check if the module is the name of a directory (and thus a package). + if cache_module in cache: + base_path = _path_join(self.path, tail_module) + for suffix, loader_class in self._loaders: + init_filename = '__init__' + suffix + full_path = _path_join(base_path, init_filename) + if _path_isfile(full_path): + return self._get_spec(loader_class, fullname, full_path, [base_path], target) + else: + # If a namespace package, return the path if we don't + # find a module in the next section. + is_namespace = _path_isdir(base_path) + # Check for a file w/ a proper suffix exists. + for suffix, loader_class in self._loaders: + try: + full_path = _path_join(self.path, tail_module + suffix) + except ValueError: + return None + _bootstrap._verbose_message('trying {}', full_path, verbosity=2) + if cache_module + suffix in cache: + if _path_isfile(full_path): + return self._get_spec(loader_class, fullname, full_path, + None, target) + if is_namespace: + _bootstrap._verbose_message('possible namespace for {}', base_path) + spec = _bootstrap.ModuleSpec(fullname, None) + spec.submodule_search_locations = [base_path] + return spec + return None + + def _fill_cache(self): + """Fill the cache of potential modules and packages for this directory.""" + path = self.path + try: + contents = _os.listdir(path or _os.getcwd()) + except (FileNotFoundError, PermissionError, NotADirectoryError): + # Directory has either been removed, turned into a file, or made + # unreadable. + contents = [] + # We store two cached versions, to handle runtime changes of the + # PYTHONCASEOK environment variable. + if not sys.platform.startswith('win'): + self._path_cache = set(contents) + else: + # Windows users can import modules with case-insensitive file + # suffixes (for legacy reasons). Make the suffix lowercase here + # so it's done once instead of for every import. This is safe as + # the specified suffixes to check against are always specified in a + # case-sensitive manner. + lower_suffix_contents = set() + for item in contents: + name, dot, suffix = item.partition('.') + if dot: + new_name = '{}.{}'.format(name, suffix.lower()) + else: + new_name = name + lower_suffix_contents.add(new_name) + self._path_cache = lower_suffix_contents + if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS): + self._relaxed_path_cache = {fn.lower() for fn in contents} + + @classmethod + def path_hook(cls, *loader_details): + """A class method which returns a closure to use on sys.path_hook + which will return an instance using the specified loaders and the path + called on the closure. + + If the path called on the closure is not a directory, ImportError is + raised. + + """ + def path_hook_for_FileFinder(path): + """Path hook for importlib.machinery.FileFinder.""" + if not _path_isdir(path): + raise ImportError('only directories are supported', path=path) + return cls(path, *loader_details) + + return path_hook_for_FileFinder + + def __repr__(self): + return 'FileFinder({!r})'.format(self.path) + + +# Import setup ############################################################### + +def _fix_up_module(ns, name, pathname, cpathname=None): + # This function is used by PyImport_ExecCodeModuleObject(). + loader = ns.get('__loader__') + spec = ns.get('__spec__') + if not loader: + if spec: + loader = spec.loader + elif pathname == cpathname: + loader = SourcelessFileLoader(name, pathname) + else: + loader = SourceFileLoader(name, pathname) + if not spec: + spec = spec_from_file_location(name, pathname, loader=loader) + try: + ns['__spec__'] = spec + ns['__loader__'] = loader + ns['__file__'] = pathname + ns['__cached__'] = cpathname + except Exception: + # Not important enough to report. + pass + + +def _get_supported_file_loaders(): + """Returns a list of file-based module loaders. + + Each item is a tuple (loader, suffixes). + """ + extensions = ExtensionFileLoader, _imp.extension_suffixes() + source = SourceFileLoader, SOURCE_SUFFIXES + bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES + return [extensions, source, bytecode] + + +def _set_bootstrap_module(_bootstrap_module): + global _bootstrap + _bootstrap = _bootstrap_module + + +def _install(_bootstrap_module): + """Install the path-based import components.""" + _set_bootstrap_module(_bootstrap_module) + supported_loaders = _get_supported_file_loaders() + sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)]) + sys.meta_path.append(PathFinder) diff --git a/shared/package-files/7c/7c9d4feaad9ef2aec2aca4c8cda92746d2633f87fc5b33ce2cde6740b854537d/test_core.cpython-311.pyc b/shared/package-files/7c/7c9d4feaad9ef2aec2aca4c8cda92746d2633f87fc5b33ce2cde6740b854537d/test_core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d08ed9bf368e0db9627a774bc01f3bd3514ee7a2 Binary files /dev/null and b/shared/package-files/7c/7c9d4feaad9ef2aec2aca4c8cda92746d2633f87fc5b33ce2cde6740b854537d/test_core.cpython-311.pyc differ diff --git a/shared/package-files/7c/7ca05f87d5d1d3d0d1b1f8823bfd57cfd73313d9cf737054a5e182f0efc93d4e/_cslt_sparse_mm_search.h b/shared/package-files/7c/7ca05f87d5d1d3d0d1b1f8823bfd57cfd73313d9cf737054a5e182f0efc93d4e/_cslt_sparse_mm_search.h new file mode 100644 index 0000000000000000000000000000000000000000..9c1e06fa7242726d49a7e1a594d325cffcde5958 --- /dev/null +++ b/shared/package-files/7c/7ca05f87d5d1d3d0d1b1f8823bfd57cfd73313d9cf737054a5e182f0efc93d4e/_cslt_sparse_mm_search.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cslt_sparse_mm_search(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False) -> int +inline int64_t _cslt_sparse_mm_search(const at::Tensor & compressed_A, const at::Tensor & dense_B, const ::std::optional & bias={}, const ::std::optional & alpha={}, ::std::optional out_dtype=::std::nullopt, bool transpose_result=false) { + return at::_ops::_cslt_sparse_mm_search::call(compressed_A, dense_B, bias, alpha, out_dtype, transpose_result); +} + +} diff --git a/shared/package-files/7c/7ca3b660a7fcdfa4ac931d3ec11194076379b5dce1c7427469bb7dca392f3fed/__init__.cpython-311.pyc b/shared/package-files/7c/7ca3b660a7fcdfa4ac931d3ec11194076379b5dce1c7427469bb7dca392f3fed/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be8300e2e14499de23912127fb033cce75a17262 Binary files /dev/null and b/shared/package-files/7c/7ca3b660a7fcdfa4ac931d3ec11194076379b5dce1c7427469bb7dca392f3fed/__init__.cpython-311.pyc differ diff --git a/shared/package-files/7c/7ca479c43a395702b71c047686abde8ff4c1ba86c157f473c5076b322c0b5417/full_compositeexplicitautograd_dispatch.h b/shared/package-files/7c/7ca479c43a395702b71c047686abde8ff4c1ba86c157f473c5076b322c0b5417/full_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4d85aa566cec158d40123473ea769e3c5563307e --- /dev/null +++ b/shared/package-files/7c/7ca479c43a395702b71c047686abde8ff4c1ba86c157f473c5076b322c0b5417/full_compositeexplicitautograd_dispatch.h @@ -0,0 +1,34 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names, at::TensorOptions options={}); +TORCH_API at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor & full_out(at::Tensor & out, at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names); +TORCH_API at::Tensor & full_outf(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional names, at::Tensor & out); +TORCH_API at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}); +TORCH_API at::Tensor full(at::IntArrayRef size, const at::Scalar & fill_value, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::TensorOptions options={}); +TORCH_API at::Tensor full_symint(c10::SymIntArrayRef size, const at::Scalar & fill_value, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor & full_out(at::Tensor & out, at::IntArrayRef size, const at::Scalar & fill_value); +TORCH_API at::Tensor & full_outf(at::IntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); +TORCH_API at::Tensor & full_symint_out(at::Tensor & out, c10::SymIntArrayRef size, const at::Scalar & fill_value); +TORCH_API at::Tensor & full_symint_outf(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/7c/7ca74b7493dbff810f1fe1da4c81a60bbfb944803cef1aad3e970690276415a5/order.cpython-311.pyc b/shared/package-files/7c/7ca74b7493dbff810f1fe1da4c81a60bbfb944803cef1aad3e970690276415a5/order.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d84924b3f39b680af8d7a83b394aee2e2d648a1 Binary files /dev/null and b/shared/package-files/7c/7ca74b7493dbff810f1fe1da4c81a60bbfb944803cef1aad3e970690276415a5/order.cpython-311.pyc differ diff --git a/shared/package-files/7c/7ca8a261320f9b20f745db6bf351dca12811207f27e0ab2759f45053fd9ff908/schemas.py b/shared/package-files/7c/7ca8a261320f9b20f745db6bf351dca12811207f27e0ab2759f45053fd9ff908/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..6259d082e2ae8c1b0393dab584a000619db56f54 --- /dev/null +++ b/shared/package-files/7c/7ca8a261320f9b20f745db6bf351dca12811207f27e0ab2759f45053fd9ff908/schemas.py @@ -0,0 +1,910 @@ +# mypy: allow-untyped-defs +""" +The various dataclasses, Enums, namedtuples etc used in AOTAutograd. This includes +input/output types, metadata, config, function signatures etc. +""" + +import collections +import dataclasses +import functools +from collections.abc import Iterable +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Callable, NewType, Optional, Union + +import torch +import torch.utils._pytree as pytree +from torch._guards import Source +from torch._ops import OpOverload +from torch._subclasses import FakeTensor +from torch._subclasses.fake_tensor import is_fake +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .functional_utils import ( + _check_if_mutation_can_be_in_graph, + FunctionalTensorMetadataEq, +) +from .utils import strict_zip + + +zip = strict_zip + + +OutputType = Enum( + "OutputType", + ( + # output is not an alias + "non_alias", + # output aliases an input + "alias_of_input", + # output **is** an input tensor + "is_input", + # output has a ._base tensor, which is a graph intermediate. + # We need to return its ._base as a graph output, + # so its requires_grad info is populated correctly. + # Instructs the runtime code to regenerate the current output + # from a base tensor, graph_intermediates[base_idx] + "alias_of_intermediate_save_as_output", + # Same as above; but we don't need to explicitly add its ._base + # as a graph output, because it already **is** a graph output. + "alias_of_intermediate", + # Same as above; but the output's ._base is **already** a user output. + # Instructs the runtime code to regenerate the current output from + # a base tensor, user_outputs[base_idx] + "alias_of_intermediate_base_is_user_output", + # See Note [Intermediate Bases Optimization] + "unsafe_view_alias", + # output is an alias, but has a custom autograd.Function backward. + # In this case, we don't want to do view-replay, since we won't be able to replay the custom function. + # Instead, we'll treat this output "normally", and trace its backward into the graph. + "custom_function_view", + ), +) + + +# This class stores info about every user output. +@dataclass(frozen=True) +class OutputAliasInfo: + # Tells us if this output is: + # (1) a regular (non-aliased) output + # (2) an alias of a forward input + # (3) **is** a forward input (special case of "alias_of_input") + # (4) an alias of an intermediate (aka an alias of an output of the inner traced forward) + # (5) an alias of an intermediate, that explicitly requires returning the intermediate + # as a graph output + # (6) an alias of an intermediate, where that intermediate is also a user output + output_type: OutputType + # The raw type of the output (torch.Tensor, SymInt, etc) + raw_type: type + # If (1) above, then + # - base_idx is None + # If (2) or (3) above, then + # - Tells us that the base of this alias is user_fwd_input[base_idx] + # (This is an index into the inputs *before* we make synthetic bases) + # If (4) or (5) above, then + # - Tells us that the base of this alias is output_graph_intermediates[base_idx] + # here, this refers to the index of the *direct* traced + # If (6) above, then: + # - Tells us that the base of this alias is output_user_fwds[base_idx] + # here, this refers to the index of the *direct* traced + base_idx: Optional[int] + # If it is a Tensor, what the dynamic dims are (otherwise is None) + dynamic_dims: Optional[set[int]] + # requires_grad + requires_grad: bool + # FunctionalTensorWrapper that represents this output. + # + # Provides us the means to replay views from it. + # + # We need to wrap the actual FunctionalTensorWrapper with this class so that + # we only compare the tensor's metadata. That's because with the transformations + # of the model throughout AOTAutograd, the sequence of ViewMeta and the base + # tensor might change. + functional_tensor: Optional[FunctionalTensorMetadataEq] = None + + +class MutationType(Enum): + NOT_MUTATED = 1 + MUTATED_IN_GRAPH = 2 + MUTATED_OUT_GRAPH = 3 + + +# This class tells us info about user inputs. +@dataclass(frozen=True) +class InputAliasInfo: + is_leaf: bool + mutates_data: bool + mutates_metadata: bool + mutations_hidden_from_autograd: bool + mutations_under_no_grad_or_inference_mode: bool + mutation_inductor_storage_resize: bool + mutates_storage_metadata: bool + requires_grad: bool + keep_input_mutations: bool + + def __post_init__(self): + if self.mutates_storage_metadata: + # For convenience, we guarantee that this is always true. + # In practice, If we call .set_(), then at runtime there is no need + # to additionally fix up the tensor metadata, since our runtime + # call to inp.set_(updated_inp) will already have the right metadata + assert self.mutates_metadata + + @functools.cached_property + def mutation_type(self) -> MutationType: + if ( + (not self.mutates_data) + and (not self.mutates_metadata) + and not (self.mutation_inductor_storage_resize) + ): + return MutationType.NOT_MUTATED + + if _check_if_mutation_can_be_in_graph( + self.keep_input_mutations, + self.mutates_data, + self.mutates_metadata, + self.mutations_hidden_from_autograd, + self.mutations_under_no_grad_or_inference_mode, + self.mutates_storage_metadata, + self.mutation_inductor_storage_resize, + self.requires_grad, + ): + return MutationType.MUTATED_IN_GRAPH + + return MutationType.MUTATED_OUT_GRAPH + + +@dataclass +class PlainTensorMeta: + unwrapped_idx: int + memory_format: Optional[torch.memory_format] = None + + +@dataclass +class SubclassCreationMeta: + """ + Used for AOTDispatch. + This dataclass gives us the information we need to reconstruct a tensor subclass + from our flat inputs. + Why is this important? The graph that we'd like to trace out contains flat tensor inputs, + But the user's original model may have subclass inputs and outputs. + So we need to wrap/unwrap subclasses as necessary to translate between the user's + view (subclass inps/outs), and the backend compiler's view (graph with no subclass args). + + Complications arise mostly from the fact that a subclass can hold more than one inner tensor; + So for a given subclass input/output, we need to carefully track which indices map + to the subclass tensor in the corresponding "dense-tensor-only" graph. + """ + + # In the inner graph that only takes in dense tensor inputs, + # this maps to the first index of "tensors that should go in this subclass wrapper" + flat_tensor_start_idx: int + # arg_count is inclusive of the arg_counts of any + # inner tensor subclasses: If I have a TwoTensor and + # both of its inner elements are TwoTensors, then the + # arg_count of the outer-most sublass will be 4 + arg_count: int + # Mark where or not symints were included. This flag is only used in one assertion + # in "wrap_tensor_subclasses" + included_subclass_symints: bool + # meta and attrs are produced by the subclass's __tensor_flatten__. + # We need to keep them around along with outer_size / outer_stride to plumb them + # into __tensor_unflatten__ + attrs: dict[str, Union["SubclassCreationMeta", PlainTensorMeta]] + outer_size: Iterable[Union[None, int, torch.SymInt]] + outer_stride: Iterable[Union[None, int, torch.SymInt]] + meta: Any + # Stores the original subclass itself. + # This is needed because we need the autograd metadata on the original subclass + # (this is guaranteed to be a wrapper subclass that holds a fake tensor, + # so holding onto this at runtime shouldn't leak memory) + # This field is nulled out after calling make_runtime_safe() + original_subclass: Optional[torch.Tensor] + + # Used at runtime to determine the subclass type, so we don't need to save the original subclass + original_subclass_type: Optional[type] = None + memory_format: Optional[torch.memory_format] = None + + def compute_outer_size_and_stride( + self, + all_args, + *, + curr_start_idx: int, + ): + from .subclass_utils import compute_symint_placeholders + + def compute(outer, start_idx): + placeholders = compute_symint_placeholders(outer) + has_symbolic = any(placeholders) + + if has_symbolic: + start = curr_start_idx + end = start_idx + sum(placeholders) + it_args = iter(all_args[start:end]) + it_placeholders = iter(placeholders) + return pytree.tree_map_only( + lambda _: next(it_placeholders), lambda _: next(it_args), outer + ), start + len(placeholders) + else: + return outer, start_idx + + outer_size, next_idx = compute(self.outer_size, curr_start_idx) + outer_stride, _ = compute(self.outer_stride, next_idx) + return outer_size, outer_stride + + def creation_fn( + self, + all_args, + *, + is_runtime: bool, + ): + inner_tensors = {} + + curr_start_idx = self.flat_tensor_start_idx + for attr, creation_meta in self.attrs.items(): + if isinstance(creation_meta, PlainTensorMeta): + subclass = all_args[curr_start_idx] + curr_start_idx += 1 + else: + subclass = creation_meta.creation_fn( + all_args, + is_runtime=is_runtime, + ) + curr_start_idx += creation_meta.arg_count + inner_tensors[attr] = subclass + + if is_runtime: + assert self.original_subclass_type is not None + original_subclass_type = self.original_subclass_type + else: + original_subclass_type = type(self.original_subclass) + + if is_runtime: + outer_size, outer_stride = self.compute_outer_size_and_stride( + all_args, + curr_start_idx=curr_start_idx, + ) + else: + outer_size, outer_stride = self.outer_size, self.outer_stride + + rebuilt = original_subclass_type.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, self.meta, outer_size, outer_stride + ) + + if not is_runtime: + # After wrapping up the inner dense tensors into a subclass, we need to make sure that our new wrapper + # has correct autograd metadata, since we'll be tracing through the autograd engine with the subclass. + # We don't trace through the autograd engine at runtime though, so no need + # to compute this extra metadata then! + torch._mirror_autograd_meta_to(self.original_subclass, rebuilt) # type: ignore[attr-defined] + + return rebuilt + + def make_runtime_safe(self): + def _make_size_runtime_safe(x: Union[None, int, torch.SymInt]) -> Optional[int]: + dummy = -1 + if isinstance(x, torch.SymInt): + # Replace nested ints by a dummy value (-1) as NJT ignores + # the outer_size/outer_stride at runtime. + return dummy if x.node.is_nested_int() else None + return x + + assert self.original_subclass is not None + self.original_subclass_type = type(self.original_subclass) + self.original_subclass = None + + # Note: NJT outer_size in AOTDispatcher + # `_make_size_runtime_safe` replaces any nested int with a dummy value (-1) + # to prevent serializing a SymInt at runtime. Internally, nested tensor __tensor_unflatten__ + # is designed to safely ignore this dummy value. + # For more details, see: https://github.com/pytorch/pytorch/blob/5141ade8e30c64e873e14dcc8de233da45d15025/torch/nested/_internal/nested_tensor.py#L266-L299 # noqa: B950 + self.outer_size = tuple(map(_make_size_runtime_safe, self.outer_size)) + self.outer_stride = tuple(map(_make_size_runtime_safe, self.outer_stride)) + + # Recurse on nested subclass info + for creation_meta in self.attrs.values(): + if isinstance(creation_meta, SubclassCreationMeta): + creation_meta.make_runtime_safe() + + def __post_init__(self): + # sanity assert to make sure we don't leak memory + assert is_fake(self.original_subclass) + + +# This class encapsulates all aliasing + mutation info we need about the forward graph +# See a more detailed overview of the edge case handling at +# https://docs.google.com/document/d/19UoIh_SVrMy_b2Sx5ZaeOJttm6P0Qmyss2rdBuyfoic/edit +@dataclass(eq=False) +class ViewAndMutationMeta: + # length = # user inputs + # This gives us info about every input, and what sort of mutation happened to it (if any) + input_info: list[InputAliasInfo] + + # length = # user outputs + # This gives us info about every output (mostly around whether it aliases other tensors) + output_info: list[OutputAliasInfo] + + # length = the number of intermediate bases appended as outputs to the end of the forward graph. + # Note: this is not necessarily the same thing as: + # len([x for x in output_info if x.output_type == OutputType.alias_of_intermediate]) + # Because outputs might share a ._base, or an output's ._base might itself be + # another user output (in both cases, we won't redundantly append bases to the end of the graph) + num_intermediate_bases: int + + # For inference only: instructs us to keep data-only input mutations directly in the graph + keep_input_mutations: bool + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # These are the FakeTensor (or potential SymInt) outputs that we traced from our + # metadata pass of the user's forward function. + # Their only use today is to pass them as a best-guess for tangents when tracing the joint. + # Stashing them as part of our "metadata" makes it simpler if we want to run our analysis + # pass once, and re-use the output throughout AOTAutograd + traced_tangents: list[Any] + + # Each of these is a list telling us about subclasses for the inputs/outputs/grad_outs + # They are used throughout AOTDispatch to tell us how to generate a list of subclass tensors, + # Given a (potentially larger) list of plain torch tensors. + + # Taking subclass_inp_meta as an example: + # subclass_inp_meta[i] = j (an int) tells us: + # "The i'th user input is not a subclass, and corresponds to inputs[j] of the plain-tensor graph." + # subclass_inp_meta[i] = SubclassCreationMeta(flat_tensor_start_idx=3, arg_count=2) + # "The i'th user input is subclass holding two inner tensors, which are + # inputs[3] and inputs[4] of the plain-tensor graph". + + # length = # user inputs + subclass_inp_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]] + # So, the full set of outputs to the forward graph looks something like: + # (*mutated_inps, *user_outs, *intermediate_bases, *saved_for_bw_tensors) + # where the first 3 of those 4 can be subclasses + # (but not saved_for_bw tensors, since these are internal to the compiler + # and not user visible, so there's no point in wrapping/unwrapping them at runtime). + # This list contains subclass information on all of the fw graph outputs + # except for saved_for_bw_tensors. + subclass_fw_graph_out_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]] + # length = # backward graph inputs + subclass_tangent_meta: list[Union[PlainTensorMeta, SubclassCreationMeta]] + # TODO: we should kill this + # (need to default it to not break internal) + is_train: bool = False + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # At runtime, we don't keep the traced_tangents around since they're not serializable. + # Instead, we keep any necessary subclass metadata necessary about each traced_tangent. + # This list is generated after calling make_runtime_safe(). + traced_tangent_metas: Optional[list[Any]] = None + + num_symints_saved_for_bw: Optional[int] = None + + # The grad_enabled mutation that will be emitted in the runtime_wrapper epilogue + # NOTE: AOTAutograd will assume that the ambient `is_grad_enabled` is the grad mode + # that is intended to be in effect prior to running the graph, in keeping with + # equivalence to eager mode. It is the responsibility of upstream graph acquisition + # to reset the grad mode to its pre-graph value prior to calling aot_autograd. + grad_enabled_mutation: Optional[bool] = None + + # Keeps track of whether `torch.use_deterministic_algorithms` was turned on + # when the forward was run. If deterministic mode was turned off during the + # forward, but is turned on during the backward call, then an error is + # raised + deterministic: Optional[bool] = None + + # Keeps track of which input indices store parameters (which we will treat as static) + static_input_indices: list[int] = field(default_factory=list) + + # Map of effect type (ex. _EffectType.ORDERED) to token. If there are + # side-effectful operators, FunctionalTensorMode will populate this + # dictionary telling us how many tokens we will need during tracing. + tokens: dict[Any, torch.Tensor] = field(default_factory=dict) + + # Only filled in if/when we trace the joint function + # If an input requires grad and is mutated in the backward, it is only safe to keep the mutation + # in the graph if gradients are disabled while the backward runs + # (grad mode is disabled by default when users run the backward, but can be turned on with create_graph=True) + # At runtime during the backward, we use this list of indices to error properly if we find out + # that it was not safe to include a backward mutation in the graph. + indices_of_inputs_that_requires_grad_with_mutations_in_bw: list[int] = field( + default_factory=list + ) + + # Indexes of saved tensors which are donated buffer. + # Donated buffer means the tensor is not alias of any forward user input, forward user output, + # and backward output. + bw_donated_idxs: Optional[list[int]] = None + + # Number of tokens used in backward, appended at the end of backward outputs. + # Filled after tracing joint function. + num_backward_tokens: int = 0 + + # Number of rng states that will get thread into the forward and backward for + # cudagraph compatible run_and_save_rng + num_graphsafe_rng_states: int = 0 + + graphsafe_rng_state_index: Optional[int] = None + + def __post_init__(self): + # pre-compute the indices of the inputs that are mutated. + # When keep_input_mutations is set, we don't need to worry about our epilogue + # handling data-only mutations, because we keep them directly in the graph. + mutated_inp_runtime_indices = [ + i + for i, m in enumerate(self.input_info) + if (m.mutation_type == MutationType.MUTATED_OUT_GRAPH) + ] + + mutated_graph_handled_indices = [ + i + for i, m in enumerate(self.input_info) + if m.mutation_type == MutationType.MUTATED_IN_GRAPH + ] + self.mutated_graph_handled_indices = mutated_graph_handled_indices + self.num_mutated_graph_handled_indices = len(self.mutated_graph_handled_indices) + + mutated_graph_handled_indices_seen_by_autograd = [ + i + for i in mutated_graph_handled_indices + if not self.input_info[i].mutations_hidden_from_autograd + ] + + self.mutated_graph_handled_indices_seen_by_autograd = ( + mutated_graph_handled_indices_seen_by_autograd + ) + self.num_mutated_graph_handled_indices_seen_by_autograd = len( + self.mutated_graph_handled_indices_seen_by_autograd + ) + + aliased_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type + not in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + unsafe_view_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type is OutputType.unsafe_view_alias + ] + + # This is pre-computed in post_init for perf. + # It contains the index of every element + # of input_info that corresponds to a mutation (data or metadata or both) + self.mutated_inp_runtime_indices = mutated_inp_runtime_indices + self.num_mutated_inp_runtime_indices = len(self.mutated_inp_runtime_indices) + + # This is pre-computed for perf. + # It contains the index of every element + # of output_info that corresponds to an alias (either of an input or intermediate) + self.aliased_out_indices = aliased_out_indices + self.unsafe_view_out_indices = unsafe_view_out_indices + self.num_outputs = len(self.output_info) + self.num_outputs_non_aliased = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + ) + self.num_outputs_aliased_to_inputs = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_input, + OutputType.is_input, + ] + ] + ) + self.num_unsafe_view_outputs = len(self.unsafe_view_out_indices) + self.num_outputs_aliased_to_intermediates = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + OutputType.alias_of_intermediate_base_is_user_output, + ] + ] + ) + self.num_outputs_aliased = ( + self.num_outputs_aliased_to_inputs + + self.num_outputs_aliased_to_intermediates + ) + + self.dynamic_outputs = any(o.dynamic_dims for o in self.output_info) + # See Note: [AOTAutograd Backward Guards] + # This is pre-computed for fast asserts on the types of our grad_outputs in the backward. + # Eventually, we should kill this and replace with real backward guards. + # (we want to precompute the "runtime" types, so replace FakeTensor with torch.Tensor) + self.output_types = [ + torch.Tensor if isinstance(x, FakeTensor) else type(x) + for x in self.traced_tangents + ] + + self.is_rng_op_functionalized = config.functionalize_rng_ops + # All of the above metadata is collected by tracing the fw function. + # However, extra outputs for rng offsets behave differently. Both fwd + # and bwd graphs have their own outputs for the total consumed offsets. + # Unlike mutated inputs, we don't have to worry about sending the right + # set of tensors between fwd and bwd. Fwd and bwd offsets are + # independent and simpler to handle. Therefore, we track them + # separately. + self.num_outputs_rng_offset = 1 if self.is_rng_op_functionalized else 0 + + # Our forward() returns both (tokens, mutated_inputs, outputs, output_intermediate_bases, saved_tensors, saved_symints) + # Tokens will be split out before mutations/view handling and we do not count them here. + self.num_forward_returns = ( + self.num_mutated_inp_runtime_indices + + self.num_outputs + + self.num_intermediate_bases + ) + # In case of functionalization of rng ops, the fw_module returns one + # additional output for rng offset. This rng offset is used right + # away to advance the rng state, and is not passed on to the raw + # outputs. However, we need to know the exact boundary to identify + # which tensors to be saved for the bwd graph. num_forward captures + # this information. + self.num_forward = self.num_forward_returns + self.num_outputs_rng_offset + + def make_runtime_safe(self): + """ + There are various fields in ViewAndMutationMeta that aren't serializable. This function is called after all tracing + is completed to simplify certain fields in the metadata so that they can be safely cached. + + Doing so may lose information (in the case of traced_tangents), but none of the information is needed at runtime. + """ + # TODO: This function is only a best effort: there are other fields that may not be cache safe + # (i.e., there's no guarantee that tensor_flatten() returns a serializable result), or that + # SubclassCreationMeta is cache safe. + assert self.traced_tangent_metas is None + + def extract_metadata(t): + if isinstance(t, torch.Tensor) and is_traceable_wrapper_subclass(t): + (inner_tensors, flatten_spec) = t.__tensor_flatten__() # type: ignore[attr-defined] + # Technically, we only need the flatten_spec, not the inner tensors. + # However, some Tensor subclasses (like TwoTensor) may have flatten_spec = None. + # And we want to be able to assert that this metadata is non-None, + # to distinguish between "this was a tensor subclass with no metadata" vs. + # "this wasn't a tensor subclass at all". + return (inner_tensors, flatten_spec) + else: + return None + + self.traced_tangent_metas = [extract_metadata(t) for t in self.traced_tangents] + # Clear traced tangents at runtime + self.traced_tangents = [] + new_output_info = [] + for out in self.output_info: + if config.view_replay_for_aliased_outputs: + new_out = out + else: + # If we're not using view_replay, remove the functional tensor. + # Functional tensors are unfortunately not serializable, + # so doing this is required for AOTAutograd caching. + new_out = dataclasses.replace(out, functional_tensor=None) + new_output_info.append(new_out) + self.output_info = new_output_info + for inp_meta in self.subclass_inp_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_fw_graph_out_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_tangent_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + + @property + def tensors_saved_for_backwards_slice(self): + assert self.num_symints_saved_for_bw is not None + if self.num_symints_saved_for_bw > 0: + return slice(self.num_forward, -self.num_symints_saved_for_bw) + else: + return slice(self.num_forward, None) + + @property + def symints_saved_for_backwards_slice(self): + assert self.num_symints_saved_for_bw is not None + if self.num_symints_saved_for_bw > 0: + return slice(-self.num_symints_saved_for_bw, None) + else: + return slice(0, 0) # empty slice + + def __eq__(self, other): + if not isinstance(other, ViewAndMutationMeta): + return NotImplemented + return ( + self.input_info == other.input_info + and self.output_info == other.output_info + and self.num_intermediate_bases == other.num_intermediate_bases + and self.keep_input_mutations == other.keep_input_mutations + and self.is_rng_op_functionalized == other.is_rng_op_functionalized + and self.num_outputs_rng_offset == other.num_outputs_rng_offset + and len(self.traced_tangents) == len(other.traced_tangents) + and all( + x.shape == y.shape and x.dtype == y.dtype + for x, y, in zip(self.traced_tangents, other.traced_tangents) + ) + and self.num_backward_tokens == other.num_backward_tokens + ) + + +@dataclass(eq=False) +class SubclassMeta: + # A copy of all forward metadata, but computed on the *dense* tensor forward (after desugaring subclasses) + # So for example, if the user had a model containing two `TwoTensor` inputs, + # Then `SubclassMeta.fw_metadata.input_infos` would have length 4 here. + fw_metadata: ViewAndMutationMeta + + # Note: [Computing Subclass Metadata about grad_inputs] + # Given a list of flattened, plain tensor grad_inputs, this tells us how to reconstruct the grad_input subclasses + # + # You might think: why not just assume that all grad_inputs will have the same subclass-ness as the original inputs? + # (AOTAutograd generally assumes other properties, e.g. that grad_outputs are contiguous) + # + # This doesn't really work though. take this example: + # + # def f(DoubleTensor, DenseTensor): + # return DoubleTensor * DenseTensor + # + # In the above example, the .grad field of *both* DoubleTensor and DenseTensor will be a DoubleTensor. + # When we trace out a joint fw-bw graph, we'll end up returning two subclasses for the two grad_inputs. + # This means that our backward graph will return 4 outputs (two dense tensors for each DoubleTensor grad_input) + # and we need to properly store the metadata that tells us how to turn these 4 outputs back into DoubleTensors. + # + # Note that this info **cannot** easily be figured out from ViewAndMutationMeta. + # We can only compute this info by tracing the entire joint and examining the grad_inputs that we computed. + # + # See Note: [AOTAutograd Backward Guards] + # This will also eventually require us to install backward guards, + # in case we made incorrect assumptions about the subclass-ness of our grad_outputs + # + # Optional field because we don't compute for inference graphs + grad_input_metas: Optional[ + list[Union[PlainTensorMeta, SubclassCreationMeta]] + ] = None + + def __init__(self) -> None: + # The fields in this class get set after its construction. + pass + + +# This class exists because: +# - the autograd.Function.forward() in aot autograd returns outputs that might alias inputs +# - we only care about the metadata on those aliases, so we can regenerate them. +# We do not want them to participate in the autograd.Function. +# We do that by wrapping them in an opaque class, so the autograd.Function +# does not know to treat them as tensors. +@dataclass(frozen=True) +class TensorAlias: + alias: torch.Tensor + + +@dataclass +class BackwardSignature: + """ + Provides information about the backward section of an exported + joint forward-backward graph. + For a particular fx GraphModule, this class contains information on: + (1) A mapping from each gradient (backwards output) to the parameter + it corresponds to (forward input) + (2) A mapping from each gradient (backwards output) to the user input + it corresponds to (forward input) + (3) Which of the forward outputs corresponds to the loss, that we backprop on. + + Each string name is the `node.name` of the corresponding node in the fx graph. + """ + + gradients_to_parameters: dict[str, str] + gradients_to_user_inputs: dict[str, str] + loss_output: str + + +GraphOutputName = NewType("GraphOutputName", str) +GraphInputName = NewType("GraphInputName", str) +FQN = NewType("FQN", str) + + +@dataclass +class GraphSignature: + """ + Provides information about an exported module. + For a particular fx GraphModule, this class contains information on: + (1) Which graph inputs are parameters, buffers, or user inputs + (2) (for params/buffers) a mapping from the name of each graph argument + to its parameter/buffer FQN in the original nn.Module. + (3) If there are input mutations, these are represented as extra outputs + in the fx GraphModule. We provide a mapping from these + extra output names to the names of the actual inputs. + (4) The pytree metadata on how to flatten/unflatten inputs and outputs. + The corresponding FX GraphModule only accepts and returns + pytree-flattened inputs/outputs. + (5) (Optionally) if the FX is a joint forward-backward graph, we provide + a signature on the backward section of the joint graph. + """ + + parameters: list[FQN] + buffers: list[FQN] + + user_inputs: list[GraphInputName] + user_outputs: list[GraphOutputName] + inputs_to_parameters: dict[GraphInputName, FQN] + inputs_to_buffers: dict[GraphInputName, FQN] + + # If the user's module mutates a buffer, + # it's represented in the graph as an extra graph output. + # This dict is a mapping from + # "graph outputs that correspond to updated buffers" + # to the FQN names of those mutated buffers. + buffers_to_mutate: dict[GraphOutputName, FQN] + user_inputs_to_mutate: dict[GraphOutputName, GraphInputName] + + in_spec: pytree.TreeSpec + out_spec: pytree.TreeSpec + + backward_signature: Optional[BackwardSignature] + + input_tokens: list[GraphInputName] + output_tokens: list[GraphOutputName] + + @classmethod + def from_tracing_metadata( + cls, + *, + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + graph_input_names: list[str], + graph_output_names: list[str], + view_mutation_metadata: ViewAndMutationMeta, + named_parameters: list[str], + named_buffers: list[str], + num_user_inputs: int, + num_user_outputs: int, + loss_index: Optional[int], + backward_signature: Optional[BackwardSignature], + ) -> "GraphSignature": + graph_inputs = graph_input_names + graph_outputs = graph_output_names + parameters = list(named_parameters) + buffers = list(named_buffers) + num_tokens = len(view_mutation_metadata.tokens) + + # Calling convention assumptions: + # (1) graph inputs = (input_tokens, params, buffers, user_inputs) + # (2) graph outputs = (output_tokens, mutated_inputs, user_outs, param_gradients) + # (If we are capturing an inference graph, this convention is identical + # except that param_gradients is empty) + # See Note [Side-Effectful Tokens in AOTAutograd] for information on tokens + + # Address input calling conventions: + start, stop = 0, num_tokens + input_tokens = graph_inputs[start:stop] + + start, stop = stop, stop + len(parameters) + inputs_to_parameters = dict(zip(graph_inputs[start:stop], parameters)) + + start, stop = stop, stop + len(buffers) + inputs_to_buffers = dict( + zip( + graph_inputs[start:stop], + buffers, + ) + ) + + start, stop = stop, stop + num_user_inputs + user_inputs = graph_inputs[start:stop] + + # We should've gone through all the inputs now + assert len(graph_inputs) - stop == 0 + + # Address output calling conventions: + start, stop = 0, num_tokens + output_tokens = graph_outputs[start:stop] + + names = [*input_tokens, *parameters, *buffers, *user_inputs] + mutations = [] + for idx, input_info in enumerate(view_mutation_metadata.input_info): + if input_info.mutates_data: + # Only buffers can be mutated, not parameters + assert idx >= len(parameters) + mutations.append(names[idx + num_tokens]) + + assert len(mutations) == view_mutation_metadata.num_mutated_inp_runtime_indices + + start, stop = ( + stop, + stop + view_mutation_metadata.num_mutated_inp_runtime_indices, + ) + outputs_to_mutations = dict(zip(graph_outputs[start:stop], mutations)) + + user_inputs_to_mutate = {} + buffers_to_mutate = {} + for output_name, mutation_name in outputs_to_mutations.items(): + if mutation_name in user_inputs: + user_inputs_to_mutate[output_name] = mutation_name + else: + assert mutation_name in buffers + buffers_to_mutate[output_name] = mutation_name + + start, stop = stop, stop + num_user_outputs + user_outputs = graph_outputs[start:stop] + + unused_outputs = len(graph_outputs) - stop + if backward_signature is not None: + unused_outputs -= len(backward_signature.gradients_to_parameters) + len( + backward_signature.gradients_to_user_inputs + ) + assert unused_outputs == 0 + + return GraphSignature( + parameters=parameters, # type: ignore[arg-type] + buffers=buffers, # type: ignore[arg-type] + user_inputs=user_inputs, # type: ignore[arg-type] + user_outputs=user_outputs, # type: ignore[arg-type] + inputs_to_buffers=inputs_to_buffers, # type: ignore[arg-type] + inputs_to_parameters=inputs_to_parameters, # type: ignore[arg-type] + user_inputs_to_mutate=user_inputs_to_mutate, + buffers_to_mutate=buffers_to_mutate, # type: ignore[arg-type] + in_spec=in_spec, + out_spec=out_spec, + backward_signature=backward_signature, + input_tokens=input_tokens, # type: ignore[arg-type] + output_tokens=output_tokens, # type: ignore[arg-type] + ) + + +@dataclass +class AOTAutogradCacheInfo: + cache_key: str + start_time_ns: int + + +@dataclass +class AOTConfig: + """ + Configuration for AOTDispatcher + """ + + fw_compiler: Callable + bw_compiler: Callable + partition_fn: Callable + decompositions: dict[OpOverload, Callable] + num_params_buffers: int + aot_id: int + keep_inference_input_mutations: bool + is_export: bool = False + no_tangents: bool = False + dynamic_shapes: bool = False + aot_autograd_arg_pos_to_source: Optional[list[Source]] = None + static_input_indices: Optional[list[int]] = None + inference_compiler: Optional[Callable] = None + enable_log: bool = True + # this is always false outside of export. + pre_dispatch: bool = False + # Key to use for AOTAutogradCache + cache_info: Optional[AOTAutogradCacheInfo] = None + + def __post_init__(self): + if self.pre_dispatch: + assert self.is_export, "Can only have pre_dispatch IR for export." + + +SubclassTracingInfo = collections.namedtuple( + "SubclassTracingInfo", + ["plain_tensor_trace_fn", "plain_tensor_args", "maybe_subclass_meta"], +) diff --git a/shared/package-files/7c/7ca96986b6057bed829dc1372f25807e4cb339537180cb12ec76c9969ea1e3bc/vcfcall.c b/shared/package-files/7c/7ca96986b6057bed829dc1372f25807e4cb339537180cb12ec76c9969ea1e3bc/vcfcall.c new file mode 100644 index 0000000000000000000000000000000000000000..13e516f83879956a2487757e3dd0d1b90efa57c1 --- /dev/null +++ b/shared/package-files/7c/7ca96986b6057bed829dc1372f25807e4cb339537180cb12ec76c9969ea1e3bc/vcfcall.c @@ -0,0 +1,1206 @@ +/* vcfcall.c -- SNP/indel variant calling from VCF/BCF. + + Copyright (C) 2013-2024 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "call.h" +#include "prob1.h" +#include "ploidy.h" +#include "gvcf.h" +#include "regidx.h" +#include "vcfbuf.h" + +void error(const char *format, ...); + +#define CF_NO_GENO 1 +#define CF_INS_MISSED (1<<1) +#define CF_CCALL (1<<2) +// (1<<3) +// (1<<4) +// (1<<5) +#define CF_ACGT_ONLY (1<<6) +#define CF_QCALL (1<<7) +#define CF_ADJLD (1<<8) +#define CF_NO_INDEL (1<<9) +#define CF_ANNO_MAX (1<<10) +#define CF_MCALL (1<<11) +#define CF_PAIRCALL (1<<12) +#define CF_QCNT (1<<13) +#define CF_INDEL_ONLY (1<<14) + +typedef struct +{ + tgt_als_t *als; + int nmatch_als, ibuf; +} +rec_tgt_t; + +typedef struct +{ + int flag; // combination of CF_* flags above + int output_type, n_threads, record_cmd_line, clevel; + htsFile *bcf_in, *out_fh; + char *bcf_fname, *output_fname; + char **samples; // for subsampling and ploidy + int nsamples, *samples_map; // mapping from output sample names to original VCF + char *regions, *targets; // regions to process + int regions_is_file, targets_is_file, regions_overlap; + regidx_t *tgt_idx; + regitr_t *tgt_itr, *tgt_itr_prev, *tgt_itr_tmp; + vcfbuf_t *vcfbuf; + + char *samples_fname; + int samples_is_file; + int *sample2sex; // mapping for ploidy. If negative, interpreted as -1*ploidy + int *sex2ploidy, *sex2ploidy_prev, nsex; + ploidy_t *ploidy; + gvcf_t *gvcf; + + bcf1_t *missed_line; + call_t aux; // parameters and temporary data + kstring_t str; + + int argc; + char **argv; + char *index_fn; + int write_index; + + // int flag, prior_type, n1, n_sub, *sublist, n_perm; + // uint32_t *trio_aux; + // char *prior_file, **subsam; + // uint8_t *ploidy; + // double theta, pref, indel_frac, min_smpl_frac, min_lrt; + // Permutation tests + // int n_perm, *seeds; + // double min_perm_p; + // void *bed; +} +args_t; + +static char **add_sample(void *name2idx, char **lines, int *nlines, int *mlines, char *name, char sex, int *ith) +{ + int ret = khash_str2int_get(name2idx, name, ith); + if ( ret==0 ) return lines; + + hts_expand(char*,(*nlines+1),*mlines,lines); + int len = strlen(name); + lines[*nlines] = (char*) malloc(len+3); + memcpy(lines[*nlines],name,len); + lines[*nlines][len] = ' '; + lines[*nlines][len+1] = sex; + lines[*nlines][len+2] = 0; + *ith = *nlines; + (*nlines)++; + khash_str2int_set(name2idx, strdup(name), *ith); + return lines; +} + +typedef struct +{ + const char *alias, *about, *ploidy; +} +ploidy_predef_t; + +static ploidy_predef_t ploidy_predefs[] = +{ + { .alias = "GRCh37", + .about = "Human Genome reference assembly GRCh37 / hg19", + .ploidy = + "X 1 60000 M 1\n" + "X 2699521 154931043 M 1\n" + "Y 1 59373566 M 1\n" + "Y 1 59373566 F 0\n" + "MT 1 16569 M 1\n" + "MT 1 16569 F 1\n" + "chrX 1 60000 M 1\n" + "chrX 2699521 154931043 M 1\n" + "chrY 1 59373566 M 1\n" + "chrY 1 59373566 F 0\n" + "chrM 1 16569 M 1\n" + "chrM 1 16569 F 1\n" + "* * * M 2\n" + "* * * F 2\n" + }, + { .alias = "GRCh38", + .about = "Human Genome reference assembly GRCh38 / hg38", + .ploidy = + "X 1 9999 M 1\n" + "X 2781480 155701381 M 1\n" + "Y 1 57227415 M 1\n" + "Y 1 57227415 F 0\n" + "MT 1 16569 M 1\n" + "MT 1 16569 F 1\n" + "chrX 1 9999 M 1\n" + "chrX 2781480 155701381 M 1\n" + "chrY 1 57227415 M 1\n" + "chrY 1 57227415 F 0\n" + "chrM 1 16569 M 1\n" + "chrM 1 16569 F 1\n" + "* * * M 2\n" + "* * * F 2\n" + }, + { .alias = "X", + .about = "Treat male samples as haploid and female as diploid regardless of the chromosome name", + .ploidy = + "* * * M 1\n" + "* * * F 2\n" + }, + { .alias = "Y", + .about = "Treat male samples as haploid and female as no-copy, regardless of the chromosome name", + .ploidy = + "* * * M 1\n" + "* * * F 0\n" + }, + { .alias = "1", + .about = "Treat all samples as haploid", + .ploidy = + "* * * * 1\n" + }, + { .alias = "2", + .about = "Treat all samples as diploid", + .ploidy = + "* * * * 2\n" + }, + { + .alias = NULL, + .about = NULL, + .ploidy = NULL, + } +}; + +// only 5 columns are required and the first is ignored: +// ignored,sample,father(or 0),mother(or 0),sex(1=M,2=F) +static char **parse_ped_samples(call_t *call, char **vals, int nvals, int *nsmpl) +{ + int i, j, mlines = 0, nlines = 0; + kstring_t str = {0,0,0}, fam_str = {0,0,0}; + void *name2idx = khash_str2int_init(); + char **lines = NULL; + for (i=0; infams++; + hts_expand(family_t, call->nfams, call->mfams, call->fams); + family_t *fam = &call->fams[call->nfams-1]; + fam_str.l = 0; + ksprintf(&fam_str,"father=%s, mother=%s, child=%s", col_ends[1]+1,col_ends[2]+1,col_ends[0]+1); + fam->name = strdup(fam_str.s); + + if ( !khash_str2int_has_key(name2idx, col_ends[1]+1) ) + lines = add_sample(name2idx, lines, &nlines, &mlines, col_ends[1]+1, 'M', &fam->sample[FATHER]); + if ( !khash_str2int_has_key(name2idx, col_ends[2]+1) ) + lines = add_sample(name2idx, lines, &nlines, &mlines, col_ends[2]+1, 'F', &fam->sample[MOTHER]); + + khash_str2int_get(name2idx, col_ends[0]+1, &fam->sample[CHILD]); + khash_str2int_get(name2idx, col_ends[1]+1, &fam->sample[FATHER]); + khash_str2int_get(name2idx, col_ends[2]+1, &fam->sample[MOTHER]); + } + } + free(str.s); + free(fam_str.s); + khash_str2int_destroy_free(name2idx); + + if ( i!=nvals ) return NULL; // not a ped file + + *nsmpl = nlines; + return lines; +} + + +/* + * Reads sample names and their ploidy (optional) from a file. + * Alternatively, if no such file exists, the file name is interpreted + * as a comma-separated list of samples. When ploidy is not present, + * the default ploidy 2 is assumed. + */ +static void set_samples(args_t *args, const char *fn, int is_file) +{ + int i, nlines; + char **lines = hts_readlist(fn, is_file, &nlines); + if ( !lines ) error("Could not read the file: %s\n", fn); + + int nsmpls; + char **smpls = parse_ped_samples(&args->aux, lines, nlines, &nsmpls); + if ( smpls ) + { + for (i=0; isamples_map = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr)); // for subsetting + args->sample2sex = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr)); + int dflt_sex_id = ploidy_nsex(args->ploidy) - 1; + for (i=0; iaux.hdr); i++) args->sample2sex[i] = dflt_sex_id; + + int *old2new = (int*) malloc(sizeof(int)*bcf_hdr_nsamples(args->aux.hdr)); + for (i=0; iaux.hdr); i++) old2new[i] = -1; + + int nsmpl = 0, map_needed = 0; + for (i=0; iaux.hdr, BCF_DT_SAMPLE, ss); + if ( ismpl < 0 ) { fprintf(stderr,"Warning: No such sample in the VCF: %s\n",ss); continue; } + if ( old2new[ismpl] != -1 ) { fprintf(stderr,"Warning: The sample is listed multiple times: %s\n",ss); continue; } + + ss = se+(x != '\0'); + while ( *ss && isspace(*ss) ) ss++; + if ( !*ss ) ss = "2"; // default ploidy + se = ss; + while ( *se && !isspace(*se) ) se++; + if ( se==ss ) { *xptr = x; error("Could not parse: \"%s\"\n", lines[i]); } + + if ( ss[1]==0 && (ss[0]=='0' || ss[0]=='1' || ss[0]=='2') ) + args->sample2sex[nsmpl] = -1*(ss[0]-'0'); + else + args->sample2sex[nsmpl] = ploidy_add_sex(args->ploidy, ss); + + if ( ismpl!=nsmpl ) map_needed = 1; + args->samples_map[nsmpl] = ismpl; + old2new[ismpl] = nsmpl; + nsmpl++; + } + + for (i=0; iaux.nfams; i++) + { + int j, nmiss = 0; + family_t *fam = &args->aux.fams[i]; + for (j=0; j<3; j++) + { + fam->sample[i] = old2new[fam->sample[i]]; + if ( fam->sample[i]<0 ) nmiss++; + } + assert( nmiss==0 || nmiss==3 ); + } + free(old2new); + + if ( !map_needed ) { free(args->samples_map); args->samples_map = NULL; } + + args->nsamples = nsmpl; + args->samples = lines; +} + +static void init_missed_line(args_t *args) +{ + int i; + for (i=0; iaux.hdr); i++) + { + args->aux.gts[i*2] = bcf_gt_missing; + args->aux.gts[i*2+1] = bcf_int32_vector_end; + } + args->missed_line = bcf_init1(); + bcf_update_genotypes(args->aux.hdr, args->missed_line, args->aux.gts, 2*bcf_hdr_nsamples(args->aux.hdr)); + bcf_float_set_missing(args->missed_line->qual); +} + +static int tgt_parse(const char *line, char **chr_beg, char **chr_end, uint32_t *beg, uint32_t *end, void *payload, void *usr) +{ + char *ss = (char*) line; + while ( *ss && isspace(*ss) ) ss++; + if ( !*ss ) { fprintf(stderr,"Could not parse the line: %s\n", line); return -2; } + if ( *ss=='#' ) return -1; // skip comments + + char *se = ss; + while ( *se && !isspace(*se) ) se++; + + *chr_beg = ss; + *chr_end = se-1; + + if ( !*se ) { fprintf(stderr,"Could not parse the line: %s\n", line); return -2; } + + ss = se+1; + *beg = strtod(ss, &se); + if ( ss==se ) { fprintf(stderr,"Could not parse tab line: %s\n", line); return -2; } + if ( *beg==0 ) { fprintf(stderr,"Could not parse tab line, expected 1-based coordinate: %s\n", line); return -2; } + (*beg)--; + *end = *beg; + + if ( !usr ) return 0; // allele information not required + + ss = se+1; + tgt_als_t *als = (tgt_als_t*)payload; + als->used = 0; + als->n = 0; + als->allele = NULL; + while ( *ss ) + { + se = ss; + while ( *se && *se!=',' && !isspace(*se) ) se++; + als->n++; + als->allele = (char**)realloc(als->allele,als->n*sizeof(*als->allele)); + als->allele[als->n-1] = (char*)malloc(se-ss+1); + memcpy(als->allele[als->n-1],ss,se-ss); + als->allele[als->n-1][se-ss] = 0; + ss = se+1; + if ( !*se || isspace(*se) ) break; + } + if ( als->n<2 ) error("Unable to parse the -T file; expected CHROM\\tPOS\\tREF,ALT with -C alleles but found instead:\n\t%s\n",line); + return 0; +} +static void tgt_free(void *payload) +{ + tgt_als_t *als = (tgt_als_t*)payload; + int i; + for (i=0; in; i++) free(als->allele[i]); + free(als->allele); +} +static void tgt_flush_region(args_t *args, char *chr, uint32_t beg, uint32_t end) +{ + if ( !regidx_overlap(args->tgt_idx, chr,beg,end,args->tgt_itr_tmp) ) return; + while ( regitr_overlap(args->tgt_itr_tmp) ) + { + if ( args->tgt_itr_tmp->beg < beg ) continue; + + tgt_als_t *tgt_als = ®itr_payload(args->tgt_itr_tmp,tgt_als_t); + if ( tgt_als->used ) continue; + + args->missed_line->rid = bcf_hdr_name2id(args->aux.hdr,chr); + args->missed_line->pos = args->tgt_itr_tmp->beg; + bcf_unpack(args->missed_line,BCF_UN_ALL); + bcf_update_alleles(args->aux.hdr, args->missed_line, (const char**)tgt_als->allele, tgt_als->n); + tgt_als->used = 1; + if ( bcf_write1(args->out_fh, args->aux.hdr, args->missed_line)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args->output_fname); + } +} +static void tgt_flush(args_t *args, bcf1_t *rec) +{ + if ( rec ) + { + char *chr = (char*)bcf_seqname(args->aux.hdr,rec); + + if ( !args->tgt_itr_prev ) // first record + tgt_flush_region(args,chr,0,rec->pos-1); + + else if ( strcmp(chr,args->tgt_itr_prev->seq) ) // first record on a new chromosome + { + tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg+1,REGIDX_MAX); + tgt_flush_region(args,chr,0,rec->pos-1); + } + else // another record on the same chromosome + tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg,rec->pos-1); + } + else + { + // flush everything + if ( args->tgt_itr_prev ) + tgt_flush_region(args,args->tgt_itr_prev->seq,args->tgt_itr_prev->beg,REGIDX_MAX); + + int i, nchr = 0; + char **chr = regidx_seq_names(args->tgt_idx, &nchr); + for (i=0; i" is not present at indels sites and there are no other symbolic alleles than <*> + if ( als[1][0]=='<' ) return 0; + + int i; + for (i=0; ivcfbuf ) + { + while ( bcf_sr_next_line(args->aux.srs) ) + { + rec = args->aux.srs->readers[0].buffer[0]; + if ( args->aux.srs->errnum || rec->errcode ) error("Error: could not parse the input VCF\n"); + if ( args->tgt_idx ) + { + if ( !regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec),rec->pos,rec->pos,args->tgt_itr) ) continue; + + // For backward compatibility: require the exact position, not an interval overlap + int pos_match = 0; + while ( regitr_overlap(args->tgt_itr) ) + { + if ( args->tgt_itr->beg != rec->pos ) continue; + pos_match = 1; + break; + } + if ( !pos_match ) continue; + } + if ( args->samples_map ) bcf_subset(args->aux.hdr, rec, args->nsamples, args->samples_map); + bcf_unpack(rec, BCF_UN_STR); + return rec; + } + return NULL; + } + + // If we are here,-C alleles was given and vcfbuf and tgt_idx are set + + // Fill the buffer with duplicate lines + int vcfbuf_full = 1; + int nbuf = vcfbuf_nsites(args->vcfbuf); + bcf1_t *rec0 = NULL, *recN = NULL; + if ( nbuf==0 ) vcfbuf_full = 0; + else if ( nbuf==1 ) + { + vcfbuf_full = 0; + rec0 = vcfbuf_peek(args->vcfbuf, 0); + } + else + { + rec0 = vcfbuf_peek(args->vcfbuf, 0); + recN = vcfbuf_peek(args->vcfbuf, nbuf-1); + if ( rec0->rid == recN->rid && rec0->pos == recN->pos ) vcfbuf_full = 0; + } + if ( !vcfbuf_full ) + { + while ( bcf_sr_next_line(args->aux.srs) ) + { + rec = args->aux.srs->readers[0].buffer[0]; + if ( args->aux.srs->errnum || rec->errcode ) error("Error: could not parse the input VCF\n"); + if ( !regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec),rec->pos,rec->pos,args->tgt_itr) ) continue; + // as above: require the exact position, not an interval overlap + int exact_match = 0; + while ( regitr_overlap(args->tgt_itr) ) + { + if ( args->tgt_itr->beg != rec->pos ) continue; + exact_match = 1; + break; + } + if ( !exact_match ) continue; + + if ( args->samples_map ) bcf_subset(args->aux.hdr, rec, args->nsamples, args->samples_map); + bcf_unpack(rec, BCF_UN_STR); + if ( !rec0 ) rec0 = rec; + recN = rec; + args->aux.srs->readers[0].buffer[0] = vcfbuf_push(args->vcfbuf, rec); + if ( rec0->rid!=recN->rid || rec0->pos!=recN->pos ) break; + } + } + + nbuf = vcfbuf_nsites(args->vcfbuf); + int n, i,j; + for (n=nbuf; n>1; n--) + { + recN = vcfbuf_peek(args->vcfbuf, n-1); + if ( rec0->rid==recN->rid && rec0->pos==recN->pos ) break; + } + if ( n==0 ) + { + assert( !nbuf ); + return NULL; + } + + // Find the VCF and tab record with the best matching combination of alleles, prioritize + // records of the same type (snp vs indel) + rec_tgt_t rec_tgt; + memset(&rec_tgt,0,sizeof(rec_tgt)); + regidx_overlap(args->tgt_idx, bcf_seqname(args->aux.hdr,rec0),rec0->pos,rec0->pos,args->tgt_itr); + regitr_t *tmp_itr = regitr_init(args->tgt_idx); + for (i=0; itgt_itr); + rec = vcfbuf_peek(args->vcfbuf, i); + int rec_indel = is_indel(rec->n_allele, rec->d.allele) ? 1 : -1; + while ( regitr_overlap(tmp_itr) ) + { + if ( tmp_itr->beg != rec->pos ) continue; + tgt_als_t *als = ®itr_payload(tmp_itr,tgt_als_t); + if ( als->used ) continue; + int nmatch_als = 0; + vcmp_t *vcmp = vcmp_init(); + int ret = vcmp_set_ref(vcmp, rec->d.allele[0], als->allele[0]); + if ( ret==0 ) + { + nmatch_als++; + if ( rec->n_allele > 1 && als->n > 1 ) + { + for (j=1; jn; j++) + { + if ( vcmp_find_allele(vcmp, rec->d.allele+1, rec->n_allele-1, als->allele[j])>=0 ) nmatch_als++; + } + } + } + int als_indel = is_indel(als->n, als->allele) ? 1 : -1; + nmatch_als *= rec_indel*als_indel; + if ( nmatch_als > rec_tgt.nmatch_als || !rec_tgt.als ) + { + rec_tgt.nmatch_als = nmatch_als; + rec_tgt.als = als; + rec_tgt.ibuf = i; + } + vcmp_destroy(vcmp); + } + } + regitr_destroy(tmp_itr); + + args->aux.tgt_als = rec_tgt.als; + if ( rec_tgt.als ) rec_tgt.als->used = 1; + + rec = vcfbuf_remove(args->vcfbuf, rec_tgt.ibuf); + return rec; +} + +static void init_data(args_t *args) +{ + args->aux.srs = bcf_sr_init(); + + // Open files for input and output, initialize structures + if ( args->targets ) + { + args->tgt_idx = regidx_init(args->targets, tgt_parse, args->aux.flag&CALL_CONSTR_ALLELES ? tgt_free : (regidx_free_f) NULL, sizeof(tgt_als_t), args->aux.flag&CALL_CONSTR_ALLELES ? args : NULL); + args->tgt_itr = regitr_init(args->tgt_idx); + args->tgt_itr_tmp = regitr_init(args->tgt_idx); + } + + if ( args->regions ) + { + bcf_sr_set_opt(args->aux.srs,BCF_SR_REGIONS_OVERLAP,args->regions_overlap); + if ( bcf_sr_set_regions(args->aux.srs, args->regions, args->regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions); + } + + if ( !bcf_sr_add_reader(args->aux.srs, args->bcf_fname) ) + error("Failed to read from %s: %s\n", !strcmp("-",args->bcf_fname)?"standard input":args->bcf_fname,bcf_sr_strerror(args->aux.srs->errnum)); + args->aux.hdr = bcf_sr_get_header(args->aux.srs,0); + + int i; + if ( args->samples_fname ) + { + set_samples(args, args->samples_fname, args->samples_is_file); + if ( args->aux.flag&CALL_CONSTR_TRIO ) + { + if ( 3*args->aux.nfams!=args->nsamples ) error("Expected only trios in %s, sorry!\n", args->samples_fname); + fprintf(stderr,"Detected %d samples in %d trio families\n", args->nsamples,args->aux.nfams); + } + } + if ( args->ploidy ) + { + args->nsex = ploidy_nsex(args->ploidy); + args->sex2ploidy = (int*) calloc(args->nsex,sizeof(int)); + args->sex2ploidy_prev = (int*) calloc(args->nsex,sizeof(int)); + if ( !args->nsamples ) + { + args->nsamples = bcf_hdr_nsamples(args->aux.hdr); + args->sample2sex = (int*) malloc(sizeof(int)*args->nsamples); + for (i=0; insamples; i++) args->sample2sex[i] = args->nsex - 1; + } + } + if ( args->nsamples ) + { + args->aux.ploidy = (uint8_t*) malloc(args->nsamples); + for (i=0; insamples; i++) args->aux.ploidy[i] = ploidy_max(args->ploidy); + for (i=0; insex; i++) args->sex2ploidy_prev[i] = ploidy_max(args->ploidy); + for (i=0; insamples; i++) + if ( args->sample2sex[i] >= args->nsex ) args->sample2sex[i] = args->nsex - 1; + } + + if ( args->gvcf ) + { + int id = bcf_hdr_id2int(args->aux.hdr,BCF_DT_ID,"DP"); + if ( id<0 || !bcf_hdr_idinfo_exists(args->aux.hdr,BCF_HL_FMT,id) ) error("--gvcf output mode requires FORMAT/DP tag, which is not present in the input header\n"); + gvcf_update_header(args->gvcf, args->aux.hdr); + } + + if ( args->samples_map ) + { + args->aux.hdr = bcf_hdr_subset(bcf_sr_get_header(args->aux.srs,0), args->nsamples, args->samples, args->samples_map); + if ( !args->aux.hdr ) error("Error occurred while subsetting samples\n"); + for (i=0; insamples; i++) + if ( args->samples_map[i]<0 ) error("No such sample: %s\n", args->samples[i]); + if ( !bcf_hdr_nsamples(args->aux.hdr) ) error("No matching sample found\n"); + } + else + { + args->aux.hdr = bcf_hdr_dup(bcf_sr_get_header(args->aux.srs,0)); + if ( args->samples ) + { + for (i=0; insamples; i++) + if ( bcf_hdr_id2int(args->aux.hdr,BCF_DT_SAMPLE,args->samples[i])<0 ) + error("No such sample: %s\n", args->samples[i]); + } + } + + if ( args->aux.flag & CALL_CONSTR_ALLELES ) + { + args->vcfbuf = vcfbuf_init(args->aux.hdr, 0); + vcfbuf_set(args->vcfbuf,VCFBUF_DUMMY,1); + } + + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( args->out_fh == NULL ) error("Error: cannot write to \"%s\": %s\n", args->output_fname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads); + + if ( args->flag & CF_QCALL ) + return; + + if ( args->flag & CF_MCALL ) + mcall_init(&args->aux); + + if ( args->flag & CF_CCALL ) + ccall_init(&args->aux); + + bcf_hdr_remove(args->aux.hdr, BCF_HL_INFO, "QS"); + bcf_hdr_remove(args->aux.hdr, BCF_HL_INFO, "I16"); + + if (args->record_cmd_line) bcf_hdr_append_version(args->aux.hdr, args->argc, args->argv, "bcftools_call"); + if ( bcf_hdr_write(args->out_fh, args->aux.hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname); + if ( init_index2(args->out_fh,args->aux.hdr,args->output_fname, + &args->index_fn, args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->output_fname); + + if ( args->flag&CF_INS_MISSED ) init_missed_line(args); +} + +static void destroy_data(args_t *args) +{ + if ( args->vcfbuf ) vcfbuf_destroy(args->vcfbuf); + if ( args->tgt_idx ) + { + regidx_destroy(args->tgt_idx); + regitr_destroy(args->tgt_itr); + regitr_destroy(args->tgt_itr_tmp); + if ( args->tgt_itr_prev ) regitr_destroy(args->tgt_itr_prev); + } + if ( args->flag & CF_CCALL ) ccall_destroy(&args->aux); + else if ( args->flag & CF_MCALL ) mcall_destroy(&args->aux); + else if ( args->flag & CF_QCALL ) qcall_destroy(&args->aux); + int i; + if ( args->samples ) + { + for (i=0; insamples; i++) free(args->samples[i]); + } + if ( args->aux.fams ) + { + for (i=0; iaux.nfams; i++) free(args->aux.fams[i].name); + free(args->aux.fams); + } + if ( args->missed_line ) bcf_destroy(args->missed_line); + ploidy_destroy(args->ploidy); + free(args->sex2ploidy); + free(args->sex2ploidy_prev); + free(args->samples); + free(args->samples_map); + free(args->sample2sex); + free(args->aux.ploidy); + free(args->str.s); + if ( args->gvcf ) gvcf_destroy(args->gvcf); + bcf_hdr_destroy(args->aux.hdr); + if ( args->write_index ) + { + if ( bcf_idx_save(args->out_fh)<0 ) + { + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname); + bcf_sr_destroy(args->aux.srs); +} + +void parse_novel_rate(args_t *args, const char *str) +{ + if ( sscanf(str,"%le,%le,%le",&args->aux.trio_Pm_SNPs,&args->aux.trio_Pm_del,&args->aux.trio_Pm_ins)==3 ) // explicit for all + { + args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs; + args->aux.trio_Pm_del = 1 - args->aux.trio_Pm_del; + args->aux.trio_Pm_ins = 1 - args->aux.trio_Pm_ins; + } + else if ( sscanf(str,"%le,%le",&args->aux.trio_Pm_SNPs,&args->aux.trio_Pm_del)==2 ) // dynamic for indels + { + args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs; + args->aux.trio_Pm_ins = -1; // negative value for dynamic calculation + } + else if ( sscanf(str,"%le",&args->aux.trio_Pm_SNPs)==1 ) // same for all + { + args->aux.trio_Pm_SNPs = 1 - args->aux.trio_Pm_SNPs; + args->aux.trio_Pm_del = -1; + args->aux.trio_Pm_ins = -1; + } + else error("Could not parse --novel-rate %s\n", str); +} + +static void list_annotations(FILE *fp) +{ + fprintf(fp, + "\n" + "Optional INFO annotations available with -m (\"INFO/\" prefix is optional):\n" + " INFO/PV4 .. P-values for strand bias, baseQ bias, mapQ bias and tail distance bias (Number=4,Type=Float)\n" + "\n" + "Optional FORMAT annotations available with -m (\"FORMAT/\" prefix is optional):\n" + " FORMAT/GQ .. Phred-scaled genotype quality (Number=1,Type=Integer)\n" + " FORMAT/GP .. Phred-scaled genotype posterior probabilities (Number=G,Type=Float)\n" + "\n"); +} + +static int parse_output_tags(const char *str) +{ + int flag = 0; + const char *ss = str; + while ( *ss ) + { + const char *se = ss; + while ( *se && *se!=',' ) se++; + if ( !strncasecmp(ss,"GQ",se-ss) || !strncasecmp(ss,"FORMAT/GQ",se-ss) || !strncasecmp(ss,"FMT/GQ",se-ss) ) flag |= CALL_FMT_GQ; + else if ( !strncasecmp(ss,"GP",se-ss) || !strncasecmp(ss,"FORMAT/GP",se-ss) || !strncasecmp(ss,"FMT/GP",se-ss) ) flag |= CALL_FMT_GP; + else if ( !strncasecmp(ss,"PV4",se-ss) || !strncasecmp(ss,"INFO/PV4",se-ss) ) flag |= CALL_FMT_PV4; + else + { + fprintf(stderr,"Could not parse \"%s\"\n", str); + exit(1); + } + if ( !*se ) break; + ss = se + 1; + } + return flag; +} + +static void set_ploidy(args_t *args, bcf1_t *rec) +{ + ploidy_query(args->ploidy,(char*)bcf_seqname(args->aux.hdr,rec),rec->pos,args->sex2ploidy,NULL,NULL); + + int i; + for (i=0; insex; i++) + if ( args->sex2ploidy[i]!=args->sex2ploidy_prev[i] ) break; + + if ( i==args->nsex ) return; // ploidy same as previously + + for (i=0; insamples; i++) + { + if ( args->sample2sex[i]<0 ) + args->aux.ploidy[i] = -1*args->sample2sex[i]; + else + args->aux.ploidy[i] = args->sex2ploidy[args->sample2sex[i]]; + } + int *tmp = args->sex2ploidy; args->sex2ploidy = args->sex2ploidy_prev; args->sex2ploidy_prev = tmp; +} + +ploidy_t *init_ploidy(char *alias) +{ + const ploidy_predef_t *pld = ploidy_predefs; + + int detailed = 0, len = strlen(alias); + if ( alias[len-1]=='?' ) { detailed = 1; alias[len-1] = 0; } + + while ( pld->alias && strcasecmp(alias,pld->alias) ) pld++; + + if ( !pld->alias ) + { + fprintf(stderr,"\nPRE-DEFINED PLOIDY FILES\n\n"); + fprintf(stderr," * Columns are: CHROM,FROM,TO,SEX,PLOIDY\n"); + fprintf(stderr," * Coordinates are 1-based inclusive.\n"); + fprintf(stderr," * A '*' means any value not otherwise defined.\n\n"); + pld = ploidy_predefs; + while ( pld->alias ) + { + fprintf(stderr,"%s\n .. %s\n\n", pld->alias,pld->about); + if ( detailed ) + fprintf(stderr,"%s\n", pld->ploidy); + pld++; + } + fprintf(stderr,"Run as --ploidy (e.g. --ploidy GRCh37).\n"); + fprintf(stderr,"To see the detailed ploidy definition, append a question mark (e.g. --ploidy GRCh37?).\n"); + fprintf(stderr,"\n"); + exit(-1); + } + else if ( detailed ) + { + fprintf(stderr,"%s", pld->ploidy); + exit(-1); + } + return ploidy_init_string(pld->ploidy,2); +} + +static void usage(args_t *args) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: SNP/indel variant calling from VCF/BCF. To be used in conjunction with bcftools mpileup.\n"); + fprintf(stderr, " This command replaces the former \"bcftools view\" caller. Some of the original\n"); + fprintf(stderr, " functionality has been temporarily lost in the process of transition to htslib,\n"); + fprintf(stderr, " but will be added back on popular demand. The original calling model can be\n"); + fprintf(stderr, " invoked with the -c option.\n"); + fprintf(stderr, "Usage: bcftools call [options] \n"); + fprintf(stderr, "\n"); + fprintf(stderr, "File format options:\n"); + fprintf(stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(stderr, " -O, --output-type b|u|z|v Output type: 'b' compressed BCF; 'u' uncompressed BCF; 'z' compressed VCF; 'v' uncompressed VCF [v]\n"); + fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(stderr, " --ploidy ASSEMBLY[?] Predefined ploidy, 'list' to print available settings, append '?' for details [2]\n"); + fprintf(stderr, " --ploidy-file FILE Space/tab-delimited list of CHROM,FROM,TO,SEX,PLOIDY\n"); + fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(stderr, " -s, --samples LIST List of samples to include [all samples]\n"); + fprintf(stderr, " -S, --samples-file FILE PED file or a file with an optional column with sex (see man page for details) [all samples]\n"); + fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(stderr, " --threads INT Use multithreading with INT worker threads [0]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Input/output options:\n"); + fprintf(stderr, " -A, --keep-alts Keep all possible alternate alleles at variant sites\n"); + fprintf(stderr, " -*, --keep-unseen-allele Keep the unobserved allele <*> or \n"); + fprintf(stderr, " -a, --annotate LIST Optional tags to output (lowercase allowed); '?' to list available tags\n"); + fprintf(stderr, " -F, --prior-freqs AN,AC Use prior allele frequencies, determined from these pre-filled tags\n"); + fprintf(stderr, " -G, --group-samples FILE|- Group samples by population (file with \"sample\\tgroup\") or \"-\" for single-sample calling.\n"); + fprintf(stderr, " This requires FORMAT/QS or other Number=R,Type=Integer tag such as FORMAT/AD\n"); + fprintf(stderr, " --group-samples-tag TAG The tag to use with -G, by default FORMAT/QS and FORMAT/AD are checked automatically\n"); + fprintf(stderr, " -g, --gvcf INT,[...] Group non-variant sites into gVCF blocks by minimum per-sample DP\n"); + fprintf(stderr, " -i, --insert-missed Output also sites missed by mpileup but present in -T\n"); + fprintf(stderr, " -M, --keep-masked-ref Keep sites with masked reference allele (REF=N)\n"); + fprintf(stderr, " -V, --skip-variants TYPE Skip indels/snps\n"); + fprintf(stderr, " -v, --variants-only Output variant sites only\n"); + fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Consensus/variant calling options:\n"); + fprintf(stderr, " -c, --consensus-caller The original calling method (conflicts with -m)\n"); + fprintf(stderr, " -C, --constrain STR One of: alleles, trio (see manual)\n"); + fprintf(stderr, " -m, --multiallelic-caller Alternative model for multiallelic and rare-variant calling (conflicts with -c)\n"); + fprintf(stderr, " -n, --novel-rate FLOAT,[...] Likelihood of novel mutation for constrained trio calling, see man page for details [1e-8,1e-9,1e-9]\n"); + fprintf(stderr, " -p, --pval-threshold FLOAT Variant if P(ref|D)aux.min_lrt); + // fprintf(stderr, " -U INT number of permutations for association testing (effective with -1) [0]\n"); + // fprintf(stderr, " -X FLOAT only perform permutations for P(chi^2)aux.min_perm_p); + fprintf(stderr, "\n"); + exit(-1); +} + +int main_vcfcall(int argc, char *argv[]) +{ + char *ploidy_fname = NULL, *ploidy = NULL; + args_t args; + memset(&args, 0, sizeof(args_t)); + args.argc = argc; args.argv = argv; + args.aux.prior_type = -1; + args.aux.indel_frac = -1; + args.aux.theta = 1.1e-3; + args.aux.pref = 0.5; + args.aux.min_perm_p = 0.01; + args.aux.min_lrt = 1; + args.flag = CF_ACGT_ONLY; + args.output_fname = "-"; + args.output_type = FT_VCF; + args.n_threads = 0; + args.record_cmd_line = 1; + args.aux.trio_Pm_SNPs = 1 - 1e-8; + args.aux.trio_Pm_ins = args.aux.trio_Pm_del = 1 - 1e-9; + args.regions_overlap = 1; + args.clevel = -1; + + int c; + static struct option loptions[] = + { + {"help",no_argument,NULL,'h'}, + {"format-fields",required_argument,NULL,'f'}, + {"annotate",required_argument,NULL,'a'}, + {"prior-freqs",required_argument,NULL,'F'}, + {"gvcf",required_argument,NULL,'g'}, + {"group-samples",required_argument,NULL,'G'}, + {"group-samples-tag",required_argument,NULL,3}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,4}, + {"samples",required_argument,NULL,'s'}, + {"samples-file",required_argument,NULL,'S'}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"threads",required_argument,NULL,9}, + {"keep-alts",no_argument,NULL,'A'}, + {"keep-unseen-allele",no_argument,NULL,'*'}, + {"insert-missed",no_argument,NULL,'i'}, + {"skip-Ns",no_argument,NULL,'N'}, // now the new default + {"keep-masked-refs",no_argument,NULL,'M'}, + {"skip-variants",required_argument,NULL,'V'}, + {"variants-only",no_argument,NULL,'v'}, + {"consensus-caller",no_argument,NULL,'c'}, + {"constrain",required_argument,NULL,'C'}, + {"multiallelic-caller",no_argument,NULL,'m'}, + {"pval-threshold",required_argument,NULL,'p'}, + {"prior",required_argument,NULL,'P'}, + {"novel-rate",required_argument,NULL,'n'}, + {"ploidy",required_argument,NULL,1}, + {"ploidy-file",required_argument,NULL,2}, + {"chromosome-X",no_argument,NULL,'X'}, + {"chromosome-Y",no_argument,NULL,'Y'}, + {"no-version",no_argument,NULL,8}, + {"write-index",optional_argument,NULL,'W'}, + {NULL,0,NULL,0} + }; + + char *tmp = NULL; + while ((c = getopt_long(argc, argv, "h?o:O:r:R:s:S:t:T:A*NMV:vcmp:C:n:P:f:a:ig:XYF:G:W::", loptions, NULL)) >= 0) + { + switch (c) + { + case 2 : ploidy_fname = optarg; break; + case 1 : ploidy = optarg; break; + case 'X': ploidy = "X"; fprintf(stderr,"Warning: -X will be deprecated, please use --ploidy instead.\n"); break; + case 'Y': ploidy = "Y"; fprintf(stderr,"Warning: -Y will be deprecated, please use --ploidy instead.\n"); break; + case 'G': args.aux.sample_groups = optarg; break; + case 3 : args.aux.sample_groups_tag = optarg; break; + case 'f': fprintf(stderr,"Warning: -f, --format-fields will be deprecated, please use -a, --annotate instead.\n"); + case 'a': + if (optarg[0]=='?') { list_annotations(stderr); return 1; } + args.aux.output_tags |= parse_output_tags(optarg); + break; + case 'M': args.flag &= ~CF_ACGT_ONLY; break; // keep sites where REF is N + case 'N': args.flag |= CF_ACGT_ONLY; break; // omit sites where first base in REF is N (the new default) + case 'A': args.aux.flag |= CALL_KEEPALT; break; + case '*': args.aux.flag |= CALL_KEEP_UNSEEN; break; + case 'c': args.flag |= CF_CCALL; break; // the original EM based calling method + case 'i': args.flag |= CF_INS_MISSED; break; + case 'v': args.aux.flag |= CALL_VARONLY; break; + case 'F': + args.aux.prior_AN = optarg; + args.aux.prior_AC = strchr(optarg,','); + if ( !args.aux.prior_AC ) error("Expected two tags with -F (e.g. AN,AC), got \"%s\"\n",optarg); + *args.aux.prior_AC = 0; + args.aux.prior_AC++; + break; + case 'g': + args.gvcf = gvcf_init(optarg); + if ( !args.gvcf ) error("Could not parse: --gvcf %s\n", optarg); + break; + case 'o': args.output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args.output_type = FT_BCF_GZ; break; + case 'u': args.output_type = FT_BCF; break; + case 'z': args.output_type = FT_VCF_GZ; break; + case 'v': args.output_type = FT_VCF; break; + default: + { + args.clevel = strtol(optarg,&tmp,10); + if ( *tmp || args.clevel<0 || args.clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args.clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args.clevel<0 || args.clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'C': + if ( !strcasecmp(optarg,"alleles") ) args.aux.flag |= CALL_CONSTR_ALLELES; + else if ( !strcasecmp(optarg,"trio") ) args.aux.flag |= CALL_CONSTR_TRIO; + else error("Unknown argument to -C: \"%s\"\n", optarg); + break; + case 'V': + if ( !strcasecmp(optarg,"snps") ) args.flag |= CF_INDEL_ONLY; + else if ( !strcasecmp(optarg,"indels") ) args.flag |= CF_NO_INDEL; + else error("Unknown skip category \"%s\" (-S argument must be \"snps\" or \"indels\")\n", optarg); + break; + case 'm': args.flag |= CF_MCALL; break; // multiallelic calling method + case 'p': + args.aux.pref = strtod(optarg,&tmp); + if ( *tmp ) error("Could not parse: --pval-threshold %s\n", optarg); + break; + case 'P': args.aux.theta = strtod(optarg,&tmp); + if ( *tmp ) error("Could not parse, expected float argument: -P %s\n", optarg); + break; + case 'n': parse_novel_rate(&args,optarg); break; + case 'r': args.regions = optarg; break; + case 'R': args.regions = optarg; args.regions_is_file = 1; break; + case 't': args.targets = optarg; break; + case 'T': args.targets = optarg; args.targets_is_file = 1; break; + case 's': args.samples_fname = optarg; break; + case 'S': args.samples_fname = optarg; args.samples_is_file = 1; break; + case 9 : args.n_threads = strtol(optarg, 0, 0); break; + case 8 : args.record_cmd_line = 0; break; + case 4 : + args.regions_overlap = parse_overlap_option(optarg); + if ( args.regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 'W': + if (!(args.write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + default: usage(&args); + } + } + // Sanity check options and initialize + if ( ploidy_fname ) args.ploidy = ploidy_init(ploidy_fname, 2); + else if ( ploidy ) args.ploidy = init_ploidy(ploidy); + + if ( optind>=argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) args.bcf_fname = "-"; // reading from stdin + else usage(&args); + } + else args.bcf_fname = argv[optind++]; + + if ( !ploidy_fname && !ploidy ) + { + if ( !args.samples_is_file ) fprintf(stderr,"Note: none of --samples-file, --ploidy or --ploidy-file given, assuming all sites are diploid\n"); + args.ploidy = ploidy_init_string("* * * 0 0\n* * * 1 1\n* * * 2 2\n",2); + } + + if ( !args.ploidy ) error("Could not initialize ploidy\n"); + if ( (args.flag & CF_CCALL ? 1 : 0) + (args.flag & CF_MCALL ? 1 : 0) + (args.flag & CF_QCALL ? 1 : 0) > 1 ) error("Only one of -c or -m options can be given\n"); + if ( !(args.flag & CF_CCALL) && !(args.flag & CF_MCALL) && !(args.flag & CF_QCALL) ) error("Expected -c or -m option\n"); + if ( (args.flag & CF_CCALL ? 1: 0) && args.gvcf ) error("gvcf -g option not functional with -c calling mode yet\n"); + if ( args.aux.n_perm && args.aux.ngrp1_samples<=0 ) error("Expected -1 with -U\n"); // not sure about this, please fix + if ( args.aux.flag & CALL_CONSTR_ALLELES ) + { + if ( !args.targets ) error("Expected -t or -T with \"-C alleles\"\n"); + if ( !(args.flag & CF_MCALL) ) error("The \"-C alleles\" mode requires -m\n"); + } + if ( args.flag & CF_INS_MISSED && !(args.aux.flag&CALL_CONSTR_ALLELES) ) error("The -i option requires -C alleles\n"); + if ( args.aux.flag&CALL_VARONLY && args.gvcf ) error("The two options cannot be combined: --variants-only and --gvcf\n"); + if ( args.aux.sample_groups && !(args.flag & CF_MCALL) ) error("The -G feature is supported only with the -m calling mode\n"); + init_data(&args); + + bcf1_t *bcf_rec; + while ( (bcf_rec = next_line(&args)) ) + { + // Skip duplicate positions with all matching `-C alleles -T` used up + if ( args.aux.flag&CALL_CONSTR_ALLELES && !args.aux.tgt_als ) continue; + + // Skip unwanted sites + int i, is_indel = bcf_is_snp(bcf_rec) ? 0 : 1; + if ( (args.flag & CF_INDEL_ONLY) && !is_indel ) continue; + if ( (args.flag & CF_NO_INDEL) && is_indel ) continue; + if ( (args.flag & CF_ACGT_ONLY) && (bcf_rec->d.allele[0][0]=='N' || bcf_rec->d.allele[0][0]=='n') ) continue; // REF[0] is 'N' + + // Which allele is symbolic? All SNPs should have it, but not indels + args.aux.unseen = 0; + for (i=1; in_allele; i++) + { + if ( bcf_rec->d.allele[i][0]=='X' ) { args.aux.unseen = i; break; } // old X + if ( bcf_rec->d.allele[i][0]=='<' ) + { + if ( bcf_rec->d.allele[i][1]=='X' && bcf_rec->d.allele[i][2]=='>' ) { args.aux.unseen = i; break; } // old + if ( bcf_rec->d.allele[i][1]=='*' && bcf_rec->d.allele[i][2]=='>' ) { args.aux.unseen = i; break; } // new <*> + } + } + int is_ref = (bcf_rec->n_allele==1 || (bcf_rec->n_allele==2 && args.aux.unseen>0)) ? 1 : 0; + + if ( is_ref && args.aux.flag&CALL_VARONLY ) + continue; + + bcf_unpack(bcf_rec, BCF_UN_ALL); + if ( args.nsex ) set_ploidy(&args, bcf_rec); + + // Various output modes: QCall output (todo) + if ( args.flag & CF_QCALL ) + { + qcall(&args.aux, bcf_rec); + continue; + } + + if ( args.flag & CF_INS_MISSED ) + { + tgt_flush(&args,bcf_rec); + if ( !args.tgt_itr_prev ) args.tgt_itr_prev = regitr_init(args.tgt_idx); + regitr_copy(args.tgt_itr_prev, args.tgt_itr); + } + + // Calling modes which output VCFs + int ret; + if ( args.flag & CF_MCALL ) + ret = mcall(&args.aux, bcf_rec); + else + ret = ccall(&args.aux, bcf_rec); + if ( ret==-1 ) error("Something is wrong\n"); + else if ( ret==-2 ) continue; // skip the site + + // Normal output + if ( (args.aux.flag & CALL_VARONLY) && ret==0 && !args.gvcf ) continue; // not a variant + if ( args.gvcf ) + bcf_rec = gvcf_write(args.gvcf, args.out_fh, args.aux.hdr, bcf_rec, ret==1?1:0); + if ( bcf_rec && bcf_write1(args.out_fh, args.aux.hdr, bcf_rec)!=0 ) error("[%s] Error: failed to write to %s\n", __func__,args.output_fname); + } + if ( args.gvcf ) gvcf_write(args.gvcf, args.out_fh, args.aux.hdr, NULL, 0); + if ( args.flag & CF_INS_MISSED ) tgt_flush(&args,NULL); + destroy_data(&args); + return 0; +} + diff --git a/shared/package-files/7c/7cadf9b527a41bffbd130af90619756d1770032db8ed9f736787501450d0f71c/test_edgelist.py b/shared/package-files/7c/7cadf9b527a41bffbd130af90619756d1770032db8ed9f736787501450d0f71c/test_edgelist.py new file mode 100644 index 0000000000000000000000000000000000000000..66be8a2f5b3e1f9486594c63015295ad6a270efa --- /dev/null +++ b/shared/package-files/7c/7cadf9b527a41bffbd130af90619756d1770032db8ed9f736787501450d0f71c/test_edgelist.py @@ -0,0 +1,240 @@ +""" +Unit tests for bipartite edgelists. +""" + +import io + +import pytest + +import networkx as nx +from networkx.algorithms import bipartite +from networkx.utils import edges_equal, graphs_equal, nodes_equal + + +class TestEdgelist: + @classmethod + def setup_class(cls): + cls.G = nx.Graph(name="test") + e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] + cls.G.add_edges_from(e) + cls.G.add_nodes_from(["a", "c", "e"], bipartite=0) + cls.G.add_nodes_from(["b", "d", "f"], bipartite=1) + cls.G.add_node("g", bipartite=0) + cls.DG = nx.DiGraph(cls.G) + cls.MG = nx.MultiGraph() + cls.MG.add_edges_from([(1, 2), (1, 2), (1, 2)]) + cls.MG.add_node(1, bipartite=0) + cls.MG.add_node(2, bipartite=1) + + def test_read_edgelist_1(self): + s = b"""\ +# comment line +1 2 +# comment line +2 3 +""" + bytesIO = io.BytesIO(s) + G = bipartite.read_edgelist(bytesIO, nodetype=int) + assert edges_equal(G.edges(), [(1, 2), (2, 3)]) + + def test_read_edgelist_3(self): + s = b"""\ +# comment line +1 2 {'weight':2.0} +# comment line +2 3 {'weight':3.0} +""" + bytesIO = io.BytesIO(s) + G = bipartite.read_edgelist(bytesIO, nodetype=int, data=False) + assert edges_equal(G.edges(), [(1, 2), (2, 3)]) + + bytesIO = io.BytesIO(s) + G = bipartite.read_edgelist(bytesIO, nodetype=int, data=True) + assert edges_equal( + G.edges(data=True), [(1, 2, {"weight": 2.0}), (2, 3, {"weight": 3.0})] + ) + + def test_write_edgelist_1(self): + fh = io.BytesIO() + G = nx.Graph() + G.add_edges_from([(1, 2), (2, 3)]) + G.add_node(1, bipartite=0) + G.add_node(2, bipartite=1) + G.add_node(3, bipartite=0) + bipartite.write_edgelist(G, fh, data=False) + fh.seek(0) + assert fh.read() == b"1 2\n3 2\n" + + def test_write_edgelist_2(self): + fh = io.BytesIO() + G = nx.Graph() + G.add_edges_from([(1, 2), (2, 3)]) + G.add_node(1, bipartite=0) + G.add_node(2, bipartite=1) + G.add_node(3, bipartite=0) + bipartite.write_edgelist(G, fh, data=True) + fh.seek(0) + assert fh.read() == b"1 2 {}\n3 2 {}\n" + + def test_write_edgelist_3(self): + fh = io.BytesIO() + G = nx.Graph() + G.add_edge(1, 2, weight=2.0) + G.add_edge(2, 3, weight=3.0) + G.add_node(1, bipartite=0) + G.add_node(2, bipartite=1) + G.add_node(3, bipartite=0) + bipartite.write_edgelist(G, fh, data=True) + fh.seek(0) + assert fh.read() == b"1 2 {'weight': 2.0}\n3 2 {'weight': 3.0}\n" + + def test_write_edgelist_4(self): + fh = io.BytesIO() + G = nx.Graph() + G.add_edge(1, 2, weight=2.0) + G.add_edge(2, 3, weight=3.0) + G.add_node(1, bipartite=0) + G.add_node(2, bipartite=1) + G.add_node(3, bipartite=0) + bipartite.write_edgelist(G, fh, data=[("weight")]) + fh.seek(0) + assert fh.read() == b"1 2 2.0\n3 2 3.0\n" + + def test_unicode(self, tmp_path): + G = nx.Graph() + name1 = chr(2344) + chr(123) + chr(6543) + name2 = chr(5543) + chr(1543) + chr(324) + G.add_edge(name1, "Radiohead", **{name2: 3}) + G.add_node(name1, bipartite=0) + G.add_node("Radiohead", bipartite=1) + + fname = tmp_path / "edgelist.txt" + bipartite.write_edgelist(G, fname) + H = bipartite.read_edgelist(fname) + assert graphs_equal(G, H) + + def test_latin1_issue(self, tmp_path): + G = nx.Graph() + name1 = chr(2344) + chr(123) + chr(6543) + name2 = chr(5543) + chr(1543) + chr(324) + G.add_edge(name1, "Radiohead", **{name2: 3}) + G.add_node(name1, bipartite=0) + G.add_node("Radiohead", bipartite=1) + + fname = tmp_path / "edgelist.txt" + with pytest.raises(UnicodeEncodeError): + bipartite.write_edgelist(G, fname, encoding="latin-1") + + def test_latin1(self, tmp_path): + G = nx.Graph() + name1 = "Bj" + chr(246) + "rk" + name2 = chr(220) + "ber" + G.add_edge(name1, "Radiohead", **{name2: 3}) + G.add_node(name1, bipartite=0) + G.add_node("Radiohead", bipartite=1) + + fname = tmp_path / "edgelist.txt" + bipartite.write_edgelist(G, fname, encoding="latin-1") + H = bipartite.read_edgelist(fname, encoding="latin-1") + assert graphs_equal(G, H) + + def test_edgelist_graph(self, tmp_path): + G = self.G + fname = tmp_path / "edgelist.txt" + bipartite.write_edgelist(G, fname) + H = bipartite.read_edgelist(fname) + H2 = bipartite.read_edgelist(fname) + assert H is not H2 # they should be different graphs + G.remove_node("g") # isolated nodes are not written in edgelist + assert nodes_equal(list(H), list(G)) + assert edges_equal(list(H.edges()), list(G.edges())) + + def test_edgelist_integers(self, tmp_path): + G = nx.convert_node_labels_to_integers(self.G) + fname = tmp_path / "edgelist.txt" + bipartite.write_edgelist(G, fname) + H = bipartite.read_edgelist(fname, nodetype=int) + # isolated nodes are not written in edgelist + G.remove_nodes_from(list(nx.isolates(G))) + assert nodes_equal(list(H), list(G)) + assert edges_equal(list(H.edges()), list(G.edges())) + + def test_edgelist_multigraph(self, tmp_path): + G = self.MG + fname = tmp_path / "edgelist.txt" + bipartite.write_edgelist(G, fname) + H = bipartite.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph()) + H2 = bipartite.read_edgelist(fname, nodetype=int, create_using=nx.MultiGraph()) + assert H is not H2 # they should be different graphs + assert nodes_equal(list(H), list(G)) + assert edges_equal(list(H.edges()), list(G.edges())) + + def test_empty_digraph(self): + with pytest.raises(nx.NetworkXNotImplemented): + bytesIO = io.BytesIO() + bipartite.write_edgelist(nx.DiGraph(), bytesIO) + + def test_raise_attribute(self): + with pytest.raises(AttributeError): + G = nx.path_graph(4) + bytesIO = io.BytesIO() + bipartite.write_edgelist(G, bytesIO) + + def test_parse_edgelist(self): + """Tests for conditions specific to + parse_edge_list method""" + + # ignore strings of length less than 2 + lines = ["1 2", "2 3", "3 1", "4", " "] + G = bipartite.parse_edgelist(lines, nodetype=int) + assert list(G.nodes) == [1, 2, 3] + + # Exception raised when node is not convertible + # to specified data type + with pytest.raises(TypeError, match=".*Failed to convert nodes"): + lines = ["a b", "b c", "c a"] + G = bipartite.parse_edgelist(lines, nodetype=int) + + # Exception raised when format of data is not + # convertible to dictionary object + with pytest.raises(TypeError, match=".*Failed to convert edge data"): + lines = ["1 2 3", "2 3 4", "3 1 2"] + G = bipartite.parse_edgelist(lines, nodetype=int) + + # Exception raised when edge data and data + # keys are not of same length + with pytest.raises(IndexError): + lines = ["1 2 3 4", "2 3 4"] + G = bipartite.parse_edgelist( + lines, nodetype=int, data=[("weight", int), ("key", int)] + ) + + # Exception raised when edge data is not + # convertible to specified data type + with pytest.raises(TypeError, match=".*Failed to convert key data"): + lines = ["1 2 3 a", "2 3 4 b"] + G = bipartite.parse_edgelist( + lines, nodetype=int, data=[("weight", int), ("key", int)] + ) + + +def test_bipartite_edgelist_consistent_strip_handling(): + """See gh-7462 + + Input when printed looks like: + + A B interaction 2 + B C interaction 4 + C A interaction + + Note the trailing \\t in the last line, which indicates the existence of + an empty data field. + """ + lines = io.StringIO( + "A\tB\tinteraction\t2\nB\tC\tinteraction\t4\nC\tA\tinteraction\t" + ) + descr = [("type", str), ("weight", str)] + # Should not raise + G = nx.bipartite.parse_edgelist(lines, delimiter="\t", data=descr) + expected = [("A", "B", "2"), ("A", "C", ""), ("B", "C", "4")] + assert sorted(G.edges(data="weight")) == expected diff --git a/shared/package-files/7c/7caf2e3668f8f0032bac34312009598fe10b1b12d6ee43e37acb92332f878a3d/miopen_depthwise_convolution_cuda_dispatch.h b/shared/package-files/7c/7caf2e3668f8f0032bac34312009598fe10b1b12d6ee43e37acb92332f878a3d/miopen_depthwise_convolution_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3f4afa486b40929a96500dc9b7d3ef3ad7aa55d6 --- /dev/null +++ b/shared/package-files/7c/7caf2e3668f8f0032bac34312009598fe10b1b12d6ee43e37acb92332f878a3d/miopen_depthwise_convolution_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor miopen_depthwise_convolution(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic); +TORCH_API at::Tensor miopen_depthwise_convolution_symint(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/7c/7caf8019a0012ca73ef89e2c0d15f93e310ecf77d106f85d578293b33624095a/BatchLinearAlgebra.h b/shared/package-files/7c/7caf8019a0012ca73ef89e2c0d15f93e310ecf77d106f85d578293b33624095a/BatchLinearAlgebra.h new file mode 100644 index 0000000000000000000000000000000000000000..1b8ce2bdf5417af55f3bd3557c33847c0bd85a23 --- /dev/null +++ b/shared/package-files/7c/7caf8019a0012ca73ef89e2c0d15f93e310ecf77d106f85d578293b33624095a/BatchLinearAlgebra.h @@ -0,0 +1,321 @@ +#pragma once + +#include +#include +#include +#include + +// Forward declare TI +namespace at { +class Tensor; +struct TensorIterator; + +namespace native { +enum class TransposeType; +} + +} + +namespace at::native { + +enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss}; + +#if AT_BUILD_WITH_LAPACK() +// Define per-batch functions to be used in the implementation of batched +// linear algebra operations + +template +void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info); + +template +void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info); + +template +void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info); + +template +void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info); + +template +void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info); + +template +void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info); + +template +void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info); + +template +void lapackGels(char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info); + +template +void lapackGelsd(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + value_t *s, value_t rcond, int *rank, + scalar_t* work, int lwork, + value_t *rwork, int* iwork, int *info); + +template +void lapackGelsy(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + int *jpvt, value_t rcond, int *rank, + scalar_t *work, int lwork, value_t* rwork, int *info); + +template +void lapackGelss(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + value_t *s, value_t rcond, int *rank, + scalar_t *work, int lwork, + value_t *rwork, int *info); + +template +struct lapackLstsq_impl; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGels( + trans, m, n, nrhs, + a, lda, b, ldb, + work, lwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelsy( + m, n, nrhs, + a, lda, b, ldb, + jpvt, rcond, rank, + work, lwork, rwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelsd( + m, n, nrhs, + a, lda, b, ldb, + s, rcond, rank, + work, lwork, + rwork, iwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelss( + m, n, nrhs, + a, lda, b, ldb, + s, rcond, rank, + work, lwork, + rwork, info); + } +}; + +template +void lapackLstsq( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackLstsq_impl::call( + trans, m, n, nrhs, + a, lda, b, ldb, + work, lwork, info, + jpvt, rcond, rank, rwork, + s, + iwork); +} + +template +void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info); + +template +void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info); + +template +void lapackLdlHermitian( + char uplo, + int n, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* work, + int lwork, + int* info); + +template +void lapackLdlSymmetric( + char uplo, + int n, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* work, + int lwork, + int* info); + +template +void lapackLdlSolveHermitian( + char uplo, + int n, + int nrhs, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* b, + int ldb, + int* info); + +template +void lapackLdlSolveSymmetric( + char uplo, + int n, + int nrhs, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* b, + int ldb, + int* info); + +template +void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info); +#endif + +#if AT_BUILD_WITH_BLAS() +template +void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb); +#endif + +using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/); +DECLARE_DISPATCH(cholesky_fn, cholesky_stub) + +using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/); + +DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub) + +using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/); + +DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub) + +using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/); +DECLARE_DISPATCH(geqrf_fn, geqrf_stub) + +using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/); +DECLARE_DISPATCH(orgqr_fn, orgqr_stub) + +using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/); +DECLARE_DISPATCH(ormqr_fn, ormqr_stub) + +using linalg_eigh_fn = void (*)( + const Tensor& /*eigenvalues*/, + const Tensor& /*eigenvectors*/, + const Tensor& /*infos*/, + bool /*upper*/, + bool /*compute_eigenvectors*/); +DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub) + +using lstsq_fn = void (*)( + const Tensor& /*a*/, + Tensor& /*b*/, + Tensor& /*rank*/, + Tensor& /*singular_values*/, + Tensor& /*infos*/, + double /*rcond*/, + std::string /*driver_name*/); +DECLARE_DISPATCH(lstsq_fn, lstsq_stub) + +using triangular_solve_fn = void (*)( + const Tensor& /*A*/, + const Tensor& /*B*/, + bool /*left*/, + bool /*upper*/, + TransposeType /*transpose*/, + bool /*unitriangular*/); +DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub) + +using lu_factor_fn = void (*)( + const Tensor& /*input*/, + const Tensor& /*pivots*/, + const Tensor& /*infos*/, + bool /*compute_pivots*/); +DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub) + +using unpack_pivots_fn = void(*)( + TensorIterator& iter, + const int64_t dim_size, + const int64_t max_pivot); +DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub) + +using lu_solve_fn = void (*)( + const Tensor& /*LU*/, + const Tensor& /*pivots*/, + const Tensor& /*B*/, + TransposeType /*trans*/); +DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub) + +using ldl_factor_fn = void (*)( + const Tensor& /*LD*/, + const Tensor& /*pivots*/, + const Tensor& /*info*/, + bool /*upper*/, + bool /*hermitian*/); +DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub) + +using svd_fn = void (*)( + const Tensor& /*A*/, + const bool /*full_matrices*/, + const bool /*compute_uv*/, + const std::optional& /*driver*/, + const Tensor& /*U*/, + const Tensor& /*S*/, + const Tensor& /*Vh*/, + const Tensor& /*info*/); +DECLARE_DISPATCH(svd_fn, svd_stub) + +using ldl_solve_fn = void (*)( + const Tensor& /*LD*/, + const Tensor& /*pivots*/, + const Tensor& /*result*/, + bool /*upper*/, + bool /*hermitian*/); +DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub) +} // namespace at::native diff --git a/shared/package-files/7c/7cb1e6aaf8a450b4005e922ff0c4a2b11aadf7b582d479ba1395f46a4d697415/slice_inverse_ops.h b/shared/package-files/7c/7cb1e6aaf8a450b4005e922ff0c4a2b11aadf7b582d479ba1395f46a4d697415/slice_inverse_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..99286d4bad4172d247b8f503c3120accd4169a34 --- /dev/null +++ b/shared/package-files/7c/7cb1e6aaf8a450b4005e922ff0c4a2b11aadf7b582d479ba1395f46a4d697415/slice_inverse_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API slice_inverse { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, int64_t, ::std::optional, ::std::optional, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::slice_inverse"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & src, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7cb443a0d82689e5af582afd4237178d7bce08414f620255a9134164eba5f2e9/linalg_eigvalsh.h b/shared/package-files/7c/7cb443a0d82689e5af582afd4237178d7bce08414f620255a9134164eba5f2e9/linalg_eigvalsh.h new file mode 100644 index 0000000000000000000000000000000000000000..eb34096e345a6127f7cafe7c37162a49d3980097 --- /dev/null +++ b/shared/package-files/7c/7cb443a0d82689e5af582afd4237178d7bce08414f620255a9134164eba5f2e9/linalg_eigvalsh.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::linalg_eigvalsh(Tensor self, str UPLO="L") -> Tensor +inline at::Tensor linalg_eigvalsh(const at::Tensor & self, c10::string_view UPLO="L") { + return at::_ops::linalg_eigvalsh::call(self, UPLO); +} + +// aten::linalg_eigvalsh.out(Tensor self, str UPLO="L", *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_eigvalsh_out(at::Tensor & out, const at::Tensor & self, c10::string_view UPLO="L") { + return at::_ops::linalg_eigvalsh_out::call(self, UPLO, out); +} +// aten::linalg_eigvalsh.out(Tensor self, str UPLO="L", *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & linalg_eigvalsh_outf(const at::Tensor & self, c10::string_view UPLO, at::Tensor & out) { + return at::_ops::linalg_eigvalsh_out::call(self, UPLO, out); +} + +} diff --git a/shared/package-files/7c/7cb5867c740d0b762a8f1b53ef341b3fef82bb49a370fc1205f8e2e0303b04fd/test_line.py b/shared/package-files/7c/7cb5867c740d0b762a8f1b53ef341b3fef82bb49a370fc1205f8e2e0303b04fd/test_line.py new file mode 100644 index 0000000000000000000000000000000000000000..5158ec05ab414020fbbe2681a2658454dd15b6eb --- /dev/null +++ b/shared/package-files/7c/7cb5867c740d0b762a8f1b53ef341b3fef82bb49a370fc1205f8e2e0303b04fd/test_line.py @@ -0,0 +1,861 @@ +from sympy.core.numbers import (Float, Rational, oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, cos, sin) +from sympy.sets import EmptySet +from sympy.simplify.simplify import simplify +from sympy.functions.elementary.trigonometric import tan +from sympy.geometry import (Circle, GeometryError, Line, Point, Ray, + Segment, Triangle, intersection, Point3D, Line3D, Ray3D, Segment3D, + Point2D, Line2D, Plane) +from sympy.geometry.line import Undecidable +from sympy.geometry.polygon import _asa as asa +from sympy.utilities.iterables import cartes +from sympy.testing.pytest import raises, warns + + +x = Symbol('x', real=True) +y = Symbol('y', real=True) +z = Symbol('z', real=True) +k = Symbol('k', real=True) +x1 = Symbol('x1', real=True) +y1 = Symbol('y1', real=True) +t = Symbol('t', real=True) +a, b = symbols('a,b', real=True) +m = symbols('m', real=True) + + +def test_object_from_equation(): + from sympy.abc import x, y, a, b + assert Line(3*x + y + 18) == Line2D(Point2D(0, -18), Point2D(1, -21)) + assert Line(3*x + 5 * y + 1) == Line2D( + Point2D(0, Rational(-1, 5)), Point2D(1, Rational(-4, 5))) + assert Line(3*a + b + 18, x="a", y="b") == Line2D( + Point2D(0, -18), Point2D(1, -21)) + assert Line(3*x + y) == Line2D(Point2D(0, 0), Point2D(1, -3)) + assert Line(x + y) == Line2D(Point2D(0, 0), Point2D(1, -1)) + assert Line(Eq(3*a + b, -18), x="a", y=b) == Line2D( + Point2D(0, -18), Point2D(1, -21)) + # issue 22361 + assert Line(x - 1) == Line2D(Point2D(1, 0), Point2D(1, 1)) + assert Line(2*x - 2, y=x) == Line2D(Point2D(0, 1), Point2D(1, 1)) + assert Line(y) == Line2D(Point2D(0, 0), Point2D(1, 0)) + assert Line(2*y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) + assert Line(y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) + raises(ValueError, lambda: Line(x / y)) + raises(ValueError, lambda: Line(a / b, x='a', y='b')) + raises(ValueError, lambda: Line(y / x)) + raises(ValueError, lambda: Line(b / a, x='a', y='b')) + raises(ValueError, lambda: Line((x + 1)**2 + y)) + + +def feq(a, b): + """Test if two floating point values are 'equal'.""" + t_float = Float("1.0E-10") + return -t_float < a - b < t_float + + +def test_angle_between(): + a = Point(1, 2, 3, 4) + b = a.orthogonal_direction + o = a.origin + assert feq(Line.angle_between(Line(Point(0, 0), Point(1, 1)), + Line(Point(0, 0), Point(5, 0))).evalf(), pi.evalf() / 4) + assert Line(a, o).angle_between(Line(b, o)) == pi / 2 + z = Point3D(0, 0, 0) + assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)), + Line3D(z, Point3D(5, 0, 0))) == acos(sqrt(3) / 3) + # direction of points is used to determine angle + assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)), + Line3D(Point3D(5, 0, 0), z)) == acos(-sqrt(3) / 3) + + +def test_closing_angle(): + a = Ray((0, 0), angle=0) + b = Ray((1, 2), angle=pi/2) + assert a.closing_angle(b) == -pi/2 + assert b.closing_angle(a) == pi/2 + assert a.closing_angle(a) == 0 + + +def test_smallest_angle(): + a = Line(Point(1, 1), Point(1, 2)) + b = Line(Point(1, 1),Point(2, 3)) + assert a.smallest_angle_between(b) == acos(2*sqrt(5)/5) + + +def test_svg(): + a = Line(Point(1, 1),Point(1, 2)) + assert a._svg() == '' + a = Segment(Point(1, 0),Point(1, 1)) + assert a._svg() == '' + a = Ray(Point(2, 3), Point(3, 5)) + assert a._svg() == '' + + +def test_arbitrary_point(): + l1 = Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) + l2 = Line(Point(x1, x1), Point(y1, y1)) + assert l2.arbitrary_point() in l2 + assert Ray((1, 1), angle=pi / 4).arbitrary_point() == \ + Point(t + 1, t + 1) + assert Segment((1, 1), (2, 3)).arbitrary_point() == Point(1 + t, 1 + 2 * t) + assert l1.perpendicular_segment(l1.arbitrary_point()) == l1.arbitrary_point() + assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]).arbitrary_point() == \ + Point3D(t + 1, 2 * t + 1, 3 * t + 1) + assert Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).midpoint == \ + Point3D(S.Half, S.Half, S.Half) + assert Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)).length == sqrt(3) * sqrt((x1 - y1) ** 2) + assert Segment3D((1, 1, 1), (2, 3, 4)).arbitrary_point() == \ + Point3D(t + 1, 2 * t + 1, 3 * t + 1) + raises(ValueError, (lambda: Line((x, 1), (2, 3)).arbitrary_point(x))) + + +def test_are_concurrent_2d(): + l1 = Line(Point(0, 0), Point(1, 1)) + l2 = Line(Point(x1, x1), Point(x1, 1 + x1)) + assert Line.are_concurrent(l1) is False + assert Line.are_concurrent(l1, l2) + assert Line.are_concurrent(l1, l1, l1, l2) + assert Line.are_concurrent(l1, l2, Line(Point(5, x1), Point(Rational(-3, 5), x1))) + assert Line.are_concurrent(l1, Line(Point(0, 0), Point(-x1, x1)), l2) is False + + +def test_are_concurrent_3d(): + p1 = Point3D(0, 0, 0) + l1 = Line(p1, Point3D(1, 1, 1)) + parallel_1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) + parallel_2 = Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0)) + assert Line3D.are_concurrent(l1) is False + assert Line3D.are_concurrent(l1, Line(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False + assert Line3D.are_concurrent(l1, Line3D(p1, Point3D(x1, x1, x1)), + Line(Point3D(x1, x1, x1), Point3D(x1, 1 + x1, 1))) is True + assert Line3D.are_concurrent(parallel_1, parallel_2) is False + + +def test_arguments(): + """Functions accepting `Point` objects in `geometry` + should also accept tuples, lists, and generators and + automatically convert them to points.""" + from sympy.utilities.iterables import subsets + + singles2d = ((1, 2), [1, 3], Point(1, 5)) + doubles2d = subsets(singles2d, 2) + l2d = Line(Point2D(1, 2), Point2D(2, 3)) + singles3d = ((1, 2, 3), [1, 2, 4], Point(1, 2, 6)) + doubles3d = subsets(singles3d, 2) + l3d = Line(Point3D(1, 2, 3), Point3D(1, 1, 2)) + singles4d = ((1, 2, 3, 4), [1, 2, 3, 5], Point(1, 2, 3, 7)) + doubles4d = subsets(singles4d, 2) + l4d = Line(Point(1, 2, 3, 4), Point(2, 2, 2, 2)) + # test 2D + test_single = ['contains', 'distance', 'equals', 'parallel_line', 'perpendicular_line', 'perpendicular_segment', + 'projection', 'intersection'] + for p in doubles2d: + Line2D(*p) + for func in test_single: + for p in singles2d: + getattr(l2d, func)(p) + # test 3D + for p in doubles3d: + Line3D(*p) + for func in test_single: + for p in singles3d: + getattr(l3d, func)(p) + # test 4D + for p in doubles4d: + Line(*p) + for func in test_single: + for p in singles4d: + getattr(l4d, func)(p) + + +def test_basic_properties_2d(): + p1 = Point(0, 0) + p2 = Point(1, 1) + p10 = Point(2000, 2000) + p_r3 = Ray(p1, p2).random_point() + p_r4 = Ray(p2, p1).random_point() + + l1 = Line(p1, p2) + l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) + l4 = Line(p1, Point(1, 0)) + + r1 = Ray(p1, Point(0, 1)) + r2 = Ray(Point(0, 1), p1) + + s1 = Segment(p1, p10) + p_s1 = s1.random_point() + + assert Line((1, 1), slope=1) == Line((1, 1), (2, 2)) + assert Line((1, 1), slope=oo) == Line((1, 1), (1, 2)) + assert Line((1, 1), slope=oo).bounds == (1, 1, 1, 2) + assert Line((1, 1), slope=-oo) == Line((1, 1), (1, 2)) + assert Line(p1, p2).scale(2, 1) == Line(p1, Point(2, 1)) + assert Line(p1, p2) == Line(p1, p2) + assert Line(p1, p2) != Line(p2, p1) + assert l1 != Line(Point(x1, x1), Point(y1, y1)) + assert l1 != l3 + assert Line(p1, p10) != Line(p10, p1) + assert Line(p1, p10) != p1 + assert p1 in l1 # is p1 on the line l1? + assert p1 not in l3 + assert s1 in Line(p1, p10) + assert Ray(Point(0, 0), Point(0, 1)) in Ray(Point(0, 0), Point(0, 2)) + assert Ray(Point(0, 0), Point(0, 2)) in Ray(Point(0, 0), Point(0, 1)) + assert Ray(Point(0, 0), Point(0, 2)).xdirection == S.Zero + assert Ray(Point(0, 0), Point(1, 2)).xdirection == S.Infinity + assert Ray(Point(0, 0), Point(-1, 2)).xdirection == S.NegativeInfinity + assert Ray(Point(0, 0), Point(2, 0)).ydirection == S.Zero + assert Ray(Point(0, 0), Point(2, 2)).ydirection == S.Infinity + assert Ray(Point(0, 0), Point(2, -2)).ydirection == S.NegativeInfinity + assert (r1 in s1) is False + assert Segment(p1, p2) in s1 + assert Ray(Point(x1, x1), Point(x1, 1 + x1)) != Ray(p1, Point(-1, 5)) + assert Segment(p1, p2).midpoint == Point(S.Half, S.Half) + assert Segment(p1, Point(-x1, x1)).length == sqrt(2 * (x1 ** 2)) + + assert l1.slope == 1 + assert l3.slope is oo + assert l4.slope == 0 + assert Line(p1, Point(0, 1)).slope is oo + assert Line(r1.source, r1.random_point()).slope == r1.slope + assert Line(r2.source, r2.random_point()).slope == r2.slope + assert Segment(Point(0, -1), Segment(p1, Point(0, 1)).random_point()).slope == Segment(p1, Point(0, 1)).slope + + assert l4.coefficients == (0, 1, 0) + assert Line((-x, x), (-x + 1, x - 1)).coefficients == (1, 1, 0) + assert Line(p1, Point(0, 1)).coefficients == (1, 0, 0) + # issue 7963 + r = Ray((0, 0), angle=x) + assert r.subs(x, 3 * pi / 4) == Ray((0, 0), (-1, 1)) + assert r.subs(x, 5 * pi / 4) == Ray((0, 0), (-1, -1)) + assert r.subs(x, -pi / 4) == Ray((0, 0), (1, -1)) + assert r.subs(x, pi / 2) == Ray((0, 0), (0, 1)) + assert r.subs(x, -pi / 2) == Ray((0, 0), (0, -1)) + + for ind in range(0, 5): + assert l3.random_point() in l3 + + assert p_r3.x >= p1.x and p_r3.y >= p1.y + assert p_r4.x <= p2.x and p_r4.y <= p2.y + assert p1.x <= p_s1.x <= p10.x and p1.y <= p_s1.y <= p10.y + assert hash(s1) != hash(Segment(p10, p1)) + + assert s1.plot_interval() == [t, 0, 1] + assert Line(p1, p10).plot_interval() == [t, -5, 5] + assert Ray((0, 0), angle=pi / 4).plot_interval() == [t, 0, 10] + + +def test_basic_properties_3d(): + p1 = Point3D(0, 0, 0) + p2 = Point3D(1, 1, 1) + p3 = Point3D(x1, x1, x1) + p5 = Point3D(x1, 1 + x1, 1) + + l1 = Line3D(p1, p2) + l3 = Line3D(p3, p5) + + r1 = Ray3D(p1, Point3D(-1, 5, 0)) + r3 = Ray3D(p1, p2) + + s1 = Segment3D(p1, p2) + + assert Line3D((1, 1, 1), direction_ratio=[2, 3, 4]) == Line3D(Point3D(1, 1, 1), Point3D(3, 4, 5)) + assert Line3D((1, 1, 1), direction_ratio=[1, 5, 7]) == Line3D(Point3D(1, 1, 1), Point3D(2, 6, 8)) + assert Line3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Line3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) + assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).direction_cosine == [1, 0, 0] + assert Line3D(Line3D(p1, Point3D(0, 1, 0))) == Line3D(p1, Point3D(0, 1, 0)) + assert Ray3D(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))) == Ray3D(p1, Point3D(1, 0, 0)) + assert Line3D(p1, p2) != Line3D(p2, p1) + assert l1 != l3 + assert l1 != Line3D(p3, Point3D(y1, y1, y1)) + assert r3 != r1 + assert Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) in Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) in Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).xdirection == S.Infinity + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).ydirection == S.Infinity + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).zdirection == S.Infinity + assert Ray3D(Point3D(0, 0, 0), Point3D(-2, 2, 2)).xdirection == S.NegativeInfinity + assert Ray3D(Point3D(0, 0, 0), Point3D(2, -2, 2)).ydirection == S.NegativeInfinity + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, -2)).zdirection == S.NegativeInfinity + assert Ray3D(Point3D(0, 0, 0), Point3D(0, 2, 2)).xdirection == S.Zero + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 0, 2)).ydirection == S.Zero + assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 0)).zdirection == S.Zero + assert p1 in l1 + assert p1 not in l3 + + assert l1.direction_ratio == [1, 1, 1] + + assert s1.midpoint == Point3D(S.Half, S.Half, S.Half) + # Test zdirection + assert Ray3D(p1, Point3D(0, 0, -1)).zdirection is S.NegativeInfinity + + +def test_contains(): + p1 = Point(0, 0) + + r = Ray(p1, Point(4, 4)) + r1 = Ray3D(p1, Point3D(0, 0, -1)) + r2 = Ray3D(p1, Point3D(0, 1, 0)) + r3 = Ray3D(p1, Point3D(0, 0, 1)) + + l = Line(Point(0, 1), Point(3, 4)) + # Segment contains + assert Point(0, (a + b) / 2) in Segment((0, a), (0, b)) + assert Point((a + b) / 2, 0) in Segment((a, 0), (b, 0)) + assert Point3D(0, 1, 0) in Segment3D((0, 1, 0), (0, 1, 0)) + assert Point3D(1, 0, 0) in Segment3D((1, 0, 0), (1, 0, 0)) + assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains([]) is True + assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains( + Segment3D(Point3D(2, 2, 2), Point3D(3, 2, 2))) is False + # Line contains + assert l.contains(Point(0, 1)) is True + assert l.contains((0, 1)) is True + assert l.contains((0, 0)) is False + # Ray contains + assert r.contains(p1) is True + assert r.contains((1, 1)) is True + assert r.contains((1, 3)) is False + assert r.contains(Segment((1, 1), (2, 2))) is True + assert r.contains(Segment((1, 2), (2, 5))) is False + assert r.contains(Ray((2, 2), (3, 3))) is True + assert r.contains(Ray((2, 2), (3, 5))) is False + assert r1.contains(Segment3D(p1, Point3D(0, 0, -10))) is True + assert r1.contains(Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))) is False + assert r2.contains(Point3D(0, 0, 0)) is True + assert r3.contains(Point3D(0, 0, 0)) is True + assert Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)).contains([]) is False + assert Line3D((0, 0, 0), (x, y, z)).contains((2 * x, 2 * y, 2 * z)) + with warns(UserWarning, test_stacklevel=False): + assert Line3D(p1, Point3D(0, 1, 0)).contains(Point(1.0, 1.0)) is False + + with warns(UserWarning, test_stacklevel=False): + assert r3.contains(Point(1.0, 1.0)) is False + + +def test_contains_nonreal_symbols(): + u, v, w, z = symbols('u, v, w, z') + l = Segment(Point(u, w), Point(v, z)) + p = Point(u*Rational(2, 3) + v/3, w*Rational(2, 3) + z/3) + assert l.contains(p) + + +def test_distance_2d(): + p1 = Point(0, 0) + p2 = Point(1, 1) + half = S.Half + + s1 = Segment(Point(0, 0), Point(1, 1)) + s2 = Segment(Point(half, half), Point(1, 0)) + + r = Ray(p1, p2) + + assert s1.distance(Point(0, 0)) == 0 + assert s1.distance((0, 0)) == 0 + assert s2.distance(Point(0, 0)) == 2 ** half / 2 + assert s2.distance(Point(Rational(3) / 2, Rational(3) / 2)) == 2 ** half + assert Line(p1, p2).distance(Point(-1, 1)) == sqrt(2) + assert Line(p1, p2).distance(Point(1, -1)) == sqrt(2) + assert Line(p1, p2).distance(Point(2, 2)) == 0 + assert Line(p1, p2).distance((-1, 1)) == sqrt(2) + assert Line((0, 0), (0, 1)).distance(p1) == 0 + assert Line((0, 0), (0, 1)).distance(p2) == 1 + assert Line((0, 0), (1, 0)).distance(p1) == 0 + assert Line((0, 0), (1, 0)).distance(p2) == 1 + assert r.distance(Point(-1, -1)) == sqrt(2) + assert r.distance(Point(1, 1)) == 0 + assert r.distance(Point(-1, 1)) == sqrt(2) + assert Ray((1, 1), (2, 2)).distance(Point(1.5, 3)) == 3 * sqrt(2) / 4 + assert r.distance((1, 1)) == 0 + + +def test_dimension_normalization(): + with warns(UserWarning, test_stacklevel=False): + assert Ray((1, 1), (2, 1, 2)) == Ray((1, 1, 0), (2, 1, 2)) + + +def test_distance_3d(): + p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1) + p3 = Point3D(Rational(3) / 2, Rational(3) / 2, Rational(3) / 2) + + s1 = Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) + s2 = Segment3D(Point3D(S.Half, S.Half, S.Half), Point3D(1, 0, 1)) + + r = Ray3D(p1, p2) + + assert s1.distance(p1) == 0 + assert s2.distance(p1) == sqrt(3) / 2 + assert s2.distance(p3) == 2 * sqrt(6) / 3 + assert s1.distance((0, 0, 0)) == 0 + assert s2.distance((0, 0, 0)) == sqrt(3) / 2 + assert s1.distance(p1) == 0 + assert s2.distance(p1) == sqrt(3) / 2 + assert s2.distance(p3) == 2 * sqrt(6) / 3 + assert s1.distance((0, 0, 0)) == 0 + assert s2.distance((0, 0, 0)) == sqrt(3) / 2 + # Line to point + assert Line3D(p1, p2).distance(Point3D(-1, 1, 1)) == 2 * sqrt(6) / 3 + assert Line3D(p1, p2).distance(Point3D(1, -1, 1)) == 2 * sqrt(6) / 3 + assert Line3D(p1, p2).distance(Point3D(2, 2, 2)) == 0 + assert Line3D(p1, p2).distance((2, 2, 2)) == 0 + assert Line3D(p1, p2).distance((1, -1, 1)) == 2 * sqrt(6) / 3 + assert Line3D((0, 0, 0), (0, 1, 0)).distance(p1) == 0 + assert Line3D((0, 0, 0), (0, 1, 0)).distance(p2) == sqrt(2) + assert Line3D((0, 0, 0), (1, 0, 0)).distance(p1) == 0 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(p2) == sqrt(2) + # Line to line + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 0, 0), (0, 1, 2))) == 0 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 0, 0), (1, 0, 0))) == 0 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((10, 0, 0), (10, 1, 2))) == 0 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Line3D((0, 1, 0), (0, 1, 1))) == 1 + # Line to plane + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((2, 0, 0), (0, 0, 1))) == 0 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((0, 1, 0), (0, 1, 0))) == 1 + assert Line3D((0, 0, 0), (1, 0, 0)).distance(Plane((1, 1, 3), (1, 0, 0))) == 0 + # Ray to point + assert r.distance(Point3D(-1, -1, -1)) == sqrt(3) + assert r.distance(Point3D(1, 1, 1)) == 0 + assert r.distance((-1, -1, -1)) == sqrt(3) + assert r.distance((1, 1, 1)) == 0 + assert Ray3D((0, 0, 0), (1, 1, 2)).distance((-1, -1, 2)) == 4 * sqrt(3) / 3 + assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, -3, -1)) == Rational(9) / 2 + assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == sqrt(78) / 6 + + +def test_equals(): + p1 = Point(0, 0) + p2 = Point(1, 1) + + l1 = Line(p1, p2) + l2 = Line((0, 5), slope=m) + l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) + + assert l1.perpendicular_line(p1.args).equals(Line(Point(0, 0), Point(1, -1))) + assert l1.perpendicular_line(p1).equals(Line(Point(0, 0), Point(1, -1))) + assert Line(Point(x1, x1), Point(y1, y1)).parallel_line(Point(-x1, x1)). \ + equals(Line(Point(-x1, x1), Point(-y1, 2 * x1 - y1))) + assert l3.parallel_line(p1.args).equals(Line(Point(0, 0), Point(0, -1))) + assert l3.parallel_line(p1).equals(Line(Point(0, 0), Point(0, -1))) + assert (l2.distance(Point(2, 3)) - 2 * abs(m + 1) / sqrt(m ** 2 + 1)).equals(0) + assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False + assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(Point3D(-5, 0, 0), Point3D(-1, 0, 0))) is True + assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(p1, Point3D(0, 1, 0))) is False + assert Ray3D(p1, Point3D(0, 0, -1)).equals(Point(1.0, 1.0)) is False + assert Ray3D(p1, Point3D(0, 0, -1)).equals(Ray3D(p1, Point3D(0, 0, -1))) is True + assert Line3D((0, 0), (t, t)).perpendicular_line(Point(0, 1, 0)).equals( + Line3D(Point3D(0, 1, 0), Point3D(S.Half, S.Half, 0))) + assert Line3D((0, 0), (t, t)).perpendicular_segment(Point(0, 1, 0)).equals(Segment3D((0, 1), (S.Half, S.Half))) + assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False + + +def test_equation(): + p1 = Point(0, 0) + p2 = Point(1, 1) + l1 = Line(p1, p2) + l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) + + assert simplify(l1.equation()) in (x - y, y - x) + assert simplify(l3.equation()) in (x - x1, x1 - x) + assert simplify(l1.equation()) in (x - y, y - x) + assert simplify(l3.equation()) in (x - x1, x1 - x) + + assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y + assert Line(p1, Point(0, 1)).equation() == x + assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2 + assert Line(p2, Point(2, 1)).equation() == y - 1 + + assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1) + ).equation() == (-x + y, -x + z) + assert Line3D(Point(1, 2, 3), Point(2, 3, 4) + ).equation() == (-x + y - 1, -x + z - 2) + assert Line3D(Point(1, 2, 3), Point(1, 3, 4) + ).equation() == (x - 1, -y + z - 1) + assert Line3D(Point(1, 2, 3), Point(2, 2, 4) + ).equation() == (y - 2, -x + z - 2) + assert Line3D(Point(1, 2, 3), Point(2, 3, 3) + ).equation() == (-x + y - 1, z - 3) + assert Line3D(Point(1, 2, 3), Point(1, 2, 4) + ).equation() == (x - 1, y - 2) + assert Line3D(Point(1, 2, 3), Point(1, 3, 3) + ).equation() == (x - 1, z - 3) + assert Line3D(Point(1, 2, 3), Point(2, 2, 3) + ).equation() == (y - 2, z - 3) + + +def test_intersection_2d(): + p1 = Point(0, 0) + p2 = Point(1, 1) + p3 = Point(x1, x1) + p4 = Point(y1, y1) + + l1 = Line(p1, p2) + l3 = Line(Point(0, 0), Point(3, 4)) + + r1 = Ray(Point(1, 1), Point(2, 2)) + r2 = Ray(Point(0, 0), Point(3, 4)) + r4 = Ray(p1, p2) + r6 = Ray(Point(0, 1), Point(1, 2)) + r7 = Ray(Point(0.5, 0.5), Point(1, 1)) + + s1 = Segment(p1, p2) + s2 = Segment(Point(0.25, 0.25), Point(0.5, 0.5)) + s3 = Segment(Point(0, 0), Point(3, 4)) + + assert intersection(l1, p1) == [p1] + assert intersection(l1, Point(x1, 1 + x1)) == [] + assert intersection(l1, Line(p3, p4)) in [[l1], [Line(p3, p4)]] + assert intersection(l1, l1.parallel_line(Point(x1, 1 + x1))) == [] + assert intersection(l3, l3) == [l3] + assert intersection(l3, r2) == [r2] + assert intersection(l3, s3) == [s3] + assert intersection(s3, l3) == [s3] + assert intersection(Segment(Point(-10, 10), Point(10, 10)), Segment(Point(-5, -5), Point(-5, 5))) == [] + assert intersection(r2, l3) == [r2] + assert intersection(r1, Ray(Point(2, 2), Point(0, 0))) == [Segment(Point(1, 1), Point(2, 2))] + assert intersection(r1, Ray(Point(1, 1), Point(-1, -1))) == [Point(1, 1)] + assert intersection(r1, Segment(Point(0, 0), Point(2, 2))) == [Segment(Point(1, 1), Point(2, 2))] + + assert r4.intersection(s2) == [s2] + assert r4.intersection(Segment(Point(2, 3), Point(3, 4))) == [] + assert r4.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] + assert r4.intersection(Ray(p2, p1)) == [s1] + assert Ray(p2, p1).intersection(r6) == [] + assert r4.intersection(r7) == r7.intersection(r4) == [r7] + assert Ray3D((0, 0), (3, 0)).intersection(Ray3D((1, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] + assert Ray3D((1, 0), (3, 0)).intersection(Ray3D((0, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] + assert Ray(Point(0, 0), Point(0, 4)).intersection(Ray(Point(0, 1), Point(0, -1))) == \ + [Segment(Point(0, 0), Point(0, 1))] + + assert Segment3D((0, 0), (3, 0)).intersection( + Segment3D((1, 0), (2, 0))) == [Segment3D((1, 0), (2, 0))] + assert Segment3D((1, 0), (2, 0)).intersection( + Segment3D((0, 0), (3, 0))) == [Segment3D((1, 0), (2, 0))] + assert Segment3D((0, 0), (3, 0)).intersection( + Segment3D((3, 0), (4, 0))) == [Point3D((3, 0))] + assert Segment3D((0, 0), (3, 0)).intersection( + Segment3D((2, 0), (5, 0))) == [Segment3D((2, 0), (3, 0))] + assert Segment3D((0, 0), (3, 0)).intersection( + Segment3D((-2, 0), (1, 0))) == [Segment3D((0, 0), (1, 0))] + assert Segment3D((0, 0), (3, 0)).intersection( + Segment3D((-2, 0), (0, 0))) == [Point3D(0, 0)] + assert s1.intersection(Segment(Point(1, 1), Point(2, 2))) == [Point(1, 1)] + assert s1.intersection(Segment(Point(0.5, 0.5), Point(1.5, 1.5))) == [Segment(Point(0.5, 0.5), p2)] + assert s1.intersection(Segment(Point(4, 4), Point(5, 5))) == [] + assert s1.intersection(Segment(Point(-1, -1), p1)) == [p1] + assert s1.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] + assert s1.intersection(Line(Point(1, 0), Point(2, 1))) == [] + assert s1.intersection(s2) == [s2] + assert s2.intersection(s1) == [s2] + + assert asa(120, 8, 52) == \ + Triangle( + Point(0, 0), + Point(8, 0), + Point(-4 * cos(19 * pi / 90) / sin(2 * pi / 45), + 4 * sqrt(3) * cos(19 * pi / 90) / sin(2 * pi / 45))) + assert Line((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] + assert Line((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] + assert Ray((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] + assert Ray((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] + assert Ray((0, 0), (10, 10)).contains(Segment((1, 1), (2, 2))) is True + assert Segment((1, 1), (2, 2)) in Line((0, 0), (10, 10)) + assert s1.intersection(Ray((1, 1), (4, 4))) == [Point(1, 1)] + + # This test is disabled because it hangs after rref changes which simplify + # intermediate results and return a different representation from when the + # test was written. + # # 16628 - this should be fast + # p0 = Point2D(Rational(249, 5), Rational(497999, 10000)) + # p1 = Point2D((-58977084786*sqrt(405639795226) + 2030690077184193 + + # 20112207807*sqrt(630547164901) + 99600*sqrt(255775022850776494562626)) + # /(2000*sqrt(255775022850776494562626) + 1991998000*sqrt(405639795226) + # + 1991998000*sqrt(630547164901) + 1622561172902000), + # (-498000*sqrt(255775022850776494562626) - 995999*sqrt(630547164901) + + # 90004251917891999 + + # 496005510002*sqrt(405639795226))/(10000*sqrt(255775022850776494562626) + # + 9959990000*sqrt(405639795226) + 9959990000*sqrt(630547164901) + + # 8112805864510000)) + # p2 = Point2D(Rational(497, 10), Rational(-497, 10)) + # p3 = Point2D(Rational(-497, 10), Rational(-497, 10)) + # l = Line(p0, p1) + # s = Segment(p2, p3) + # n = (-52673223862*sqrt(405639795226) - 15764156209307469 - + # 9803028531*sqrt(630547164901) + + # 33200*sqrt(255775022850776494562626)) + # d = sqrt(405639795226) + 315274080450 + 498000*sqrt( + # 630547164901) + sqrt(255775022850776494562626) + # assert intersection(l, s) == [ + # Point2D(n/d*Rational(3, 2000), Rational(-497, 10))] + + +def test_line_intersection(): + # see also test_issue_11238 in test_matrices.py + x0 = tan(pi*Rational(13, 45)) + x1 = sqrt(3) + x2 = x0**2 + x, y = [8*x0/(x0 + x1), (24*x0 - 8*x1*x2)/(x2 - 3)] + assert Line(Point(0, 0), Point(1, -sqrt(3))).contains(Point(x, y)) is True + + +def test_intersection_3d(): + p1 = Point3D(0, 0, 0) + p2 = Point3D(1, 1, 1) + + l1 = Line3D(p1, p2) + l2 = Line3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) + + r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) + r2 = Ray3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) + + s1 = Segment3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) + + assert intersection(l1, p1) == [p1] + assert intersection(l1, Point3D(x1, 1 + x1, 1)) == [] + assert intersection(l1, l1.parallel_line(p1)) == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))] + assert intersection(l2, r2) == [r2] + assert intersection(l2, s1) == [s1] + assert intersection(r2, l2) == [r2] + assert intersection(r1, Ray3D(Point3D(1, 1, 1), Point3D(-1, -1, -1))) == [Point3D(1, 1, 1)] + assert intersection(r1, Segment3D(Point3D(0, 0, 0), Point3D(2, 2, 2))) == [ + Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] + assert intersection(Ray3D(Point3D(1, 0, 0), Point3D(-1, 0, 0)), Ray3D(Point3D(0, 1, 0), Point3D(0, -1, 0))) \ + == [Point3D(0, 0, 0)] + assert intersection(r1, Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0))) == \ + [Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] + assert intersection(s1, r2) == [s1] + + assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).intersection(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) == \ + [Point3D(2, 2, 1)] + assert Line3D((0, 1, 2), (0, 2, 3)).intersection(Line3D((0, 1, 2), (0, 1, 1))) == [Point3D(0, 1, 2)] + assert Line3D((0, 0), (t, t)).intersection(Line3D((0, 1), (t, t))) == \ + [Point3D(t, t)] + + assert Ray3D(Point3D(0, 0, 0), Point3D(0, 4, 0)).intersection(Ray3D(Point3D(0, 1, 1), Point3D(0, -1, 1))) == [] + + +def test_is_parallel(): + p1 = Point3D(0, 0, 0) + p2 = Point3D(1, 1, 1) + p3 = Point3D(x1, x1, x1) + + l2 = Line(Point(x1, x1), Point(y1, y1)) + l2_1 = Line(Point(x1, x1), Point(x1, 1 + x1)) + + assert Line.is_parallel(Line(Point(0, 0), Point(1, 1)), l2) + assert Line.is_parallel(l2, Line(Point(x1, x1), Point(x1, 1 + x1))) is False + assert Line.is_parallel(l2, l2.parallel_line(Point(-x1, x1))) + assert Line.is_parallel(l2_1, l2_1.parallel_line(Point(0, 0))) + assert Line3D(p1, p2).is_parallel(Line3D(p1, p2)) # same as in 2D + assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False + assert Line3D(p1, p2).parallel_line(p3) == Line3D(Point3D(x1, x1, x1), + Point3D(x1 + 1, x1 + 1, x1 + 1)) + assert Line3D(p1, p2).parallel_line(p3.args) == \ + Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1)) + assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False + + +def test_is_perpendicular(): + p1 = Point(0, 0) + p2 = Point(1, 1) + + l1 = Line(p1, p2) + l2 = Line(Point(x1, x1), Point(y1, y1)) + l1_1 = Line(p1, Point(-x1, x1)) + # 2D + assert Line.is_perpendicular(l1, l1_1) + assert Line.is_perpendicular(l1, l2) is False + p = l1.random_point() + assert l1.perpendicular_segment(p) == p + # 3D + assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), + Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is True + assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), + Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))) is False + assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)), + Line3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False + + +def test_is_similar(): + p1 = Point(2000, 2000) + p2 = p1.scale(2, 2) + + r1 = Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)) + r2 = Ray(Point(0, 0), Point(0, 1)) + + s1 = Segment(Point(0, 0), p1) + + assert s1.is_similar(Segment(p1, p2)) + assert s1.is_similar(r2) is False + assert r1.is_similar(Line3D(Point3D(1, 1, 1), Point3D(1, 0, 0))) is True + assert r1.is_similar(Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is False + + +def test_length(): + s2 = Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)) + assert Line(Point(0, 0), Point(1, 1)).length is oo + assert s2.length == sqrt(3) * sqrt((x1 - y1) ** 2) + assert Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).length is oo + + +def test_projection(): + p1 = Point(0, 0) + p2 = Point3D(0, 0, 0) + p3 = Point(-x1, x1) + + l1 = Line(p1, Point(1, 1)) + l2 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) + l3 = Line3D(p2, Point3D(1, 1, 1)) + + r1 = Ray(Point(1, 1), Point(2, 2)) + + s1 = Segment(Point2D(0, 0), Point2D(0, 1)) + s2 = Segment(Point2D(1, 0), Point2D(2, 1/2)) + + assert Line(Point(x1, x1), Point(y1, y1)).projection(Point(y1, y1)) == Point(y1, y1) + assert Line(Point(x1, x1), Point(x1, 1 + x1)).projection(Point(1, 1)) == Point(x1, 1) + assert Segment(Point(-2, 2), Point(0, 4)).projection(r1) == Segment(Point(-1, 3), Point(0, 4)) + assert Segment(Point(0, 4), Point(-2, 2)).projection(r1) == Segment(Point(0, 4), Point(-1, 3)) + assert s2.projection(s1) == EmptySet + assert l1.projection(p3) == p1 + assert l1.projection(Ray(p1, Point(-1, 5))) == Ray(Point(0, 0), Point(2, 2)) + assert l1.projection(Ray(p1, Point(-1, 1))) == p1 + assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) + assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) + assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) + assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) + assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) + assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) + + assert l3.projection(Ray3D(p2, Point3D(-1, 5, 0))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(4, 3), Rational(4, 3), Rational(4, 3))) + assert l3.projection(Ray3D(p2, Point3D(-1, 1, 1))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(1, 3), Rational(1, 3), Rational(1, 3))) + assert l2.projection(Point3D(5, 5, 0)) == Point3D(5, 0) + assert l2.projection(Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))).equals(l2) + + +def test_perpendicular_line(): + # 3d - requires a particular orthogonal to be selected + p1, p2, p3 = Point(0, 0, 0), Point(2, 3, 4), Point(-2, 2, 0) + l = Line(p1, p2) + p = l.perpendicular_line(p3) + assert p.p1 == p3 + assert p.p2 in l + # 2d - does not require special selection + p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) + l = Line(p1, p2) + p = l.perpendicular_line(p3) + assert p.p1 == p3 + # p is directed from l to p3 + assert p.direction.unit == (p3 - l.projection(p3)).unit + + +def test_perpendicular_bisector(): + s1 = Segment(Point(0, 0), Point(1, 1)) + aline = Line(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))) + on_line = Segment(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))).midpoint + + assert s1.perpendicular_bisector().equals(aline) + assert s1.perpendicular_bisector(on_line).equals(Segment(s1.midpoint, on_line)) + assert s1.perpendicular_bisector(on_line + (1, 0)).equals(aline) + + +def test_raises(): + d, e = symbols('a,b', real=True) + s = Segment((d, 0), (e, 0)) + + raises(TypeError, lambda: Line((1, 1), 1)) + raises(ValueError, lambda: Line(Point(0, 0), Point(0, 0))) + raises(Undecidable, lambda: Point(2 * d, 0) in s) + raises(ValueError, lambda: Ray3D(Point(1.0, 1.0))) + raises(ValueError, lambda: Line3D(Point3D(0, 0, 0), Point3D(0, 0, 0))) + raises(TypeError, lambda: Line3D((1, 1), 1)) + raises(ValueError, lambda: Line3D(Point3D(0, 0, 0))) + raises(TypeError, lambda: Ray((1, 1), 1)) + raises(GeometryError, lambda: Line(Point(0, 0), Point(1, 0)) + .projection(Circle(Point(0, 0), 1))) + + +def test_ray_generation(): + assert Ray((1, 1), angle=pi / 4) == Ray((1, 1), (2, 2)) + assert Ray((1, 1), angle=pi / 2) == Ray((1, 1), (1, 2)) + assert Ray((1, 1), angle=-pi / 2) == Ray((1, 1), (1, 0)) + assert Ray((1, 1), angle=-3 * pi / 2) == Ray((1, 1), (1, 2)) + assert Ray((1, 1), angle=5 * pi / 2) == Ray((1, 1), (1, 2)) + assert Ray((1, 1), angle=5.0 * pi / 2) == Ray((1, 1), (1, 2)) + assert Ray((1, 1), angle=pi) == Ray((1, 1), (0, 1)) + assert Ray((1, 1), angle=3.0 * pi) == Ray((1, 1), (0, 1)) + assert Ray((1, 1), angle=4.0 * pi) == Ray((1, 1), (2, 1)) + assert Ray((1, 1), angle=0) == Ray((1, 1), (2, 1)) + assert Ray((1, 1), angle=4.05 * pi) == Ray(Point(1, 1), + Point(2, -sqrt(5) * sqrt(2 * sqrt(5) + 10) / 4 - sqrt( + 2 * sqrt(5) + 10) / 4 + 2 + sqrt(5))) + assert Ray((1, 1), angle=4.02 * pi) == Ray(Point(1, 1), + Point(2, 1 + tan(4.02 * pi))) + assert Ray((1, 1), angle=5) == Ray((1, 1), (2, 1 + tan(5))) + + assert Ray3D((1, 1, 1), direction_ratio=[4, 4, 4]) == Ray3D(Point3D(1, 1, 1), Point3D(5, 5, 5)) + assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) + assert Ray3D((1, 1, 1), direction_ratio=[1, 1, 1]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) + + +def test_issue_7814(): + circle = Circle(Point(x, 0), y) + line = Line(Point(k, z), slope=0) + _s = sqrt((y - z)*(y + z)) + assert line.intersection(circle) == [Point2D(x + _s, z), Point2D(x - _s, z)] + + +def test_issue_2941(): + def _check(): + for f, g in cartes(*[(Line, Ray, Segment)] * 2): + l1 = f(a, b) + l2 = g(c, d) + assert l1.intersection(l2) == l2.intersection(l1) + # intersect at end point + c, d = (-2, -2), (-2, 0) + a, b = (0, 0), (1, 1) + _check() + # midline intersection + c, d = (-2, -3), (-2, 0) + _check() + + +def test_parameter_value(): + t = Symbol('t') + p1, p2 = Point(0, 1), Point(5, 6) + l = Line(p1, p2) + assert l.parameter_value((5, 6), t) == {t: 1} + raises(ValueError, lambda: l.parameter_value((0, 0), t)) + + +def test_bisectors(): + r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) + r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0)) + bisections = r1.bisectors(r2) + assert bisections == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), + Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] + ans = [Line3D(Point3D(0, 0, 0), Point3D(1, 0, 1)), + Line3D(Point3D(0, 0, 0), Point3D(-1, 0, 1))] + l1 = (0, 0, 0), (0, 0, 1) + l2 = (0, 0), (1, 0) + for a, b in cartes((Line, Segment, Ray), repeat=2): + assert a(*l1).bisectors(b(*l2)) == ans + + +def test_issue_8615(): + a = Line3D(Point3D(6, 5, 0), Point3D(6, -6, 0)) + b = Line3D(Point3D(6, -1, 19/10), Point3D(6, -1, 0)) + assert a.intersection(b) == [Point3D(6, -1, 0)] + + +def test_issue_12598(): + r1 = Ray(Point(0, 1), Point(0.98, 0.79).n(2)) + r2 = Ray(Point(0, 0), Point(0.71, 0.71).n(2)) + assert str(r1.intersection(r2)[0]) == 'Point2D(0.82, 0.82)' + l1 = Line((0, 0), (1, 1)) + l2 = Segment((-1, 1), (0, -1)).n(2) + assert str(l1.intersection(l2)[0]) == 'Point2D(-0.33, -0.33)' + l2 = Segment((-1, 1), (-1/2, 1/2)).n(2) + assert not l1.intersection(l2) diff --git a/shared/package-files/7c/7cb7f0a38e6ec1ac3b6983ab4993ca74393753c20b09858784c9405818b4e71e/cummaxmin_backward_native.h b/shared/package-files/7c/7cb7f0a38e6ec1ac3b6983ab4993ca74393753c20b09858784c9405818b4e71e/cummaxmin_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2bf7388e6b2a38cc5eaa0f7f734d5e4c7d156a0b --- /dev/null +++ b/shared/package-files/7c/7cb7f0a38e6ec1ac3b6983ab4993ca74393753c20b09858784c9405818b4e71e/cummaxmin_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor cummaxmin_backward(const at::Tensor & grad, const at::Tensor & input, const at::Tensor & indices, int64_t dim); +} // namespace native +} // namespace at diff --git a/shared/package-files/7c/7cb8c14dfa1b70ad6feda06f8f346a17b27e3f741c66576132f10c54a3ac8a92/as_strided.h b/shared/package-files/7c/7cb8c14dfa1b70ad6feda06f8f346a17b27e3f741c66576132f10c54a3ac8a92/as_strided.h new file mode 100644 index 0000000000000000000000000000000000000000..d5acb50c66fcc0d2e528ccc618890da4919a74ca --- /dev/null +++ b/shared/package-files/7c/7cb8c14dfa1b70ad6feda06f8f346a17b27e3f741c66576132f10c54a3ac8a92/as_strided.h @@ -0,0 +1,70 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) +inline at::Tensor as_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided::call(self, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? ::std::make_optional(c10::SymInt(*storage_offset)) : ::std::nullopt); +} +namespace symint { + template >> + at::Tensor as_strided(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided::call(self, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? ::std::make_optional(c10::SymInt(*storage_offset)) : ::std::nullopt); + } +} + +// aten::as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) +inline at::Tensor as_strided_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided::call(self, size, stride, storage_offset); +} +namespace symint { + template >> + at::Tensor as_strided(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided::call(self, size, stride, storage_offset); + } +} + +// aten::as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) +inline const at::Tensor & as_strided_(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided_::call(self, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? ::std::make_optional(c10::SymInt(*storage_offset)) : ::std::nullopt); +} +namespace symint { + template >> + const at::Tensor & as_strided_(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided_::call(self, c10::fromIntArrayRefSlow(size), c10::fromIntArrayRefSlow(stride), storage_offset.has_value() ? ::std::make_optional(c10::SymInt(*storage_offset)) : ::std::nullopt); + } +} + +// aten::as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) +inline const at::Tensor & as_strided__symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided_::call(self, size, stride, storage_offset); +} +namespace symint { + template >> + const at::Tensor & as_strided_(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional storage_offset=::std::nullopt) { + return at::_ops::as_strided_::call(self, size, stride, storage_offset); + } +} + +} diff --git a/shared/package-files/7c/7ccaad70eba2a473ba44a3e1d58079a3b77df3974b2a8efa5a1a77beb21e8b61/sandbox.py b/shared/package-files/7c/7ccaad70eba2a473ba44a3e1d58079a3b77df3974b2a8efa5a1a77beb21e8b61/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..2d84242d667c7df6a20aa56eabce6ac34ddc4a7e --- /dev/null +++ b/shared/package-files/7c/7ccaad70eba2a473ba44a3e1d58079a3b77df3974b2a8efa5a1a77beb21e8b61/sandbox.py @@ -0,0 +1,536 @@ +from __future__ import annotations + +import builtins +import contextlib +import functools +import itertools +import operator +import os +import pickle +import re +import sys +import tempfile +import textwrap +from types import TracebackType +from typing import TYPE_CHECKING, Any, ClassVar + +import pkg_resources +from pkg_resources import working_set + +from distutils.errors import DistutilsError + +if TYPE_CHECKING: + import os as _os +elif sys.platform.startswith('java'): + import org.python.modules.posix.PosixModule as _os # pyright: ignore[reportMissingImports] +else: + _os = sys.modules[os.name] +_open = open + + +if TYPE_CHECKING: + from typing_extensions import Self + +__all__ = [ + "AbstractSandbox", + "DirectorySandbox", + "SandboxViolation", + "run_setup", +] + + +def _execfile(filename, globals, locals=None): + """ + Python 3 implementation of execfile. + """ + mode = 'rb' + with open(filename, mode) as stream: + script = stream.read() + if locals is None: + locals = globals + code = compile(script, filename, 'exec') + exec(code, globals, locals) + + +@contextlib.contextmanager +def save_argv(repl=None): + saved = sys.argv[:] + if repl is not None: + sys.argv[:] = repl + try: + yield saved + finally: + sys.argv[:] = saved + + +@contextlib.contextmanager +def save_path(): + saved = sys.path[:] + try: + yield saved + finally: + sys.path[:] = saved + + +@contextlib.contextmanager +def override_temp(replacement): + """ + Monkey-patch tempfile.tempdir with replacement, ensuring it exists + """ + os.makedirs(replacement, exist_ok=True) + + saved = tempfile.tempdir + + tempfile.tempdir = replacement + + try: + yield + finally: + tempfile.tempdir = saved + + +@contextlib.contextmanager +def pushd(target): + saved = os.getcwd() + os.chdir(target) + try: + yield saved + finally: + os.chdir(saved) + + +class UnpickleableException(Exception): + """ + An exception representing another Exception that could not be pickled. + """ + + @staticmethod + def dump(type, exc): + """ + Always return a dumped (pickled) type and exc. If exc can't be pickled, + wrap it in UnpickleableException first. + """ + try: + return pickle.dumps(type), pickle.dumps(exc) + except Exception: + # get UnpickleableException inside the sandbox + from setuptools.sandbox import UnpickleableException as cls + + return cls.dump(cls, cls(repr(exc))) + + +class ExceptionSaver: + """ + A Context Manager that will save an exception, serialize, and restore it + later. + """ + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> bool: + if not exc: + return False + + # dump the exception + self._saved = UnpickleableException.dump(type, exc) + self._tb = tb + + # suppress the exception + return True + + def resume(self): + "restore and re-raise any exception" + + if '_saved' not in vars(self): + return + + _type, exc = map(pickle.loads, self._saved) + raise exc.with_traceback(self._tb) + + +@contextlib.contextmanager +def save_modules(): + """ + Context in which imported modules are saved. + + Translates exceptions internal to the context into the equivalent exception + outside the context. + """ + saved = sys.modules.copy() + with ExceptionSaver() as saved_exc: + yield saved + + sys.modules.update(saved) + # remove any modules imported since + del_modules = ( + mod_name + for mod_name in sys.modules + if mod_name not in saved + # exclude any encodings modules. See #285 + and not mod_name.startswith('encodings.') + ) + _clear_modules(del_modules) + + saved_exc.resume() + + +def _clear_modules(module_names): + for mod_name in list(module_names): + del sys.modules[mod_name] + + +@contextlib.contextmanager +def save_pkg_resources_state(): + saved = pkg_resources.__getstate__() + try: + yield saved + finally: + pkg_resources.__setstate__(saved) + + +@contextlib.contextmanager +def setup_context(setup_dir): + temp_dir = os.path.join(setup_dir, 'temp') + with save_pkg_resources_state(): + with save_modules(): + with save_path(): + hide_setuptools() + with save_argv(): + with override_temp(temp_dir): + with pushd(setup_dir): + # ensure setuptools commands are available + __import__('setuptools') + yield + + +_MODULES_TO_HIDE = { + 'setuptools', + 'distutils', + 'pkg_resources', + 'Cython', + '_distutils_hack', +} + + +def _needs_hiding(mod_name): + """ + >>> _needs_hiding('setuptools') + True + >>> _needs_hiding('pkg_resources') + True + >>> _needs_hiding('setuptools_plugin') + False + >>> _needs_hiding('setuptools.__init__') + True + >>> _needs_hiding('distutils') + True + >>> _needs_hiding('os') + False + >>> _needs_hiding('Cython') + True + """ + base_module = mod_name.split('.', 1)[0] + return base_module in _MODULES_TO_HIDE + + +def hide_setuptools(): + """ + Remove references to setuptools' modules from sys.modules to allow the + invocation to import the most appropriate setuptools. This technique is + necessary to avoid issues such as #315 where setuptools upgrading itself + would fail to find a function declared in the metadata. + """ + _distutils_hack = sys.modules.get('_distutils_hack', None) + if _distutils_hack is not None: + _distutils_hack._remove_shim() + + modules = filter(_needs_hiding, sys.modules) + _clear_modules(modules) + + +def run_setup(setup_script, args): + """Run a distutils setup script, sandboxed in its directory""" + setup_dir = os.path.abspath(os.path.dirname(setup_script)) + with setup_context(setup_dir): + try: + sys.argv[:] = [setup_script] + list(args) + sys.path.insert(0, setup_dir) + # reset to include setup dir, w/clean callback list + working_set.__init__() + working_set.callbacks.append(lambda dist: dist.activate()) + + with DirectorySandbox(setup_dir): + ns = dict(__file__=setup_script, __name__='__main__') + _execfile(setup_script, ns) + except SystemExit as v: + if v.args and v.args[0]: + raise + # Normal exit, just return + + +class AbstractSandbox: + """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts""" + + _active = False + + def __init__(self) -> None: + self._attrs = [ + name + for name in dir(_os) + if not name.startswith('_') and hasattr(self, name) + ] + + def _copy(self, source): + for name in self._attrs: + setattr(os, name, getattr(source, name)) + + def __enter__(self) -> None: + self._copy(self) + builtins.open = self._open + self._active = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ): + self._active = False + builtins.open = _open + self._copy(_os) + + def run(self, func): + """Run 'func' under os sandboxing""" + with self: + return func() + + def _mk_dual_path_wrapper(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, src, dst, *args, **kw): + if self._active: + src, dst = self._remap_pair(name, src, dst, *args, **kw) + return original(src, dst, *args, **kw) + + return wrap + + for __name in ["rename", "link", "symlink"]: + if hasattr(_os, __name): + locals()[__name] = _mk_dual_path_wrapper(__name) + + def _mk_single_path_wrapper(name: str, original=None): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = original or getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return original(path, *args, **kw) + + return wrap + + _open = _mk_single_path_wrapper('open', _open) + for __name in [ + "stat", + "listdir", + "chdir", + "open", + "chmod", + "chown", + "mkdir", + "remove", + "unlink", + "rmdir", + "utime", + "lchown", + "chroot", + "lstat", + "startfile", + "mkfifo", + "mknod", + "pathconf", + "access", + ]: + if hasattr(_os, __name): + locals()[__name] = _mk_single_path_wrapper(__name) + + def _mk_single_with_return(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, path, *args, **kw): + if self._active: + path = self._remap_input(name, path, *args, **kw) + return self._remap_output(name, original(path, *args, **kw)) + return original(path, *args, **kw) + + return wrap + + for __name in ['readlink', 'tempnam']: + if hasattr(_os, __name): + locals()[__name] = _mk_single_with_return(__name) + + def _mk_query(name: str): # type: ignore[misc] # https://github.com/pypa/setuptools/pull/4099 + original = getattr(_os, name) + + def wrap(self, *args, **kw): + retval = original(*args, **kw) + if self._active: + return self._remap_output(name, retval) + return retval + + return wrap + + for __name in ['getcwd', 'tmpnam']: + if hasattr(_os, __name): + locals()[__name] = _mk_query(__name) + + def _validate_path(self, path): + """Called to remap or validate any path, whether input or output""" + return path + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + return self._validate_path(path) + + def _remap_output(self, operation, path): + """Called for path outputs""" + return self._validate_path(path) + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + return ( + self._remap_input(operation + '-from', src, *args, **kw), + self._remap_input(operation + '-to', dst, *args, **kw), + ) + + if TYPE_CHECKING: + # This is a catch-all for all the dynamically created attributes. + # This isn't public API anyway + def __getattribute__(self, name: str) -> Any: ... + + +if hasattr(os, 'devnull'): + _EXCEPTIONS = [os.devnull] +else: + _EXCEPTIONS = [] + + +class DirectorySandbox(AbstractSandbox): + """Restrict operations to a single subdirectory - pseudo-chroot""" + + write_ops: ClassVar[dict[str, None]] = dict.fromkeys([ + "open", + "chmod", + "chown", + "mkdir", + "remove", + "unlink", + "rmdir", + "utime", + "lchown", + "chroot", + "mkfifo", + "mknod", + "tempnam", + ]) + + _exception_patterns: list[str | re.Pattern] = [] + "exempt writing to paths that match the pattern" + + def __init__(self, sandbox, exceptions=_EXCEPTIONS) -> None: + self._sandbox = os.path.normcase(os.path.realpath(sandbox)) + self._prefix = os.path.join(self._sandbox, '') + self._exceptions = [ + os.path.normcase(os.path.realpath(path)) for path in exceptions + ] + AbstractSandbox.__init__(self) + + def _violation(self, operation, *args, **kw): + from setuptools.sandbox import SandboxViolation + + raise SandboxViolation(operation, args, kw) + + def _open(self, path, mode='r', *args, **kw): + if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path): + self._violation("open", path, mode, *args, **kw) + return _open(path, mode, *args, **kw) + + def tmpnam(self) -> None: + self._violation("tmpnam") + + def _ok(self, path): + active = self._active + try: + self._active = False + realpath = os.path.normcase(os.path.realpath(path)) + return ( + self._exempted(realpath) + or realpath == self._sandbox + or realpath.startswith(self._prefix) + ) + finally: + self._active = active + + def _exempted(self, filepath): + start_matches = ( + filepath.startswith(exception) for exception in self._exceptions + ) + pattern_matches = ( + re.match(pattern, filepath) for pattern in self._exception_patterns + ) + candidates = itertools.chain(start_matches, pattern_matches) + return any(candidates) + + def _remap_input(self, operation, path, *args, **kw): + """Called for path inputs""" + if operation in self.write_ops and not self._ok(path): + self._violation(operation, os.path.realpath(path), *args, **kw) + return path + + def _remap_pair(self, operation, src, dst, *args, **kw): + """Called for path pairs like rename, link, and symlink operations""" + if not self._ok(src) or not self._ok(dst): + self._violation(operation, src, dst, *args, **kw) + return (src, dst) + + def open(self, file, flags, mode: int = 0o777, *args, **kw) -> int: + """Called for low-level os.open()""" + if flags & WRITE_FLAGS and not self._ok(file): + self._violation("os.open", file, flags, mode, *args, **kw) + return _os.open(file, flags, mode, *args, **kw) + + +WRITE_FLAGS = functools.reduce( + operator.or_, + [ + getattr(_os, a, 0) + for a in "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split() + ], +) + + +class SandboxViolation(DistutilsError): + """A setup script attempted to modify the filesystem outside the sandbox""" + + tmpl = textwrap.dedent( + """ + SandboxViolation: {cmd}{args!r} {kwargs} + + The package setup script has attempted to modify files on your system + that are not within the EasyInstall build area, and has been aborted. + + This package cannot be safely installed by EasyInstall, and may not + support alternate installation locations even if you run its setup + script by hand. Please inform the package's author and the EasyInstall + maintainers to find out if a fix or workaround is available. + """ + ).lstrip() + + def __str__(self) -> str: + cmd, args, kwargs = self.args + return self.tmpl.format(**locals()) diff --git a/shared/package-files/7c/7ccd4619121b8f3ad543b12b7e45b3e97cdf8efca6d37d013a85a540bc77ece7/c_parser.py b/shared/package-files/7c/7ccd4619121b8f3ad543b12b7e45b3e97cdf8efca6d37d013a85a540bc77ece7/c_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7223f8351205272e803773589649fcf1902f15 --- /dev/null +++ b/shared/package-files/7c/7ccd4619121b8f3ad543b12b7e45b3e97cdf8efca6d37d013a85a540bc77ece7/c_parser.py @@ -0,0 +1,1059 @@ +from sympy.external import import_module +import os + +cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) + +""" +This module contains all the necessary Classes and Function used to Parse C and +C++ code into SymPy expression +The module serves as a backend for SymPyExpression to parse C code +It is also dependent on Clang's AST and SymPy's Codegen AST. +The module only supports the features currently supported by the Clang and +codegen AST which will be updated as the development of codegen AST and this +module progresses. +You might find unexpected bugs and exceptions while using the module, feel free +to report them to the SymPy Issue Tracker + +Features Supported +================== + +- Variable Declarations (integers and reals) +- Assignment (using integer & floating literal and function calls) +- Function Definitions and Declaration +- Function Calls +- Compound statements, Return statements + +Notes +===== + +The module is dependent on an external dependency which needs to be installed +to use the features of this module. + +Clang: The C and C++ compiler which is used to extract an AST from the provided +C source code. + +References +========== + +.. [1] https://github.com/sympy/sympy/issues +.. [2] https://clang.llvm.org/docs/ +.. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html + +""" + +if cin: + from sympy.codegen.ast import (Variable, Integer, Float, + FunctionPrototype, FunctionDefinition, FunctionCall, + none, Return, Assignment, intc, int8, int16, int64, + uint8, uint16, uint32, uint64, float32, float64, float80, + aug_assign, bool_, While, CodeBlock) + from sympy.codegen.cnodes import (PreDecrement, PostDecrement, + PreIncrement, PostIncrement) + from sympy.core import Add, Mod, Mul, Pow, Rel + from sympy.logic.boolalg import And, as_Boolean, Not, Or + from sympy.core.symbol import Symbol + from sympy.core.sympify import sympify + from sympy.logic.boolalg import (false, true) + import sys + import tempfile + + class BaseParser: + """Base Class for the C parser""" + + def __init__(self): + """Initializes the Base parser creating a Clang AST index""" + self.index = cin.Index.create() + + def diagnostics(self, out): + """Diagostics function for the Clang AST""" + for diag in self.tu.diagnostics: + # tu = translation unit + print('%s %s (line %s, col %s) %s' % ( + { + 4: 'FATAL', + 3: 'ERROR', + 2: 'WARNING', + 1: 'NOTE', + 0: 'IGNORED', + }[diag.severity], + diag.location.file, + diag.location.line, + diag.location.column, + diag.spelling + ), file=out) + + class CCodeConverter(BaseParser): + """The Code Convereter for Clang AST + + The converter object takes the C source code or file as input and + converts them to SymPy Expressions. + """ + + def __init__(self): + """Initializes the code converter""" + super().__init__() + self._py_nodes = [] + self._data_types = { + "void": { + cin.TypeKind.VOID: none + }, + "bool": { + cin.TypeKind.BOOL: bool_ + }, + "int": { + cin.TypeKind.SCHAR: int8, + cin.TypeKind.SHORT: int16, + cin.TypeKind.INT: intc, + cin.TypeKind.LONG: int64, + cin.TypeKind.UCHAR: uint8, + cin.TypeKind.USHORT: uint16, + cin.TypeKind.UINT: uint32, + cin.TypeKind.ULONG: uint64 + }, + "float": { + cin.TypeKind.FLOAT: float32, + cin.TypeKind.DOUBLE: float64, + cin.TypeKind.LONGDOUBLE: float80 + } + } + + def parse(self, filename, flags): + """Function to parse a file with C source code + + It takes the filename as an attribute and creates a Clang AST + Translation Unit parsing the file. + Then the transformation function is called on the translation unit, + whose results are collected into a list which is returned by the + function. + + Parameters + ========== + + filename : string + Path to the C file to be parsed + + flags: list + Arguments to be passed to Clang while parsing the C code + + Returns + ======= + + py_nodes: list + A list of SymPy AST nodes + + """ + filepath = os.path.abspath(filename) + self.tu = self.index.parse( + filepath, + args=flags, + options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD + ) + for child in self.tu.cursor.get_children(): + if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL: + self._py_nodes.append(self.transform(child)) + return self._py_nodes + + def parse_str(self, source, flags): + """Function to parse a string with C source code + + It takes the source code as an attribute, stores it in a temporary + file and creates a Clang AST Translation Unit parsing the file. + Then the transformation function is called on the translation unit, + whose results are collected into a list which is returned by the + function. + + Parameters + ========== + + source : string + A string containing the C source code to be parsed + + flags: list + Arguments to be passed to Clang while parsing the C code + + Returns + ======= + + py_nodes: list + A list of SymPy AST nodes + + """ + file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') + file.write(source) + file.flush() + file.seek(0) + self.tu = self.index.parse( + file.name, + args=flags, + options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD + ) + file.close() + for child in self.tu.cursor.get_children(): + if child.kind == cin.CursorKind.VAR_DECL or child.kind == cin.CursorKind.FUNCTION_DECL: + self._py_nodes.append(self.transform(child)) + return self._py_nodes + + def transform(self, node): + """Transformation Function for Clang AST nodes + + It determines the kind of node and calls the respective + transformation function for that node. + + Raises + ====== + + NotImplementedError : if the transformation for the provided node + is not implemented + + """ + handler = getattr(self, 'transform_%s' % node.kind.name.lower(), None) + + if handler is None: + print( + "Ignoring node of type %s (%s)" % ( + node.kind, + ' '.join( + t.spelling for t in node.get_tokens()) + ), + file=sys.stderr + ) + + return handler(node) + + def transform_var_decl(self, node): + """Transformation Function for Variable Declaration + + Used to create nodes for variable declarations and assignments with + values or function call for the respective nodes in the clang AST + + Returns + ======= + + A variable node as Declaration, with the initial value if given + + Raises + ====== + + NotImplementedError : if called for data types not currently + implemented + + Notes + ===== + + The function currently supports following data types: + + Boolean: + bool, _Bool + + Integer: + 8-bit: signed char and unsigned char + 16-bit: short, short int, signed short, + signed short int, unsigned short, unsigned short int + 32-bit: int, signed int, unsigned int + 64-bit: long, long int, signed long, + signed long int, unsigned long, unsigned long int + + Floating point: + Single Precision: float + Double Precision: double + Extended Precision: long double + + """ + if node.type.kind in self._data_types["int"]: + type = self._data_types["int"][node.type.kind] + elif node.type.kind in self._data_types["float"]: + type = self._data_types["float"][node.type.kind] + elif node.type.kind in self._data_types["bool"]: + type = self._data_types["bool"][node.type.kind] + else: + raise NotImplementedError("Only bool, int " + "and float are supported") + try: + children = node.get_children() + child = next(children) + + #ignoring namespace and type details for the variable + while child.kind == cin.CursorKind.NAMESPACE_REF or child.kind == cin.CursorKind.TYPE_REF: + child = next(children) + + val = self.transform(child) + + supported_rhs = [ + cin.CursorKind.INTEGER_LITERAL, + cin.CursorKind.FLOATING_LITERAL, + cin.CursorKind.UNEXPOSED_EXPR, + cin.CursorKind.BINARY_OPERATOR, + cin.CursorKind.PAREN_EXPR, + cin.CursorKind.UNARY_OPERATOR, + cin.CursorKind.CXX_BOOL_LITERAL_EXPR + ] + + if child.kind in supported_rhs: + if isinstance(val, str): + value = Symbol(val) + elif isinstance(val, bool): + if node.type.kind in self._data_types["int"]: + value = Integer(0) if val == False else Integer(1) + elif node.type.kind in self._data_types["float"]: + value = Float(0.0) if val == False else Float(1.0) + elif node.type.kind in self._data_types["bool"]: + value = sympify(val) + elif isinstance(val, (Integer, int, Float, float)): + if node.type.kind in self._data_types["int"]: + value = Integer(val) + elif node.type.kind in self._data_types["float"]: + value = Float(val) + elif node.type.kind in self._data_types["bool"]: + value = sympify(bool(val)) + else: + value = val + + return Variable( + node.spelling + ).as_Declaration( + type = type, + value = value + ) + + elif child.kind == cin.CursorKind.CALL_EXPR: + return Variable( + node.spelling + ).as_Declaration( + value = val + ) + + else: + raise NotImplementedError("Given " + "variable declaration \"{}\" " + "is not possible to parse yet!" + .format(" ".join( + t.spelling for t in node.get_tokens() + ) + )) + + except StopIteration: + return Variable( + node.spelling + ).as_Declaration( + type = type + ) + + def transform_function_decl(self, node): + """Transformation Function For Function Declaration + + Used to create nodes for function declarations and definitions for + the respective nodes in the clang AST + + Returns + ======= + + function : Codegen AST node + - FunctionPrototype node if function body is not present + - FunctionDefinition node if the function body is present + + + """ + + if node.result_type.kind in self._data_types["int"]: + ret_type = self._data_types["int"][node.result_type.kind] + elif node.result_type.kind in self._data_types["float"]: + ret_type = self._data_types["float"][node.result_type.kind] + elif node.result_type.kind in self._data_types["bool"]: + ret_type = self._data_types["bool"][node.result_type.kind] + elif node.result_type.kind in self._data_types["void"]: + ret_type = self._data_types["void"][node.result_type.kind] + else: + raise NotImplementedError("Only void, bool, int " + "and float are supported") + body = [] + param = [] + + # Subsequent nodes will be the parameters for the function. + for child in node.get_children(): + decl = self.transform(child) + if child.kind == cin.CursorKind.PARM_DECL: + param.append(decl) + elif child.kind == cin.CursorKind.COMPOUND_STMT: + for val in decl: + body.append(val) + else: + body.append(decl) + + if body == []: + function = FunctionPrototype( + return_type = ret_type, + name = node.spelling, + parameters = param + ) + else: + function = FunctionDefinition( + return_type = ret_type, + name = node.spelling, + parameters = param, + body = body + ) + return function + + def transform_parm_decl(self, node): + """Transformation function for Parameter Declaration + + Used to create parameter nodes for the required functions for the + respective nodes in the clang AST + + Returns + ======= + + param : Codegen AST Node + Variable node with the value and type of the variable + + Raises + ====== + + ValueError if multiple children encountered in the parameter node + + """ + if node.type.kind in self._data_types["int"]: + type = self._data_types["int"][node.type.kind] + elif node.type.kind in self._data_types["float"]: + type = self._data_types["float"][node.type.kind] + elif node.type.kind in self._data_types["bool"]: + type = self._data_types["bool"][node.type.kind] + else: + raise NotImplementedError("Only bool, int " + "and float are supported") + try: + children = node.get_children() + child = next(children) + + # Any namespace nodes can be ignored + while child.kind in [cin.CursorKind.NAMESPACE_REF, + cin.CursorKind.TYPE_REF, + cin.CursorKind.TEMPLATE_REF]: + child = next(children) + + # If there is a child, it is the default value of the parameter. + lit = self.transform(child) + if node.type.kind in self._data_types["int"]: + val = Integer(lit) + elif node.type.kind in self._data_types["float"]: + val = Float(lit) + elif node.type.kind in self._data_types["bool"]: + val = sympify(bool(lit)) + else: + raise NotImplementedError("Only bool, int " + "and float are supported") + + param = Variable( + node.spelling + ).as_Declaration( + type = type, + value = val + ) + except StopIteration: + param = Variable( + node.spelling + ).as_Declaration( + type = type + ) + + try: + self.transform(next(children)) + raise ValueError("Can't handle multiple children on parameter") + except StopIteration: + pass + + return param + + def transform_integer_literal(self, node): + """Transformation function for integer literal + + Used to get the value and type of the given integer literal. + + Returns + ======= + + val : list + List with two arguments type and Value + type contains the type of the integer + value contains the value stored in the variable + + Notes + ===== + + Only Base Integer type supported for now + + """ + try: + value = next(node.get_tokens()).spelling + except StopIteration: + # No tokens + value = node.literal + return int(value) + + def transform_floating_literal(self, node): + """Transformation function for floating literal + + Used to get the value and type of the given floating literal. + + Returns + ======= + + val : list + List with two arguments type and Value + type contains the type of float + value contains the value stored in the variable + + Notes + ===== + + Only Base Float type supported for now + + """ + try: + value = next(node.get_tokens()).spelling + except (StopIteration, ValueError): + # No tokens + value = node.literal + return float(value) + + def transform_string_literal(self, node): + #TODO: No string type in AST + #type = + #try: + # value = next(node.get_tokens()).spelling + #except (StopIteration, ValueError): + # No tokens + # value = node.literal + #val = [type, value] + #return val + pass + + def transform_character_literal(self, node): + """Transformation function for character literal + + Used to get the value of the given character literal. + + Returns + ======= + + val : int + val contains the ascii value of the character literal + + Notes + ===== + + Only for cases where character is assigned to a integer value, + since character literal is not in SymPy AST + + """ + try: + value = next(node.get_tokens()).spelling + except (StopIteration, ValueError): + # No tokens + value = node.literal + return ord(str(value[1])) + + def transform_cxx_bool_literal_expr(self, node): + """Transformation function for boolean literal + + Used to get the value of the given boolean literal. + + Returns + ======= + + value : bool + value contains the boolean value of the variable + + """ + try: + value = next(node.get_tokens()).spelling + except (StopIteration, ValueError): + value = node.literal + return True if value == 'true' else False + + def transform_unexposed_decl(self,node): + """Transformation function for unexposed declarations""" + pass + + def transform_unexposed_expr(self, node): + """Transformation function for unexposed expression + + Unexposed expressions are used to wrap float, double literals and + expressions + + Returns + ======= + + expr : Codegen AST Node + the result from the wrapped expression + + None : NoneType + No children are found for the node + + Raises + ====== + + ValueError if the expression contains multiple children + + """ + # Ignore unexposed nodes; pass whatever is the first + # (and should be only) child unaltered. + try: + children = node.get_children() + expr = self.transform(next(children)) + except StopIteration: + return None + + try: + next(children) + raise ValueError("Unexposed expression has > 1 children.") + except StopIteration: + pass + + return expr + + def transform_decl_ref_expr(self, node): + """Returns the name of the declaration reference""" + return node.spelling + + def transform_call_expr(self, node): + """Transformation function for a call expression + + Used to create function call nodes for the function calls present + in the C code + + Returns + ======= + + FunctionCall : Codegen AST Node + FunctionCall node with parameters if any parameters are present + + """ + param = [] + children = node.get_children() + child = next(children) + + while child.kind == cin.CursorKind.NAMESPACE_REF: + child = next(children) + while child.kind == cin.CursorKind.TYPE_REF: + child = next(children) + + first_child = self.transform(child) + try: + for child in children: + arg = self.transform(child) + if child.kind == cin.CursorKind.INTEGER_LITERAL: + param.append(Integer(arg)) + elif child.kind == cin.CursorKind.FLOATING_LITERAL: + param.append(Float(arg)) + else: + param.append(arg) + return FunctionCall(first_child, param) + + except StopIteration: + return FunctionCall(first_child) + + def transform_return_stmt(self, node): + """Returns the Return Node for a return statement""" + return Return(next(node.get_children()).spelling) + + def transform_compound_stmt(self, node): + """Transformation function for compound statements + + Returns + ======= + + expr : list + list of Nodes for the expressions present in the statement + + None : NoneType + if the compound statement is empty + + """ + expr = [] + children = node.get_children() + + for child in children: + expr.append(self.transform(child)) + return expr + + def transform_decl_stmt(self, node): + """Transformation function for declaration statements + + These statements are used to wrap different kinds of declararions + like variable or function declaration + The function calls the transformer function for the child of the + given node + + Returns + ======= + + statement : Codegen AST Node + contains the node returned by the children node for the type of + declaration + + Raises + ====== + + ValueError if multiple children present + + """ + try: + children = node.get_children() + statement = self.transform(next(children)) + except StopIteration: + pass + + try: + self.transform(next(children)) + raise ValueError("Don't know how to handle multiple statements") + except StopIteration: + pass + + return statement + + def transform_paren_expr(self, node): + """Transformation function for Parenthesized expressions + + Returns the result from its children nodes + + """ + return self.transform(next(node.get_children())) + + def transform_compound_assignment_operator(self, node): + """Transformation function for handling shorthand operators + + Returns + ======= + + augmented_assignment_expression: Codegen AST node + shorthand assignment expression represented as Codegen AST + + Raises + ====== + + NotImplementedError + If the shorthand operator for bitwise operators + (~=, ^=, &=, |=, <<=, >>=) is encountered + + """ + return self.transform_binary_operator(node) + + def transform_unary_operator(self, node): + """Transformation function for handling unary operators + + Returns + ======= + + unary_expression: Codegen AST node + simplified unary expression represented as Codegen AST + + Raises + ====== + + NotImplementedError + If dereferencing operator(*), address operator(&) or + bitwise NOT operator(~) is encountered + + """ + # supported operators list + operators_list = ['+', '-', '++', '--', '!'] + tokens = list(node.get_tokens()) + + # it can be either pre increment/decrement or any other operator from the list + if tokens[0].spelling in operators_list: + child = self.transform(next(node.get_children())) + # (decl_ref) e.g.; int a = ++b; or simply ++b; + if isinstance(child, str): + if tokens[0].spelling == '+': + return Symbol(child) + if tokens[0].spelling == '-': + return Mul(Symbol(child), -1) + if tokens[0].spelling == '++': + return PreIncrement(Symbol(child)) + if tokens[0].spelling == '--': + return PreDecrement(Symbol(child)) + if tokens[0].spelling == '!': + return Not(Symbol(child)) + # e.g.; int a = -1; or int b = -(1 + 2); + else: + if tokens[0].spelling == '+': + return child + if tokens[0].spelling == '-': + return Mul(child, -1) + if tokens[0].spelling == '!': + return Not(sympify(bool(child))) + + # it can be either post increment/decrement + # since variable name is obtained in token[0].spelling + elif tokens[1].spelling in ['++', '--']: + child = self.transform(next(node.get_children())) + if tokens[1].spelling == '++': + return PostIncrement(Symbol(child)) + if tokens[1].spelling == '--': + return PostDecrement(Symbol(child)) + else: + raise NotImplementedError("Dereferencing operator, " + "Address operator and bitwise NOT operator " + "have not been implemented yet!") + + def transform_binary_operator(self, node): + """Transformation function for handling binary operators + + Returns + ======= + + binary_expression: Codegen AST node + simplified binary expression represented as Codegen AST + + Raises + ====== + + NotImplementedError + If a bitwise operator or + unary operator(which is a child of any binary + operator in Clang AST) is encountered + + """ + # get all the tokens of assignment + # and store it in the tokens list + tokens = list(node.get_tokens()) + + # supported operators list + operators_list = ['+', '-', '*', '/', '%','=', + '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', + '*=', '/=', '%='] + + # this stack will contain variable content + # and type of variable in the rhs + combined_variables_stack = [] + + # this stack will contain operators + # to be processed in the rhs + operators_stack = [] + + # iterate through every token + for token in tokens: + # token is either '(', ')' or + # any of the supported operators from the operator list + if token.kind == cin.TokenKind.PUNCTUATION: + + # push '(' to the operators stack + if token.spelling == '(': + operators_stack.append('(') + + elif token.spelling == ')': + # keep adding the expression to the + # combined variables stack unless + # '(' is found + while (operators_stack + and operators_stack[-1] != '('): + if len(combined_variables_stack) < 2: + raise NotImplementedError( + "Unary operators as a part of " + "binary operators is not " + "supported yet!") + rhs = combined_variables_stack.pop() + lhs = combined_variables_stack.pop() + operator = operators_stack.pop() + combined_variables_stack.append( + self.perform_operation( + lhs, rhs, operator)) + + # pop '(' + operators_stack.pop() + + # token is an operator (supported) + elif token.spelling in operators_list: + while (operators_stack + and self.priority_of(token.spelling) + <= self.priority_of( + operators_stack[-1])): + if len(combined_variables_stack) < 2: + raise NotImplementedError( + "Unary operators as a part of " + "binary operators is not " + "supported yet!") + rhs = combined_variables_stack.pop() + lhs = combined_variables_stack.pop() + operator = operators_stack.pop() + combined_variables_stack.append( + self.perform_operation( + lhs, rhs, operator)) + + # push current operator + operators_stack.append(token.spelling) + + # token is a bitwise operator + elif token.spelling in ['&', '|', '^', '<<', '>>']: + raise NotImplementedError( + "Bitwise operator has not been " + "implemented yet!") + + # token is a shorthand bitwise operator + elif token.spelling in ['&=', '|=', '^=', '<<=', + '>>=']: + raise NotImplementedError( + "Shorthand bitwise operator has not been " + "implemented yet!") + else: + raise NotImplementedError( + "Given token {} is not implemented yet!" + .format(token.spelling)) + + # token is an identifier(variable) + elif token.kind == cin.TokenKind.IDENTIFIER: + combined_variables_stack.append( + [token.spelling, 'identifier']) + + # token is a literal + elif token.kind == cin.TokenKind.LITERAL: + combined_variables_stack.append( + [token.spelling, 'literal']) + + # token is a keyword, either true or false + elif (token.kind == cin.TokenKind.KEYWORD + and token.spelling in ['true', 'false']): + combined_variables_stack.append( + [token.spelling, 'boolean']) + else: + raise NotImplementedError( + "Given token {} is not implemented yet!" + .format(token.spelling)) + + # process remaining operators + while operators_stack: + if len(combined_variables_stack) < 2: + raise NotImplementedError( + "Unary operators as a part of " + "binary operators is not " + "supported yet!") + rhs = combined_variables_stack.pop() + lhs = combined_variables_stack.pop() + operator = operators_stack.pop() + combined_variables_stack.append( + self.perform_operation(lhs, rhs, operator)) + + return combined_variables_stack[-1][0] + + def priority_of(self, op): + """To get the priority of given operator""" + if op in ['=', '+=', '-=', '*=', '/=', '%=']: + return 1 + if op in ['&&', '||']: + return 2 + if op in ['<', '<=', '>', '>=', '==', '!=']: + return 3 + if op in ['+', '-']: + return 4 + if op in ['*', '/', '%']: + return 5 + return 0 + + def perform_operation(self, lhs, rhs, op): + """Performs operation supported by the SymPy core + + Returns + ======= + + combined_variable: list + contains variable content and type of variable + + """ + lhs_value = self.get_expr_for_operand(lhs) + rhs_value = self.get_expr_for_operand(rhs) + if op == '+': + return [Add(lhs_value, rhs_value), 'expr'] + if op == '-': + return [Add(lhs_value, -rhs_value), 'expr'] + if op == '*': + return [Mul(lhs_value, rhs_value), 'expr'] + if op == '/': + return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] + if op == '%': + return [Mod(lhs_value, rhs_value), 'expr'] + if op in ['<', '<=', '>', '>=', '==', '!=']: + return [Rel(lhs_value, rhs_value, op), 'expr'] + if op == '&&': + return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] + if op == '||': + return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] + if op == '=': + return [Assignment(Variable(lhs_value), rhs_value), 'expr'] + if op in ['+=', '-=', '*=', '/=', '%=']: + return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr'] + + def get_expr_for_operand(self, combined_variable): + """Gives out SymPy Codegen AST node + + AST node returned is corresponding to + combined variable passed.Combined variable contains + variable content and type of variable + + """ + if combined_variable[1] == 'identifier': + return Symbol(combined_variable[0]) + if combined_variable[1] == 'literal': + if '.' in combined_variable[0]: + return Float(float(combined_variable[0])) + else: + return Integer(int(combined_variable[0])) + if combined_variable[1] == 'expr': + return combined_variable[0] + if combined_variable[1] == 'boolean': + return true if combined_variable[0] == 'true' else false + + def transform_null_stmt(self, node): + """Handles Null Statement and returns None""" + return none + + def transform_while_stmt(self, node): + """Transformation function for handling while statement + + Returns + ======= + + while statement : Codegen AST Node + contains the while statement node having condition and + statement block + + """ + children = node.get_children() + + condition = self.transform(next(children)) + statements = self.transform(next(children)) + + if isinstance(statements, list): + statement_block = CodeBlock(*statements) + else: + statement_block = CodeBlock(statements) + + return While(condition, statement_block) + + + +else: + class CCodeConverter(): # type: ignore + def __init__(self, *args, **kwargs): + raise ImportError("Module not Installed") + + +def parse_c(source): + """Function for converting a C source code + + The function reads the source code present in the given file and parses it + to give out SymPy Expressions + + Returns + ======= + + src : list + List of Python expression strings + + """ + converter = CCodeConverter() + if os.path.exists(source): + src = converter.parse(source, flags = []) + else: + src = converter.parse_str(source, flags = []) + return src diff --git a/shared/package-files/7c/7ccd49d7dcf4d00b83968cc7b74b2ba4226bfb5b965b8923fdf2dd4890db758f/exception_translation.h b/shared/package-files/7c/7ccd49d7dcf4d00b83968cc7b74b2ba4226bfb5b965b8923fdf2dd4890db758f/exception_translation.h new file mode 100644 index 0000000000000000000000000000000000000000..2764180bb078c4ed2b9648de9d6752040256d295 --- /dev/null +++ b/shared/package-files/7c/7ccd49d7dcf4d00b83968cc7b74b2ba4226bfb5b965b8923fdf2dd4890db758f/exception_translation.h @@ -0,0 +1,71 @@ +/* + pybind11/detail/exception_translation.h: means to translate C++ exceptions to Python exceptions + + Copyright (c) 2024 The Pybind Development Team. + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#pragma once + +#include "common.h" +#include "internals.h" + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) +PYBIND11_NAMESPACE_BEGIN(detail) + +// Apply all the extensions translators from a list +// Return true if one of the translators completed without raising an exception +// itself. Return of false indicates that if there are other translators +// available, they should be tried. +inline bool apply_exception_translators(std::forward_list &translators) { + auto last_exception = std::current_exception(); + + for (auto &translator : translators) { + try { + translator(last_exception); + return true; + } catch (...) { + last_exception = std::current_exception(); + } + } + return false; +} + +inline void try_translate_exceptions() { + /* When an exception is caught, give each registered exception + translator a chance to translate it to a Python exception. First + all module-local translators will be tried in reverse order of + registration. If none of the module-locale translators handle + the exception (or there are no module-locale translators) then + the global translators will be tried, also in reverse order of + registration. + + A translator may choose to do one of the following: + + - catch the exception and call py::set_error() + to set a standard (or custom) Python exception, or + - do nothing and let the exception fall through to the next translator, or + - delegate translation to the next translator by throwing a new type of exception. + */ + + bool handled = with_internals([&](internals &internals) { + auto &local_exception_translators = get_local_internals().registered_exception_translators; + if (detail::apply_exception_translators(local_exception_translators)) { + return true; + } + auto &exception_translators = internals.registered_exception_translators; + if (detail::apply_exception_translators(exception_translators)) { + return true; + } + return false; + }); + + if (!handled) { + set_error(PyExc_SystemError, "Exception escaped from default exception translator!"); + } +} + +PYBIND11_NAMESPACE_END(detail) +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/shared/package-files/7c/7cd1e2d79abb881a00eb5f0fbc430234f93121b1892a9ce18aa9960758540ab8/test_qexpr.cpython-311.pyc b/shared/package-files/7c/7cd1e2d79abb881a00eb5f0fbc430234f93121b1892a9ce18aa9960758540ab8/test_qexpr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bfd2c90a8f144cafb9c87c7cf853e267da99f1a Binary files /dev/null and b/shared/package-files/7c/7cd1e2d79abb881a00eb5f0fbc430234f93121b1892a9ce18aa9960758540ab8/test_qexpr.cpython-311.pyc differ diff --git a/shared/package-files/7c/7cd378b7e1010db61ef68688818341f1c42e21738953325c19fe29aaa3dd48d9/bcf_sr_sort.h b/shared/package-files/7c/7cd378b7e1010db61ef68688818341f1c42e21738953325c19fe29aaa3dd48d9/bcf_sr_sort.h new file mode 100644 index 0000000000000000000000000000000000000000..c8bd787a1e2c69cd74141e0b90f1f456219fcffc --- /dev/null +++ b/shared/package-files/7c/7cd378b7e1010db61ef68688818341f1c42e21738953325c19fe29aaa3dd48d9/bcf_sr_sort.h @@ -0,0 +1,108 @@ +/* + Copyright (C) 2017 Genome Research Ltd. + + Author: Petr Danecek + + 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. +*/ + +/* + Reorder duplicate lines so that compatible variant types are + returned together by bcf_sr_next_line() + + - readers grouped by variants. Even with many readers there will be + typically only several groups + +*/ + +#ifndef BCF_SR_SORT_H +#define BCF_SR_SORT_H + +#include "htslib/synced_bcf_reader.h" +#include "htslib/kbitset.h" + +typedef struct +{ + int nrec, mrec; + bcf1_t **rec; +} +vcf_buf_t; + +typedef struct +{ + char *str; // "A>C" for biallelic records or "A>C,A>CC" for multiallelic records + int type; // VCF_SNP, VCF_REF, etc. + int nalt; // number of alternate alleles in this record + int nvcf, mvcf, *vcf; // the list of readers with the same variants + bcf1_t **rec; // list of VCF records in the readers + kbitset_t *mask; // which groups contain the variant +} +var_t; + +typedef struct +{ + char *key; // only for debugging + int nvar, mvar, *var; // the variants and their type + int nvcf; // number of readers with the same variants +} +grp_t; + +typedef struct +{ + int nvar, mvar, *var; // list of compatible variants that can be output together + int cnt; // number of readers in this group + kbitset_t *mask; // which groups are populated in this set (replace with expandable bitmask) +} +varset_t; + +typedef struct +{ + uint8_t score[256]; + int nvar, mvar; + var_t *var; // list of all variants from all readers + int nvset, mvset; + int mpmat, *pmat; // pairing matrix, i-th vset and j-th group accessible as i*ngrp+j + int ngrp, mgrp; + int mcnt, *cnt; // number of VCF covered by a varset + grp_t *grp; // list of VCF representatives, each with a unique combination of duplicate lines + varset_t *vset; // list of variant sets - combinations of compatible variants across multiple groups ready for output + vcf_buf_t *vcf_buf; // records sorted in output order, for each VCF + bcf_srs_t *sr; + void *grp_str2int; + void *var_str2int; + kstring_t str; + int moff, noff, *off, mcharp; + char **charp; + const char *chr; + hts_pos_t pos; + int nsr, msr; + int pair; + int nactive, mactive, *active; // list of readers with lines at the current pos +} +sr_sort_t; + +sr_sort_t *bcf_sr_sort_init(sr_sort_t *srt); +void bcf_sr_sort_reset(sr_sort_t *srt); +int bcf_sr_sort_next(bcf_srs_t *readers, sr_sort_t *srt, const char *chr, hts_pos_t pos); +int bcf_sr_sort_set_active(sr_sort_t *srt, int i); +int bcf_sr_sort_add_active(sr_sort_t *srt, int i); +void bcf_sr_sort_destroy(sr_sort_t *srt); +void bcf_sr_sort_remove_reader(bcf_srs_t *readers, sr_sort_t *srt, int i); + +#endif diff --git a/shared/package-files/7c/7cd555bb792875f93b056f500c0bbcb68f8aec63f11b11e22e03dbd902554538/_symbolic_trace.py b/shared/package-files/7c/7cd555bb792875f93b056f500c0bbcb68f8aec63f11b11e22e03dbd902554538/_symbolic_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0f553c860d4564301f556680f5bcf6205a4e69 --- /dev/null +++ b/shared/package-files/7c/7cd555bb792875f93b056f500c0bbcb68f8aec63f11b11e22e03dbd902554538/_symbolic_trace.py @@ -0,0 +1,1320 @@ +# mypy: allow-untyped-defs +import builtins +import collections +import contextlib +import copy +import functools +import inspect +import math +import os +import warnings +from itertools import chain +from types import CodeType, FunctionType, ModuleType +from typing import Any, Callable, NamedTuple, Optional, Union + +import torch +import torch.utils._pytree as pytree +from torch._C import ScriptObject # type: ignore[attr-defined] +from torch._library.fake_class_registry import FakeScriptObject + +from ._compatibility import compatibility +from ._lazy_graph_module import _make_graph_module +from .graph import _PyTreeCodeGen, _PyTreeInfo, Graph +from .graph_module import GraphModule +from .node import Argument, base_types, map_aggregate +from .proxy import ParameterProxy, Proxy, Scope, ScopeContextManager, TracerBase + + +HAS_VARSTUFF = inspect.CO_VARARGS | inspect.CO_VARKEYWORDS + +# These need to run in global scope to handle nested calls correctly +_orig_module_call: Callable = torch.nn.Module.__call__ +_orig_module_getattr: Callable = torch.nn.Module.__getattr__ + +_proxyable_classes: dict[type, None] = {} + +_is_fx_tracing_flag = False + + +def is_fx_tracing(): + return _is_fx_tracing_flag + + +@compatibility(is_backward_compatible=True) +class ProxyableClassMeta(type): + """ + ProxyableClassMeta allows you to make construction of a given Python class + symbolically traceable. For example:: + + import torch + import torch.fx + + + class TensorPair(metaclass=torch.fx.ProxyableClassMeta): + def __init__(self, left, right): + self.left, self.right = left, right + + def add(self, other): + l = self.left + other.left + r = self.right + other.right + return TensorPair(l, r) + + def mul(self, other): + l = self.left * other.left + r = self.right * other.right + return TensorPair(l, r) + + + def use_tensor_pair_ctor(x: TensorPair, y: torch.Tensor): + s = x.add(TensorPair(y, y)) + return s.mul(x) + + + x = TensorPair(torch.randn(5, 3), torch.randn(5, 3)) + y = torch.randn(5, 3) + ref_out = use_tensor_pair_ctor(x, y) + + traced = torch.fx.symbolic_trace(use_tensor_pair_ctor) + print(traced.code) + ''' + def forward(self, x : __main___TensorPair, y : torch.Tensor): + tensor_pair = __main___TensorPair(y, y); y = None + add = x.add(tensor_pair); tensor_pair = None + mul = add.mul(x); add = x = None + return mul + ''' + + From this example, we can see that construction of a class (``TensorPair``) + defined with ``ProxyableClassMeta`` as metaclass can be recorded in symbolic + tracing. + """ + + def __init__(cls, name, bases, attrs): + _proxyable_classes.setdefault(cls) + super().__init__(name, bases, attrs) + + def __call__(cls, *args, **kwargs): + instance = cls.__new__(cls) # type: ignore[call-overload] + + if not is_fx_tracing(): + cls.__init__(instance, *args, **kwargs) # type: ignore[misc] + return instance + + found_proxies = [] + + def check_proxy(a): + if isinstance(a, Proxy): + found_proxies.append(a) + + map_aggregate(args, check_proxy) + map_aggregate(kwargs, check_proxy) + + if len(found_proxies) != 0: + tracer = found_proxies[0].tracer + return tracer.create_proxy("call_function", cls, args, kwargs) + else: + cls.__init__(instance, *args, **kwargs) # type: ignore[misc] + return instance + + +def _patch_function(fn: FunctionType, nargs: int) -> FunctionType: + co = fn.__code__ + co_flags = co.co_flags & ~HAS_VARSTUFF + co_args: tuple + if hasattr(co, "co_qualname"): + # Python-3.11+ code signature + co_args = ( + nargs, + 0, + 0, + co.co_nlocals, + co.co_stacksize, + co_flags, + co.co_code, + co.co_consts, + co.co_names, + co.co_varnames, + co.co_filename, + co.co_name, + co.co_qualname, # type: ignore[attr-defined] + co.co_firstlineno, + co.co_lnotab, + co.co_exceptiontable, # type: ignore[attr-defined] + co.co_freevars, + co.co_cellvars, + ) + elif hasattr(co, "co_posonlyargcount"): + co_args = ( + nargs, + 0, + 0, + co.co_nlocals, + co.co_stacksize, + co_flags, + co.co_code, + co.co_consts, + co.co_names, + co.co_varnames, + co.co_filename, + co.co_name, + co.co_firstlineno, + co.co_lnotab, + co.co_freevars, + co.co_cellvars, + ) + else: + co_args = ( + nargs, + 0, + co.co_nlocals, + co.co_stacksize, + co_flags, + co.co_code, + co.co_consts, + co.co_names, + co.co_varnames, + co.co_filename, + co.co_name, + co.co_firstlineno, + co.co_lnotab, + co.co_freevars, + co.co_cellvars, + ) + new_code = CodeType(*co_args) # type: ignore[arg-type] + return FunctionType( + new_code, fn.__globals__, fn.__name__, fn.__defaults__, fn.__closure__ + ) + + # we need to insert placeholder nodes for *args and **kwargs + # we can't call this function normally, otherwise it would try to unpack them + # instead, let's make python think that args and kwargs are normal variables + + +@compatibility(is_backward_compatible=False) +class PHBase: + """ + Object representing an input placeholder to `concrete_args` + """ + + def __repr__(self): + return "PH" + + +PH = PHBase() + + +@compatibility(is_backward_compatible=False) +class PHWithMeta(PHBase): + """ + Object representing an input placeholder to `concrete_args` + """ + + def __init__(self, ph_key: Optional[str] = None): + super().__init__() + + # Provide a hey for user to identify placeholder node during analysis + self.ph_key = ph_key + + +def _transfer_attrs(fr, to): + for attr_name in dir(fr): + attr_val = getattr(fr, attr_name) + if ( + not callable(attr_val) + and not attr_name.startswith("__") + and not hasattr(to, attr_name) + ): + setattr(to, attr_name, attr_val) + + +@compatibility(is_backward_compatible=True) +class Tracer(TracerBase): + # Reference: https://github.com/pytorch/pytorch/issues/54354 + # The first line of this docstring overrides the one Sphinx generates for the + # documentation. We need it so that Sphinx doesn't leak `math`s path from the + # build environment (e.g. ` None: + # This method's signature is overridden by the first line of this class' + # docstring. If this method's signature is modified, the signature that + # overrides it also should be modified accordingly. + + """ + Construct a Tracer object. + + Args: + + autowrap_modules (Tuple[ModuleType]): defaults to `(math, )`, + Python modules whose functions should be wrapped automatically + without needing to use fx.wrap(). Backward-compatibility for + this parameter is guaranteed. + + autowrap_functions (Tuple[Callable, ...]): defaults to `()`, + Python functions that should be wrapped automatically without + needing to use fx.wrap(). Backward compatibility for this + parameter is guaranteed. + + param_shapes_constant (bool): When this flag is set, calls to shape, + size and a few other shape like attributes of a module's parameter + will be evaluated directly, rather than returning a new Proxy value + for an attribute access. Backward compatibility for this parameter + is guaranteed. + """ + + super().__init__() + + # Functions we will eagerly wrap when we see them while tracing + # this captures both `math.sqrt()` and `from math import sqrt` automatically + self._autowrap_function_ids: set[int] = { + id(value) + for name, value in chain.from_iterable( + m.__dict__.items() for m in autowrap_modules + ) + if not name.startswith("_") and callable(value) + } + self._autowrap_function_ids.update({id(f) for f in autowrap_functions}) + + # Python modules to apply autowrap to at the start, in addition to + # modules we see while tracing + self._autowrap_search: list[ModuleType] = list(autowrap_modules) + self.param_shapes_constant = param_shapes_constant + + self.submodule_paths: Optional[dict[torch.nn.Module, str]] = None + self.root_module_name: str = "" + # Maps the containing module's name to the operator name + self.scope = Scope("", None) + # Records the module call stack + self.module_stack = collections.OrderedDict() + self.num_calls: dict[str, int] = {} + # Mapping of node name to module scope + self.node_name_to_scope: dict[str, tuple[str, type]] = {} + + _qualname_counter: dict[str, int] = collections.defaultdict(int) + + @compatibility(is_backward_compatible=True) + def get_fresh_qualname(self, prefix: str) -> str: + """ + Gets a fresh name for a prefix and returns it. This function ensures + that it will not clash with an existing attribute on the graph. + """ + # The idea here is that if the module doesn't have this prefix at all we + # should reset the counter to start from the beginning + # It's a ... little bit hacky (doesn't cover all cases) but the precise + # naming of the prefixes isn't a correctness issue, just a niceness + # issue + qualname = f"{prefix}0" + if not hasattr(self.root, qualname): + self._qualname_counter[prefix] = 0 + return qualname + + i = self._qualname_counter[prefix] + while True: + qualname = f"{prefix}{i}" + i += 1 + if not hasattr(self.root, qualname): + break + self._qualname_counter[prefix] = i + + return qualname + + @compatibility(is_backward_compatible=True) + def create_arg(self, a: Any) -> "Argument": + """ + A method to specify the behavior of tracing when preparing values to + be used as arguments to nodes in the ``Graph``. + + By default, the behavior includes: + + #. Iterate through collection types (e.g. tuple, list, dict) and recursively + call ``create_args`` on the elements. + #. Given a Proxy object, return a reference to the underlying IR ``Node`` + #. Given a non-Proxy Tensor object, emit IR for various cases: + + * For a Parameter, emit a ``get_attr`` node referring to that Parameter + * For a non-Parameter Tensor, store the Tensor away in a special + attribute referring to that attribute. + + This method can be overridden to support more types. + + Args: + + a (Any): The value to be emitted as an ``Argument`` in the ``Graph``. + + + Returns: + + The value ``a`` converted into the appropriate ``Argument`` + """ + # The base tracer is used to construct Graphs when there is no associated + # module hierarchy, so it can never create parameter references. + # The default tracer adds the ability to refer to parameters when + # tracing modules. + if isinstance(a, torch.nn.Parameter): + for n, p in self.root.named_parameters(): + if a is p: + return self.create_node("get_attr", n, (), {}) + raise NameError("parameter is not a member of this module") + elif isinstance(a, torch.Tensor): + for n_, p_ in self.root.named_buffers(): + if a is p_: + return self.create_node("get_attr", n_, (), {}) + elif isinstance(a, torch.nn.Module): + for n_, p_ in self.root.named_modules(): + if a is p_: + return self.create_node("get_attr", n_, (), {}) + # For NamedTuple instances that appear literally as args, we emit + # a node to construct the NamedTuple and use that Node as the argument. + if isinstance(a, tuple) and hasattr(a, "_fields"): + args = tuple(self.create_arg(elem) for elem in a) + return self.create_node("call_function", a.__class__, args, {}) + + # Tensors do not have a reliable string repr() from which they can be + # constructed (and we probably don't want to rely on that, either), so + # for any constant Tensor values we encounter, first search for if they + # are an attribute of some module in the module hierarchy. If so, emit + # a get_attr to retrieve that tensor. Otherwise, we'll store away the + # tensor value into a special attribute on the Module s.t. we can + # retrieve it with a get_attr. + if isinstance(a, (torch.Tensor, ScriptObject, FakeScriptObject)): + qualname: Optional[str] = self.tensor_attrs.get(a) + + # Tensor was not found in the Module hierarchy, stow it away in a + # special attribute and set the qualname to refer to that + if not qualname: + base_name = ( + "_tensor_constant" + if isinstance(a, torch.Tensor) + else "_torchbind_obj" + ) + qualname = self.get_fresh_qualname(base_name) + assert isinstance(qualname, str) + self.tensor_attrs[a] = qualname + setattr(self.root, qualname, a) + + return self.create_node("get_attr", qualname, (), {}) + + if type(a) in _proxyable_classes: + # This is an instance of a proxyable class for which we did not + # witness its construction. Intern this as a constant attribute + + # TODO: binary search + qualname = self.get_fresh_qualname(f"_{a.__class__.__name__}_constant_") + assert isinstance(qualname, str) + setattr(self.root, qualname, a) + + return self.create_node("get_attr", qualname, (), {}) + + return super().create_arg(a) + + @compatibility(is_backward_compatible=True) + def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool: + """ + A method to specify whether a given ``nn.Module`` is a "leaf" module. + + Leaf modules are the atomic units that appear in + the IR, referenced by ``call_module`` calls. By default, + Modules in the PyTorch standard library namespace (torch.nn) + are leaf modules. All other modules are traced through and + their constituent ops are recorded, unless specified otherwise + via this parameter. + + Args: + + m (Module): The module being queried about + module_qualified_name (str): The path to root of this module. For example, + if you have a module hierarchy where submodule ``foo`` contains + submodule ``bar``, which contains submodule ``baz``, that module will + appear with the qualified name ``foo.bar.baz`` here. + """ + return ( + m.__module__.startswith("torch.nn") + or m.__module__.startswith("torch.ao.nn") + ) and not isinstance(m, torch.nn.Sequential) + + @compatibility(is_backward_compatible=True) + def path_of_module(self, mod: torch.nn.Module) -> str: + """ + Helper method to find the qualified name of ``mod`` in the Module hierarchy + of ``root``. For example, if ``root`` has a submodule named ``foo``, which has + a submodule named ``bar``, passing ``bar`` into this function will return + the string "foo.bar". + + Args: + + mod (str): The ``Module`` to retrieve the qualified name for. + """ + # Prefer the O(1) algorithm + if self.submodule_paths: + path = self.submodule_paths.get(mod) + if path is None: + raise NameError("module is not installed as a submodule") + assert isinstance(path, str) + return path + # O(N^2) fallback in the case that we didn't store the submodule + # paths. + else: + for n, p in self.root.named_modules(): + if mod is p: + return n + raise NameError("module is not installed as a submodule") + + @compatibility(is_backward_compatible=True) + def call_module( + self, + m: torch.nn.Module, + forward: Callable[..., Any], + args: tuple[Any, ...], + kwargs: dict[str, Any], + ) -> Any: + """ + Method that specifies the behavior of this ``Tracer`` when it encounters + a call to an ``nn.Module`` instance. + + By default, the behavior is to check if the called module is a leaf module + via ``is_leaf_module``. If it is, emit a ``call_module`` node referring to + ``m`` in the ``Graph``. Otherwise, call the ``Module`` normally, tracing through + the operations in its ``forward`` function. + + This method can be overridden to--for example--create nested traced + GraphModules, or any other behavior you would want while tracing across + ``Module`` boundaries. + + Args: + + m (Module): The module for which a call is being emitted + forward (Callable): The forward() method of the ``Module`` to be invoked + args (Tuple): args of the module callsite + kwargs (Dict): kwargs of the module callsite + + Return: + + The return value from the Module call. In the case that a ``call_module`` + node was emitted, this is a ``Proxy`` value. Otherwise, it is whatever + value was returned from the ``Module`` invocation. + """ + module_qualified_name = self.path_of_module(m) + with ScopeContextManager( + self.scope, Scope(module_qualified_name, type(m)) + ) as _scope: + # module_stack is an ordered dict so writing then deleting the + # entry is equivalent to push/pop on a list + num_calls = self.num_calls.get(module_qualified_name, 0) + module_key = ( + f"{_scope.module_path}@{num_calls}" + if num_calls > 0 + else _scope.module_path + ) + self.module_stack[module_key] = (module_qualified_name, _scope.module_type) + self.num_calls[module_qualified_name] = num_calls + 1 + if not self.is_leaf_module(m, module_qualified_name): + ret_val = forward(*args, **kwargs) + else: + ret_val = self.create_proxy( + "call_module", module_qualified_name, args, kwargs + ) + key, _ = self.module_stack.popitem(last=True) + assert key == module_key, f" Unexpected key {key}" + + return ret_val + + @compatibility(is_backward_compatible=False) + def getattr(self, attr: str, attr_val: Any, parameter_proxy_cache: dict[str, Any]): + """ + Method that specifies the behavior of this ``Tracer`` when we call getattr + on a call to an ``nn.Module`` instance. + + By default, the behavior is to return a proxy value for the attribute. It + also stores the proxy value in the ``parameter_proxy_cache``, so that future + calls will reuse the proxy rather than creating a new one. + + This method can be overridden to --for example-- not return proxies when + querying parameters. + + Args: + + attr (str): The name of the attribute being queried + attr_val (Any): The value of the attribute + parameter_proxy_cache (Dict[str, Any]): A cache of attr names to proxies + + Return: + + The return value from the getattr call. + """ + + def maybe_get_proxy_for_attr( + attr_val, collection_to_search, parameter_proxy_cache + ): + for n, p in collection_to_search: + if attr_val is p: + if n not in parameter_proxy_cache: + kwargs = {} + if ( + "proxy_factory_fn" + in inspect.signature(self.create_proxy).parameters + ): + kwargs["proxy_factory_fn"] = ( + None + if not self.param_shapes_constant + else lambda node: ParameterProxy( + self, node, n, attr_val + ) + ) + val_proxy = self.create_proxy("get_attr", n, (), {}, **kwargs) # type: ignore[arg-type] + parameter_proxy_cache[n] = val_proxy + return parameter_proxy_cache[n] + return None + + if isinstance(attr_val, torch.nn.Parameter): + maybe_parameter_proxy = maybe_get_proxy_for_attr( + attr_val, self.root.named_parameters(), parameter_proxy_cache + ) + if maybe_parameter_proxy is not None: + return maybe_parameter_proxy + + if self.proxy_buffer_attributes and isinstance(attr_val, torch.Tensor): + maybe_buffer_proxy = maybe_get_proxy_for_attr( + attr_val, self.root.named_buffers(), parameter_proxy_cache + ) + if maybe_buffer_proxy is not None: + return maybe_buffer_proxy + + return attr_val + + # This method will be refactored + @compatibility(is_backward_compatible=False) + def create_args_for_root(self, root_fn, is_module, concrete_args=None): + """ + Create ``placeholder`` nodes corresponding to the signature of the ``root`` + Module. This method introspects root's signature and emits those + nodes accordingly, also supporting ``*args`` and ``**kwargs``. + """ + # In some cases, a function or method has been decorated with a wrapper + # defined via ``functools.wraps``. In this case, the outer code object + # will likely not contain the actual parameters we care about, so unwrap + # the function to get to the innermost callable. + fn_for_analysis = inspect.unwrap(root_fn) + co = fn_for_analysis.__code__ + total_args = co.co_argcount + co.co_kwonlyargcount + orig_args = list(co.co_varnames) + names_iter = iter(co.co_varnames) + args: list[Any] = [] + skip_arg_idx = 0 + if is_module: + if total_args == 0: + raise RuntimeError( + "``self`` argument cannot be part of *args expansion!" + ) + skip_arg_idx = 1 + next(names_iter) # skip self + args.append(self.root) + + sig = inspect.signature(fn_for_analysis) + + # This covers the very specific case where we are passing in flat + # concrete_args as a tuple, but our traced fn takes (*args, **kwargs). + # In this case, just take the concrete_args and pass them through. + name_idx = 0 + if ( + isinstance(concrete_args, tuple) + and len(concrete_args) > 0 + and (co.co_flags & HAS_VARSTUFF) + and total_args == 1 + ): + for concrete_arg in concrete_args: + out = self.create_proxy("placeholder", f"input_{name_idx}", (), {}) + if isinstance(concrete_arg, PHBase): + if concrete_arg != PH: + # Transfer attrs in the case where you're using a placeholder other + # than the singleton PH (PH has no attributes to transfer). + # Proxies were created out of the placeholders. + # Transfer any metadata (put on the placeholders in the form of + # attributes set by the user) from the placeholder to the + # underlying nodes (the proxy is unwrapped by the user, but + # the metadata should hold). + _transfer_attrs(fr=concrete_arg, to=out.node) + args.append(out) + name_idx += 1 + return root_fn, args + + arg_names = [next(names_iter) for idx in range(skip_arg_idx, total_args)] + if isinstance(concrete_args, tuple): + if len(arg_names) != len(concrete_args): + raise RuntimeError( + f"Tracing expected {len(arg_names)} arguments but got {len(concrete_args)} concrete arguments" + ) + concrete_args = dict(zip(arg_names, concrete_args)) + + def proxy_placeholder(name): + return self._proxy_placeholder(name, concrete_args, sig, fn_for_analysis) + + args.extend(proxy_placeholder(names) for names in arg_names) + + if co.co_kwonlyargcount > 0 or co.co_flags & HAS_VARSTUFF: + # TODO: type annotations for *args and **kwargs + if co.co_flags & inspect.CO_VARARGS: + args.append(proxy_placeholder("*" + next(names_iter))) + if co.co_flags & inspect.CO_VARKEYWORDS: + args.append(proxy_placeholder("**" + next(names_iter))) + root_fn = _patch_function(root_fn, len(args)) + + flat_args, in_spec = pytree.tree_flatten(tuple(args)) + if not all(child.is_leaf() for child in in_spec.children_specs): + # In the case that we have pytree-flattened inputs in + # `concrete_args`, generate a flattening wrapper around the + # original root function and return that. + self.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo(orig_args[:total_args], in_spec, None) + ) + + def flatten_fn(*args): + tree_args = pytree.tree_unflatten(list(args), in_spec) + tree_out = root_fn(*tree_args) + out_args, out_spec = pytree.tree_flatten(tree_out) + assert isinstance(self.graph._codegen, _PyTreeCodeGen) + self.graph._codegen.pytree_info = ( + self.graph._codegen.pytree_info._replace(out_spec=out_spec) + ) + return out_args + + return flatten_fn, flat_args + return root_fn, args + + @compatibility(is_backward_compatible=True) + def trace( + self, + root: Union[torch.nn.Module, Callable[..., Any]], + concrete_args: Optional[dict[str, Any]] = None, + ) -> Graph: + """ + Trace ``root`` and return the corresponding FX ``Graph`` representation. ``root`` + can either be an ``nn.Module`` instance or a Python callable. + + Note that after this call, ``self.root`` may be different from the ``root`` passed + in here. For example, when a free function is passed to ``trace()``, we will + create an ``nn.Module`` instance to use as the root and add embedded constants + to. + + + Args: + + root (Union[Module, Callable]): Either a ``Module`` or a function to be + traced through. Backwards-compatibility for this parameter is + guaranteed. + concrete_args (Optional[Dict[str, any]]): Concrete arguments that should + not be treated as Proxies. This parameter is experimental and + its backwards-compatibility is *NOT* guaranteed. + + Returns: + + A ``Graph`` representing the semantics of the passed-in ``root``. + """ + global _is_fx_tracing_flag + old_is_fx_tracing_flag = _is_fx_tracing_flag + _is_fx_tracing_flag = True + try: + if isinstance(root, torch.nn.Module): + # do real recompilation for _LazyGraphModule before retracing since the trace + # method can not trace the _lazy_forward method. Got error: + # https://gist.github.com/shunting314/75549c2e82ae07ac1139c94a3583d259 + # without this. + from torch.fx._lazy_graph_module import _LazyGraphModule + + _LazyGraphModule.force_recompile(root) + + self.root = root + + assert hasattr( + type(root), self.traced_func_name + ), f"traced_func_name={self.traced_func_name} doesn't exist in {type(root).__name__}" + + fn = getattr(type(root), self.traced_func_name) + self.root_module_name = root._get_name() + self.submodule_paths = {mod: name for name, mod in root.named_modules()} + else: + self.root = torch.nn.Module() + fn = root + + tracer_cls: Optional[type[Tracer]] = getattr(self, "__class__", None) + self.graph = Graph(tracer_cls=tracer_cls) + if hasattr(fn, "__code__"): + code = fn.__code__ + self.graph._co_fields = { + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + } + + # When we encounter a Tensor value that's not a parameter, we look if it + # is some other attribute on the model. Construct a dict mapping Tensor + # values to the qualified name here for efficiency. This is used downstream + # in create_arg + self.tensor_attrs: dict[ + Union[torch.Tensor, ScriptObject, FakeScriptObject], str + ] = {} + + def collect_tensor_attrs(m: torch.nn.Module, prefix_atoms: list[str]): + for k, v in m.__dict__.items(): + if isinstance(v, (torch.Tensor, ScriptObject, FakeScriptObject)): + self.tensor_attrs[v] = ".".join(prefix_atoms + [k]) + for k, v in m.named_children(): + collect_tensor_attrs(v, prefix_atoms + [k]) + + collect_tensor_attrs(self.root, []) + + assert isinstance(fn, FunctionType) + + fn_globals = fn.__globals__ # run before it gets patched + fn, args = self.create_args_for_root( + fn, isinstance(root, torch.nn.Module), concrete_args + ) + + parameter_proxy_cache: dict[ + str, Proxy + ] = {} # Reduce number of get_attr calls + + # Method dispatch on parameters is not recorded unless it's directly used. + # Thus, we need to insert a proxy when __getattr__ requests a parameter. + @functools.wraps(_orig_module_getattr) + def module_getattr_wrapper(mod, attr): + attr_val = _orig_module_getattr(mod, attr) + return self.getattr(attr, attr_val, parameter_proxy_cache) + + @functools.wraps(_orig_module_call) + def module_call_wrapper(mod, *args, **kwargs): + def forward(*args, **kwargs): + return _orig_module_call(mod, *args, **kwargs) + + _autowrap_check( + patcher, # type: ignore[has-type] + getattr(getattr(mod, "forward", mod), "__globals__", {}), + self._autowrap_function_ids, + ) + return self.call_module(mod, forward, args, kwargs) + + with _new_patcher() as patcher: + # allow duplicate patches to support the case of nested calls + patcher.patch_method( + torch.nn.Module, + "__getattr__", + module_getattr_wrapper, + deduplicate=False, + ) + patcher.patch_method( + torch.nn.Module, + "__call__", + module_call_wrapper, + deduplicate=False, + ) + _patch_wrapped_functions(patcher) + _autowrap_check(patcher, fn_globals, self._autowrap_function_ids) + for module in self._autowrap_search: + _autowrap_check( + patcher, module.__dict__, self._autowrap_function_ids + ) + self.create_node( + "output", + "output", + (self.create_arg(fn(*args)),), + {}, + type_expr=fn.__annotations__.get("return", None), + ) + + self.submodule_paths = None + except RuntimeError as e: + if isinstance(e.args[0], str) and "data-dependent" in e.args[0]: + partial_fx_graph = self.graph.python_code( + root_module="self", + verbose=True, + ).src + e.partial_fx_graph = partial_fx_graph # type: ignore[attr-defined] + raise + + raise + finally: + _is_fx_tracing_flag = old_is_fx_tracing_flag + return self.graph + + def __deepcopy__(self, memo): + # _autowrap_search contains modules, which cannot be deepcopied. + new_tracer = Tracer.__new__(Tracer) + + for k, v in self.__dict__.items(): + if k in {"_autowrap_search"}: + new_obj = copy.copy(v) + else: + new_obj = copy.deepcopy(v, memo) + + new_tracer.__dict__[k] = new_obj + + return new_tracer + + def _proxy_placeholder(self, name, concrete_args, sig, fn_for_analysis): + if concrete_args is not None and name in concrete_args: + cnt = 0 + + def replace_ph(x): + nonlocal cnt + cnt += 1 + param = sig.parameters[name] + default: tuple[Any, ...] = ( + () if param.default is inspect.Parameter.empty else (param.default,) + ) + out = self.create_proxy( + "placeholder", f"{name}_{str(cnt)}", default, {} + ) + if isinstance(x, PHBase): + if x != PH: + # Transfer attrs in the case where you're using a placeholder other + # than the singleton PH (PH has no attributes to transfer). + # Proxies were created out of the placeholders. + # Transfer any metadata (put on the placeholders in the form of + # attributes set by the user) from the placeholder to the + # underlying nodes (the proxy is unwrapped by the user, but + # the metadata should hold). + _transfer_attrs(fr=x, to=out.node) + + return out + # Union[int, bool] == bool in Python <= 3.6 + if type(x) == bool or type(x) in base_types and type(x) != torch.Tensor: + torch._assert( + out == x, + f"{name} has been specialized to have value {x} but got another value", + ) + elif x is None: + args = ( + out, + f"{name} has been specialized to have value None but got another value", + ) + self.create_proxy("call_function", _assert_is_none, args, {}) + else: + warnings.warn( + f"Was not able to add assertion to guarantee correct input {name} to " + f"specialized function. It is up to the user to make sure that your inputs match the " + f"inputs you specialized the function with." + ) + + return x + + return pytree.tree_map(replace_ph, concrete_args[name]) + if name[0] == "*": + default: tuple[Any, ...] = () + else: + param = sig.parameters[name] + default = ( # type: ignore[assignment] + () if param.default is inspect.Parameter.empty else (param.default,) + ) + return self.create_proxy( + "placeholder", + name, + default, + {}, + type_expr=fn_for_analysis.__annotations__.get(name, None), + ) + + +# Dictionary of (id(globals dict), function name) => globals_dict to patch for +# the purposes of the wrap() API. +# We key by the globals dict id and function name to ensure we're wrapping a given +# function only once. +_wrapped_fns_to_patch: dict[tuple[int, str], dict] = {} + +# List of methods on classes to wrap (class type, function name) +# this currently only works for Tensor.* methods that aren't traced properly +_wrapped_methods_to_patch: list[tuple[type, str]] = [] + +if os.environ.get("FX_PATCH_GETITEM") == "1": + # This change is needed to trace models like PositionalEmbedding from BERT: + # https://github.com/pytorch/benchmark/blob/master/torchbenchmark/models/BERT_pytorch/bert_pytorch/model/embedding/position.py + # but causes issues in quantization documented here: + # https://github.com/pytorch/pytorch/issues/50710 + # once that is fixed we can make this the default behavior. + _wrapped_methods_to_patch.append((torch.Tensor, "__getitem__")) + + +def _find_proxy(*objects_to_search): + """ + Recursively search a data structure for a Proxy() and return it, + return None if not found. + """ + proxy = None + + def find_proxy(x): + nonlocal proxy + if isinstance(x, Proxy): + proxy = x + + map_aggregate(objects_to_search, find_proxy) + return proxy + + +def _create_wrapped_func(orig_fn): + @functools.wraps(orig_fn) + def wrapped(*args, **kwargs): + """ + Given an closed-over ``orig_function`` to invoke, search the args and kwargs for + a Proxy object. If there is one, emit a ``call_function`` node to preserve the + call to this leaf function directly. Otherwise, just return the results of + this function call, as this function is not being traced. + """ + proxy = _find_proxy(args, kwargs) + if proxy is not None: + return_proxy = proxy.tracer.create_proxy( + "call_function", orig_fn, args, kwargs + ) + return_proxy.node.meta["is_wrapped"] = True + return return_proxy + return orig_fn(*args, **kwargs) + + return wrapped + + +def _create_wrapped_method(cls, name): + orig_fn = getattr(cls, name) + + @functools.wraps(orig_fn) + def wrapped(*args, **kwargs): + """ + Search the args and kwargs for a Proxy object. If there is one, + emit a ``call_method`` node to preserve the call to this method + directly. Otherwise, just return the results of this function + call, as this function is not being traced. + """ + proxy = _find_proxy(args, kwargs) + if proxy is not None: + return proxy.tracer.create_proxy("call_method", name, args, kwargs) + return orig_fn(*args, **kwargs) + + return wrapped + + +class _PatchedFn(NamedTuple): + frame_dict: Any + fn_name: str + orig_fn: Any + new_fn: Any + + def revert(self): + raise NotImplementedError + + def patch(self): + raise NotImplementedError + + +class _PatchedFnSetItem(_PatchedFn): + def revert(self): + self.frame_dict[self.fn_name] = self.orig_fn + + def patch(self): + self.frame_dict[self.fn_name] = self.new_fn + + +class _PatchedFnDel(_PatchedFn): + def revert(self): + del self.frame_dict[self.fn_name] + + def patch(self): + self.frame_dict[self.fn_name] = self.new_fn + + +class _PatchedFnSetAttr(_PatchedFn): + def revert(self): + setattr(self.frame_dict, self.fn_name, self.orig_fn) + + def patch(self): + setattr(self.frame_dict, self.fn_name, self.new_fn) + + +class _Patcher: + def __init__(self) -> None: + super().__init__() + self.patches_made: list[_PatchedFn] = [] + self.visited: set[int] = set() + + def patch( + self, + frame_dict: dict[str, Any], + name: str, + new_fn: Callable, + deduplicate: bool = True, + ): + """ + Replace frame_dict[name] with new_fn until we exit the context manager. + """ + new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined] + if name not in frame_dict and hasattr(builtins, name): + self.patches_made.append(_PatchedFnDel(frame_dict, name, None, new_fn)) + self.patches_made[-1].patch() + elif getattr(frame_dict[name], "__fx_already_patched", False): + return # already patched, no need to do it again + else: + self.patches_made.append( + _PatchedFnSetItem(frame_dict, name, frame_dict[name], new_fn) + ) + self.patches_made[-1].patch() + + def patch_method( + self, cls: type, name: str, new_fn: Callable, deduplicate: bool = True + ): + """ + Replace object_or_dict.name with new_fn until we exit the context manager. + """ + new_fn.__fx_already_patched = deduplicate # type: ignore[attr-defined] + orig_fn = getattr(cls, name) + if getattr(orig_fn, "__fx_already_patched", False): + return # already patched, no need to do it again + self.patches_made.append(_PatchedFnSetAttr(cls, name, orig_fn, new_fn)) + self.patches_made[-1].patch() + + def visit_once(self, thing: Any): + """Return True on the first call to with thing, otherwise false""" + idx = id(thing) + if idx in self.visited: + return False + self.visited.add(idx) + return True + + def revert_all_patches(self): + """ + Remove all the stored patcheds. It doesn't modify patches_made. + """ + for patch in self.patches_made: + patch.revert() + return self.patches_made + + def reapply_all_patches(self): + """ + Patch all the stored patcheds. It doesn't modify patches_made. + """ + for patch in self.patches_made: + patch.patch() + return self.patches_made + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + Undo all the changes made via self.patch() and self.patch_method() + """ + while self.patches_made: + # unpatch in reverse order to handle duplicates correctly + self.patches_made.pop().revert() + self.visited.clear() + + +CURRENT_PATCHER: Optional[_Patcher] = None + + +@contextlib.contextmanager +def _new_patcher(): + global CURRENT_PATCHER + prior_patcher = CURRENT_PATCHER + try: + CURRENT_PATCHER = _Patcher() + yield CURRENT_PATCHER + finally: + # Clear all the patches made by when using current patcher. + assert CURRENT_PATCHER is not None + CURRENT_PATCHER.revert_all_patches() + CURRENT_PATCHER = prior_patcher + + +@contextlib.contextmanager +def _maybe_revert_all_patches(): + current_patcher = CURRENT_PATCHER + patches_made = None + patches_removed = None + try: + if current_patcher is not None: + patches_removed = current_patcher.revert_all_patches() + yield + finally: + if current_patcher is not None: + patches_made = current_patcher.reapply_all_patches() + assert ( + patches_made == patches_removed + ), "CURRENT_PATCHER was changed during a revert_all_patches" + + +def _patch_wrapped_functions(patcher: _Patcher): + """ + Go through ``_wrapped_fn_patch_table`` and, for each frame object, wrap + the listed global functions in the `_create_wrapped_func` wrapper. + """ + for (_, name), frame_dict in _wrapped_fns_to_patch.copy().items(): + if name not in frame_dict and hasattr(builtins, name): + orig_fn = getattr(builtins, name) + else: + orig_fn = frame_dict[name] + patcher.patch(frame_dict, name, _create_wrapped_func(orig_fn)) + + for cls, name in _wrapped_methods_to_patch: + patcher.patch_method(cls, name, _create_wrapped_method(cls, name)) + + +def _autowrap_check( + patcher: _Patcher, frame_dict: dict[str, Any], function_ids: set[int] +): + """ + Some methods, like `math.sqrt` are common enough we want to automatically wrap them as we see them. + This method searches a scope for them and patches them if found. + """ + if patcher.visit_once(frame_dict): + for name, value in frame_dict.items(): + if ( + not name.startswith("_") + and callable(value) + and id(value) in function_ids + ): + patcher.patch(frame_dict, name, _create_wrapped_func(value)) + + +@compatibility(is_backward_compatible=True) +def wrap(fn_or_name: Union[str, Callable]): + """ + This function can be called at module-level scope to register fn_or_name as a "leaf function". + A "leaf function" will be preserved as a CallFunction node in the FX trace instead of being + traced through:: + + # foo/bar/baz.py + def my_custom_function(x, y): + return x * x + y * y + + + torch.fx.wrap("my_custom_function") + + + def fn_to_be_traced(x, y): + # When symbolic tracing, the below call to my_custom_function will be inserted into + # the graph rather than tracing it. + return my_custom_function(x, y) + + This function can also equivalently be used as a decorator:: + + # foo/bar/baz.py + @torch.fx.wrap + def my_custom_function(x, y): + return x * x + y * y + + A wrapped function can be thought of a "leaf function", analogous to the concept of + "leaf modules", that is, they are functions that are left as calls in the FX trace + rather than traced through. + + Args: + + fn_or_name (Union[str, Callable]): The function or name of the global function to insert into the + graph when it's called + """ + if not callable(fn_or_name) and not isinstance(fn_or_name, str): + raise RuntimeError( + "Unsupported type for global function! Must be either a callable or " + "string name" + ) + + if callable(fn_or_name): + assert not isinstance(fn_or_name, str) # to make mypy happy + fn_name = fn_or_name.__name__ + else: + assert isinstance( + fn_or_name, str + ), "fn_or_name must be a global function or string name" + fn_name = fn_or_name + + currentframe = inspect.currentframe() + assert currentframe is not None + f = currentframe.f_back + assert f is not None + if f.f_code.co_name != "": + raise NotImplementedError("wrap must be called at the top level of a module") + + # consider implementing Callable version of this via _autowrap_function_ids / _autowrap_search + # semantics would be slightly different, but would add support `from x import wrapped_function` + _wrapped_fns_to_patch[(id(f.f_globals), fn_name)] = f.f_globals + return fn_or_name + + +@compatibility(is_backward_compatible=True) +def symbolic_trace( + root: Union[torch.nn.Module, Callable[..., Any]], + concrete_args: Optional[dict[str, Any]] = None, +) -> GraphModule: + """ + Symbolic tracing API + + Given an ``nn.Module`` or function instance ``root``, this function will return a ``GraphModule`` + constructed by recording operations seen while tracing through ``root``. + + ``concrete_args`` allows you to partially specialize your function, whether it's to remove control flow or data structures. + + For example:: + + def f(a, b): + if b == True: + return a + else: + return a * 2 + + FX can typically not trace through this due to the presence of control + flow. However, we can use `concrete_args` to specialize on the value of + `b` to trace through this:: + + f = fx.symbolic_trace(f, concrete_args={"b": False}) + assert f(3, False) == 6 + + Note that although you can still pass in different values of `b`, they will be ignored. + + We can also use `concrete_args` to eliminate data-structure handling from + our function. This will use pytrees to flatten your input. To avoid + overspecializing, pass in `fx.PH` for values that shouldn't be + specialized. For example:: + + def f(x): + out = 0 + for v in x.values(): + out += v + return out + + + f = fx.symbolic_trace(f, concrete_args={"x": {"a": fx.PH, "b": fx.PH, "c": fx.PH}}) + assert f({"a": 1, "b": 2, "c": 4}) == 7 + + + Args: + root (Union[torch.nn.Module, Callable]): Module or function to be traced and converted + into a Graph representation. + concrete_args (Optional[Dict[str, any]]): Inputs to be partially specialized + + Returns: + GraphModule: a Module created from the recorded operations from ``root``. + """ + tracer = Tracer() + graph = tracer.trace(root, concrete_args) + name = ( + root.__class__.__name__ if isinstance(root, torch.nn.Module) else root.__name__ + ) + return _make_graph_module(tracer.root, graph, name) + + +@wrap +def _assert_is_none(value, msg): + assert value is None, msg diff --git a/shared/package-files/7c/7cdcd8bad25e4f68cc76368a9aa03d24d52a9599020ddde3b914935350ff2963/build_py.cpython-311.pyc b/shared/package-files/7c/7cdcd8bad25e4f68cc76368a9aa03d24d52a9599020ddde3b914935350ff2963/build_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aca04c6990c3e1414de3c7c45ee9acb464edf4f8 Binary files /dev/null and b/shared/package-files/7c/7cdcd8bad25e4f68cc76368a9aa03d24d52a9599020ddde3b914935350ff2963/build_py.cpython-311.pyc differ diff --git a/shared/package-files/7c/7ce2c32b2e01833d48f6bf1b9c1ddfa6dad84e1e2318939930b3ffa1343e408a/batch_norm_backward_elemt.h b/shared/package-files/7c/7ce2c32b2e01833d48f6bf1b9c1ddfa6dad84e1e2318939930b3ffa1343e408a/batch_norm_backward_elemt.h new file mode 100644 index 0000000000000000000000000000000000000000..20834d66632cdc192a9eaf76cd32cc216c839dfb --- /dev/null +++ b/shared/package-files/7c/7ce2c32b2e01833d48f6bf1b9c1ddfa6dad84e1e2318939930b3ffa1343e408a/batch_norm_backward_elemt.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count) -> Tensor +inline at::Tensor batch_norm_backward_elemt(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional & weight, const at::Tensor & sum_dy, const at::Tensor & sum_dy_xmu, const at::Tensor & count) { + return at::_ops::batch_norm_backward_elemt::call(grad_out, input, mean, invstd, weight, sum_dy, sum_dy_xmu, count); +} + +// aten::batch_norm_backward_elemt.out(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & batch_norm_backward_elemt_out(at::Tensor & out, const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional & weight, const at::Tensor & sum_dy, const at::Tensor & sum_dy_xmu, const at::Tensor & count) { + return at::_ops::batch_norm_backward_elemt_out::call(grad_out, input, mean, invstd, weight, sum_dy, sum_dy_xmu, count, out); +} +// aten::batch_norm_backward_elemt.out(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & batch_norm_backward_elemt_outf(const at::Tensor & grad_out, const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional & weight, const at::Tensor & sum_dy, const at::Tensor & sum_dy_xmu, const at::Tensor & count, at::Tensor & out) { + return at::_ops::batch_norm_backward_elemt_out::call(grad_out, input, mean, invstd, weight, sum_dy, sum_dy_xmu, count, out); +} + +} diff --git a/shared/package-files/7c/7ce63fb8908c64d678564fcb8c359da86e69933ea5545c7893a7a92a6d346d2f/container.h b/shared/package-files/7c/7ce63fb8908c64d678564fcb8c359da86e69933ea5545c7893a7a92a6d346d2f/container.h new file mode 100644 index 0000000000000000000000000000000000000000..03e84ca5b76d06703191bdb292daa747f0559052 --- /dev/null +++ b/shared/package-files/7c/7ce63fb8908c64d678564fcb8c359da86e69933ea5545c7893a7a92a6d346d2f/container.h @@ -0,0 +1,162 @@ +#pragma once + +#include +#include + +#include + +namespace torch::distributed::autograd { + +// Singleton class per worker which is responsible for storing the distributed +// autograd context for each autograd pass and also cleans up data for an +// autograd pass once its done. +// +// Each autograd pass is assigned a unique autograd_context_id and all data for +// that pass (DistAutogradContext) is stored in this container indexed by the +// autograd_context_id. The autograd_context_id itself is a 64 bit globally +// unique id. The first 16 bits is the worker_id and the next 48 bits is an +// auto-incrementing id for each worker. +// +// This container is also responsible for maintaining a globally unique message +// id, which is used to associate send/recv autograd function pairs. The format +// is similar to the autograd_context_id where we have a 64 bit integer with +// first 16 bits being the worker id and next 48 bits are auto-incrementing. +class TORCH_API DistAutogradContainer { + public: + explicit DistAutogradContainer(uint32_t num_shards); + + // One time initialization of the container. + static DistAutogradContainer& init(int64_t worker_id); + + // Retrieve the singleton instance of the container, ensures we have + // initialized the container. + static DistAutogradContainer& getInstance(); + + // Create a new context for a distributed autograd pass. + const ContextPtr newContext(); + + // Clean up resources for a given context_id once the autograd pass is done. + // Sends RPC to other workers this worker knows about, telling them to clean + // up their context as well. Throws an exception if the context_id does not + // exist. + void releaseContext(int64_t context_id); + + // Releases an autograd context if it is present on this node. Also sends RPC + // to other workers this worker knows about, telling them to clean up their + // context. Does nothing if it is not present. + void releaseContextIfPresent(int64_t context_id); + + // Checks if the passed in context_id is valid. + void isValidContext(int64_t context_id); + + // Retrieve the autograd context for a given context_id. + ContextPtr retrieveContext(int64_t context_id); + + // Retrieves the currently active autograd context for the current thread. + ContextPtr currentContext(); + + // Checks whether or not the current thread has a valid autograd context. + bool hasValidContext() const; + + // Generate a new autograd_message_id for send/recv autograd functions. + int64_t newAutogradMessageId(); + + // Creates a new autograd context with the provided context_id. If a context + // already exists with the provided context_id, we just return it. + // This does not set the current context for the current thread. + ContextPtr getOrCreateContext(int64_t context_id); + + // Retrieves the maximum possible autograd_context_id/autograd_message_id that + // can be generated by this worker. + int64_t getMaxId(); + + // Retrieves the worker ID for this node + rpc::worker_id_t getWorkerId() const; + + // Can set current context id if there is no valid context yet + static void setCurrentContextId(int64_t contextId); + + // Forcibly sets the thread local current context id. Should only be used in + // cases where you know what you're doing and need to override the thread + // local. Otherwise, use setCurrentContextId instead. + static void forceCurrentContextId(int64_t contextId); + + // Clear current context id + void clearCurrentContext(); + + // Returns the number of autograd contexts in the container. + size_t numAutogradContexts() const; + + // Returns the current thread local context id for this thread. + static int64_t currentContextId(); + + DistAutogradContainer() = delete; + ~DistAutogradContainer() = default; + DistAutogradContainer(const DistAutogradContainer&) = delete; + DistAutogradContainer& operator=(const DistAutogradContainer&) = delete; + DistAutogradContainer(DistAutogradContainer&&) = delete; + DistAutogradContainer& operator=(DistAutogradContainer&&) = delete; + + private: + // Number of shards for the map storing autograd contexts. We'd like this + // to be a power of 2 and we don't expect a value much higher than the + // number of cores would provide much benefit. + static constexpr uint32_t kNumDefaultShards = 128; + + // Use cache line size for alignment. + static constexpr int kCacheLineSize = 64; + + // Structure holding one shard of the sharded autograd context map with its + // associated lock. Align to cache line size to avoid contention between + // adjacent entries. + struct alignas(kCacheLineSize) ContextsShard { + // Lock for this shard. + mutable std::mutex lock; + + // Map storing autograd contexts for this shard. + std::unordered_map contexts; + }; + + static DistAutogradContainer& getInstanceInternal(); + + // Retrieve the shard for given context_id. + ContextsShard& getShard(int64_t context_id); + + // Sends an RPC to the workers that have a context corresponding to passed in + // context_id. This function should be called with the lock. + void sendReleaseContextRpc( + const std::unordered_set& workerIds, + int64_t context_id); + + // Erase context_id from the autograd context map, and reset the thread local + // current context id if it corresponds to the passed in context id. This + // function should be called with the lock. + void eraseContextIdAndReset(ContextsShard& shard, int64_t context_id); + + // Compute the number of shards for the autograd_contexts_ map. + static uint32_t computeNumShards(); + + // Auto incrementing context id used to identify unique autograd passes. + // Initialized with the first 16 bits being the worker_id. + std::atomic next_context_id_; + + // Unique id to identify a worker in the distributed setting. + int16_t worker_id_; + + // Whether or not the container has been initialized appropriately. + bool initialized_; + + // Sharded autograd context map. + std::vector autograd_contexts_; + + // Number of shards for the sharded autograd_contexts_ map. + uint32_t num_shards_; + + // Autograd message id to identify unique send/recv autograd function pairs. + std::atomic next_autograd_message_id_; + + // Maximum allowed value for autograd_context_id or autograd_message_id. + int64_t max_id_; +}; + +} // namespace torch::distributed::autograd diff --git a/shared/package-files/7c/7ce7e935ac7f3d82023f2d5fe60579aef107a733ccfbff6ae471718c24104ef0/_functional_sym_constrain_range.h b/shared/package-files/7c/7ce7e935ac7f3d82023f2d5fe60579aef107a733ccfbff6ae471718c24104ef0/_functional_sym_constrain_range.h new file mode 100644 index 0000000000000000000000000000000000000000..ffdbec7ad711d01619ba6c11f463560920e93625 --- /dev/null +++ b/shared/package-files/7c/7ce7e935ac7f3d82023f2d5fe60579aef107a733ccfbff6ae471718c24104ef0/_functional_sym_constrain_range.h @@ -0,0 +1,31 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_functional_sym_constrain_range(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor +inline at::Tensor _functional_sym_constrain_range(const at::Scalar & size, ::std::optional min, ::std::optional max, const at::Tensor & dep_token) { + return at::_ops::_functional_sym_constrain_range::call(size, min, max, dep_token); +} + +} diff --git a/shared/package-files/7c/7ceb32c888bbf41538ce3cb147d965a3a6267c27c4d7b4dcf640377732b3fdd3/python.py b/shared/package-files/7c/7ceb32c888bbf41538ce3cb147d965a3a6267c27c4d7b4dcf640377732b3fdd3/python.py new file mode 100644 index 0000000000000000000000000000000000000000..1d40d607f4bce113a3203247e0fc31a61169bb1b --- /dev/null +++ b/shared/package-files/7c/7ceb32c888bbf41538ce3cb147d965a3a6267c27c4d7b4dcf640377732b3fdd3/python.py @@ -0,0 +1,1517 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api import cpp +from torchgen.api.types import Binding, CppSignature, CppSignatureGroup +from torchgen.gen import pythonify_default +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + Type, + Variant, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Data Models +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# [Notes] python binding codegen +# +# The Python binding codegen produces code that takes the input list of +# PyObjects, finds the matching ATen C++ function using PythonArgParser, +# converts the PyObjects into C++ types and calls the ATen C++ function: +# +# +--------+ parsing +------------------------+ binding +-----------------------+ +# | PyObjs | ---------> | PythonArgParser Output | ---------> | Cpp Function Dispatch | +# +--------+ +------------------------+ +-----------------------+ +# +# The following examples demonstrate the data models the Python binding +# codegen needs to deal with and the tasks it needs to accomplish. It +# helps understand the purpose of the new data types we introduced below. +# +# - Function Schema (source of truth) +# +# aten::empty.names(int[] size, *, Dimname[]? names, +# ScalarType? dtype=None, Layout? layout=None, +# Device? device=None, bool? pin_memory=None, +# MemoryFormat? memory_format=None) -> Tensor +# +# - Python Signature +# +# It's used to generate input schema string for PythonArgParser. +# Note: TensorOptions fields are reordered and the additional +# 'requires_grad' field is added: +# +# empty(IntArrayRef size, *, DimnameList? names, +# MemoryFormat? memory_format=None, ScalarType dtype=None, +# Layout layout=torch.strided, Device device=None, +# bool pin_memory=False, bool requires_grad=False) +# +# - C++ Signature +# +# It's used to generate C++ lambda formals & dispatch call. +# Note: the scattered TensorOptions fields are packed into 'options'. +# +# auto dispatch_empty = +# [](IntArrayRef size, std::optional names, +# const TensorOptions & options, +# std::optional memory_format) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return torch::empty(size, names, options, memory_format); +# }; +# +# - Binding between Python Arguments and C++ Arguments +# +# Given a set of Python Arguments in scope, we need produce the +# binding expressions that translate the Python API into C++ API: +# +# Python Args Cpp Args Binding Exprs +# ----------------------------------------------------------------- +# 0: size size '_r.intlist(0)' +# 1: names names 'names' [special init] +# 2: memory_format -------+ +# 3: dtype -----+-|--> options 'options' [special packing] +# 4: layout / | +# 5: device / +--> memory_format '_r.memoryformatOptional(2)' +# 6: pin_memory / +# 7: requires_grad -+ +# +# So the full dispatch expression would look like: +# +# dispatch_empty(_r.intlist(0), names, options, +# _r.memoryformatOptional(2)) +# +# Where does 'names' come from? It involves special local init: +# +# auto __names = _r.toDimnameListOptional(1); +# std::optional names = +# __names ? std::make_optional(DimnameList(__names.value())) +# : std::nullopt; +# +# Where does 'options' come from? It involves special local init +# for TensorOptions. Note that Python side has the additional +# 'requires_grad' field: +# +# const auto options = TensorOptions() +# .dtype(_r.scalartype(3)) +# .device(_r.device(5)) +# .layout(_r.layoutOptional(4)) +# .requires_grad(_r.toBool(7)) +# .pinned_memory(_r.toBool(6)); +# +# In some other cases one Python Argument can map to multiple C++ +# Arguments. For example: +# +# aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False) +# -> (Tensor values, Tensor indices) +# +# Python Args Cpp Args Binding Exprs +# --------------------------------------------------------------------- +# +----> max 'out[0]' +# /-----> max_values 'out[1] +# 0: input / self '_r.tensor(0)' +# 1: dim / dim '_r.dimname(1)' +# 2: keepdim / keepdim '_r.toBool(2)' +# 3: out -----+ [local init] out '_r.tensorlist_n<2>(3)' +# +# As demonstrated above, the binding can involve reordering, +# packing, unpacking and special local inits. +# +# +# Let's look at a concrete example: +# +# static PythonArgParser parser({ +# "abs(Tensor input, *, Tensor out=None)", +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- Python Schema, represented by PythonSignature and PythonArgument +# +# }, /*traceable=*/true); +# +# ParsedArgs<2> parsed_args; +# auto _r = parser.parse(nullptr, args, kwargs, parsed_args); +# +# ... +# +# if (_r.isNone(1)) { +# ~~~~~~~~~~~~ <--- Scattered PythonArgParser output (arg name = 'out') +# represented by PythonArgParserOutputExpr +# +# // aten::abs(Tensor self) -> Tensor +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- NativeFunction schema, base version +# +# auto dispatch_abs = [](const Tensor & self) -> Tensor { +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- dispatch_lambda_args / dispatch_lambda_return_str +# generated from NativeFunction / CppSignature +# (deprecated PythonSignature is special) +# arguments are represented by DispatchLambdaArgument +# +# pybind11::gil_scoped_release no_gil; +# return self.abs(); +# ~~~~~~~~~~~ <--- cpp_dispatch_target / cpp_dispatch_exprs +# generated from NativeFunction / CppSignature +# }; +# return wrap(dispatch_abs(_r.tensor(0))); +# ~~~~~~~~~~~~~ +# ^ +# +--- dispatch_lambda_exprs +# binding PythonArgParserOutputExpr (python args) +# and DispatchLambdaArgument (c++ args) +# +# } else { +# // aten::abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- NativeFunction schema, out-variant +# +# auto dispatch_abs_out = [](Tensor out, const Tensor & self) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return at::abs_out(out, self); +# }; +# return wrap(dispatch_abs_out(_r.tensor(1), _r.tensor(0))); +# } +# +# +# [Notes] python interface codegen +# The python dataclasses below are used used to generate both python binding code +# and pyi type hint signatures. +# In theory these two should look very similar, but there are number of differences +# in how pyi signatures vs. python_arg_parser signatures are generated. +# These differences have been encapsulated in signature_str() vs. signature_str_pyi() +# to display the full signatures, and argument_str() vs argument_str_pyi() to display arguments. +# For examples, only pyi signatures include return types. + + +@dataclass(frozen=True) +class PythonReturns: + returns: tuple[Return, ...] + + +@dataclass(frozen=True) +class PythonArgument: + name: str + type: Type + default: str | None + + # Used to generate the default init expr for some PythonArgParser outputs, e.g.: + # + # _r.layoutWithDefault(3, layout_from_backend(self.options().backend()))) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # ^ + # +--- default_init str + default_init: str | None + + # Compute argument formal for python argument parsing. + # Needs to be consistent with torch/csrc/utils/python_arg_parser.h. + def argument_str(self, *, method: bool = False, symint: bool = True) -> str: + type_str = ( + argument_type_str(self.type, symint=symint) + .replace("const ", "") + .replace(" &", "") + ) + + name = self.name + # s/self/input/ outside method bindings + # [old codegen] TODO: remove this? doesn't rename in codegen, it's just + # for the parse string + if name == "self" and type_str in ["Tensor", "Number"] and not method: + name = "input" + + # add default + if self.default is not None: + default = { + "nullptr": "None", + "::std::nullopt": "None", + "std::nullopt": "None", + "{}": "None", + }.get(self.default, self.default) + return f"{type_str} {name}={default}" + else: + return f"{type_str} {name}" + + def argument_str_pyi( + self, *, method: bool = False, deprecated: bool = False + ) -> str: + type_str = argument_type_str_pyi(self.type) + + name = self.name + # s/self/input/ outside method bindings + # [old codegen] TODO: remove this? doesn't rename in codegen, it's just + # for the parse string + if name == "self" and type_str == "Tensor" and not method and not deprecated: + name = "input" + + if name == "from": # from is a Python keyword... + name += "_" + + # pyi merges the _out and functional variants into the same signature, with an optional out arg + if name == "out" and type_str == "Tensor" and not deprecated: + type_str = "Optional[" + type_str + "]" + + # pyi deprecated signatures don't get defaults for their out arg + treat_as_no_default = ( + deprecated + and isinstance(self, PythonOutArgument) + and self.default == "None" + ) + + # add default + if self.default is not None and not treat_as_no_default: + if ( + isinstance(self.type, ListType) + and self.type.elem == BaseType(BaseTy.int) + and self.default.startswith("{") + and self.default.endswith("}") + ): + default = ( + "(" + ", ".join(map(str.strip, self.default[1:-1].split(","))) + ")" + ) + else: + default = { + "nullptr": "None", + "::std::nullopt": "None", + "std::nullopt": "None", + "{}": "None", + "c10::MemoryFormat::Contiguous": "contiguous_format", + "QScheme::PER_TENSOR_AFFINE": "per_tensor_affine", + }.get(self.default, self.default) + return f"{name}: {type_str} = {default}" + else: + return f"{name}: {type_str}" + + +@dataclass(frozen=True) +class PythonOutArgument(PythonArgument): + # In Python signature multiple output fields are packed into one 'out' argument. + # When binding to C++, it's first binded to a local 'out' variable: + # 'auto out = _r.tensorlist_n<2>(2);', + # then binded to scattered C++ output arguments as 'out[0]', 'out[1]', and etc. + # TODO: maybe don't need keep scattered out fields for python signature? + outputs: tuple[PythonArgument, ...] + + @staticmethod + def from_outputs(outputs: tuple[PythonArgument, ...]) -> PythonOutArgument | None: + if not outputs: + return None + + size = len(outputs) + if size == 1: + return PythonOutArgument( + name=outputs[0].name, + type=outputs[0].type, + default="None", + default_init=None, + outputs=outputs, + ) + elif size > 1: + if any(not a.type.is_tensor_like() for a in outputs): + raise RuntimeError(f"Unsupported output type: {outputs}") + return PythonOutArgument( + name="out", + # TODO: shouldn't this be OptionalType[ListType[...]], since it defaults to None? + type=ListType(BaseType(BaseTy.Tensor), size), + default="None", + default_init=None, + outputs=outputs, + ) + raise AssertionError(r"Unexpected PythonOutArgument size") + + +@dataclass(frozen=True) +class PythonSignature: + # Base operator name, without inplace/outplace suffix. + name: str + + # Positional arguments. + # TODO: create a dedicated SelfArgument type for 'self'? + input_args: tuple[PythonArgument, ...] + + # Keyword arguments excluding the 'out' argument and scattered kwargs belonging + # to TensorOptions (dtype, layout, device, pin_memory, requires_grad, etc). + input_kwargs: tuple[PythonArgument, ...] + + output_args: PythonOutArgument | None + + # Return types, which are only used by pyi + returns: PythonReturns + + # These are scattered kwargs arguments belonging to TensorOptions. + # When binding to C++, they are packed into a TensorOptions object 'options'. + # It's possible that the C++ signature doesn't take TensorOptions object (e.g. + # for out variant), in which case they will be used as scattered fields without + # being packed into 'options'. + # TODO: maybe create a PythonTensorOptionsArgument? + tensor_options_args: tuple[PythonArgument, ...] + + # method or function signature? + method: bool + + @property + def deprecated(self) -> bool: + return False + + def arguments( + self, *, skip_outputs: bool = False, skip_tensor_options: bool = False + ) -> tuple[PythonArgument | PythonOutArgument, ...]: + result: list[PythonArgument | PythonOutArgument] = [] + result.extend(self.input_args) + result.extend(self.input_kwargs) + if self.output_args is not None and not skip_outputs: + result.append(self.output_args) + if not skip_tensor_options: + result.extend(self.tensor_options_args) + return tuple(result) + + def arguments_count(self) -> int: + return len(self.arguments()) + + def output_idx(self) -> int: + return len(self.input_args) + len(self.input_kwargs) + + # [old codegen] Compute the Python function signature for argument parsing, + # as specified in torch/csrc/utils/python_arg_parser.h. WARNING: + # this is NOT the same type signature as specified by PEP 484 + # as understood by mypy; our format was independently developed + # and has some quirks to make it more suitable specifically + # for error parsing. + # + # For a translation to mypy-valid type signatures, see + # signature_str_pyi(). + def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str(method=self.method, symint=symint) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + return f"{self.name}({', '.join(schema_formals)})" + + def signature_str_pyi(self, *, skip_outputs: bool = False) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + # only pyi signatures include returns + returns_str = returns_str_pyi(self) + # pyi also includes self (with no typing/defaults) for methods + if self.method: + schema_formals.insert(0, "self") + return f"def {self.name}({', '.join(schema_formals)}) -> {returns_str}: ..." + + def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None: + # only pyi uses vararg signatures + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method) for a in args + ] + # vararg only applies to pyi signatures. vararg variants are not generated for all signatures + num_args = self.arguments_count() + num_positionalargs = len(self.input_args) + + have_vararg_version = False + if num_args > 0: + vararg_type = args[0].type + if ( + isinstance(vararg_type, ListType) + and str(vararg_type.elem) in ["int", "SymInt"] + and num_positionalargs == 1 + ): + have_vararg_version = True + + if not have_vararg_version: + return None + + # Below are the major changes in vararg vs. regular pyi signatures + # vararg signatures also omit the asterix + assert isinstance(vararg_type, ListType) + schema_formals[0] = ( + "*" + args[0].name + ": " + argument_type_str_pyi(vararg_type.elem) + ) + + returns_str = returns_str_pyi(self) + # pyi also includes self (with no typing/defaults) for methods + if self.method: + schema_formals.insert(0, "self") + return f"def {self.name}({', '.join(schema_formals)}) -> {returns_str}: ..." + + +# The deprecated python signature involves some special logic, so create a +# dedicated data model to store these extra properties. +@dataclass(frozen=True) +class PythonSignatureDeprecated(PythonSignature): + # Schema for the deprecated function + deprecated_schema: FunctionSchema + + # The deprecated signature might miss some arguments that the corresponding + # C++ signature expects. We need store the constant default values to pass in. + # For example: + # [deprecate signature]: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) + # [func schema]: aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + # [func call]: self.addmm(mat1, mat2, beta, 1) + # We store ['self', 'mat1', 'mat2', 'beta', '1'] in this case. + deprecated_args_exprs: tuple[str, ...] + + @property + def deprecated(self) -> bool: + return True + + def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str: + return ( + PythonSignature.signature_str( + self, skip_outputs=skip_outputs, symint=symint + ) + + "|deprecated" + ) + + def signature_str_pyi(self, *, skip_outputs: bool = False) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method, deprecated=True) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + returns_str = returns_str_pyi(self) + return f"def {self.name}({', '.join(schema_formals)}) -> {returns_str}: ..." + + def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None: + # the codegen doesn't include vararg variants for deprecated signatures + return None + + +# This struct is used to hold the PythonSignature and its corresponding +# NativeFunction BEFORE grouping base and out-variant functions. +# Why not store NativeFunction in PythonSignature or construct PythonSignature +# from NativeFunction? Because they are not 1-1 mapped. +# One native function could have both deprecated and non-deprecated python +# signatures - NativeFunction doesn't contain information to construct the +# deprecated python signature. +# One python signature is used to handle both the base and the out-variant +# function - see 'PythonSignatureGroup'. +@dataclass(frozen=True) +class PythonSignatureNativeFunctionPair: + signature: PythonSignature + function: NativeFunction + + +# We merge pairs of functions with signatures that are equivalent mod +# output arguments, and use a single entry in the python_arg_parser sig +# list for both (output arguments become optional). +@dataclass(frozen=True) +class PythonSignatureGroup: + # The signature used for Python argument parsing. The outplace signature + # is preferred if exists, because it can be used to parse inputs for both + # the out-place variant and the base version (with output omitted). + signature: PythonSignature + + # The regular ATen declaration (e.g. conv2d) + base: NativeFunction + + # The out variant (e.g. conv2d_out) + outplace: NativeFunction | None + + @classmethod + def from_pairs( + cls, + functional: PythonSignatureNativeFunctionPair, + out: PythonSignatureNativeFunctionPair | None, + ) -> PythonSignatureGroup: + if out is None: + return PythonSignatureGroup( + signature=functional.signature, + base=functional.function, + outplace=None, + ) + + # prefer the signature with optional out=... arguments because it's the + # superset that can be used to parse input for both base and outplace. + signature_kwargs = out.signature.__dict__.copy() + + # Out overloads in C++ don't have TensorOptions arguments, + # so take these from the functional variant + signature_kwargs["tensor_options_args"] = ( + functional.signature.tensor_options_args + ) + + return PythonSignatureGroup( + signature=type(out.signature)(**signature_kwargs), + base=functional.function, + outplace=out.function, + ) + + +# C++ function dispatch is wrapped in a lambda function. The lambda function +# has almost the same signature as the C++ function, only with some small +# variants - see details below. +# This data model is used to represent arguments of the lambda function +# signature. +@dataclass(frozen=True) +class DispatchLambdaArgument: + name: str + type_str: str + is_out_arg: bool + + +# To pass PyObjects arguments to C++ function (via the lambda wrapper), +# we need first convert PyObjects into simple C++ objects. This work +# is done by PythonArgParser. +# This data model is used to represent the output of PythonArgParser. +# It has 1-1 mapping with PythonArgument in PythonSignature. +@dataclass(frozen=True) +class PythonArgParserOutputExpr: + # argument name + name: str + + # RHS expression to reference PythonArgParser output. + expr: str + + # In some special cases we need create different expr, e.g.: + # '_r.isNone(1)' instead of '_r.tensor(1)'. + index: int + + # The python argument it maps to. + argument: PythonArgument + + @property + def is_none_expr(self) -> str: + return f"_r.isNone({self.index})" + + +# To pass PythonArgParser output to the lambda wrapper, we need bind +# PythonArgParserOutputExpr to DispatchLambdaArgument. +# They are not always 1-1 mapped, e.g. scattered TensorOptions fields +# need be packed into a TensorOptions object, which is the argument +# that the lambda function wrapper takes. +@dataclass(frozen=True) +class DispatchLambdaArgumentExprs: + # The exprs that provide the binding for lambda arguments, e.g.: + # + # 'self' -> '_r.tensor(0)' + # 'min' -> 'out[0]' / 'min_indices' -> 'out[1]' + # 'options' -> 'options' + # + # It has 1-1 mapping with DispatchLambdaArgument. + exprs: Sequence[str] + + # Special local inits, which might introduce new variables that + # the 'exprs' above reference, e.g.: + # + # 'auto out = _r.tensorlist_n<2>(2);' + # + inits: Sequence[str] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Helper Functions +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _cpp_signature(f: NativeFunction, *, method: bool = False) -> CppSignature: + return CppSignatureGroup.from_native_function(f, method=method).signature + + +def has_tensor_options(f: NativeFunction) -> bool: + return f.func.arguments.tensor_options is not None + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python Signature +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# 'simple_type' was introduced by the old codegen, which is slightly +# different from the python schema type, e.g.: doesn't have '?' suffix +# for optional Tensor/TensorList; doesn't have '[size]' suffix for list type. +def argument_type_str( + t: Type, *, simple_type: bool = False, symint: bool = True +) -> str: + if isinstance(t, BaseType): + if t.name == BaseTy.int: + return "int64_t" + elif t.name == BaseTy.float: + return "double" + elif t.name == BaseTy.str: + return "c10::string_view" + elif t.name in [ + BaseTy.Tensor, + BaseTy.bool, + BaseTy.QScheme, + BaseTy.Scalar, + BaseTy.ScalarType, + BaseTy.Generator, + BaseTy.Storage, + BaseTy.Layout, + BaseTy.Device, + BaseTy.DeviceIndex, + BaseTy.MemoryFormat, + BaseTy.Dimname, + BaseTy.Stream, + BaseTy.SymInt, + ]: + # These python schema type names line up with their function schema names + return t.name.name + + elif isinstance(t, OptionalType): + elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint) + return f"{elem}?" + elif isinstance(t, ListType): + size = t.size if not simple_type else None + if str(t.elem) == "bool": + assert t.size is not None + return f"::std::array" + elif str(t.elem) == "int": + return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef" + elif str(t.elem) == "SymInt": + if symint: + return ( + f"SymIntArrayRef[{size}]" if size is not None else "SymIntArrayRef" + ) + else: + return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef" + elif str(t.elem) == "Tensor": + return f"TensorList[{size}]" if size is not None else "TensorList" + elif str(t.elem) == "Scalar": + return f"ScalarList[{size}]" if size is not None else "ScalarList" + elif str(t.elem) == "Tensor?": + if simple_type: + return "c10::List<::std::optional>" + else: + return "const c10::List<::std::optional> &" + elif str(t.elem) == "Dimname": + return f"DimnameList[{size}]" if size is not None else "DimnameList" + elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint) + return f"ArrayRef<{elem}>" + + raise RuntimeError(f"unrecognized type {repr(t)}") + + +def argument_type_size(t: Type) -> int | None: + l = t.is_list_like() + if l is not None and str(l.elem) != "bool": + return l.size + else: + return None + + +def argument(a: Argument) -> PythonArgument: + return PythonArgument( + name=a.name, + type=a.type, + # TODO: directly translate a.default to python default + default=( + str(pythonify_default(cpp.default_expr(a.default, a.type, symint=False))) + if a.default is not None + else None + ), + default_init=None, + ) + + +# Generates a PythonSignature that can be used for either .pyi or PythonArgParser codegen +def signature( + f: NativeFunction, *, method: bool = False, pyi: bool = False +) -> PythonSignature: + return signature_from_schema( + f.func, category_override=f.category_override, method=method, pyi=pyi + ) + + +def signature_from_schema( + func: FunctionSchema, + *, + category_override: str | None, + method: bool = False, + pyi: bool = False, +) -> PythonSignature: + args: list[Argument] = [] + args.extend(func.arguments.pre_self_positional) + # Skip SelfArgument if this is method. + if not method and func.arguments.self_arg is not None: + args.append(func.arguments.self_arg.argument) + args.extend(func.arguments.post_self_positional) + args.extend(func.arguments.pre_tensor_options_kwarg_only) + # Skip TensorOptionsArguments. Python side TensorOptions + # arguments are created based on different rules - see below. + args.extend(func.arguments.post_tensor_options_kwarg_only) + args.extend(func.arguments.out) + + input_arg_set = {a.name for a in func.arguments.flat_positional} + kwarg_only_set = {a.name for a in func.arguments.flat_kwarg_only} + out_arg_set = {a.name for a in func.arguments.out} + + input_args = tuple(map(argument, filter(lambda a: a.name in input_arg_set, args))) + input_kwargs = tuple( + map(argument, filter(lambda a: a.name in kwarg_only_set, args)) + ) + outputs = tuple(map(argument, filter(lambda a: a.name in out_arg_set, args))) + + # Reintroduce the scattered fields of TensorOptions for Python. + # Compared to the cpp counterpart, the python arguments have new property + # (default_init) and a new argument 'requires_grad', which require some + # special handlings. + # [old codegen] TODO: because these aren't guaranteed to be 100% faithful + # to the original versions in the yaml, this recreation is a potential + # source of drift between eager and JIT. Pull this logic out to a shared place. + + has_tensor_input_arg = any( + a.type.is_tensor_like() for a in func.arguments.flat_non_out + ) + if any(a.name == "requires_grad" for a in func.schema_order_arguments()): + raise ValueError( + "argument named requires_grad is reserved, should not explicitly add it in the schema" + ) + + # [old codegen] this probably won't work if one of the returns is not a tensor, + # but it will produce a compile-time error that is obvious. + has_tensor_return = any(r.type.is_tensor_like() for r in func.returns) + + name: str = cpp.name(func) + is_factory_function = category_override == "factory" or ( + has_tensor_return and not has_tensor_input_arg + ) + is_like_or_new_function = ( + category_override in ("new", "like") + or name.startswith("new_") + or name.endswith("_like") + ) + is_dummy_function = category_override == "dummy" + + tensor_options_args: list[PythonArgument] = [] + if (is_factory_function or is_like_or_new_function) and not is_dummy_function: + + def topt_default_init(name: str) -> str | None: + topt_args = func.arguments.tensor_options + if topt_args is None: + return None + a = getattr(topt_args, name) + if a.default is None or a.default == "None": + return None + return cpp.default_expr(a.default, a.type, symint=False) + + tensor_options_args.append( + PythonArgument( + name="dtype", + type=OptionalType(BaseType(BaseTy.ScalarType)), + default="None", + default_init=( + None if is_like_or_new_function else topt_default_init("dtype") + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="layout", + type=OptionalType(BaseType(BaseTy.Layout)), + default="None", + default_init=( + None if is_like_or_new_function else topt_default_init("layout") + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="device", + type=OptionalType(BaseType(BaseTy.Device)), + default="None", + default_init=( + None + if is_like_or_new_function + else ( + topt_default_init("device") + or "torch::tensors::get_default_device()" + ) + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="pin_memory", + type=OptionalType(BaseType(BaseTy.bool)), + default="False", + default_init=None, + ) + ) + tensor_options_args.append( + PythonArgument( + name="requires_grad", + type=OptionalType(BaseType(BaseTy.bool)), + default="False", + default_init=None, + ) + ) + + returns = PythonReturns(returns=func.returns) + + return PythonSignature( + name=str(func.name.name), + input_args=input_args, + input_kwargs=input_kwargs, + output_args=PythonOutArgument.from_outputs(outputs), + tensor_options_args=tuple(tensor_options_args), + returns=returns, + method=method, + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python Interface +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def structseq_fieldnames(returns: tuple[Return, ...]) -> list[str]: + if len(returns) <= 1 or all(r.name is None for r in returns): + return [] + else: + if any(r.name is None for r in returns): + # When building on Windows, `PyStructSequence_UnnamedField` could not be + # resolved by the linker for some reason, which cause error in building: + # + # python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol + # PyStructSequence_UnnamedField + # + # Thus, at this point in time, we do not support unnamed + # fields in structseq; you must either name all fields, + # or none of them. + raise ValueError("Unnamed field is not supported by codegen") + + return [str(r.name) for r in returns] + + +def argument_type_str_pyi(t: Type) -> str: + add_optional = False + if isinstance(t, OptionalType): + t = t.elem + add_optional = True + + if isinstance(t, BaseType): + if t.name in [BaseTy.int, BaseTy.DeviceIndex]: + ret = "_int" + if t.name == BaseTy.SymInt: + ret = "Union[_int, SymInt]" + elif t.name == BaseTy.float: + ret = "_float" + elif t.name == BaseTy.str: + ret = "str" + elif t.name == BaseTy.Scalar: + ret = "Union[Number, _complex]" + elif t.name == BaseTy.ScalarType: + ret = "_dtype" + elif t.name == BaseTy.bool: + ret = "_bool" + elif t.name == BaseTy.QScheme: + ret = "_qscheme" + elif t.name == BaseTy.Layout: + ret = "_layout" + elif t.name == BaseTy.Device: + ret = "Optional[DeviceLikeType]" + elif t.name == BaseTy.MemoryFormat: + ret = "memory_format" + elif t.name == BaseTy.Dimname: + ret = "Union[str, ellipsis, None]" + elif t.name == BaseTy.Storage: + ret = "Union[Storage, UntypedStorage]" + elif t.name in [BaseTy.Tensor, BaseTy.Generator, BaseTy.Stream]: + # These python schema type names line up with their function schema names + ret = t.name.name + + elif isinstance(t, ListType): + if str(t.elem) == "int": + ret = "Union[_int, _size]" if t.size is not None else "_size" + elif t.is_tensor_like(): + # TODO: this doesn't seem right... + # Tensor?[] currently translates to Optional[Union[tuple[Tensor, ...], list[Tensor]]] + # It should probably translate to Union[tuple[Optional[Tensor], ...], list[Optional[Tensor]]] + add_optional = True + ret = ( + "Union[Tensor, tuple[Tensor, ...], list[Tensor]]" + if t.size is not None + else "Union[tuple[Tensor, ...], list[Tensor]]" + ) + elif str(t.elem) == "float": + ret = "Sequence[_float]" + elif str(t.elem) == "SymInt" and t.size is not None: + elem = argument_type_str_pyi(t.elem) + ret = f"Union[{elem}, Sequence[{elem}]]" + else: + elem = argument_type_str_pyi(t.elem) + ret = f"Sequence[{elem}]" + + else: + raise RuntimeError(f"unrecognized type {repr(t)}") + + if add_optional: + ret = "Optional[" + ret + "]" + + return ret + + +def return_type_str_pyi(t: Type) -> str: + # Where arguments are open to accepting Union, return types should return + # concrete types + + if isinstance(t, OptionalType): + inner = return_type_str_pyi(t.elem) + return f"Optional[{inner}]" + + if isinstance(t, BaseType): + if t.name == BaseTy.Device: + return "_device" + elif t.name == BaseTy.Dimname: + return "Optional[str]" + else: + return argument_type_str_pyi(t) + + if isinstance(t, ListType): + inner = return_type_str_pyi(t.elem) + return f"tuple[{inner}, ...]" + + return argument_type_str_pyi(t) + + +def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None: + python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns] + structseq_name = signature.name + field_names = structseq_fieldnames(signature.returns.returns) + if field_names: + # These types are structseq objects which act like named NamedTuples, but + # the constructor acts like the constructor of tuple. Using typing.NamedTuple + # does not allow us to override __init__. + seq_type = f"tuple[{', '.join(python_returns)}]" + structseq_def_lines = [ + f"class {structseq_name}({seq_type}):", + ] + for name, typ in zip(field_names, python_returns): + structseq_def_lines.extend( + [ + " @property", + f" def {name}(self) -> {typ}: ...", + ] + ) + structseq_def_lines.extend( + [ + f" def __new__(cls, sequence: {seq_type}): ...", + f" n_fields: _int = {len(field_names)}", + f" n_sequeunce_fields: _int = {len(field_names)}", + " n_unnamed_fields: _int = 0", + " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing", + "", # add an extra newline + ] + ) + structseq_def = "\n".join(structseq_def_lines) + # Example: + # structseq_def = ( + # "class max(tuple[Tensor, Tensor]):\n" + # " @property\n" + # " def values(self) -> Tensor: ...\n" + # " @property\n" + # " def indices(self) -> Tensor: ...\n" + # " def __new__(cls, sequence: tuple[Tensor, Tensor]): ...\n" + # " n_fields: _int = 2", + # " n_sequeunce_fields: _int = 2", + # " n_unnamed_fields: _int = 0", + # " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing", + # ) + return structseq_name, structseq_def + return None + + +def returns_str_pyi(signature: PythonSignature) -> str: + field_names = structseq_fieldnames(signature.returns.returns) + if field_names: + return f"torch.return_types.{signature.name}" + + python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns] + if len(python_returns) > 1: + return "tuple[" + ", ".join(python_returns) + "]" + if len(python_returns) == 1: + return python_returns[0] + return "None" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# C++ Function Dispatch +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# This section provides APIs to generate the code that does C++ function +# dispatch. The C++ function call is wrapped by a lambda function. +# For example: +# +# // aten::selu_(Tensor(a!) self) -> Tensor(a!) +# auto dispatch_selu_ = [](Tensor self) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return at::selu_(self); +# }; +# +# The lambda function's signature follows the C++ signature in common +# cases, e.g.: +# +# // aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +# [](const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor +# +# For out variant the 'out' argument's type is changed from 'Tensor &' +# to 'Tensor'. It's because when calling the lambda it passes in the +# PythonArgParser output '_r.tensor(3)', which is stack allocated object +# and needs to pass by value. Also see comments in 'dispatch_lambda_return_str()'. +# +# // aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) +# [](Tensor out, const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor +# +# For multi-output case it can keep using reference type because the +# PythonArgParser output has been unpacked to local variables, e.g.: +# +# // aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, +# // Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +# [](Tensor & max, Tensor & max_values, const Tensor & self, Dimname dim, bool keepdim) -> std::tuple +# +# For deprecated python signature, it should follow deprecated python arg order. +# TODO: This is to keep same byte-for-byte result as the old codegen - maybe unnecessary? + + +def dispatch_lambda_args( + ps: PythonSignature, f: NativeFunction, symint: bool = True +) -> tuple[DispatchLambdaArgument, ...]: + if isinstance(ps, PythonSignatureDeprecated): + schema = ps.deprecated_schema + else: + schema = f.func + + # Start with cpp arguments - dispatch lambda signature always include 'self' + cpp_args = cpp.arguments( + arguments=schema.arguments, + faithful=False, + symint=symint, + method=False, + cpp_no_default_args=f.cpp_no_default_args, + ) + out_args: set[str] = {a.name for a in schema.arguments.out} + + # Convert from cpp argument to lambda argument + def dispatch_lambda_arg(cpp_arg: Binding) -> DispatchLambdaArgument: + type_str = cpp_arg.type + is_out_arg = cpp_arg.name in out_args + if ps.method and cpp_arg.name == "self": + # For method's 'self', we can use 'const Tensor &' and simply ignore mutability! + type_str = "const at::Tensor &" + else: + # For other cases we need prevent dangling refs to temps (unless it's + # unpacked scattered output) + # The reason is explained in the comments above and in 'dispatch_lambda_return_str()'. + # TODO: avoid this special handling? + ensure_temp_safe = len(out_args) <= 1 or not is_out_arg + if ensure_temp_safe: + type_str = { + "at::Tensor &": "at::Tensor", + }.get(type_str, type_str) + return DispatchLambdaArgument( + name=cpp_arg.name, + type_str=type_str, + is_out_arg=is_out_arg, + ) + + return tuple(map(dispatch_lambda_arg, cpp_args)) + + +# [old codegen] XXX: if you got here because of an assertion failure, it doesn't mean +# it's enough to just extend the list here. Before you do this, make sure +# to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h. +SUPPORTED_RETURN_TYPES = { + "at::Tensor", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple>", + "::std::vector", + # Needed for flash attention forw/backward + "::std::tuple", + "at::Scalar", + "bool", + "int64_t", + "void*", + "void", + "at::QScheme", + "double", + "at::IntArrayRef", + "at::ScalarType", + "at::Stream", +} + + +def dispatch_lambda_return_str(f: NativeFunction) -> str: + # [old codegen] Remove type annotation (e.g. 'Tensor' rather than 'Tensor &') + # because the dispatch lambdas take mutable arguments *by value*, not + # by reference. If you then return a reference to such an argument, you + # will now have a pointer to a dangling stack entry. Not good. + # + # You want: + # + # auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); }; + # ^^^^^^ + # + # *not* + # + # auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); }; + # ^^^^^^^ + # + # (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing + # codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a + # mutable reference to temporary. Maybe we could assign it to a + # variable itself.) + returns_without_annotation = tuple( + Return(r.name, r.type, None) for r in f.func.returns + ) + return_str = cpp.returns_type(returns_without_annotation, symint=True).cpp_type() + if return_str not in SUPPORTED_RETURN_TYPES: + raise RuntimeError(f"{f.func.name} returns unsupported type {return_str}") + return return_str + + +def cpp_dispatch_target(f: NativeFunction) -> str: + symint = f.func.has_symint() + name = cpp.name(f.func, symint_overload=symint) + if Variant.method in f.variants: + return f"self.{name}" + if Variant.function in f.variants: + if has_tensor_options(f) or f.func.name.name.base.endswith("_like"): + namespace = "torch" + else: + namespace = "at" + return f"{namespace}::{name}" + raise RuntimeError(f"could not dispatch, neither function nor method: {f.func}") + + +def cpp_dispatch_exprs( + f: NativeFunction, + *, + python_signature: PythonSignature | None = None, +) -> tuple[str, ...]: + cpp_args: Sequence[Binding] = _cpp_signature(f, method=False).arguments() + + exprs: tuple[str, ...] = () + if not isinstance(python_signature, PythonSignatureDeprecated): + # By default the exprs are consistent with the C++ signature. + exprs = tuple(a.name for a in cpp_args) + else: + # For deprecated python signature we may need fill in some constants. + exprs = tuple( + filter( + lambda n: n != "out" or f.func.is_out_fn(), + python_signature.deprecated_args_exprs, + ) + ) + + if Variant.method in f.variants: + exprs = tuple(filter("self".__ne__, exprs)) + + return exprs + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python / C++ Args Binding +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# We explicitly enumerate the PythonArgParser unpacking methods for all +# supported types. This might be more verbose than necessary, partially +# because of the irregularity of unpacking method naming, partially +# because we want to mimic the old codegen behavior - to reject +# unexpected and/or unsupported cases which the old codegen rejects. +# For certain cases it is intentionally more restrictive than necessary, +# e.g.: it doesn't accepts doublelist with definite size. +def arg_parser_unpack_method( + t: Type, default: str | None, default_init: str | None, *, symint: bool = True +) -> str: + has_default_init = default_init is not None + if has_default_init and str(t) not in ( + "ScalarType?", + "ScalarType", + "Device", + "Device?", + "Layout", + "Layout?", + "bool", + "bool?", + ): + raise RuntimeError(f"type '{t}' does not supported unpacking with default") + + if isinstance(t, BaseType): + if t.name in [ + BaseTy.Tensor, + BaseTy.Stream, + BaseTy.Storage, + BaseTy.Scalar, + BaseTy.Dimname, + ]: + # These unpack methods line up with their schema names + return t.name.name.lower() + elif t.name == BaseTy.ScalarType: + return "scalartypeWithDefault" if has_default_init else "scalartype" + elif t.name == BaseTy.Device: + return "deviceWithDefault" if has_default_init else "device" + elif t.name == BaseTy.DeviceIndex: + return "toInt64" + elif t.name == BaseTy.int: + return "toInt64" + elif t.name == BaseTy.SymInt: + return "toSymInt" if symint else "toInt64" + elif t.name == BaseTy.bool: + return "toBoolWithDefault" if has_default_init else "toBool" + elif t.name == BaseTy.float: + return "toDouble" + elif t.name == BaseTy.str: + return "stringView" + elif t.name == BaseTy.Layout: + return "layoutWithDefault" if has_default_init else "layout" + elif t.name == BaseTy.MemoryFormat: + return "memoryformat" + + elif isinstance(t, OptionalType): + if str(t.elem) == "Tensor": + return "optionalTensor" + elif str(t.elem) == "Generator": + return "generator" + elif str(t.elem) == "Dimname[]": + return "toDimnameListOptional" + elif not has_default_init and default in ( + None, + "None", + "::std::nullopt", + "std::nullopt", + ): + # If default is None: append 'Optional' to elem's unpacking method + return ( + arg_parser_unpack_method(t.elem, None, None, symint=symint) + "Optional" + ) + else: + # Otherwise, load as underlying type with default + return arg_parser_unpack_method( + t.elem, default, default_init, symint=symint + ) + + elif isinstance(t, ListType): + if str(t.elem) == "Tensor": + # accept and use definite size + return f"tensorlist_n<{t.size}>" if t.size is not None else "tensorlist" + elif str(t.elem) == "Tensor?": + return "list_of_optional_tensors" + elif str(t.elem) == "Dimname": + # accept definite size + return "dimnamelist" + elif str(t.elem) == "int": + # accept definite size + return "intlist" + elif str(t.elem) == "float": + return "doublelist" + elif str(t.elem) == "SymInt": + # accept definite size + return "symintlist" if symint else "intlist" + elif str(t.elem) == "Scalar": + return "scalarlist" + raise RuntimeError(f"type '{t}' is not supported by PythonArgParser") + + +# Return RHS expression for python argument using PythonArgParser output. +# e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)' +def arg_parser_output_expr( + arg_index: int, a: PythonArgument, *, symint: bool = True +) -> PythonArgParserOutputExpr: + has_default = a.default_init is not None + unpack_method = arg_parser_unpack_method( + t=a.type, default=a.default, default_init=a.default_init, symint=symint + ) + default = f", {a.default_init}" if has_default else "" + expr = f"_r.{unpack_method}({arg_index}{default})" + + return PythonArgParserOutputExpr( + name=a.name, + expr=expr, + index=arg_index, + argument=a, + ) + + +# Returns a map with key = arg_name and value = PythonArgParserOutputExpr. +def arg_parser_output_exprs( + ps: PythonSignature, f: NativeFunction, *, symint: bool = True +) -> dict[str, PythonArgParserOutputExpr]: + return { + e.name: e + for i, a in enumerate(ps.arguments()) + for e in (arg_parser_output_expr(i, a, symint=symint),) + } + + +# argument name to type for scattered tensor options fields +TENSOR_OPTIONS_FIELDS = { + "dtype": "ScalarType?", + "device": "Device?", + "layout": "Layout?", + "pin_memory": "bool?", + "requires_grad": "bool?", +} + + +# bind arg parser outputs (python args) with dispatch lambda arguments (c++ args). +def dispatch_lambda_exprs( + ps: PythonSignature, f: NativeFunction, *, symint: bool = True +) -> DispatchLambdaArgumentExprs: + # This method is to bind 'arg_parser_outputs' and 'lambda_args' by producing + # 'inits' and 'lambda_args_exprs' for each lambda argument using arg parser + # outputs. + arg_parser_outputs = arg_parser_output_exprs(ps, f, symint=symint) + lambda_args = dispatch_lambda_args(ps, f, symint=symint) + inits: list[str] = [] + lambda_args_exprs: dict[str, str] = {} + + has_toptions = has_tensor_options(f) + + # 1. special inits/unpacking to provide binding exprs for lambda arguments. + for a in ps.arguments(skip_tensor_options=True): + name = a.name + arg_parser_expr = arg_parser_outputs[a.name].expr + + if has_toptions and name == "self": + # TODO: why this needs to be special case? + inits.extend( + [ + f"auto self = {arg_parser_expr};", + ] + ) + lambda_args_exprs[name] = name + elif ( + isinstance(a, PythonOutArgument) + and len(a.outputs) > 1 + and f.func.is_out_fn() + ): + inits.extend( + [ + f"auto out = {arg_parser_expr};", + ] + ) + for i, out_arg in enumerate(a.outputs): + lambda_args_exprs[out_arg.name] = f"out[{i}]" + elif str(a.type) == "Dimname[]?": + # [old codegen] + # TODO: make this part of something more general, or get rid of it. + # optional> are special. The PythonArgParser returns an + # optional>, which cannot be implicitly converted to + # optional>. One needs to unwrap the optional and rewrap. + inits.extend( + [ + f"auto __{name} = {arg_parser_expr};", + f"::std::optional {name} = __{name} ? ::std::make_optional(DimnameList(__{name}.value())) : ::std::nullopt;", # noqa: B950 + ] + ) + lambda_args_exprs[name] = name + else: + # default case - directly using PythonArgParser output expr + lambda_args_exprs[name] = arg_parser_expr + + # method's self is passed directly to python binding, rather than parsed + if ps.method: + lambda_args_exprs["self"] = "self" + + # 2. special packing/checking for TensorOptions. + tensor_options_args_names = [a.name for a in ps.tensor_options_args] + if has_toptions: + if f.func.is_out_fn(): + raise RuntimeError(f"{f.func}: tensor options with output arg") + for a in ps.tensor_options_args: + if a.name not in TENSOR_OPTIONS_FIELDS: + raise RuntimeError( + f"{f.func}: unrecognized tensor options field '{a.name}' in python binding arguments" + ) + if str(a.type) != TENSOR_OPTIONS_FIELDS.get(a.name): + raise RuntimeError( + f"{f.func}: unrecognized type '{str(a.type)}' for tensor options field '{a.name}'" + ) + if not all(a in tensor_options_args_names for a in TENSOR_OPTIONS_FIELDS): + raise RuntimeError( + f"{f.func}: incomplete tensor options args: {tensor_options_args_names}" + ) + + inits.append( + f"""\ +const auto options = TensorOptions() + .dtype({arg_parser_outputs["dtype"].expr}) + .device({arg_parser_outputs["device"].expr}) + .layout({arg_parser_outputs["layout"].expr}) + .requires_grad({arg_parser_outputs["requires_grad"].expr}) + .pinned_memory({arg_parser_outputs["pin_memory"].expr}); +torch::utils::maybe_initialize_device(options); +""" + ) + lambda_args_exprs["options"] = "options" + + # 3. special case - access scattered TensorOptions fields without packing + # TODO: maybe move to the generator side as it's not related to binding. + if not has_toptions and tensor_options_args_names: + if "dtype" in tensor_options_args_names: + # we're an output-arg variant, check these args against output tensor + if not f.func.is_out_fn(): + raise RuntimeError( + f"{f.func}: dtype in tensor_options_args without output arg, {ps} {ps.arguments}" + ) + if not all(a in tensor_options_args_names for a in ("layout", "device")): + raise RuntimeError( + f"{f.func}: incomplete tensor options for output check" + ) + + inits.append( + f"""\ +check_out_type_matches({arg_parser_outputs["out"].expr}, {arg_parser_outputs["dtype"].expr}, + {arg_parser_outputs["dtype"].is_none_expr}, {arg_parser_outputs["layout"].expr}, + {arg_parser_outputs["device"].expr}, {arg_parser_outputs["device"].is_none_expr}); +""" + ) + # we'll set requires_grad on outgoing tensor + if "requires_grad" not in tensor_options_args_names: + raise RuntimeError( + f'{f.func}: expected "requires_grad" in tensor_options_args absent, but found [{tensor_options_args_names}]' + ) + + return DispatchLambdaArgumentExprs( + exprs=tuple(lambda_args_exprs[a.name] for a in lambda_args), + inits=inits, + ) diff --git a/shared/package-files/7c/7cecd01eca76cdfec851a86c77f8af86974b812ecc17f80da106bc24039b3a9f/input_output_analysis.cpython-311.pyc b/shared/package-files/7c/7cecd01eca76cdfec851a86c77f8af86974b812ecc17f80da106bc24039b3a9f/input_output_analysis.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9ed9c140c73b8b5b18380d60346e5bbc9e4ba40 Binary files /dev/null and b/shared/package-files/7c/7cecd01eca76cdfec851a86c77f8af86974b812ecc17f80da106bc24039b3a9f/input_output_analysis.cpython-311.pyc differ diff --git a/shared/package-files/7c/7ceda7381fde3ced7b1b4f377a52d18f54872209ffa29f686ac1cbf04e8722e2/reduction.h b/shared/package-files/7c/7ceda7381fde3ced7b1b4f377a52d18f54872209ffa29f686ac1cbf04e8722e2/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..c65cf43be7fba00ff9cc974c7316d468deb3ad12 --- /dev/null +++ b/shared/package-files/7c/7ceda7381fde3ced7b1b4f377a52d18f54872209ffa29f686ac1cbf04e8722e2/reduction.h @@ -0,0 +1,306 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace torch::jit::tensorexpr { + +using ParameterList = const std::vector; +using ReduceInteraction = std::function; + +// A Reducer is a user interface describing a particular reduction +// operation. It has three components: An initialization value, a way of +// interacting each value with the accumulation, and a method for obtaining the +// current value to be reduced. It is materialized into a ReduceOp when loop +// variables are known. +class TORCH_API Reducer { + public: + Reducer(ExprHandle init, ReduceInteraction& interaction) + : init_(init.node()), interaction_(interaction) {} + + template + Reducer(ExprHandle init, RI interaction) + : init_(init.node()), interaction_(std::move(interaction)) {} + + ExprPtr initializer() const { + return init_; + } + + ExprHandle operator()( + const BufHandle& result_buf, + ExprHandle body, + const std::vector& output, + const std::vector& inner) const; + + ReduceOpPtr operator()( + const BufPtr& result_buf, + ExprPtr body, + const std::vector& output, + const std::vector& inner) const; + + ExprHandle operator()( + const BufHandle& result_buf, + BufHandle acc_buf, + const ExprHandle& body, + const std::vector& output, + const std::vector& inner) const; + + // Polymorphic handling of Body functions with a variety of parameters. + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + return func(vars); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 1) { + throw malformed_input("mismatch between reduce body and arg size (1)"); + } + + return func(vars[0]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 2) { + throw malformed_input("mismatch between reduce body and arg size (2)"); + } + return func(vars[0], vars[1]); + } + + static ExprHandle getReduceBody( + const std::function< + ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>& + func, + const std::vector& vars) { + if (vars.size() != 3) { + throw malformed_input("mismatch between reduce body and arg size (3)"); + } + return func(vars[0], vars[1], vars[2]); + } + + static ExprHandle getReduceBody( + const std::function& func, + const std::vector& vars) { + if (vars.size() != 4) { + throw malformed_input("mismatch between reduce body and arg size (4)"); + } + return func(vars[0], vars[1], vars[2], vars[3]); + } + + // Completes the reduction operator by applying the interaction function to + // the accumulation and the body expression. + static ExprPtr complete( + const BufPtr& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = + ExprHandle(alloc(body.dtype(), accumulator, output_args)); + auto e = interaction(std::move(accum), std::move(body)); + return e.node(); + } + static ExprHandle complete( + const BufHandle& accumulator, + const ReduceInteraction& interaction, + ExprHandle body, + const std::vector& output_args, + const std::vector& reduce_args) { + ExprHandle accum = Load::make(body.dtype(), accumulator, output_args); + auto e = interaction(std::move(accum), std::move(body)); + return e; + } + + private: + ExprPtr init_; + ReduceInteraction interaction_; +}; + +// An expression representing a Reduction operation (e.g. Sum, Max) broken into +// it's component parts: initialization, accumulation var, acquisition of value +// to be reduced and interaction. +// +// This is intended to be expanded in the loopnest and not make it to codegen. +class TORCH_API ReduceOp : public ExprNode { + public: + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + reducer_(std::move(reducer)) { + result_buf_ = nullptr; + acc_buf_ = nullptr; + ri_operand_ = nullptr; + } + + ReduceOp( + const ExprPtr& body, + std::vector reduce_args, + BufPtr result_buf, + BufPtr acc_buf, + ExprPtr ri_operand, + Reducer reducer) + : ExprNodeBase(body->dtype()), + body_(body), + reduce_args_(std::move(reduce_args)), + result_buf_(std::move(result_buf)), + acc_buf_(std::move(acc_buf)), + ri_operand_(std::move(ri_operand)), + reducer_(std::move(reducer)) {} + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + const Reducer& reducer); + + static ExprHandle make( + ExprHandle body, + const std::vector& reduce_args, + BufHandle result_buf, + BufHandle acc_buf, + ExprHandle ri_operand, + const Reducer& reducer); + + // return the body expression which obtains the value to be reduced. + ExprPtr body() const { + return body_; + } + + // Returns the original Reducer factory that can create ReduceOps. + const Reducer& reducer() const { + return reducer_; + } + + // returns variables associated with the axes of reduction. + const std::vector& reduce_args() const { + return reduce_args_; + } + + void setAccBuf(BufHandle acc_buf) { + acc_buf_ = acc_buf.node(); + } + BufPtr getAccBuf() { + return acc_buf_; + } + + void setResultBuf(BufHandle buf) { + result_buf_ = buf.node(); + } + BufPtr getResultBuf() { + return result_buf_; + } + + void setRiOperand(ExprHandle ri_operand) { + ri_operand_ = ri_operand.node(); + } + ExprPtr getRiOperand() { + return ri_operand_; + } + + private: + // body_ = reducer_->interaction_(result_buf_, ri_operand_) + ExprPtr body_; + std::vector reduce_args_; + + BufPtr result_buf_; + BufPtr acc_buf_; + ExprPtr ri_operand_; + + const Reducer reducer_; +}; + +class Sum : public Reducer { + public: + Sum() + : Reducer(ExprHandle(0), [](const ExprHandle& a, const ExprHandle& b) { + return a + b; + }) {} +}; + +inline ExprHandle maximumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::max()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } + return ExprHandle(); +} + +inline ExprHandle minimumVal(ScalarType type) { + switch (type) { +#define MAX_BY_TYPE_CASE(Type, Name) \ + case ScalarType::Name: \ + return ExprHandle(std::numeric_limits::min()); + AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE) +#undef MAX_BY_TYPE_CASE + default: + throw unsupported_dtype(); + } +} + +class Maximum : public Reducer { + public: + // TODO possible to remove this arg by deferring the init value until we + // know the dtype of the body. + Maximum(Dtype dtype) + : Reducer( + minimumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} + Maximum(ExprHandle initializer) + : Reducer( + std::move(initializer), + [](const ExprHandle& a, const ExprHandle& b) { + return Max::make(a, b, true); + }) {} +}; + +class Minimum : public Reducer { + public: + Minimum(Dtype dtype) + : Reducer( + maximumVal(dtype.scalar_type()), + [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} + Minimum(const ExprHandle& initializer) + : Reducer(initializer, [](const ExprHandle& a, const ExprHandle& b) { + return Min::make(a, b, true); + }) {} +}; + +class ReductionExpander : public IRMutator { + public: + StmtPtr expand(const StmtPtr& s) { + return s->accept_mutator(this); + } + + ExprPtr mutate(const ReduceOpPtr& v) override { + return v->body(); + } +}; + +} // namespace torch::jit::tensorexpr diff --git a/shared/package-files/7c/7cef32b5b2a471affc93a54ec8a730a3f58bb349b02f3f1af625840c8807cb65/_constants.cpython-311.pyc b/shared/package-files/7c/7cef32b5b2a471affc93a54ec8a730a3f58bb349b02f3f1af625840c8807cb65/_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92f49259b0606d62c4c68f5cb79748bfe37ba652 Binary files /dev/null and b/shared/package-files/7c/7cef32b5b2a471affc93a54ec8a730a3f58bb349b02f3f1af625840c8807cb65/_constants.cpython-311.pyc differ diff --git a/shared/package-files/7c/7cefa6e7224b685fbbfa48d48d8281a00b57f4cdbe84239f8c8eb9297667ee36/quantize_pt2e.cpython-311.pyc b/shared/package-files/7c/7cefa6e7224b685fbbfa48d48d8281a00b57f4cdbe84239f8c8eb9297667ee36/quantize_pt2e.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7e64dd3f40dc6e6e6cd6a8d7aee303047090d33 Binary files /dev/null and b/shared/package-files/7c/7cefa6e7224b685fbbfa48d48d8281a00b57f4cdbe84239f8c8eb9297667ee36/quantize_pt2e.cpython-311.pyc differ diff --git a/shared/package-files/7c/7cf2a8d0e7fe69981f012c89c6480c36c92fe2c847c91d85195bea0569315e20/cached.cpython-311.pyc b/shared/package-files/7c/7cf2a8d0e7fe69981f012c89c6480c36c92fe2c847c91d85195bea0569315e20/cached.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb91181326858c5f724d1cfa28d78b5be23fcd5 Binary files /dev/null and b/shared/package-files/7c/7cf2a8d0e7fe69981f012c89c6480c36c92fe2c847c91d85195bea0569315e20/cached.cpython-311.pyc differ diff --git a/shared/package-files/7c/7cf651077d306bb7c5bdc63aea87603df03b7f6fe5a23fa75ad84a2c690e1dec/test_astype.py b/shared/package-files/7c/7cf651077d306bb7c5bdc63aea87603df03b7f6fe5a23fa75ad84a2c690e1dec/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8028e74ee5518ec97c1e571c9cb04fa0045c85 --- /dev/null +++ b/shared/package-files/7c/7cf651077d306bb7c5bdc63aea87603df03b7f6fe5a23fa75ad84a2c690e1dec/test_astype.py @@ -0,0 +1,683 @@ +from datetime import ( + datetime, + timedelta, +) +from importlib import reload +import string +import sys + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT +import pandas.util._test_decorators as td + +from pandas import ( + NA, + Categorical, + CategoricalDtype, + DatetimeTZDtype, + Index, + Interval, + NaT, + Series, + Timedelta, + Timestamp, + cut, + date_range, + to_datetime, +) +import pandas._testing as tm + + +def rand_str(nchars: int) -> str: + """ + Generate one random byte string. + """ + RANDS_CHARS = np.array( + list(string.ascii_letters + string.digits), dtype=(np.str_, 1) + ) + return "".join(np.random.default_rng(2).choice(RANDS_CHARS, nchars)) + + +class TestAstypeAPI: + def test_astype_unitless_dt64_raises(self): + # GH#47844 + ser = Series(["1970-01-01", "1970-01-01", "1970-01-01"], dtype="datetime64[ns]") + df = ser.to_frame() + + msg = "Casting to unit-less dtype 'datetime64' is not supported" + with pytest.raises(TypeError, match=msg): + ser.astype(np.datetime64) + with pytest.raises(TypeError, match=msg): + df.astype(np.datetime64) + with pytest.raises(TypeError, match=msg): + ser.astype("datetime64") + with pytest.raises(TypeError, match=msg): + df.astype("datetime64") + + def test_arg_for_errors_in_astype(self): + # see GH#14878 + ser = Series([1, 2, 3]) + + msg = ( + r"Expected value of kwarg 'errors' to be one of \['raise', " + r"'ignore'\]\. Supplied value is 'False'" + ) + with pytest.raises(ValueError, match=msg): + ser.astype(np.float64, errors=False) + + ser.astype(np.int8, errors="raise") + + @pytest.mark.parametrize("dtype_class", [dict, Series]) + def test_astype_dict_like(self, dtype_class): + # see GH#7271 + ser = Series(range(0, 10, 2), name="abc") + + dt1 = dtype_class({"abc": str}) + result = ser.astype(dt1) + expected = Series(["0", "2", "4", "6", "8"], name="abc", dtype=object) + tm.assert_series_equal(result, expected) + + dt2 = dtype_class({"abc": "float64"}) + result = ser.astype(dt2) + expected = Series([0.0, 2.0, 4.0, 6.0, 8.0], dtype="float64", name="abc") + tm.assert_series_equal(result, expected) + + dt3 = dtype_class({"abc": str, "def": str}) + msg = ( + "Only the Series name can be used for the key in Series dtype " + r"mappings\." + ) + with pytest.raises(KeyError, match=msg): + ser.astype(dt3) + + dt4 = dtype_class({0: str}) + with pytest.raises(KeyError, match=msg): + ser.astype(dt4) + + # GH#16717 + # if dtypes provided is empty, it should error + if dtype_class is Series: + dt5 = dtype_class({}, dtype=object) + else: + dt5 = dtype_class({}) + + with pytest.raises(KeyError, match=msg): + ser.astype(dt5) + + +class TestAstype: + @pytest.mark.parametrize("tz", [None, "UTC", "US/Pacific"]) + def test_astype_object_to_dt64_non_nano(self, tz): + # GH#55756, GH#54620 + ts = Timestamp("2999-01-01") + dtype = "M8[us]" + if tz is not None: + dtype = f"M8[us, {tz}]" + vals = [ts, "2999-01-02 03:04:05.678910", 2500] + ser = Series(vals, dtype=object) + result = ser.astype(dtype) + + # The 2500 is interpreted as microseconds, consistent with what + # we would get if we created DatetimeIndexes from vals[:2] and vals[2:] + # and concated the results. + pointwise = [ + vals[0].tz_localize(tz), + Timestamp(vals[1], tz=tz), + to_datetime(vals[2], unit="us", utc=True).tz_convert(tz), + ] + exp_vals = [x.as_unit("us").asm8 for x in pointwise] + exp_arr = np.array(exp_vals, dtype="M8[us]") + expected = Series(exp_arr, dtype="M8[us]") + if tz is not None: + expected = expected.dt.tz_localize("UTC").dt.tz_convert(tz) + tm.assert_series_equal(result, expected) + + def test_astype_mixed_object_to_dt64tz(self): + # pre-2.0 this raised ValueError bc of tz mismatch + # xref GH#32581 + ts = Timestamp("2016-01-04 05:06:07", tz="US/Pacific") + ts2 = ts.tz_convert("Asia/Tokyo") + + ser = Series([ts, ts2], dtype=object) + res = ser.astype("datetime64[ns, Europe/Brussels]") + expected = Series( + [ts.tz_convert("Europe/Brussels"), ts2.tz_convert("Europe/Brussels")], + dtype="datetime64[ns, Europe/Brussels]", + ) + tm.assert_series_equal(res, expected) + + @pytest.mark.parametrize("dtype", np.typecodes["All"]) + def test_astype_empty_constructor_equality(self, dtype): + # see GH#15524 + + if dtype not in ( + "S", + "V", # poor support (if any) currently + "M", + "m", # Generic timestamps raise a ValueError. Already tested. + ): + init_empty = Series([], dtype=dtype) + as_type_empty = Series([]).astype(dtype) + tm.assert_series_equal(init_empty, as_type_empty) + + @pytest.mark.parametrize("dtype", [str, np.str_]) + @pytest.mark.parametrize( + "series", + [ + Series([string.digits * 10, rand_str(63), rand_str(64), rand_str(1000)]), + Series([string.digits * 10, rand_str(63), rand_str(64), np.nan, 1.0]), + ], + ) + def test_astype_str_map(self, dtype, series, using_infer_string): + # see GH#4405 + result = series.astype(dtype) + expected = series.map(str) + if using_infer_string: + expected = expected.astype(object) + tm.assert_series_equal(result, expected) + + def test_astype_float_to_period(self): + result = Series([np.nan]).astype("period[D]") + expected = Series([NaT], dtype="period[D]") + tm.assert_series_equal(result, expected) + + def test_astype_no_pandas_dtype(self): + # https://github.com/pandas-dev/pandas/pull/24866 + ser = Series([1, 2], dtype="int64") + # Don't have NumpyEADtype in the public API, so we use `.array.dtype`, + # which is a NumpyEADtype. + result = ser.astype(ser.array.dtype) + tm.assert_series_equal(result, ser) + + @pytest.mark.parametrize("dtype", [np.datetime64, np.timedelta64]) + def test_astype_generic_timestamp_no_frequency(self, dtype, request): + # see GH#15524, GH#15987 + data = [1] + ser = Series(data) + + if np.dtype(dtype).name not in ["timedelta64", "datetime64"]: + mark = pytest.mark.xfail(reason="GH#33890 Is assigned ns unit") + request.applymarker(mark) + + msg = ( + rf"The '{dtype.__name__}' dtype has no unit\. " + rf"Please pass in '{dtype.__name__}\[ns\]' instead." + ) + with pytest.raises(ValueError, match=msg): + ser.astype(dtype) + + def test_astype_dt64_to_str(self): + # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex + dti = date_range("2012-01-01", periods=3) + result = Series(dti).astype(str) + expected = Series(["2012-01-01", "2012-01-02", "2012-01-03"], dtype=object) + tm.assert_series_equal(result, expected) + + def test_astype_dt64tz_to_str(self): + # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex + dti_tz = date_range("2012-01-01", periods=3, tz="US/Eastern") + result = Series(dti_tz).astype(str) + expected = Series( + [ + "2012-01-01 00:00:00-05:00", + "2012-01-02 00:00:00-05:00", + "2012-01-03 00:00:00-05:00", + ], + dtype=object, + ) + tm.assert_series_equal(result, expected) + + def test_astype_datetime(self, unit): + ser = Series(iNaT, dtype=f"M8[{unit}]", index=range(5)) + + ser = ser.astype("O") + assert ser.dtype == np.object_ + + ser = Series([datetime(2001, 1, 2, 0, 0)]) + + ser = ser.astype("O") + assert ser.dtype == np.object_ + + ser = Series( + [datetime(2001, 1, 2, 0, 0) for i in range(3)], dtype=f"M8[{unit}]" + ) + + ser[1] = np.nan + assert ser.dtype == f"M8[{unit}]" + + ser = ser.astype("O") + assert ser.dtype == np.object_ + + def test_astype_datetime64tz(self): + ser = Series(date_range("20130101", periods=3, tz="US/Eastern")) + + # astype + result = ser.astype(object) + expected = Series(ser.astype(object), dtype=object) + tm.assert_series_equal(result, expected) + + result = Series(ser.values).dt.tz_localize("UTC").dt.tz_convert(ser.dt.tz) + tm.assert_series_equal(result, ser) + + # astype - object, preserves on construction + result = Series(ser.astype(object)) + expected = ser.astype(object) + tm.assert_series_equal(result, expected) + + # astype - datetime64[ns, tz] + msg = "Cannot use .astype to convert from timezone-naive" + with pytest.raises(TypeError, match=msg): + # dt64->dt64tz astype deprecated + Series(ser.values).astype("datetime64[ns, US/Eastern]") + + with pytest.raises(TypeError, match=msg): + # dt64->dt64tz astype deprecated + Series(ser.values).astype(ser.dtype) + + result = ser.astype("datetime64[ns, CET]") + expected = Series(date_range("20130101 06:00:00", periods=3, tz="CET")) + tm.assert_series_equal(result, expected) + + def test_astype_str_cast_dt64(self): + # see GH#9757 + ts = Series([Timestamp("2010-01-04 00:00:00")]) + res = ts.astype(str) + + expected = Series(["2010-01-04"], dtype=object) + tm.assert_series_equal(res, expected) + + ts = Series([Timestamp("2010-01-04 00:00:00", tz="US/Eastern")]) + res = ts.astype(str) + + expected = Series(["2010-01-04 00:00:00-05:00"], dtype=object) + tm.assert_series_equal(res, expected) + + def test_astype_str_cast_td64(self): + # see GH#9757 + + td = Series([Timedelta(1, unit="d")]) + ser = td.astype(str) + + expected = Series(["1 days"], dtype=object) + tm.assert_series_equal(ser, expected) + + def test_dt64_series_astype_object(self): + dt64ser = Series(date_range("20130101", periods=3)) + result = dt64ser.astype(object) + assert isinstance(result.iloc[0], datetime) + assert result.dtype == np.object_ + + def test_td64_series_astype_object(self): + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="timedelta64[ns]") + result = tdser.astype(object) + assert isinstance(result.iloc[0], timedelta) + assert result.dtype == np.object_ + + @pytest.mark.parametrize( + "data, dtype", + [ + (["x", "y", "z"], "string[python]"), + pytest.param( + ["x", "y", "z"], + "string[pyarrow]", + marks=td.skip_if_no("pyarrow"), + ), + (["x", "y", "z"], "category"), + (3 * [Timestamp("2020-01-01", tz="UTC")], None), + (3 * [Interval(0, 1)], None), + ], + ) + @pytest.mark.parametrize("errors", ["raise", "ignore"]) + def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors): + # https://github.com/pandas-dev/pandas/issues/35471 + ser = Series(data, dtype=dtype) + if errors == "ignore": + expected = ser + result = ser.astype(float, errors="ignore") + tm.assert_series_equal(result, expected) + else: + msg = "(Cannot cast)|(could not convert)" + with pytest.raises((ValueError, TypeError), match=msg): + ser.astype(float, errors=errors) + + @pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64]) + def test_astype_from_float_to_str(self, dtype): + # https://github.com/pandas-dev/pandas/issues/36451 + ser = Series([0.1], dtype=dtype) + result = ser.astype(str) + expected = Series(["0.1"], dtype=object) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "value, string_value", + [ + (None, "None"), + (np.nan, "nan"), + (NA, ""), + ], + ) + def test_astype_to_str_preserves_na(self, value, string_value): + # https://github.com/pandas-dev/pandas/issues/36904 + ser = Series(["a", "b", value], dtype=object) + result = ser.astype(str) + expected = Series(["a", "b", string_value], dtype=object) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["float32", "float64", "int64", "int32"]) + def test_astype(self, dtype): + ser = Series(np.random.default_rng(2).standard_normal(5), name="foo") + as_typed = ser.astype(dtype) + + assert as_typed.dtype == dtype + assert as_typed.name == ser.name + + @pytest.mark.parametrize("value", [np.nan, np.inf]) + @pytest.mark.parametrize("dtype", [np.int32, np.int64]) + def test_astype_cast_nan_inf_int(self, dtype, value): + # gh-14265: check NaN and inf raise error when converting to int + msg = "Cannot convert non-finite values \\(NA or inf\\) to integer" + ser = Series([value]) + + with pytest.raises(ValueError, match=msg): + ser.astype(dtype) + + @pytest.mark.parametrize("dtype", [int, np.int8, np.int64]) + def test_astype_cast_object_int_fail(self, dtype): + arr = Series(["car", "house", "tree", "1"]) + msg = r"invalid literal for int\(\) with base 10: 'car'" + with pytest.raises(ValueError, match=msg): + arr.astype(dtype) + + def test_astype_float_to_uint_negatives_raise( + self, float_numpy_dtype, any_unsigned_int_numpy_dtype + ): + # GH#45151 We don't cast negative numbers to nonsense values + # TODO: same for EA float/uint dtypes, signed integers? + arr = np.arange(5).astype(float_numpy_dtype) - 3 # includes negatives + ser = Series(arr) + + msg = "Cannot losslessly cast from .* to .*" + with pytest.raises(ValueError, match=msg): + ser.astype(any_unsigned_int_numpy_dtype) + + with pytest.raises(ValueError, match=msg): + ser.to_frame().astype(any_unsigned_int_numpy_dtype) + + with pytest.raises(ValueError, match=msg): + # We currently catch and re-raise in Index.astype + Index(ser).astype(any_unsigned_int_numpy_dtype) + + with pytest.raises(ValueError, match=msg): + ser.array.astype(any_unsigned_int_numpy_dtype) + + def test_astype_cast_object_int(self): + arr = Series(["1", "2", "3", "4"], dtype=object) + result = arr.astype(int) + + tm.assert_series_equal(result, Series(np.arange(1, 5))) + + def test_astype_unicode(self, using_infer_string): + # see GH#7758: A bit of magic is required to set + # default encoding to utf-8 + digits = string.digits + test_series = [ + Series([digits * 10, rand_str(63), rand_str(64), rand_str(1000)]), + Series(["データーサイエンス、お前はもう死んでいる"]), + ] + + former_encoding = None + + if sys.getdefaultencoding() == "utf-8": + # GH#45326 as of 2.0 Series.astype matches Index.astype by handling + # bytes with obj.decode() instead of str(obj) + item = "野菜食べないとやばい" + ser = Series([item.encode()]) + result = ser.astype(np.str_) + expected = Series([item], dtype=object) + tm.assert_series_equal(result, expected) + + for ser in test_series: + res = ser.astype(np.str_) + expec = ser.map(str) + if using_infer_string: + expec = expec.astype(object) + tm.assert_series_equal(res, expec) + + # Restore the former encoding + if former_encoding is not None and former_encoding != "utf-8": + reload(sys) + sys.setdefaultencoding(former_encoding) + + def test_astype_bytes(self): + # GH#39474 + result = Series(["foo", "bar", "baz"]).astype(bytes) + assert result.dtypes == np.dtype("S3") + + def test_astype_nan_to_bool(self): + # GH#43018 + ser = Series(np.nan, dtype="object") + result = ser.astype("bool") + expected = Series(True, dtype="bool") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + tm.ALL_INT_EA_DTYPES + tm.FLOAT_EA_DTYPES, + ) + def test_astype_ea_to_datetimetzdtype(self, dtype): + # GH37553 + ser = Series([4, 0, 9], dtype=dtype) + result = ser.astype(DatetimeTZDtype(tz="US/Pacific")) + + expected = Series( + { + 0: Timestamp("1969-12-31 16:00:00.000000004-08:00", tz="US/Pacific"), + 1: Timestamp("1969-12-31 16:00:00.000000000-08:00", tz="US/Pacific"), + 2: Timestamp("1969-12-31 16:00:00.000000009-08:00", tz="US/Pacific"), + } + ) + + tm.assert_series_equal(result, expected) + + def test_astype_retain_attrs(self, any_numpy_dtype): + # GH#44414 + ser = Series([0, 1, 2, 3]) + ser.attrs["Location"] = "Michigan" + + result = ser.astype(any_numpy_dtype).attrs + expected = ser.attrs + + tm.assert_dict_equal(expected, result) + + +class TestAstypeString: + @pytest.mark.parametrize( + "data, dtype", + [ + ([True, NA], "boolean"), + (["A", NA], "category"), + (["2020-10-10", "2020-10-10"], "datetime64[ns]"), + (["2020-10-10", "2020-10-10", NaT], "datetime64[ns]"), + ( + ["2012-01-01 00:00:00-05:00", NaT], + "datetime64[ns, US/Eastern]", + ), + ([1, None], "UInt16"), + (["1/1/2021", "2/1/2021"], "period[M]"), + (["1/1/2021", "2/1/2021", NaT], "period[M]"), + (["1 Day", "59 Days", NaT], "timedelta64[ns]"), + # currently no way to parse IntervalArray from a list of strings + ], + ) + def test_astype_string_to_extension_dtype_roundtrip( + self, data, dtype, request, nullable_string_dtype + ): + if dtype == "boolean": + mark = pytest.mark.xfail( + reason="TODO StringArray.astype() with missing values #GH40566" + ) + request.applymarker(mark) + # GH-40351 + ser = Series(data, dtype=dtype) + + # Note: just passing .astype(dtype) fails for dtype="category" + # with bc ser.dtype.categories will be object dtype whereas + # result.dtype.categories will have string dtype + result = ser.astype(nullable_string_dtype).astype(ser.dtype) + tm.assert_series_equal(result, ser) + + +class TestAstypeCategorical: + def test_astype_categorical_to_other(self): + cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + ser = Series(np.random.default_rng(2).integers(0, 10000, 100)).sort_values() + ser = cut(ser, range(0, 10500, 500), right=False, labels=cat) + + expected = ser + tm.assert_series_equal(ser.astype("category"), expected) + tm.assert_series_equal(ser.astype(CategoricalDtype()), expected) + msg = r"Cannot cast object|string dtype to float64" + with pytest.raises(ValueError, match=msg): + ser.astype("float64") + + cat = Series(Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) + exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"], dtype=object) + tm.assert_series_equal(cat.astype("str"), exp) + s2 = Series(Categorical(["1", "2", "3", "4"])) + exp2 = Series([1, 2, 3, 4]).astype("int") + tm.assert_series_equal(s2.astype("int"), exp2) + + # object don't sort correctly, so just compare that we have the same + # values + def cmp(a, b): + tm.assert_almost_equal(np.sort(np.unique(a)), np.sort(np.unique(b))) + + expected = Series(np.array(ser.values), name="value_group") + cmp(ser.astype("object"), expected) + cmp(ser.astype(np.object_), expected) + + # array conversion + tm.assert_almost_equal(np.array(ser), np.array(ser.values)) + + tm.assert_series_equal(ser.astype("category"), ser) + tm.assert_series_equal(ser.astype(CategoricalDtype()), ser) + + roundtrip_expected = ser.cat.set_categories( + ser.cat.categories.sort_values() + ).cat.remove_unused_categories() + result = ser.astype("object").astype("category") + tm.assert_series_equal(result, roundtrip_expected) + result = ser.astype("object").astype(CategoricalDtype()) + tm.assert_series_equal(result, roundtrip_expected) + + def test_astype_categorical_invalid_conversions(self): + # invalid conversion (these are NOT a dtype) + cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + ser = Series(np.random.default_rng(2).integers(0, 10000, 100)).sort_values() + ser = cut(ser, range(0, 10500, 500), right=False, labels=cat) + + msg = ( + "dtype '' " + "not understood" + ) + with pytest.raises(TypeError, match=msg): + ser.astype(Categorical) + with pytest.raises(TypeError, match=msg): + ser.astype("object").astype(Categorical) + + def test_astype_categoricaldtype(self): + ser = Series(["a", "b", "a"]) + result = ser.astype(CategoricalDtype(["a", "b"], ordered=True)) + expected = Series(Categorical(["a", "b", "a"], ordered=True)) + tm.assert_series_equal(result, expected) + + result = ser.astype(CategoricalDtype(["a", "b"], ordered=False)) + expected = Series(Categorical(["a", "b", "a"], ordered=False)) + tm.assert_series_equal(result, expected) + + result = ser.astype(CategoricalDtype(["a", "b", "c"], ordered=False)) + expected = Series( + Categorical(["a", "b", "a"], categories=["a", "b", "c"], ordered=False) + ) + tm.assert_series_equal(result, expected) + tm.assert_index_equal(result.cat.categories, Index(["a", "b", "c"])) + + @pytest.mark.parametrize("name", [None, "foo"]) + @pytest.mark.parametrize("dtype_ordered", [True, False]) + @pytest.mark.parametrize("series_ordered", [True, False]) + def test_astype_categorical_to_categorical( + self, name, dtype_ordered, series_ordered + ): + # GH#10696, GH#18593 + s_data = list("abcaacbab") + s_dtype = CategoricalDtype(list("bac"), ordered=series_ordered) + ser = Series(s_data, dtype=s_dtype, name=name) + + # unspecified categories + dtype = CategoricalDtype(ordered=dtype_ordered) + result = ser.astype(dtype) + exp_dtype = CategoricalDtype(s_dtype.categories, dtype_ordered) + expected = Series(s_data, name=name, dtype=exp_dtype) + tm.assert_series_equal(result, expected) + + # different categories + dtype = CategoricalDtype(list("adc"), dtype_ordered) + result = ser.astype(dtype) + expected = Series(s_data, name=name, dtype=dtype) + tm.assert_series_equal(result, expected) + + if dtype_ordered is False: + # not specifying ordered, so only test once + expected = ser + result = ser.astype("category") + tm.assert_series_equal(result, expected) + + def test_astype_bool_missing_to_categorical(self): + # GH-19182 + ser = Series([True, False, np.nan]) + assert ser.dtypes == np.object_ + + result = ser.astype(CategoricalDtype(categories=[True, False])) + expected = Series(Categorical([True, False, np.nan], categories=[True, False])) + tm.assert_series_equal(result, expected) + + def test_astype_categories_raises(self): + # deprecated GH#17636, removed in GH#27141 + ser = Series(["a", "b", "a"]) + with pytest.raises(TypeError, match="got an unexpected"): + ser.astype("category", categories=["a", "b"], ordered=True) + + @pytest.mark.parametrize("items", [["a", "b", "c", "a"], [1, 2, 3, 1]]) + def test_astype_from_categorical(self, items): + ser = Series(items) + exp = Series(Categorical(items)) + res = ser.astype("category") + tm.assert_series_equal(res, exp) + + def test_astype_from_categorical_with_keywords(self): + # with keywords + lst = ["a", "b", "c", "a"] + ser = Series(lst) + exp = Series(Categorical(lst, ordered=True)) + res = ser.astype(CategoricalDtype(None, ordered=True)) + tm.assert_series_equal(res, exp) + + exp = Series(Categorical(lst, categories=list("abcdef"), ordered=True)) + res = ser.astype(CategoricalDtype(list("abcdef"), ordered=True)) + tm.assert_series_equal(res, exp) + + def test_astype_timedelta64_with_np_nan(self): + # GH45798 + result = Series([Timedelta(1), np.nan], dtype="timedelta64[ns]") + expected = Series([Timedelta(1), NaT], dtype="timedelta64[ns]") + tm.assert_series_equal(result, expected) + + @td.skip_if_no("pyarrow") + def test_astype_int_na_string(self): + # GH#57418 + ser = Series([12, NA], dtype="Int64[pyarrow]") + result = ser.astype("string[pyarrow]") + expected = Series(["12", NA], dtype="string[pyarrow]") + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/7c/7cf6b6a644021a7973c3e7bdab9ae4ddd88ff9cf76c257e9702171999a68e734/annotate_warns.h b/shared/package-files/7c/7cf6b6a644021a7973c3e7bdab9ae4ddd88ff9cf76c257e9702171999a68e734/annotate_warns.h new file mode 100644 index 0000000000000000000000000000000000000000..5a683c2b5034bd7f17ea20626c3591e21a5a798a --- /dev/null +++ b/shared/package-files/7c/7cf6b6a644021a7973c3e7bdab9ae4ddd88ff9cf76c257e9702171999a68e734/annotate_warns.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void AnnotateWarns(const std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/shared/package-files/7c/7cf925e201ca80c58dd01aeb7c502b4a3070f13fac4815374bdeb584457dd5b2/_foreach_atan_ops.h b/shared/package-files/7c/7cf925e201ca80c58dd01aeb7c502b4a3070f13fac4815374bdeb584457dd5b2/_foreach_atan_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e6f446e112d8c2f9414451414d9682c40e141e79 --- /dev/null +++ b/shared/package-files/7c/7cf925e201ca80c58dd01aeb7c502b4a3070f13fac4815374bdeb584457dd5b2/_foreach_atan_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_atan { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_atan"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_atan(Tensor[] self) -> Tensor[]"; + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_atan_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_atan_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_atan_(Tensor(a!)[] self) -> ()"; + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_atan_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_atan"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_foreach_atan.out(Tensor[] self, *, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/7c/7cfe50d356157e36f31274176e4ccfa44b5d08b7a8745c61239ab798c20f120b/cutlass_utils.cpython-311.pyc b/shared/package-files/7c/7cfe50d356157e36f31274176e4ccfa44b5d08b7a8745c61239ab798c20f120b/cutlass_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5e280605888a9dfce85d5cc1314db0c4ce28d17 Binary files /dev/null and b/shared/package-files/7c/7cfe50d356157e36f31274176e4ccfa44b5d08b7a8745c61239ab798c20f120b/cutlass_utils.cpython-311.pyc differ diff --git a/shared/package-files/7c/7cfefe460704f221cd899e95f650478a2a43a88593f6ddf8e556eb8268f744eb/_validate_sparse_csc_tensor_args_ops.h b/shared/package-files/7c/7cfefe460704f221cd899e95f650478a2a43a88593f6ddf8e556eb8268f744eb/_validate_sparse_csc_tensor_args_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..65993645fd6f2f651b372ab4f557c73a6f90fff4 --- /dev/null +++ b/shared/package-files/7c/7cfefe460704f221cd899e95f650478a2a43a88593f6ddf8e556eb8268f744eb/_validate_sparse_csc_tensor_args_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _validate_sparse_csc_tensor_args { + using schema = void (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_validate_sparse_csc_tensor_args"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_validate_sparse_csc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size) -> ()"; + static void call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size); + static void redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/93/9308ddc6e8e8fd0b7897be6da7f8aba4863f065caabde86ef7c3765297da9cff/frac_native.h b/shared/package-files/93/9308ddc6e8e8fd0b7897be6da7f8aba4863f065caabde86ef7c3765297da9cff/frac_native.h new file mode 100644 index 0000000000000000000000000000000000000000..af00a64acc1589b90a7835c95907d03f977bb7fa --- /dev/null +++ b/shared/package-files/93/9308ddc6e8e8fd0b7897be6da7f8aba4863f065caabde86ef7c3765297da9cff/frac_native.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_frac_out : public at::meta::structured_frac { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +TORCH_API at::Tensor frac_sparse(const at::Tensor & self); +TORCH_API at::Tensor & frac_sparse_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & frac_sparse_(at::Tensor & self); +TORCH_API at::Tensor frac_sparse_csr(const at::Tensor & self); +TORCH_API at::Tensor & frac_sparse_csr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & frac_sparse_csr_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/93/930dd45d3320a5380e1bc48ad69c443a5033d404b396f31115fe91b7ebca2552/yaml_utils.py b/shared/package-files/93/930dd45d3320a5380e1bc48ad69c443a5033d404b396f31115fe91b7ebca2552/yaml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..720d1944602e7c810138d71d7cf60fe351f87500 --- /dev/null +++ b/shared/package-files/93/930dd45d3320a5380e1bc48ad69c443a5033d404b396f31115fe91b7ebca2552/yaml_utils.py @@ -0,0 +1,26 @@ +# Safely load fast C Yaml loader/dumper if they are available +try: + from yaml import CSafeLoader as Loader +except ImportError: + from yaml import SafeLoader as Loader # type: ignore[assignment, misc] + +try: + from yaml import CSafeDumper as Dumper +except ImportError: + from yaml import SafeDumper as Dumper # type: ignore[assignment, misc] +YamlDumper = Dumper + + +# A custom loader for YAML that errors on duplicate keys. +# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165 +class YamlLoader(Loader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] + assert key not in mapping, ( + f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}" + ) + mapping.append(key) + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + return mapping diff --git a/shared/package-files/93/931b62c781e9c6ed296b3e3a4c70522d9cb5326b578fbc98e88677fb8698fc53/rewriting.cpython-311.pyc b/shared/package-files/93/931b62c781e9c6ed296b3e3a4c70522d9cb5326b578fbc98e88677fb8698fc53/rewriting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef78b321ff6a598c8d1f48124082662057d73ae5 Binary files /dev/null and b/shared/package-files/93/931b62c781e9c6ed296b3e3a4c70522d9cb5326b578fbc98e88677fb8698fc53/rewriting.cpython-311.pyc differ diff --git a/shared/package-files/93/932563d198978fdd0a563286c6d9c1201790dbd0cf7beb99298f02c14fa9939f/epathtools.cpython-311.pyc b/shared/package-files/93/932563d198978fdd0a563286c6d9c1201790dbd0cf7beb99298f02c14fa9939f/epathtools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0c1509f08295cb954dd23c9ac95df6ca26964c3 Binary files /dev/null and b/shared/package-files/93/932563d198978fdd0a563286c6d9c1201790dbd0cf7beb99298f02c14fa9939f/epathtools.cpython-311.pyc differ diff --git a/shared/package-files/93/933087a970ed71919540f967e76d657cde6b79d3708fa2235c9c236effc39218/kronecker.py b/shared/package-files/93/933087a970ed71919540f967e76d657cde6b79d3708fa2235c9c236effc39218/kronecker.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd175cb0d500af3e786e2d0dbf6b010947840b4 --- /dev/null +++ b/shared/package-files/93/933087a970ed71919540f967e76d657cde6b79d3708fa2235c9c236effc39218/kronecker.py @@ -0,0 +1,434 @@ +"""Implementation of the Kronecker product""" +from functools import reduce +from math import prod + +from sympy.core import Mul, sympify +from sympy.functions import adjoint +from sympy.matrices.exceptions import ShapeError +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.transpose import transpose +from sympy.matrices.expressions.special import Identity +from sympy.matrices.matrixbase import MatrixBase +from sympy.strategies import ( + canon, condition, distribute, do_one, exhaust, flatten, typed, unpack) +from sympy.strategies.traverse import bottom_up +from sympy.utilities import sift + +from .matadd import MatAdd +from .matmul import MatMul +from .matpow import MatPow + + +def kronecker_product(*matrices): + """ + The Kronecker product of two or more arguments. + + This computes the explicit Kronecker product for subclasses of + ``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic + ``KroneckerProduct`` object is returned. + + + Examples + ======== + + For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned. + Elements of this matrix can be obtained by indexing, or for MatrixSymbols + with known dimension the explicit matrix can be obtained with + ``.as_explicit()`` + + >>> from sympy import kronecker_product, MatrixSymbol + >>> A = MatrixSymbol('A', 2, 2) + >>> B = MatrixSymbol('B', 2, 2) + >>> kronecker_product(A) + A + >>> kronecker_product(A, B) + KroneckerProduct(A, B) + >>> kronecker_product(A, B)[0, 1] + A[0, 0]*B[0, 1] + >>> kronecker_product(A, B).as_explicit() + Matrix([ + [A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]], + [A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]], + [A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]], + [A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]]) + + For explicit matrices the Kronecker product is returned as a Matrix + + >>> from sympy import Matrix, kronecker_product + >>> sigma_x = Matrix([ + ... [0, 1], + ... [1, 0]]) + ... + >>> Isigma_y = Matrix([ + ... [0, 1], + ... [-1, 0]]) + ... + >>> kronecker_product(sigma_x, Isigma_y) + Matrix([ + [ 0, 0, 0, 1], + [ 0, 0, -1, 0], + [ 0, 1, 0, 0], + [-1, 0, 0, 0]]) + + See Also + ======== + KroneckerProduct + + """ + if not matrices: + raise TypeError("Empty Kronecker product is undefined") + if len(matrices) == 1: + return matrices[0] + else: + return KroneckerProduct(*matrices).doit() + + +class KroneckerProduct(MatrixExpr): + """ + The Kronecker product of two or more arguments. + + The Kronecker product is a non-commutative product of matrices. + Given two matrices of dimension (m, n) and (s, t) it produces a matrix + of dimension (m s, n t). + + This is a symbolic object that simply stores its argument without + evaluating it. To actually compute the product, use the function + ``kronecker_product()`` or call the ``.doit()`` or ``.as_explicit()`` + methods. + + >>> from sympy import KroneckerProduct, MatrixSymbol + >>> A = MatrixSymbol('A', 5, 5) + >>> B = MatrixSymbol('B', 5, 5) + >>> isinstance(KroneckerProduct(A, B), KroneckerProduct) + True + """ + is_KroneckerProduct = True + + def __new__(cls, *args, check=True): + args = list(map(sympify, args)) + if all(a.is_Identity for a in args): + ret = Identity(prod(a.rows for a in args)) + if all(isinstance(a, MatrixBase) for a in args): + return ret.as_explicit() + else: + return ret + + if check: + validate(*args) + return super().__new__(cls, *args) + + @property + def shape(self): + rows, cols = self.args[0].shape + for mat in self.args[1:]: + rows *= mat.rows + cols *= mat.cols + return (rows, cols) + + def _entry(self, i, j, **kwargs): + result = 1 + for mat in reversed(self.args): + i, m = divmod(i, mat.rows) + j, n = divmod(j, mat.cols) + result *= mat[m, n] + return result + + def _eval_adjoint(self): + return KroneckerProduct(*list(map(adjoint, self.args))).doit() + + def _eval_conjugate(self): + return KroneckerProduct(*[a.conjugate() for a in self.args]).doit() + + def _eval_transpose(self): + return KroneckerProduct(*list(map(transpose, self.args))).doit() + + def _eval_trace(self): + from .trace import trace + return Mul(*[trace(a) for a in self.args]) + + def _eval_determinant(self): + from .determinant import det, Determinant + if not all(a.is_square for a in self.args): + return Determinant(self) + + m = self.rows + return Mul(*[det(a)**(m/a.rows) for a in self.args]) + + def _eval_inverse(self): + try: + return KroneckerProduct(*[a.inverse() for a in self.args]) + except ShapeError: + from sympy.matrices.expressions.inverse import Inverse + return Inverse(self) + + def structurally_equal(self, other): + '''Determine whether two matrices have the same Kronecker product structure + + Examples + ======== + + >>> from sympy import KroneckerProduct, MatrixSymbol, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, m) + >>> B = MatrixSymbol('B', n, n) + >>> C = MatrixSymbol('C', m, m) + >>> D = MatrixSymbol('D', n, n) + >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D)) + True + >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C)) + False + >>> KroneckerProduct(A, B).structurally_equal(C) + False + ''' + # Inspired by BlockMatrix + return (isinstance(other, KroneckerProduct) + and self.shape == other.shape + and len(self.args) == len(other.args) + and all(a.shape == b.shape for (a, b) in zip(self.args, other.args))) + + def has_matching_shape(self, other): + '''Determine whether two matrices have the appropriate structure to bring matrix + multiplication inside the KroneckerProdut + + Examples + ======== + >>> from sympy import KroneckerProduct, MatrixSymbol, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', n, m) + >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A)) + True + >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B)) + False + >>> KroneckerProduct(A, B).has_matching_shape(A) + False + ''' + return (isinstance(other, KroneckerProduct) + and self.cols == other.rows + and len(self.args) == len(other.args) + and all(a.cols == b.rows for (a, b) in zip(self.args, other.args))) + + def _eval_expand_kroneckerproduct(self, **hints): + return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self)) + + def _kronecker_add(self, other): + if self.structurally_equal(other): + return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)]) + else: + return self + other + + def _kronecker_mul(self, other): + if self.has_matching_shape(other): + return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)]) + else: + return self * other + + def doit(self, **hints): + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + else: + args = self.args + return canonicalize(KroneckerProduct(*args)) + + +def validate(*args): + if not all(arg.is_Matrix for arg in args): + raise TypeError("Mix of Matrix and Scalar symbols") + + +# rules + +def extract_commutative(kron): + c_part = [] + nc_part = [] + for arg in kron.args: + c, nc = arg.args_cnc() + c_part.extend(c) + nc_part.append(Mul._from_args(nc)) + + c_part = Mul(*c_part) + if c_part != 1: + return c_part*KroneckerProduct(*nc_part) + return kron + + +def matrix_kronecker_product(*matrices): + """Compute the Kronecker product of a sequence of SymPy Matrices. + + This is the standard Kronecker product of matrices [1]. + + Parameters + ========== + + matrices : tuple of MatrixBase instances + The matrices to take the Kronecker product of. + + Returns + ======= + + matrix : MatrixBase + The Kronecker product matrix. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.matrices.expressions.kronecker import ( + ... matrix_kronecker_product) + + >>> m1 = Matrix([[1,2],[3,4]]) + >>> m2 = Matrix([[1,0],[0,1]]) + >>> matrix_kronecker_product(m1, m2) + Matrix([ + [1, 0, 2, 0], + [0, 1, 0, 2], + [3, 0, 4, 0], + [0, 3, 0, 4]]) + >>> matrix_kronecker_product(m2, m1) + Matrix([ + [1, 2, 0, 0], + [3, 4, 0, 0], + [0, 0, 1, 2], + [0, 0, 3, 4]]) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Kronecker_product + """ + # Make sure we have a sequence of Matrices + if not all(isinstance(m, MatrixBase) for m in matrices): + raise TypeError( + 'Sequence of Matrices expected, got: %s' % repr(matrices) + ) + + # Pull out the first element in the product. + matrix_expansion = matrices[-1] + # Do the kronecker product working from right to left. + for mat in reversed(matrices[:-1]): + rows = mat.rows + cols = mat.cols + # Go through each row appending kronecker product to. + # running matrix_expansion. + for i in range(rows): + start = matrix_expansion*mat[i*cols] + # Go through each column joining each item + for j in range(cols - 1): + start = start.row_join( + matrix_expansion*mat[i*cols + j + 1] + ) + # If this is the first element, make it the start of the + # new row. + if i == 0: + next = start + else: + next = next.col_join(start) + matrix_expansion = next + + MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__ + if isinstance(matrix_expansion, MatrixClass): + return matrix_expansion + else: + return MatrixClass(matrix_expansion) + + +def explicit_kronecker_product(kron): + # Make sure we have a sequence of Matrices + if not all(isinstance(m, MatrixBase) for m in kron.args): + return kron + + return matrix_kronecker_product(*kron.args) + + +rules = (unpack, + explicit_kronecker_product, + flatten, + extract_commutative) + +canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct), + do_one(*rules))) + + +def _kronecker_dims_key(expr): + if isinstance(expr, KroneckerProduct): + return tuple(a.shape for a in expr.args) + else: + return (0,) + + +def kronecker_mat_add(expr): + args = sift(expr.args, _kronecker_dims_key) + nonkrons = args.pop((0,), None) + if not args: + return expr + + krons = [reduce(lambda x, y: x._kronecker_add(y), group) + for group in args.values()] + + if not nonkrons: + return MatAdd(*krons) + else: + return MatAdd(*krons) + nonkrons + + +def kronecker_mat_mul(expr): + # modified from block matrix code + factor, matrices = expr.as_coeff_matrices() + + i = 0 + while i < len(matrices) - 1: + A, B = matrices[i:i+2] + if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct): + matrices[i] = A._kronecker_mul(B) + matrices.pop(i+1) + else: + i += 1 + + return factor*MatMul(*matrices) + + +def kronecker_mat_pow(expr): + if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args): + return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args]) + else: + return expr + + +def combine_kronecker(expr): + """Combine KronekeckerProduct with expression. + + If possible write operations on KroneckerProducts of compatible shapes + as a single KroneckerProduct. + + Examples + ======== + + >>> from sympy.matrices.expressions import combine_kronecker + >>> from sympy import MatrixSymbol, KroneckerProduct, symbols + >>> m, n = symbols(r'm, n', integer=True) + >>> A = MatrixSymbol('A', m, n) + >>> B = MatrixSymbol('B', n, m) + >>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A)) + KroneckerProduct(A*B, B*A) + >>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T)) + KroneckerProduct(A + B.T, B + A.T) + >>> C = MatrixSymbol('C', n, n) + >>> D = MatrixSymbol('D', m, m) + >>> combine_kronecker(KroneckerProduct(C, D)**m) + KroneckerProduct(C**m, D**m) + """ + def haskron(expr): + return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct) + + rule = exhaust( + bottom_up(exhaust(condition(haskron, typed( + {MatAdd: kronecker_mat_add, + MatMul: kronecker_mat_mul, + MatPow: kronecker_mat_pow}))))) + result = rule(expr) + doit = getattr(result, 'doit', None) + if doit is not None: + return doit() + else: + return result diff --git a/shared/package-files/93/9333be2e13794a5555a253f088cce9698bac9b52da159bcf177373979252cdcc/chi2.cpython-311.pyc b/shared/package-files/93/9333be2e13794a5555a253f088cce9698bac9b52da159bcf177373979252cdcc/chi2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..598167af9746df0b1a7d0413ef5246c39187de84 Binary files /dev/null and b/shared/package-files/93/9333be2e13794a5555a253f088cce9698bac9b52da159bcf177373979252cdcc/chi2.cpython-311.pyc differ diff --git a/shared/package-files/93/9333d041130c0e59f6d9bffc5134f756cd60ad7c82b794da050628364efb1e33/primetest.cpython-311.pyc b/shared/package-files/93/9333d041130c0e59f6d9bffc5134f756cd60ad7c82b794da050628364efb1e33/primetest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcdab26ad9d030abc364d8e458efa7c36b44f1a5 Binary files /dev/null and b/shared/package-files/93/9333d041130c0e59f6d9bffc5134f756cd60ad7c82b794da050628364efb1e33/primetest.cpython-311.pyc differ diff --git a/shared/package-files/93/9336afa7d6a1b90e43d7df9b30b8a43cc807f713ce52dfdd91b21a9ede74dbfb/SymFloat.h b/shared/package-files/93/9336afa7d6a1b90e43d7df9b30b8a43cc807f713ce52dfdd91b21a9ede74dbfb/SymFloat.h new file mode 100644 index 0000000000000000000000000000000000000000..d30b646a653fd08ffc24acb89a4fa59a6605959f --- /dev/null +++ b/shared/package-files/93/9336afa7d6a1b90e43d7df9b30b8a43cc807f713ce52dfdd91b21a9ede74dbfb/SymFloat.h @@ -0,0 +1,118 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace c10 { + +// NB: this is actually double precision; we're using the Python naming here +class C10_API SymFloat { + public: + /*implicit*/ SymFloat(double d) : data_(d) {} + SymFloat(SymNode ptr) + : data_(std::numeric_limits::quiet_NaN()), ptr_(std::move(ptr)) { + TORCH_CHECK(ptr_->is_float()); + } + SymFloat() : data_(0.0) {} + + SymNodeImpl* toSymNodeImplUnowned() const { + return ptr_.get(); + } + + SymNodeImpl* release() && { + return std::move(ptr_).release(); + } + + // Only valid if is_symbolic() + SymNode toSymNodeImpl() const; + + // Guaranteed to return a SymNode, wrapping using base if necessary + SymNode wrap_node(const SymNode& base) const; + + double expect_float() const { + TORCH_CHECK(!is_symbolic()); + return data_; + } + + SymFloat operator+(const SymFloat&) const; + SymFloat operator-(const SymFloat&) const; + SymFloat operator*(const SymFloat&) const; + SymFloat operator/(const SymFloat&) const; + + SymBool sym_eq(const SymFloat&) const; + SymBool sym_ne(const SymFloat&) const; + SymBool sym_lt(const SymFloat&) const; + SymBool sym_le(const SymFloat&) const; + SymBool sym_gt(const SymFloat&) const; + SymBool sym_ge(const SymFloat&) const; + + bool operator==(const SymFloat& o) const { + return sym_eq(o).guard_bool(__FILE__, __LINE__); + } + bool operator!=(const SymFloat& o) const { + return sym_ne(o).guard_bool(__FILE__, __LINE__); + } + bool operator<(const SymFloat& o) const { + return sym_lt(o).guard_bool(__FILE__, __LINE__); + } + bool operator<=(const SymFloat& o) const { + return sym_le(o).guard_bool(__FILE__, __LINE__); + } + bool operator>(const SymFloat& o) const { + return sym_gt(o).guard_bool(__FILE__, __LINE__); + } + bool operator>=(const SymFloat& o) const { + return sym_ge(o).guard_bool(__FILE__, __LINE__); + } + + SymFloat min(const SymFloat& sci) const; + SymFloat max(const SymFloat& sci) const; + + // Need guidance on where to put this code + SymFloat sqrt() const; + + // Insert a guard for the float to be its concrete value, and then return + // that value. This operation always works, even if the float is symbolic, + // so long as we know what the underlying value is. Don't blindly put this + // everywhere; you can cause overspecialization of PyTorch programs with + // this method. + // + // It should be called as guard_float(__FILE__, __LINE__). The file and line + // number can be used to diagnose overspecialization. + double guard_float(const char* file, int64_t line) const; + + bool has_hint() const; + + // N.B. It's important to keep this definition in the header + // as we expect if checks to be folded for mobile builds + // where `is_symbolic` is always false + C10_ALWAYS_INLINE bool is_symbolic() const { + return ptr_; + } + + // UNSAFELY coerce this SymFloat into a double. You MUST have + // established that this is a non-symbolic by some other means, + // typically by having tested is_symbolic(). You will get garbage + // from this function if is_symbolic() + double as_float_unchecked() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!is_symbolic()); + return data_; + } + + private: + // TODO: optimize to union + double data_; + SymNode ptr_; +}; + +C10_API std::ostream& operator<<(std::ostream& os, const SymFloat& s); +} // namespace c10 diff --git a/shared/package-files/93/9336fac577f97965d08a7f5936ecb23d8d8e7c439526dff0b6dc94c252d1119a/network2.cpython-311.pyc b/shared/package-files/93/9336fac577f97965d08a7f5936ecb23d8d8e7c439526dff0b6dc94c252d1119a/network2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f614e8a9755ce02f2f74cc0029e44c0657e8a663 Binary files /dev/null and b/shared/package-files/93/9336fac577f97965d08a7f5936ecb23d8d8e7c439526dff0b6dc94c252d1119a/network2.cpython-311.pyc differ diff --git a/shared/package-files/93/9339ec3d2501511d7dcc699a516012fa888a4e37e03c0a545cdfeefd1f288d87/autograd_function.py b/shared/package-files/93/9339ec3d2501511d7dcc699a516012fa888a4e37e03c0a545cdfeefd1f288d87/autograd_function.py new file mode 100644 index 0000000000000000000000000000000000000000..bc715c44ed85aafae9f598ef883ebe3b80e53536 --- /dev/null +++ b/shared/package-files/93/9339ec3d2501511d7dcc699a516012fa888a4e37e03c0a545cdfeefd1f288d87/autograd_function.py @@ -0,0 +1,777 @@ +# mypy: allow-untyped-defs +from typing import NamedTuple + +import torch +import torch.utils._pytree as pytree +from torch._C._functorch import ( + _unwrap_for_grad, + _wrap_for_grad, + current_level, + TransformType, +) +from torch._functorch.apis import vmap +from torch._functorch.utils import enable_single_level_autograd_function +from torch._functorch.vmap import ( + _add_batch_dim, + _broadcast_to_and_flatten, + restore_vmap, + unwrap_batched, + wrap_batched, +) +from torch._ops import HigherOrderOperator +from torch.autograd.forward_ad import _set_fwd_grad_enabled + + +# autograd.Function technically runs before the regular PyTorch dispatcher. +# This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot) +# work with it. One day we might decide to change this, but until then, +# we need to give the illusion that autograd.Function runs before those things. +# +# We do this by using creating a custom HigherOrderOperator that only functorch +# dispatches specially. +class CustomFunctionHigherOrderOperator(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("custom_function_call") + + def __call__(self, autograd_function, *args, **kwargs): + # When custom_function_call is done dispatching through functorch, + # it should just invoke the autograd.Function. This is consistent + # with the autograd.Function behavior of being invoked before the + # PyTorch dispatcher. + # + # This will lead us into trouble later down the line, but this is + # pre-existing. There is an invariant that a function traced by + # make_fx should have the same behavior when provided the same + # Tensor. However, make_fx sees autograd.Function as a composite + # (because autograd.Function happens before the Python dispatch key) + # and only traces the forward pass. + if torch._C._are_functorch_transforms_active(): + return super().__call__(autograd_function, *args, **kwargs) + return autograd_function.apply(*args, **kwargs) + + +# "custom_function_call" +# This is the mechanism for an autograd.Function that works with functorch transforms. +# It wraps an autograd.Function; interactions with functorch transforms are defined +# via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch +# dispatcher. +custom_function_call = CustomFunctionHigherOrderOperator() + + +# The grad rule for custom_function_call is to construct a new _SingleLevelFunction +# (autograd.Function that only works with a single layer (level) of functorch) that: +# - unwraps the inputs +# - redispatches to custom_function_call +# - wraps the outputs +# and whose backward pass calls the original autograd.Function's backward. +# +# Why do we need to redispatch to custom_function_call? +# ----------------------------------------------------- +# This is consistent with how ATen operators work with functorch's grad transform: +# they always redispatch to the original operator. +# Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x) +# +# grad1 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin (*) +# - rewrap the outputs on the return +# +# On the redispatch in (*), grad0 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin +# - rewrap the outputs on the return +# +# To "set up the autograd graph", we generate a _SingleLevelFunction +# and apply it. +@custom_function_call.py_impl(TransformType.Grad) +@custom_function_call.py_impl(TransformType.Jvp) +def custom_function_call_grad(interpreter, autograd_function, *operands): + Generated = generate_single_level_function(interpreter, autograd_function) + with enable_single_level_autograd_function(): + flat_out = Generated.apply(*operands) + return flat_out + + +def generate_single_level_function(interpreter, autograd_function): + level = interpreter.level() + + def forward(*operands): + unwrapped_operands = pytree.tree_map_only( + torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands + ) + # Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter + # the transform. _SingleLevelFunction will turn off both fwd and bwd + # gradient computation and we need to turn it back on here. + with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower(): + unwrapped_output = custom_function_call( + autograd_function, *unwrapped_operands + ) + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output): + return _wrap_for_grad(output, level) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn + ) + + def setup_context(ctx, inputs, output): + return autograd_function.setup_context(ctx, inputs, output) + + # backward is only used if the transform is TransformType.Grad + def backward(ctx, *grads): + result = autograd_function.backward(ctx, *grads) + return result + + # jvp is only used if the transform is TransformType.Jvp + def jvp(ctx, *tangents): + result = autograd_function.jvp(ctx, *tangents) + return result + + # This is the sequence of magic words to dynamically generate a Subclass with + # a given name. A Tensor's .grad_fn field has a class name that is the original + # autograd.Function's name + Backward, so we do this to generate some + # meaningful name. + name = f"{autograd_function.__name__}Generated" + Generated = type( + name, + (torch.autograd.function._SingleLevelFunction,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + }, + ) + return Generated + + +# wrap_outputs_maintaining_identity handles outputs from the vmap, +# backward (vjp), and jvp staticmethod. The way it distinguishes +# between the vmap case and the {backward, jvp} case is if the out_dims +# are specified or not. +# +# NB: we cannot use out_dims=None as the deciding factor. This because +# out_dims=None can still happen in the vmap staticmethod! What the +# user is saying in that case is that their output does not have a +# dimension that is being vmapped over, which is valid. +NO_OUT_DIMS = "not specified" + + +# NOTE [mark_dirty object identity check] +# autograd.Function's ctx.mark_dirty expect a returned input +# to have the same object identity as the input. +# Mode-only functorch will greatly simplify this logic. +def wrap_outputs_maintaining_identity( + outputs, unwrapped_inputs, orig_inputs, wrap_fn, out_dims=NO_OUT_DIMS +): + flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs) + flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs) + + unwrapped_input_to_orig_input = { + id(unwrapped): orig + for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs) + } + + flat_outputs, spec = pytree.tree_flatten(outputs) + result = [] + + out_dims_specified = out_dims != NO_OUT_DIMS + + if out_dims_specified: + flat_out_dims = _broadcast_to_and_flatten(out_dims, spec) + # _broadcast_to_and_flatten returns None if it is unable to broadcast. + # TODO: update following link from master to stable once that's out + if flat_out_dims is None: + raise RuntimeError( + f"The autograd.Function's vmap staticmethod returned an " + f"incompatible (output, out_dims) tuple. " + f"Expected out_dims={out_dims} " + f"to be compatible with the structure of `output`. " + f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} " + f"but output has structure {spec}. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + for i, output in enumerate(flat_outputs): + if not isinstance(output, torch.Tensor): + result.append(output) + continue + if id(output) in unwrapped_input_to_orig_input: + result.append(unwrapped_input_to_orig_input[id(output)]) + continue + if out_dims_specified: + result.append(wrap_fn(output, flat_out_dims[i])) # type: ignore[possibly-undefined, index] + else: + result.append(wrap_fn(output)) + + return pytree.tree_unflatten(result, spec) + + +# NOTE: [functorch vjp and autograd interaction] +# There's an edge case with the functorch vjp and autograd interaction +# that will eventually be fixed by mode-only functorch. +# The TL;DR is that there's no way to unwrap a dead GradTensorWrapper, +# so we (the framework) need to do it manually. Regular PyTorch operators +# automatically do so this is consistent. +# +# class MyExp(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.exp() +# +# @staticmethod +# def setup_context(ctx, inputs, output): +# y = output +# ctx.save_for_backward(y) +# +# @staticmethod +# def backward(gy): +# y, = ctx.saved_tensors() +# return MyMul.apply(gy, y) +# +# x = torch.randn([], requires_grad=True) +# gy = torch.randn([], requires_grad=True) +# _, vjp_fn = vjp(MySin.apply, x) +# result = vjp_fn(gy) +# +# MyMul is an autograd.Function that is not shown here. +# It saves a `y` for backward (since gy requires grad). +# +# in vjp_fn(gy), we get: +# > MyMul.apply(gy, GradTensorWrapper(y, level=dead)) +# Because the y that is saved for backward by MyExp is a GradTensorWrapper +# but is now dead since we are outside the vjp context. +# +# PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper, +# will automatically unwrap the GradTensorWrapper when applied. +# But since autograd.Function technically sits above the regular PyTorch +# dispatcher, it doesn't get this treatment. So we manually do +# the unwrapping to be consistent with regular PyTorch dispatcher operations. + + +class VmapInfo(NamedTuple): + batch_size: int + randomness: str + + +def has_overriden_vmap_rule(autograd_function): + return autograd_function.vmap is not torch.autograd.Function.vmap + + +def validate_vmap_returns_tuple_of_two_elements(result): + base_error_msg = ( + "Expected the vmap staticmethod to have two returns, an output " + "and out_dims with pytree structure compatible with the output. " + ) + if not isinstance(result, tuple): + raise RuntimeError(base_error_msg + f"Got a {type(result)} instead") + if not len(result) == 2: + raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead") + + +@custom_function_call.py_impl(TransformType.Vmap) +def custom_function_call_vmap(interpreter, autograd_function, *operands, **kwargs): + if any( + isinstance(val, torch.Tensor) + for val in torch.utils._pytree.tree_flatten(kwargs)[0] + ): + raise NotImplementedError( + f"Run vmap on autograd.Function with kwarg-only Tensor args. " + f"Please do not pass kwarg-only Tensors to autograd.Function. " + f"Got: {kwargs}" + ) + + if autograd_function.generate_vmap_rule: + if has_overriden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it has both generate_vmap_rule=True and an overriden vmap " + f"staticmethod. Please set generate_vmap_rule=False or delete " + f"the overriden vmap staticmethod to avoid ambiguity. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + return custom_function_call_vmap_generate_rule( + interpreter, autograd_function, *operands + ) + + if not has_overriden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it does not have vmap support. Please override and implement the " + f"vmap staticmethod or set generate_vmap_rule=True. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + return custom_function_call_vmap_helper( + interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs + ) + + +def custom_function_call_vmap_helper( + interpreter, vmap_function, op, *operands, **kwargs +): + current_level = interpreter.level() + info = VmapInfo( + batch_size=interpreter.batch_size(), + randomness=interpreter.randomness(), + ) + # We're either in the autograd.Function case (vmap staticmethod) + # or the torch.library.register_vmap case. + autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta) + + def lower_to_next(): + if autograd_function_case: + return interpreter.lower() + else: + return torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched) + ) + + unwrapped_operands, in_dims = unwrap_batched(operands, current_level) + # If none of the tensors are batched at the current level, then we skip the + # current level. This saves the user from needing to handle this case in + # their vmap staticmethod (and is consistent with our C++ batching rule API) + if pytree.tree_all(lambda dim: dim is None, in_dims): + with lower_to_next(): + if autograd_function_case: + return custom_function_call(op, *operands) + else: + return op(*operands, **kwargs) + + with lower_to_next(): + result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs) + validate_vmap_returns_tuple_of_two_elements(result) + unwrapped_output, out_dims = result + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output, out_dim): + return ( + output + if out_dim is None + else _add_batch_dim(output, out_dim, current_level) + ) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims + ) + + +def unpack_outputs(outputs): + out_dims = outputs[-1] + if isinstance(out_dims, tuple): + outputs = outputs[:-1] + else: + outputs = outputs[0] + return outputs, out_dims + + +def custom_function_call_vmap_generate_rule(interpreter, autograd_function, *operands): + unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level()) + vmapped_function = vmapify_autograd_function( + autograd_function, in_dims, interpreter.batch_size(), interpreter.randomness() + ) + with interpreter.lower(): + outputs = custom_function_call(vmapped_function, *unwrapped_operands) + + assert isinstance(outputs, tuple) + outputs, out_dims = unpack_outputs(outputs) + return wrap_batched(outputs, out_dims, interpreter.level()) + + +@custom_function_call.py_impl(TransformType.Functionalize) +def custom_function_call_functionalize( + interpreter, autograd_function, generate_vmap_rule, *operands +): + raise RuntimeError("NYI: Functionalize rule for custom_function_call") + + +def vmapify_autograd_function(autograd_function, in_dims, batch_size, randomness): + def forward(*operands): + outputs, out_dims = restore_vmap( + autograd_function.forward, in_dims, batch_size, randomness + )(*operands) + if isinstance(outputs, torch.Tensor): + return outputs, out_dims + else: + return *outputs, out_dims + + def setup_context(ctx, inputs, outputs): + outputs, out_dims = unpack_outputs(outputs) + key = id(Generated) + + def inner(inputs, outputs): + # wrapped_ctx.save_for_backward will: + # - unwrap batchedtensors into (tensor, bdim) + # - save_for_backward(*unwrapped_tensors) + # - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims + wrapped_ctx = CtxCustomSave(ctx, current_level()) + autograd_function.setup_context(wrapped_ctx, inputs, outputs) + + # input_shapes are used for reductify later to reduce expanded gradients + # to the correct shape. + # See NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # for more details + input_shapes = tuple( + inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs + ) + if not hasattr(ctx, "_pt_input_shapes"): + ctx._pt_input_shapes = {} + ctx._pt_input_shapes.update({key: input_shapes}) + + if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"): + ctx._pt_saved_tensors_bdims_stack = {} + ctx._pt_saved_tensors_bdims_stack.update( + {key: (wrapped_ctx._pt_saved_tensors_bdims)} + ) + + # See NOTE: [Why do we need to run setup_context under a vmap?] + restore_vmap( + inner, + (in_dims, out_dims), + batch_size, + randomness, + )(inputs, outputs) + + if not hasattr(ctx, "_pt_out_dims"): + ctx._pt_out_dims = {} + ctx._pt_out_dims.update({key: out_dims}) + + def jvp(ctx, *tangents): + key = id(Generated) + + def jvp_no_context(saved_tensors, tangents): + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.jvp(wrapped_ctx, *tangents) + + tangent_in_dims = get_tangents_in_dims(in_dims, tangents) + out_tangents, out_tangents_dims = restore_vmap( + jvp_no_context, + (ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims), + batch_size, + randomness, + )(ctx.saved_tensors, tangents) + + result = reductify( + out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size + ) + if isinstance(result, torch.Tensor): + return result, None + else: + return *result, None + + def backward(ctx, *grad_outputs): + key = id(Generated) + grad_outputs_ = grad_outputs[:-1] + grad_outputs_in_dims = ctx._pt_out_dims[key] + + if not isinstance(grad_outputs_in_dims, tuple): + grad_outputs_in_dims = (grad_outputs_in_dims,) + + grad_outputs_in_dims = tuple( + in_dim if grad_output is not None else None + for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims) + ) + + def backward_no_context(inputs): + saved_tensors, grad_outputs = inputs + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.backward(wrapped_ctx, *grad_outputs) + + grad_ins, grad_ins_dims = restore_vmap( + backward_no_context, + ((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),), + batch_size, + randomness, + )((ctx.saved_tensors, grad_outputs_)) + result = reductify( + grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key] + ) + return result + + name = f"Vmapped{autograd_function.__name__}" + Generated = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + "generate_vmap_rule": True, + }, + ) + + return Generated + + +# tangents might be None, so we need to replace +# the corresponding in_dims with None. +def get_tangents_in_dims(input_dims, tangents): + flat_in_dims, spec = pytree.tree_flatten(input_dims) + flat_tangents = pytree.arg_tree_leaves(*tangents) + result = [ + None if tangent is None else in_dim + for in_dim, tangent in zip(flat_in_dims, flat_tangents) + ] + return pytree.tree_unflatten(result, spec) + + +# NOTE: [Why do we need to run setup_context under a vmap?] +# Consider the following autograd.Function +# +# class Sum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.sum() +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# ctx.x_shape = inputs[0] +# @staticmethod +# def backward(ctx, gy): +# return gy.expand(ctx.x_shape) +# +# x = torch.randn(B, 4) +# in_dims = 0 +# vmap(Sum.apply, in_dims)(x) +# +# Let's assume for a moment that we didn't vmap setup_context in VmappedSum: +# +# class VmappedSum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return vmap(Sum.forward, in_dims)(x) +# +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# Sum.setup_context(ctx, inputs, outputs) +# +# @staticmethod +# def backward(ctx, gy): +# def backward_no_context(gy): +# return gy.expand(ctx.x_shape) +# +# dims = (0,) +# gx = vmap(backward_no_context, dims)(gy) +# return gx +# +# We end up saving [B, 4] as x_shape. In the backward, gy has shape [B], +# and we're doing: +# +# def backward_no_context(gy): +# return gy.expand([B, 4]) +# +# gx = vmap(backward_no_context, dims)(gy: "Tensor[B]") +# +# This gives us the wrong result (gx has shape [B, B, 4], but it should +# have shape [4]). Performing vmap over setup_context means the shape +# saved has shape [4] and leads to a correct result shape for gx. + + +# Wraps a ctx object. Forwards all attr accesses to the underlying object +# except for the attrs in _pt_attrs +class WrappedCtx: + _pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx") + + def __init__(self, ctx): + if not isinstance(ctx, WrappedCtx): + reserved_attrs = type(self)._pt_reserved_attrs + for name in reserved_attrs: + if not hasattr(ctx, name): + continue + raise RuntimeError( + f"PyTorch reserves the {reserved_attrs} field on ctx. " + "Please name your fields on ctx something else to avoid name " + "collision." + ) + self._pt_inner_ctx = ctx + + def __getattr__(self, name): + return getattr(self._pt_inner_ctx, name) + + def __setattr__(self, name, value): + if name in type(self)._pt_reserved_attrs: + self.__dict__[name] = value + return + return setattr(self._pt_inner_ctx, name, value) + + +# Wraps ctx to create a new ctx object that overrides saved_tensors. +class CtxWithSavedTensors(WrappedCtx): + _pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs) + + def __init__(self, ctx, new_saved_tensors): + super().__init__(ctx) + self._pt_new_saved_tensors = new_saved_tensors + + @property + def saved_tensors(self): + return self._pt_new_saved_tensors + + +class CtxCustomSave(WrappedCtx): + _pt_reserved_attrs = ( + "_pt_saved_tensors_bdims", + "_pt_current_level", + *WrappedCtx._pt_reserved_attrs, + ) + + def __init__(self, ctx, current_level): + super().__init__(ctx) + self._pt_saved_tensors_bdims = () + self._pt_current_level = current_level + + def save_for_backward(self, *tensors): + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_backward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + def save_for_forward(self, *tensors): + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_forward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + +def reductify( + grad_input, + grad_input_bdim, + input_bdim, + batch_size, + target_shape_without_bdim_to_reduce_to=None, +): + if not isinstance(grad_input, tuple): + grad_input = (grad_input,) + if not isinstance(grad_input_bdim, tuple): + grad_input_bdim = (grad_input_bdim,) + if not isinstance(input_bdim, tuple): + input_bdim = (input_bdim,) + + if target_shape_without_bdim_to_reduce_to is None: + target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,) + result = tuple( + reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape) + for gi, gi_bdim, i_bdim, maybe_ishape in zip( + grad_input, + grad_input_bdim, + input_bdim, + target_shape_without_bdim_to_reduce_to, + ) + ) + return result + + +def reductify_leaf( + grad_input, + grad_input_bdim, + input_bdim, + batch_size, + target_shape_without_bdim_to_reduce_to=None, +): + if grad_input is None: + return None + + if grad_input_bdim is None and input_bdim is None: + return grad_input + + if grad_input_bdim is not None and input_bdim is None: + return grad_input.sum(grad_input_bdim) + + # NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # For reverse-mode AD, + # given a grad_input and input, it is valid for the user to return a + # grad_input that has a broadcasted shape when compared to the input. + # In this situation, autograd automatically reduces the grad_input to + # the shape of the input. + # + # However, when input_bdim is not None, we have problems. + # + # [example 1] + # grad_input: Tensor[3, 4], input: Tensor[B, 4] + # We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # [example 2] + # grad_input: Tensor[3, B, 4], input: Tensor[B, 4] + # We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # This means that we need to also reduce the grad_input to the shape of the + # input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag; + # if not-None then we do the reducing manually, otherwise, we do not do a reduction. + assert input_bdim is not None + + if grad_input_bdim is None: + grad_input = grad_input.unsqueeze(input_bdim) + new_shape = list(grad_input.shape) + new_shape[input_bdim] = batch_size + grad_input = grad_input.expand(new_shape) + grad_input_bdim = input_bdim + + if target_shape_without_bdim_to_reduce_to is not None: + return vmap( + torch.Tensor.sum_to_size, + in_dims=(grad_input_bdim, None), + out_dims=input_bdim, + )(grad_input, target_shape_without_bdim_to_reduce_to) + + if input_bdim != grad_input_bdim: + grad_input = grad_input.movedim(grad_input_bdim, input_bdim) + return grad_input + + +def autograd_function_forward_rewritten(original_forward, original_setup_context): + def new_forward(ctx, *args, **kwargs): + output = original_forward(*args, **kwargs) + original_setup_context(ctx, args, output) + return output + + return new_forward + + +class AutogradFunctionApply(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("autograd_function_apply") + + def __call__(self, fwd, bwd, *fwd_args, **fwd_kwargs): + saved_values = None + args_tensor_mask = fwd_kwargs["args_tensor_mask"] + non_differentiable_idx = fwd_kwargs["non_differentiable_idx"] + length_of_tensor_args = sum(args_tensor_mask) + # Filter out the original tensor args from fwd_args, + # lifted freevars should not be args of ApplyTemplate.apply + # since we don't need to calculate the gradients of them. + new_fwd_args = fwd_args[:length_of_tensor_args] + + class ApplyTemplate(torch.autograd.Function): + @staticmethod + def forward(ctx, *args): + nonlocal saved_values + output, saved_values = fwd(None, *fwd_args) + + # If users call ctx.mark_non_differentiable() in the original fwd function. + if len(non_differentiable_idx) > 0: + non_differentiable_output = [] + for i, x in enumerate(output): + if i in non_differentiable_idx: + non_differentiable_output.append(x) + ctx.mark_non_differentiable(*non_differentiable_output) + + return output + + @staticmethod + def backward(ctx, *grad): + return bwd(None, *grad, *saved_values) + + return ApplyTemplate.apply(*new_fwd_args) + + +autograd_function_apply = AutogradFunctionApply() diff --git a/shared/package-files/93/933e87cc0cad8385767aa48ac06cdb26e63215f823e9b1525209358b5e73569d/inequalities.py b/shared/package-files/93/933e87cc0cad8385767aa48ac06cdb26e63215f823e9b1525209358b5e73569d/inequalities.py new file mode 100644 index 0000000000000000000000000000000000000000..f50f7a7572ff25e8f48a4214d7b0c5ec6b5b35f3 --- /dev/null +++ b/shared/package-files/93/933e87cc0cad8385767aa48ac06cdb26e63215f823e9b1525209358b5e73569d/inequalities.py @@ -0,0 +1,986 @@ +"""Tools for solving inequalities and systems of inequalities. """ +import itertools + +from sympy.calculus.util import (continuous_domain, periodicity, + function_range) +from sympy.core import sympify +from sympy.core.exprtools import factor_terms +from sympy.core.relational import Relational, Lt, Ge, Eq +from sympy.core.symbol import Symbol, Dummy +from sympy.sets.sets import Interval, FiniteSet, Union, Intersection +from sympy.core.singleton import S +from sympy.core.function import expand_mul +from sympy.functions.elementary.complexes import Abs +from sympy.logic import And +from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr +from sympy.polys.polyutils import _nsort +from sympy.solvers.solveset import solvify, solveset +from sympy.utilities.iterables import sift, iterable +from sympy.utilities.misc import filldedent + + +def solve_poly_inequality(poly, rel): + """Solve a polynomial inequality with rational coefficients. + + Examples + ======== + + >>> from sympy import solve_poly_inequality, Poly + >>> from sympy.abc import x + + >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==') + [{0}] + + >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=') + [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)] + + >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==') + [{-1}, {1}] + + See Also + ======== + solve_poly_inequalities + """ + if not isinstance(poly, Poly): + raise ValueError( + 'For efficiency reasons, `poly` should be a Poly instance') + if poly.as_expr().is_number: + t = Relational(poly.as_expr(), 0, rel) + if t is S.true: + return [S.Reals] + elif t is S.false: + return [S.EmptySet] + else: + raise NotImplementedError( + "could not determine truth value of %s" % t) + + reals, intervals = poly.real_roots(multiple=False), [] + + if rel == '==': + for root, _ in reals: + interval = Interval(root, root) + intervals.append(interval) + elif rel == '!=': + left = S.NegativeInfinity + + for right, _ in reals + [(S.Infinity, 1)]: + interval = Interval(left, right, True, True) + intervals.append(interval) + left = right + else: + if poly.LC() > 0: + sign = +1 + else: + sign = -1 + + eq_sign, equal = None, False + + if rel == '>': + eq_sign = +1 + elif rel == '<': + eq_sign = -1 + elif rel == '>=': + eq_sign, equal = +1, True + elif rel == '<=': + eq_sign, equal = -1, True + else: + raise ValueError("'%s' is not a valid relation" % rel) + + right, right_open = S.Infinity, True + + for left, multiplicity in reversed(reals): + if multiplicity % 2: + if sign == eq_sign: + intervals.insert( + 0, Interval(left, right, not equal, right_open)) + + sign, right, right_open = -sign, left, not equal + else: + if sign == eq_sign and not equal: + intervals.insert( + 0, Interval(left, right, True, right_open)) + right, right_open = left, True + elif sign != eq_sign and equal: + intervals.insert(0, Interval(left, left)) + + if sign == eq_sign: + intervals.insert( + 0, Interval(S.NegativeInfinity, right, True, right_open)) + + return intervals + + +def solve_poly_inequalities(polys): + """Solve polynomial inequalities with rational coefficients. + + Examples + ======== + + >>> from sympy import Poly + >>> from sympy.solvers.inequalities import solve_poly_inequalities + >>> from sympy.abc import x + >>> solve_poly_inequalities((( + ... Poly(x**2 - 3), ">"), ( + ... Poly(-x**2 + 1), ">"))) + Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo)) + """ + return Union(*[s for p in polys for s in solve_poly_inequality(*p)]) + + +def solve_rational_inequalities(eqs): + """Solve a system of rational inequalities with rational coefficients. + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy import solve_rational_inequalities, Poly + + >>> solve_rational_inequalities([[ + ... ((Poly(-x + 1), Poly(1, x)), '>='), + ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) + {1} + + >>> solve_rational_inequalities([[ + ... ((Poly(x), Poly(1, x)), '!='), + ... ((Poly(-x + 1), Poly(1, x)), '>=')]]) + Union(Interval.open(-oo, 0), Interval.Lopen(0, 1)) + + See Also + ======== + solve_poly_inequality + """ + result = S.EmptySet + + for _eqs in eqs: + if not _eqs: + continue + + global_intervals = [Interval(S.NegativeInfinity, S.Infinity)] + + for (numer, denom), rel in _eqs: + numer_intervals = solve_poly_inequality(numer*denom, rel) + denom_intervals = solve_poly_inequality(denom, '==') + + intervals = [] + + for numer_interval, global_interval in itertools.product( + numer_intervals, global_intervals): + interval = numer_interval.intersect(global_interval) + + if interval is not S.EmptySet: + intervals.append(interval) + + global_intervals = intervals + + intervals = [] + + for global_interval in global_intervals: + for denom_interval in denom_intervals: + global_interval -= denom_interval + + if global_interval is not S.EmptySet: + intervals.append(global_interval) + + global_intervals = intervals + + if not global_intervals: + break + + for interval in global_intervals: + result = result.union(interval) + + return result + + +def reduce_rational_inequalities(exprs, gen, relational=True): + """Reduce a system of rational inequalities with rational coefficients. + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.solvers.inequalities import reduce_rational_inequalities + + >>> x = Symbol('x', real=True) + + >>> reduce_rational_inequalities([[x**2 <= 0]], x) + Eq(x, 0) + + >>> reduce_rational_inequalities([[x + 2 > 0]], x) + -2 < x + >>> reduce_rational_inequalities([[(x + 2, ">")]], x) + -2 < x + >>> reduce_rational_inequalities([[x + 2]], x) + Eq(x, -2) + + This function find the non-infinite solution set so if the unknown symbol + is declared as extended real rather than real then the result may include + finiteness conditions: + + >>> y = Symbol('y', extended_real=True) + >>> reduce_rational_inequalities([[y + 2 > 0]], y) + (-2 < y) & (y < oo) + """ + exact = True + eqs = [] + solution = S.EmptySet # add pieces for each group + for _exprs in exprs: + if not _exprs: + continue + _eqs = [] + _sol = S.Reals + for expr in _exprs: + if isinstance(expr, tuple): + expr, rel = expr + else: + if expr.is_Relational: + expr, rel = expr.lhs - expr.rhs, expr.rel_op + else: + rel = '==' + + if expr is S.true: + numer, denom, rel = S.Zero, S.One, '==' + elif expr is S.false: + numer, denom, rel = S.One, S.One, '==' + else: + numer, denom = expr.together().as_numer_denom() + + try: + (numer, denom), opt = parallel_poly_from_expr( + (numer, denom), gen) + except PolynomialError: + raise PolynomialError(filldedent(''' + only polynomials and rational functions are + supported in this context. + ''')) + + if not opt.domain.is_Exact: + numer, denom, exact = numer.to_exact(), denom.to_exact(), False + + domain = opt.domain.get_exact() + + if not (domain.is_ZZ or domain.is_QQ): + expr = numer/denom + expr = Relational(expr, 0, rel) + _sol &= solve_univariate_inequality(expr, gen, relational=False) + else: + _eqs.append(((numer, denom), rel)) + + if _eqs: + _sol &= solve_rational_inequalities([_eqs]) + exclude = solve_rational_inequalities([[((d, d.one), '==') + for i in eqs for ((n, d), _) in i if d.has(gen)]]) + _sol -= exclude + + solution |= _sol + + if not exact and solution: + solution = solution.evalf() + + if relational: + solution = solution.as_relational(gen) + + return solution + + +def reduce_abs_inequality(expr, rel, gen): + """Reduce an inequality with nested absolute values. + + Examples + ======== + + >>> from sympy import reduce_abs_inequality, Abs, Symbol + >>> x = Symbol('x', real=True) + + >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x) + (2 < x) & (x < 8) + + >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x) + (-19/3 < x) & (x < 7/3) + + See Also + ======== + + reduce_abs_inequalities + """ + if gen.is_extended_real is False: + raise TypeError(filldedent(''' + Cannot solve inequalities with absolute values containing + non-real variables. + ''')) + + def _bottom_up_scan(expr): + exprs = [] + + if expr.is_Add or expr.is_Mul: + op = expr.func + + for arg in expr.args: + _exprs = _bottom_up_scan(arg) + + if not exprs: + exprs = _exprs + else: + exprs = [(op(expr, _expr), conds + _conds) for (expr, conds), (_expr, _conds) in + itertools.product(exprs, _exprs)] + elif expr.is_Pow: + n = expr.exp + if not n.is_Integer: + raise ValueError("Only Integer Powers are allowed on Abs.") + + exprs.extend((expr**n, conds) for expr, conds in _bottom_up_scan(expr.base)) + elif isinstance(expr, Abs): + _exprs = _bottom_up_scan(expr.args[0]) + + for expr, conds in _exprs: + exprs.append(( expr, conds + [Ge(expr, 0)])) + exprs.append((-expr, conds + [Lt(expr, 0)])) + else: + exprs = [(expr, [])] + + return exprs + + mapping = {'<': '>', '<=': '>='} + inequalities = [] + + for expr, conds in _bottom_up_scan(expr): + if rel not in mapping.keys(): + expr = Relational( expr, 0, rel) + else: + expr = Relational(-expr, 0, mapping[rel]) + + inequalities.append([expr] + conds) + + return reduce_rational_inequalities(inequalities, gen) + + +def reduce_abs_inequalities(exprs, gen): + """Reduce a system of inequalities with nested absolute values. + + Examples + ======== + + >>> from sympy import reduce_abs_inequalities, Abs, Symbol + >>> x = Symbol('x', extended_real=True) + + >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'), + ... (Abs(x + 25) - 13, '>')], x) + (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo))) + + >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x) + (1/2 < x) & (x < 4) + + See Also + ======== + + reduce_abs_inequality + """ + return And(*[ reduce_abs_inequality(expr, rel, gen) + for expr, rel in exprs ]) + + +def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False): + """Solves a real univariate inequality. + + Parameters + ========== + + expr : Relational + The target inequality + gen : Symbol + The variable for which the inequality is solved + relational : bool + A Relational type output is expected or not + domain : Set + The domain over which the equation is solved + continuous: bool + True if expr is known to be continuous over the given domain + (and so continuous_domain() does not need to be called on it) + + Raises + ====== + + NotImplementedError + The solution of the inequality cannot be determined due to limitation + in :func:`sympy.solvers.solveset.solvify`. + + Notes + ===== + + Currently, we cannot solve all the inequalities due to limitations in + :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities + are restricted in its periodic interval. + + See Also + ======== + + sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API + + Examples + ======== + + >>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S + >>> x = Symbol('x') + + >>> solve_univariate_inequality(x**2 >= 4, x) + ((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2)) + + >>> solve_univariate_inequality(x**2 >= 4, x, relational=False) + Union(Interval(-oo, -2), Interval(2, oo)) + + >>> domain = Interval(0, S.Infinity) + >>> solve_univariate_inequality(x**2 >= 4, x, False, domain) + Interval(2, oo) + + >>> solve_univariate_inequality(sin(x) > 0, x, relational=False) + Interval.open(0, pi) + + """ + from sympy.solvers.solvers import denoms + + if domain.is_subset(S.Reals) is False: + raise NotImplementedError(filldedent(''' + Inequalities in the complex domain are + not supported. Try the real domain by + setting domain=S.Reals''')) + elif domain is not S.Reals: + rv = solve_univariate_inequality( + expr, gen, relational=False, continuous=continuous).intersection(domain) + if relational: + rv = rv.as_relational(gen) + return rv + else: + pass # continue with attempt to solve in Real domain + + # This keeps the function independent of the assumptions about `gen`. + # `solveset` makes sure this function is called only when the domain is + # real. + _gen = gen + _domain = domain + if gen.is_extended_real is False: + rv = S.EmptySet + return rv if not relational else rv.as_relational(_gen) + elif gen.is_extended_real is None: + gen = Dummy('gen', extended_real=True) + try: + expr = expr.xreplace({_gen: gen}) + except TypeError: + raise TypeError(filldedent(''' + When gen is real, the relational has a complex part + which leads to an invalid comparison like I < 0. + ''')) + + rv = None + + if expr is S.true: + rv = domain + + elif expr is S.false: + rv = S.EmptySet + + else: + e = expr.lhs - expr.rhs + period = periodicity(e, gen) + if period == S.Zero: + e = expand_mul(e) + const = expr.func(e, 0) + if const is S.true: + rv = domain + elif const is S.false: + rv = S.EmptySet + elif period is not None: + frange = function_range(e, gen, domain) + + rel = expr.rel_op + if rel in ('<', '<='): + if expr.func(frange.sup, 0): + rv = domain + elif not expr.func(frange.inf, 0): + rv = S.EmptySet + + elif rel in ('>', '>='): + if expr.func(frange.inf, 0): + rv = domain + elif not expr.func(frange.sup, 0): + rv = S.EmptySet + + inf, sup = domain.inf, domain.sup + if sup - inf is S.Infinity: + domain = Interval(0, period, False, True).intersect(_domain) + _domain = domain + + if rv is None: + n, d = e.as_numer_denom() + try: + if gen not in n.free_symbols and len(e.free_symbols) > 1: + raise ValueError + # this might raise ValueError on its own + # or it might give None... + solns = solvify(e, gen, domain) + if solns is None: + # in which case we raise ValueError + raise ValueError + except (ValueError, NotImplementedError): + # replace gen with generic x since it's + # univariate anyway + raise NotImplementedError(filldedent(''' + The inequality, %s, cannot be solved using + solve_univariate_inequality. + ''' % expr.subs(gen, Symbol('x')))) + + expanded_e = expand_mul(e) + def valid(x): + # this is used to see if gen=x satisfies the + # relational by substituting it into the + # expanded form and testing against 0, e.g. + # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2 + # and expanded_e = x**2 + x - 2; the test is + # whether a given value of x satisfies + # x**2 + x - 2 < 0 + # + # expanded_e, expr and gen used from enclosing scope + v = expanded_e.subs(gen, expand_mul(x)) + try: + r = expr.func(v, 0) + except TypeError: + r = S.false + if r in (S.true, S.false): + return r + if v.is_extended_real is False: + return S.false + else: + v = v.n(2) + if v.is_comparable: + return expr.func(v, 0) + # not comparable or couldn't be evaluated + raise NotImplementedError( + 'relationship did not evaluate: %s' % r) + + singularities = [] + for d in denoms(expr, gen): + singularities.extend(solvify(d, gen, domain)) + if not continuous: + domain = continuous_domain(expanded_e, gen, domain) + + include_x = '=' in expr.rel_op and expr.rel_op != '!=' + + try: + discontinuities = set(domain.boundary - + FiniteSet(domain.inf, domain.sup)) + # remove points that are not between inf and sup of domain + critical_points = FiniteSet(*(solns + singularities + list( + discontinuities))).intersection( + Interval(domain.inf, domain.sup, + domain.inf not in domain, domain.sup not in domain)) + if all(r.is_number for r in critical_points): + reals = _nsort(critical_points, separated=True)[0] + else: + sifted = sift(critical_points, lambda x: x.is_extended_real) + if sifted[None]: + # there were some roots that weren't known + # to be real + raise NotImplementedError + try: + reals = sifted[True] + if len(reals) > 1: + reals = sorted(reals) + except TypeError: + raise NotImplementedError + except NotImplementedError: + raise NotImplementedError('sorting of these roots is not supported') + + # If expr contains imaginary coefficients, only take real + # values of x for which the imaginary part is 0 + make_real = S.Reals + if (coeffI := expanded_e.coeff(S.ImaginaryUnit)) != S.Zero: + check = True + im_sol = FiniteSet() + try: + a = solveset(coeffI, gen, domain) + if not isinstance(a, Interval): + for z in a: + if z not in singularities and valid(z) and z.is_extended_real: + im_sol += FiniteSet(z) + else: + start, end = a.inf, a.sup + for z in _nsort(critical_points + FiniteSet(end)): + valid_start = valid(start) + if start != end: + valid_z = valid(z) + pt = _pt(start, z) + if pt not in singularities and pt.is_extended_real and valid(pt): + if valid_start and valid_z: + im_sol += Interval(start, z) + elif valid_start: + im_sol += Interval.Ropen(start, z) + elif valid_z: + im_sol += Interval.Lopen(start, z) + else: + im_sol += Interval.open(start, z) + start = z + for s in singularities: + im_sol -= FiniteSet(s) + except (TypeError): + im_sol = S.Reals + check = False + + if im_sol is S.EmptySet: + raise ValueError(filldedent(''' + %s contains imaginary parts which cannot be + made 0 for any value of %s satisfying the + inequality, leading to relations like I < 0. + ''' % (expr.subs(gen, _gen), _gen))) + + make_real = make_real.intersect(im_sol) + + sol_sets = [S.EmptySet] + + start = domain.inf + if start in domain and valid(start) and start.is_finite: + sol_sets.append(FiniteSet(start)) + + for x in reals: + end = x + + if valid(_pt(start, end)): + sol_sets.append(Interval(start, end, True, True)) + + if x in singularities: + singularities.remove(x) + else: + if x in discontinuities: + discontinuities.remove(x) + _valid = valid(x) + else: # it's a solution + _valid = include_x + if _valid: + sol_sets.append(FiniteSet(x)) + + start = end + + end = domain.sup + if end in domain and valid(end) and end.is_finite: + sol_sets.append(FiniteSet(end)) + + if valid(_pt(start, end)): + sol_sets.append(Interval.open(start, end)) + + if coeffI != S.Zero and check: + rv = (make_real).intersect(_domain) + else: + rv = Intersection( + (Union(*sol_sets)), make_real, _domain).subs(gen, _gen) + + return rv if not relational else rv.as_relational(_gen) + + +def _pt(start, end): + """Return a point between start and end""" + if not start.is_infinite and not end.is_infinite: + pt = (start + end)/2 + elif start.is_infinite and end.is_infinite: + pt = S.Zero + else: + if (start.is_infinite and start.is_extended_positive is None or + end.is_infinite and end.is_extended_positive is None): + raise ValueError('cannot proceed with unsigned infinite values') + if (end.is_infinite and end.is_extended_negative or + start.is_infinite and start.is_extended_positive): + start, end = end, start + # if possible, use a multiple of self which has + # better behavior when checking assumptions than + # an expression obtained by adding or subtracting 1 + if end.is_infinite: + if start.is_extended_positive: + pt = start*2 + elif start.is_extended_negative: + pt = start*S.Half + else: + pt = start + 1 + elif start.is_infinite: + if end.is_extended_positive: + pt = end*S.Half + elif end.is_extended_negative: + pt = end*2 + else: + pt = end - 1 + return pt + + +def _solve_inequality(ie, s, linear=False): + """Return the inequality with s isolated on the left, if possible. + If the relationship is non-linear, a solution involving And or Or + may be returned. False or True are returned if the relationship + is never True or always True, respectively. + + If `linear` is True (default is False) an `s`-dependent expression + will be isolated on the left, if possible + but it will not be solved for `s` unless the expression is linear + in `s`. Furthermore, only "safe" operations which do not change the + sense of the relationship are applied: no division by an unsigned + value is attempted unless the relationship involves Eq or Ne and + no division by a value not known to be nonzero is ever attempted. + + Examples + ======== + + >>> from sympy import Eq, Symbol + >>> from sympy.solvers.inequalities import _solve_inequality as f + >>> from sympy.abc import x, y + + For linear expressions, the symbol can be isolated: + + >>> f(x - 2 < 0, x) + x < 2 + >>> f(-x - 6 < x, x) + x > -3 + + Sometimes nonlinear relationships will be False + + >>> f(x**2 + 4 < 0, x) + False + + Or they may involve more than one region of values: + + >>> f(x**2 - 4 < 0, x) + (-2 < x) & (x < 2) + + To restrict the solution to a relational, set linear=True + and only the x-dependent portion will be isolated on the left: + + >>> f(x**2 - 4 < 0, x, linear=True) + x**2 < 4 + + Division of only nonzero quantities is allowed, so x cannot + be isolated by dividing by y: + + >>> y.is_nonzero is None # it is unknown whether it is 0 or not + True + >>> f(x*y < 1, x) + x*y < 1 + + And while an equality (or inequality) still holds after dividing by a + non-zero quantity + + >>> nz = Symbol('nz', nonzero=True) + >>> f(Eq(x*nz, 1), x) + Eq(x, 1/nz) + + the sign must be known for other inequalities involving > or <: + + >>> f(x*nz <= 1, x) + nz*x <= 1 + >>> p = Symbol('p', positive=True) + >>> f(x*p <= 1, x) + x <= 1/p + + When there are denominators in the original expression that + are removed by expansion, conditions for them will be returned + as part of the result: + + >>> f(x < x*(2/x - 1), x) + (x < 1) & Ne(x, 0) + """ + from sympy.solvers.solvers import denoms + if s not in ie.free_symbols: + return ie + if ie.rhs == s: + ie = ie.reversed + if ie.lhs == s and s not in ie.rhs.free_symbols: + return ie + + def classify(ie, s, i): + # return True or False if ie evaluates when substituting s with + # i else None (if unevaluated) or NaN (when there is an error + # in evaluating) + try: + v = ie.subs(s, i) + if v is S.NaN: + return v + elif v not in (True, False): + return + return v + except TypeError: + return S.NaN + + rv = None + oo = S.Infinity + expr = ie.lhs - ie.rhs + try: + p = Poly(expr, s) + if p.degree() == 0: + rv = ie.func(p.as_expr(), 0) + elif not linear and p.degree() > 1: + # handle in except clause + raise NotImplementedError + except (PolynomialError, NotImplementedError): + if not linear: + try: + rv = reduce_rational_inequalities([[ie]], s) + except PolynomialError: + rv = solve_univariate_inequality(ie, s) + # remove restrictions wrt +/-oo that may have been + # applied when using sets to simplify the relationship + okoo = classify(ie, s, oo) + if okoo is S.true and classify(rv, s, oo) is S.false: + rv = rv.subs(s < oo, True) + oknoo = classify(ie, s, -oo) + if (oknoo is S.true and + classify(rv, s, -oo) is S.false): + rv = rv.subs(-oo < s, True) + rv = rv.subs(s > -oo, True) + if rv is S.true: + rv = (s <= oo) if okoo is S.true else (s < oo) + if oknoo is not S.true: + rv = And(-oo < s, rv) + else: + p = Poly(expr) + + conds = [] + if rv is None: + e = p.as_expr() # this is in expanded form + # Do a safe inversion of e, moving non-s terms + # to the rhs and dividing by a nonzero factor if + # the relational is Eq/Ne; for other relationals + # the sign must also be positive or negative + rhs = 0 + b, ax = e.as_independent(s, as_Add=True) + e -= b + rhs -= b + ef = factor_terms(e) + a, e = ef.as_independent(s, as_Add=False) + if (a.is_zero != False or # don't divide by potential 0 + a.is_negative == + a.is_positive is None and # if sign is not known then + ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne + e = ef + a = S.One + rhs /= a + if a.is_positive: + rv = ie.func(e, rhs) + else: + rv = ie.reversed.func(e, rhs) + + # return conditions under which the value is + # valid, too. + beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs) + current_denoms = denoms(rv) + for d in beginning_denoms - current_denoms: + c = _solve_inequality(Eq(d, 0), s, linear=linear) + if isinstance(c, Eq) and c.lhs == s: + if classify(rv, s, c.rhs) is S.true: + # rv is permitting this value but it shouldn't + conds.append(~c) + for i in (-oo, oo): + if (classify(rv, s, i) is S.true and + classify(ie, s, i) is not S.true): + conds.append(s < i if i is oo else i < s) + + conds.append(rv) + return And(*conds) + + +def _reduce_inequalities(inequalities, symbols): + # helper for reduce_inequalities + + poly_part, abs_part = {}, {} + other = [] + + for inequality in inequalities: + + expr, rel = inequality.lhs, inequality.rel_op # rhs is 0 + + # check for gens using atoms which is more strict than free_symbols to + # guard against EX domain which won't be handled by + # reduce_rational_inequalities + gens = expr.atoms(Symbol) + + if len(gens) == 1: + gen = gens.pop() + else: + common = expr.free_symbols & symbols + if len(common) == 1: + gen = common.pop() + other.append(_solve_inequality(Relational(expr, 0, rel), gen)) + continue + else: + raise NotImplementedError(filldedent(''' + inequality has more than one symbol of interest. + ''')) + + if expr.is_polynomial(gen): + poly_part.setdefault(gen, []).append((expr, rel)) + else: + components = expr.find(lambda u: + u.has(gen) and ( + u.is_Function or u.is_Pow and not u.exp.is_Integer)) + if components and all(isinstance(i, Abs) for i in components): + abs_part.setdefault(gen, []).append((expr, rel)) + else: + other.append(_solve_inequality(Relational(expr, 0, rel), gen)) + + poly_reduced = [reduce_rational_inequalities([exprs], gen) for gen, exprs in poly_part.items()] + abs_reduced = [reduce_abs_inequalities(exprs, gen) for gen, exprs in abs_part.items()] + + return And(*(poly_reduced + abs_reduced + other)) + + +def reduce_inequalities(inequalities, symbols=[]): + """Reduce a system of inequalities with rational coefficients. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy import reduce_inequalities + + >>> reduce_inequalities(0 <= x + 3, []) + (-3 <= x) & (x < oo) + + >>> reduce_inequalities(0 <= x + y*2 - 1, [x]) + (x < oo) & (x >= 1 - 2*y) + """ + if not iterable(inequalities): + inequalities = [inequalities] + inequalities = [sympify(i) for i in inequalities] + + gens = set().union(*[i.free_symbols for i in inequalities]) + + if not iterable(symbols): + symbols = [symbols] + symbols = (set(symbols) or gens) & gens + if any(i.is_extended_real is False for i in symbols): + raise TypeError(filldedent(''' + inequalities cannot contain symbols that are not real. + ''')) + + # make vanilla symbol real + recast = {i: Dummy(i.name, extended_real=True) + for i in gens if i.is_extended_real is None} + inequalities = [i.xreplace(recast) for i in inequalities] + symbols = {i.xreplace(recast) for i in symbols} + + # prefilter + keep = [] + for i in inequalities: + if isinstance(i, Relational): + i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0) + elif i not in (True, False): + i = Eq(i, 0) + if i == True: + continue + elif i == False: + return S.false + if i.lhs.is_number: + raise NotImplementedError( + "could not determine truth value of %s" % i) + keep.append(i) + inequalities = keep + del keep + + # solve system + rv = _reduce_inequalities(inequalities, symbols) + + # restore original symbols and return + return rv.xreplace({v: k for k, v in recast.items()}) diff --git a/shared/package-files/93/9343b5a0fdb63de75958aa72537be0d2ff9e2a0c77a886eebd71ba37642451d2/wrap.py b/shared/package-files/93/9343b5a0fdb63de75958aa72537be0d2ff9e2a0c77a886eebd71ba37642451d2/wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..604c545e586be223d9602ab2e708dd926472c426 --- /dev/null +++ b/shared/package-files/93/9343b5a0fdb63de75958aa72537be0d2ff9e2a0c77a886eebd71ba37642451d2/wrap.py @@ -0,0 +1,247 @@ +# mypy: allow-untyped-defs +import inspect +import itertools +import logging +from typing import Optional + +from torch._logging import warning_once +from torch._ops import HigherOrderOperator +from torch.types import _dtype + + +log = logging.getLogger(__name__) + +uid = itertools.count(1) + + +# Used for testing the HigherOrderOperator mechanism +class Wrap(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap") + + def __call__(self, func, *args, **kwargs): + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo # noqa: F401 + from torch._dynamo import disable + + @disable + def wrapper(): + result = func(*args, **kwargs) + return result + + return wrapper() + + +wrap = Wrap() + + +class WrapWithSetGradEnabled(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap_with_set_grad_enabled") + + def __call__(self, enable_grad, wrapped_func, *args, **kwargs): + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo # noqa: F401 + from torch._dynamo import disable + + @disable + def wrapper(): + with torch.set_grad_enabled(enable_grad): + return wrapped_func(*args, **kwargs) + + return wrapper() + + +wrap_with_set_grad_enabled = WrapWithSetGradEnabled() + + +class WrapWithAutocast(HigherOrderOperator): + def __init__(self): + super().__init__("wrap_with_autocast") + + def __call__( + self, + device_type: str, + dtype: Optional[_dtype], + enabled: bool, + cache_enabled: Optional[bool], + wrapped_func, + *args, + **kwargs, + ): + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo # noqa: F401 + from torch._dynamo import disable + + @disable + def wrapper(): + with torch.autocast(device_type, dtype, enabled, cache_enabled): + return wrapped_func(*args, **kwargs) + + return wrapper() + + +wrap_with_autocast = WrapWithAutocast() + + +class WrapActivationCheckpoint(HigherOrderOperator): + """ + This operator is used to wrap torch.utils.checkpoint. This avoids + TorchDynamo to look into saved tensor hooks and directly passes the control + to AOT Autograd, which is ok with tracing saved tensor hooks. As a result of + AOT tracing torch.utils.checkpoint code, we have a backward graph with + recomputed forward nodes. + + However, we might deprecate this operator soon. The difficulty arises in the + functionalization of rng ops. Today, there are two different + functionalization of rng ops - one at AOT autograd and other at Inductor. + And they are difficult to map to each other. The rng states also complicate + pattern matching in Inductor. Due to the ease of implementation, we are + currently inclined towards functionalization at Inductor level, which means + that duplication/recomputation is done as a compiler pass in the + partitioners. See TagActivationCheckpoint for more information. + """ + + def __init__(self) -> None: + super().__init__("wrap_activation_checkpoint", cacheable=False) + + def __call__(self, function, *args, **kwargs): + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + kwargs["use_reentrant"] = False + kwargs["preserve_rng_state"] = False + # Using interpreter allows preservation of metadata through torch.compile stack. + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(Interpreter(function).run, *args, **kwargs) + + +wrap_activation_checkpoint = WrapActivationCheckpoint() + + +class TagActivationCheckpoint(HigherOrderOperator): + """ + This operator is supposed to be used only with torch.compile stack. This + accepts a Fx graph module which needs to be checkpointed. This operator adds + "recomputable" tag to the nodes of the Fx graph that should be recomputed. + + The goal is to: + 1. Avoid using Dynamo to trace through saved tensor hooks. + 2. For selective checkpointing case, let AOTAutograd trace through + saved tensor hooks but has special logic with TorchDispatchMode to override + the usual saved_tensor_hooks fn logic in order to tag the nodes. + 3. Rely on the partitioners to actually duplicate the nodes. + This sits well in the torch.compile stack, because by the time graph + reaches partitioner, inductor has already run its functionalization of rng + ops (by setting fixed seed for each random op, see `replace_random_passes`). + Therefore, the duplication of nodes, by design, respects the rng states in + the forward and recomputed forward in backward. + """ + + def __init__(self) -> None: + super().__init__("tag_activation_checkpoint", cacheable=False) + + @staticmethod + def divide_kwargs(kwargs): + """ + checkpoint fn can have mixed kwargs between checkpointed fn and + checkpoint fn itself. For example + >> def gn(x, y, z=None): + >> a = torch.matmul(x, y) + >> if z is not None: + >> return torch.matmul(a, z) + >> return a + >> def fn(x, y, z): + >> return torch.cos(checkpoint(gn, x, y, use_reentrant=False, z=z)) + In the above case, z belongs to checkpointed function gn, but + use_reentrant belongs to the checkpoint function. This function splits + the kwargs into checkpoint_kwargs and gmod_kwargs (or + checkpointed_fn_kwargs). + We do sorting to ensure same graph from run to run for better + debuggability. It is not required for correctness. + """ + from torch.utils.checkpoint import checkpoint + + ckpt_signature = inspect.signature(checkpoint) + checkpoint_keys = set() + for name in ckpt_signature.parameters: + if name in ("function", "args", "kwargs"): + continue + checkpoint_keys.add(name) + + # `preserve_rng_state` is not a regular kwarg + checkpoint_keys.add("preserve_rng_state") + + checkpoint_kwargs = { + name: kwargs[name] for name in kwargs.keys() if name in checkpoint_keys + } + gmod_kwargs = { + name: kwargs[name] for name in kwargs.keys() if name not in checkpoint_keys + } + return checkpoint_kwargs, gmod_kwargs + + def tag_nodes(self, gmod, is_sac): + from torch.utils.checkpoint import CheckpointPolicy + + unique_graph_id = next(uid) + for node in gmod.graph.nodes: + if node.op in ("call_function", "call_method", "call_module"): + node.meta["ac_graph_id"] = unique_graph_id + if is_sac: + # For selective checkpointing, we will populate this tag later in _CachingTorchDispatchMode. + node.meta["recompute"] = None + else: + # Under vanilla activation checkpointing, all nodes should be recomputed. + node.meta["recompute"] = CheckpointPolicy.PREFER_RECOMPUTE + return gmod + + def __call__(self, gmod, *args, **kwargs): + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + if "_checkpoint_context_fn" in gmod.meta: + warning_once( + log, + """ +Detected that context_fn is passed to torch.utils.checkpoint under torch.compile. +Please make sure the checkpointed region does not contain in-place ops (e.g. torch.relu_). +""", + ) + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + kwargs["use_reentrant"] = False + # preserve_rng_state is set to False because we want to prevent AOTAutograd from tracing through + # `torch.random.fork_rng` op (which is not supported yet under CUDA). + # This doesn't mean that we don't preserve RNG state. Instead, we will always preserve RNG state + # regardless of this flag (by doing RNG functionalization via `replace_random_passes` in Inductor + # instead of in AOTAutograd). + kwargs["preserve_rng_state"] = False + kwargs["context_fn"] = gmod.meta["_checkpoint_context_fn"] + # We first tag all nodes as "recompute" in this graph, and then we undo the "recompute" tag + # for specific nodes in _CachingTorchDispatchMode in torch/utils/checkpoint.py. + gmod = self.tag_nodes(gmod, is_sac=True) + # Using interpreter allows preservation of metadata through torch.compile stack. + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(Interpreter(gmod).run, *args, **kwargs) + else: + gmod = self.tag_nodes(gmod, is_sac=False) + # Using interpreter allows preservation of metadata through torch.compile stack. + # TODO: We want to use the same `checkpoint(Interpreter(gmod).run, *args, **kwargs)` here + # as the `context_fn != None` case, but that depends on in-place op support in TorchDispatchMode + torch.compile. + # (for details on in-place op issue, run `test_compile_selective_checkpoint_inplace_op` unit test) + with fx_traceback.preserve_node_meta(): + return Interpreter(gmod).run(*args) + + +tag_activation_checkpoint = TagActivationCheckpoint() diff --git a/shared/package-files/93/934c2998af0afea17aa0223c598e8a969dcdc63a2b2eae94a81e4a12aac76124/common.cpython-311.pyc b/shared/package-files/93/934c2998af0afea17aa0223c598e8a969dcdc63a2b2eae94a81e4a12aac76124/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..375fe8c6ba31d8a00855b7a739d43c986438d090 Binary files /dev/null and b/shared/package-files/93/934c2998af0afea17aa0223c598e8a969dcdc63a2b2eae94a81e4a12aac76124/common.cpython-311.pyc differ diff --git a/shared/package-files/93/9353ad09a81d7c061945297624ec87f48ee083045e7f6b9b54d6a24a01b5cafd/test_binary.py b/shared/package-files/93/9353ad09a81d7c061945297624ec87f48ee083045e7f6b9b54d6a24a01b5cafd/test_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e534e7bcadfe93de8abc719aa83c1ce11f5a9a --- /dev/null +++ b/shared/package-files/93/9353ad09a81d7c061945297624ec87f48ee083045e7f6b9b54d6a24a01b5cafd/test_binary.py @@ -0,0 +1,451 @@ +import pytest + +import networkx as nx +from networkx.utils import edges_equal + + +def test_union_attributes(): + g = nx.Graph() + g.add_node(0, x=4) + g.add_node(1, x=5) + g.add_edge(0, 1, size=5) + g.graph["name"] = "g" + + h = g.copy() + h.graph["name"] = "h" + h.graph["attr"] = "attr" + h.nodes[0]["x"] = 7 + + gh = nx.union(g, h, rename=("g", "h")) + assert set(gh.nodes()) == {"h0", "h1", "g0", "g1"} + for n in gh: + graph, node = n + assert gh.nodes[n] == eval(graph).nodes[int(node)] + + assert gh.graph["attr"] == "attr" + assert gh.graph["name"] == "h" # h graph attributes take precedent + + +def test_intersection(): + G = nx.Graph() + H = nx.Graph() + G.add_nodes_from([1, 2, 3, 4]) + G.add_edge(1, 2) + G.add_edge(2, 3) + H.add_nodes_from([1, 2, 3, 4]) + H.add_edge(2, 3) + H.add_edge(3, 4) + I = nx.intersection(G, H) + assert set(I.nodes()) == {1, 2, 3, 4} + assert sorted(I.edges()) == [(2, 3)] + + +def test_intersection_node_sets_different(): + G = nx.Graph() + H = nx.Graph() + G.add_nodes_from([1, 2, 3, 4, 7]) + G.add_edge(1, 2) + G.add_edge(2, 3) + H.add_nodes_from([1, 2, 3, 4, 5, 6]) + H.add_edge(2, 3) + H.add_edge(3, 4) + H.add_edge(5, 6) + I = nx.intersection(G, H) + assert set(I.nodes()) == {1, 2, 3, 4} + assert sorted(I.edges()) == [(2, 3)] + + +def test_intersection_attributes(): + g = nx.Graph() + g.add_node(0, x=4) + g.add_node(1, x=5) + g.add_edge(0, 1, size=5) + g.graph["name"] = "g" + + h = g.copy() + h.graph["name"] = "h" + h.graph["attr"] = "attr" + h.nodes[0]["x"] = 7 + gh = nx.intersection(g, h) + + assert set(gh.nodes()) == set(g.nodes()) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == sorted(g.edges()) + + +def test_intersection_attributes_node_sets_different(): + g = nx.Graph() + g.add_node(0, x=4) + g.add_node(1, x=5) + g.add_node(2, x=3) + g.add_edge(0, 1, size=5) + g.graph["name"] = "g" + + h = g.copy() + h.graph["name"] = "h" + h.graph["attr"] = "attr" + h.nodes[0]["x"] = 7 + h.remove_node(2) + + gh = nx.intersection(g, h) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == sorted(g.edges()) + + +def test_intersection_multigraph_attributes(): + g = nx.MultiGraph() + g.add_edge(0, 1, key=0) + g.add_edge(0, 1, key=1) + g.add_edge(0, 1, key=2) + h = nx.MultiGraph() + h.add_edge(0, 1, key=0) + h.add_edge(0, 1, key=3) + gh = nx.intersection(g, h) + assert set(gh.nodes()) == set(g.nodes()) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == [(0, 1)] + assert sorted(gh.edges(keys=True)) == [(0, 1, 0)] + + +def test_intersection_multigraph_attributes_node_set_different(): + g = nx.MultiGraph() + g.add_edge(0, 1, key=0) + g.add_edge(0, 1, key=1) + g.add_edge(0, 1, key=2) + g.add_edge(0, 2, key=2) + g.add_edge(0, 2, key=1) + h = nx.MultiGraph() + h.add_edge(0, 1, key=0) + h.add_edge(0, 1, key=3) + gh = nx.intersection(g, h) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == [(0, 1)] + assert sorted(gh.edges(keys=True)) == [(0, 1, 0)] + + +def test_difference(): + G = nx.Graph() + H = nx.Graph() + G.add_nodes_from([1, 2, 3, 4]) + G.add_edge(1, 2) + G.add_edge(2, 3) + H.add_nodes_from([1, 2, 3, 4]) + H.add_edge(2, 3) + H.add_edge(3, 4) + D = nx.difference(G, H) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [(1, 2)] + D = nx.difference(H, G) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [(3, 4)] + D = nx.symmetric_difference(G, H) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [(1, 2), (3, 4)] + + +def test_difference2(): + G = nx.Graph() + H = nx.Graph() + G.add_nodes_from([1, 2, 3, 4]) + H.add_nodes_from([1, 2, 3, 4]) + G.add_edge(1, 2) + H.add_edge(1, 2) + G.add_edge(2, 3) + D = nx.difference(G, H) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [(2, 3)] + D = nx.difference(H, G) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [] + H.add_edge(3, 4) + D = nx.difference(H, G) + assert set(D.nodes()) == {1, 2, 3, 4} + assert sorted(D.edges()) == [(3, 4)] + + +def test_difference_attributes(): + g = nx.Graph() + g.add_node(0, x=4) + g.add_node(1, x=5) + g.add_edge(0, 1, size=5) + g.graph["name"] = "g" + + h = g.copy() + h.graph["name"] = "h" + h.graph["attr"] = "attr" + h.nodes[0]["x"] = 7 + + gh = nx.difference(g, h) + assert set(gh.nodes()) == set(g.nodes()) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == [] + # node and graph data should not be copied over + assert gh.nodes.data() != g.nodes.data() + assert gh.graph != g.graph + + +def test_difference_multigraph_attributes(): + g = nx.MultiGraph() + g.add_edge(0, 1, key=0) + g.add_edge(0, 1, key=1) + g.add_edge(0, 1, key=2) + h = nx.MultiGraph() + h.add_edge(0, 1, key=0) + h.add_edge(0, 1, key=3) + gh = nx.difference(g, h) + assert set(gh.nodes()) == set(g.nodes()) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == [(0, 1), (0, 1)] + assert sorted(gh.edges(keys=True)) == [(0, 1, 1), (0, 1, 2)] + + +def test_difference_raise(): + G = nx.path_graph(4) + H = nx.path_graph(3) + pytest.raises(nx.NetworkXError, nx.difference, G, H) + pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H) + + +def test_symmetric_difference_multigraph(): + g = nx.MultiGraph() + g.add_edge(0, 1, key=0) + g.add_edge(0, 1, key=1) + g.add_edge(0, 1, key=2) + h = nx.MultiGraph() + h.add_edge(0, 1, key=0) + h.add_edge(0, 1, key=3) + gh = nx.symmetric_difference(g, h) + assert set(gh.nodes()) == set(g.nodes()) + assert set(gh.nodes()) == set(h.nodes()) + assert sorted(gh.edges()) == 3 * [(0, 1)] + assert sorted(sorted(e) for e in gh.edges(keys=True)) == [ + [0, 1, 1], + [0, 1, 2], + [0, 1, 3], + ] + + +def test_union_and_compose(): + K3 = nx.complete_graph(3) + P3 = nx.path_graph(3) + + G1 = nx.DiGraph() + G1.add_edge("A", "B") + G1.add_edge("A", "C") + G1.add_edge("A", "D") + G2 = nx.DiGraph() + G2.add_edge("1", "2") + G2.add_edge("1", "3") + G2.add_edge("1", "4") + + G = nx.union(G1, G2) + H = nx.compose(G1, G2) + assert edges_equal(G.edges(), H.edges()) + assert not G.has_edge("A", 1) + pytest.raises(nx.NetworkXError, nx.union, K3, P3) + H1 = nx.union(H, G1, rename=("H", "G1")) + assert sorted(H1.nodes()) == [ + "G1A", + "G1B", + "G1C", + "G1D", + "H1", + "H2", + "H3", + "H4", + "HA", + "HB", + "HC", + "HD", + ] + + H2 = nx.union(H, G2, rename=("H", "")) + assert sorted(H2.nodes()) == [ + "1", + "2", + "3", + "4", + "H1", + "H2", + "H3", + "H4", + "HA", + "HB", + "HC", + "HD", + ] + + assert not H1.has_edge("NB", "NA") + + G = nx.compose(G, G) + assert edges_equal(G.edges(), H.edges()) + + G2 = nx.union(G2, G2, rename=("", "copy")) + assert sorted(G2.nodes()) == [ + "1", + "2", + "3", + "4", + "copy1", + "copy2", + "copy3", + "copy4", + ] + + assert sorted(G2.neighbors("copy4")) == [] + assert sorted(G2.neighbors("copy1")) == ["copy2", "copy3", "copy4"] + assert len(G) == 8 + assert nx.number_of_edges(G) == 6 + + E = nx.disjoint_union(G, G) + assert len(E) == 16 + assert nx.number_of_edges(E) == 12 + + E = nx.disjoint_union(G1, G2) + assert sorted(E.nodes()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + + G = nx.Graph() + H = nx.Graph() + G.add_nodes_from([(1, {"a1": 1})]) + H.add_nodes_from([(1, {"b1": 1})]) + R = nx.compose(G, H) + assert R.nodes == {1: {"a1": 1, "b1": 1}} + + +def test_union_multigraph(): + G = nx.MultiGraph() + G.add_edge(1, 2, key=0) + G.add_edge(1, 2, key=1) + H = nx.MultiGraph() + H.add_edge(3, 4, key=0) + H.add_edge(3, 4, key=1) + GH = nx.union(G, H) + assert set(GH) == set(G) | set(H) + assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True)) + + +def test_disjoint_union_multigraph(): + G = nx.MultiGraph() + G.add_edge(0, 1, key=0) + G.add_edge(0, 1, key=1) + H = nx.MultiGraph() + H.add_edge(2, 3, key=0) + H.add_edge(2, 3, key=1) + GH = nx.disjoint_union(G, H) + assert set(GH) == set(G) | set(H) + assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True)) + + +def test_compose_multigraph(): + G = nx.MultiGraph() + G.add_edge(1, 2, key=0) + G.add_edge(1, 2, key=1) + H = nx.MultiGraph() + H.add_edge(3, 4, key=0) + H.add_edge(3, 4, key=1) + GH = nx.compose(G, H) + assert set(GH) == set(G) | set(H) + assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True)) + H.add_edge(1, 2, key=2) + GH = nx.compose(G, H) + assert set(GH) == set(G) | set(H) + assert set(GH.edges(keys=True)) == set(G.edges(keys=True)) | set(H.edges(keys=True)) + + +def test_full_join_graph(): + # Simple Graphs + G = nx.Graph() + G.add_node(0) + G.add_edge(1, 2) + H = nx.Graph() + H.add_edge(3, 4) + + U = nx.full_join(G, H) + assert set(U) == set(G) | set(H) + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) + + # Rename + U = nx.full_join(G, H, rename=("g", "h")) + assert set(U) == {"g0", "g1", "g2", "h3", "h4"} + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) + + # Rename graphs with string-like nodes + G = nx.Graph() + G.add_node("a") + G.add_edge("b", "c") + H = nx.Graph() + H.add_edge("d", "e") + + U = nx.full_join(G, H, rename=("g", "h")) + assert set(U) == {"ga", "gb", "gc", "hd", "he"} + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) + + # DiGraphs + G = nx.DiGraph() + G.add_node(0) + G.add_edge(1, 2) + H = nx.DiGraph() + H.add_edge(3, 4) + + U = nx.full_join(G, H) + assert set(U) == set(G) | set(H) + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2 + + # DiGraphs Rename + U = nx.full_join(G, H, rename=("g", "h")) + assert set(U) == {"g0", "g1", "g2", "h3", "h4"} + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2 + + +def test_full_join_multigraph(): + # MultiGraphs + G = nx.MultiGraph() + G.add_node(0) + G.add_edge(1, 2) + H = nx.MultiGraph() + H.add_edge(3, 4) + + U = nx.full_join(G, H) + assert set(U) == set(G) | set(H) + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) + + # MultiGraphs rename + U = nx.full_join(G, H, rename=("g", "h")) + assert set(U) == {"g0", "g1", "g2", "h3", "h4"} + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) + + # MultiDiGraphs + G = nx.MultiDiGraph() + G.add_node(0) + G.add_edge(1, 2) + H = nx.MultiDiGraph() + H.add_edge(3, 4) + + U = nx.full_join(G, H) + assert set(U) == set(G) | set(H) + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2 + + # MultiDiGraphs rename + U = nx.full_join(G, H, rename=("g", "h")) + assert set(U) == {"g0", "g1", "g2", "h3", "h4"} + assert len(U) == len(G) + len(H) + assert len(U.edges()) == len(G.edges()) + len(H.edges()) + len(G) * len(H) * 2 + + +def test_mixed_type_union(): + G = nx.Graph() + H = nx.MultiGraph() + pytest.raises(nx.NetworkXError, nx.union, G, H) + pytest.raises(nx.NetworkXError, nx.disjoint_union, G, H) + pytest.raises(nx.NetworkXError, nx.intersection, G, H) + pytest.raises(nx.NetworkXError, nx.difference, G, H) + pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H) + pytest.raises(nx.NetworkXError, nx.compose, G, H) diff --git a/shared/package-files/93/9355791da0195b2a52626be11d159d11c9f2808a101693a25cdad3800d210a1d/py38.cpython-311.pyc b/shared/package-files/93/9355791da0195b2a52626be11d159d11c9f2808a101693a25cdad3800d210a1d/py38.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c93cc07a58f74aa8a4a7b32692ad1809fadd5f6e Binary files /dev/null and b/shared/package-files/93/9355791da0195b2a52626be11d159d11c9f2808a101693a25cdad3800d210a1d/py38.cpython-311.pyc differ diff --git a/shared/package-files/93/935a454b47b5747be29828ca04a894eb0ab0d9d69c7c40ae3a18ba834af5c381/period.cpython-311.pyc b/shared/package-files/93/935a454b47b5747be29828ca04a894eb0ab0d9d69c7c40ae3a18ba834af5c381/period.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6528b2102a194ad19caec9418c1582d37d21960b Binary files /dev/null and b/shared/package-files/93/935a454b47b5747be29828ca04a894eb0ab0d9d69c7c40ae3a18ba834af5c381/period.cpython-311.pyc differ diff --git a/shared/package-files/93/9363ded6c4cd0842eccd47d15374957fee785874638a04a9d03e750aada99910/test_nth.py b/shared/package-files/93/9363ded6c4cd0842eccd47d15374957fee785874638a04a9d03e750aada99910/test_nth.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ed9e9d5202173b25b8dc47598e49672e0c8a31 --- /dev/null +++ b/shared/package-files/93/9363ded6c4cd0842eccd47d15374957fee785874638a04a9d03e750aada99910/test_nth.py @@ -0,0 +1,921 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + Timestamp, + isna, +) +import pandas._testing as tm + + +def test_first_last_nth(df): + # tests for first / last / nth + grouped = df.groupby("A") + first = grouped.first() + expected = df.loc[[1, 0], ["B", "C", "D"]] + expected.index = Index(["bar", "foo"], name="A") + expected = expected.sort_index() + tm.assert_frame_equal(first, expected) + + nth = grouped.nth(0) + expected = df.loc[[0, 1]] + tm.assert_frame_equal(nth, expected) + + last = grouped.last() + expected = df.loc[[5, 7], ["B", "C", "D"]] + expected.index = Index(["bar", "foo"], name="A") + tm.assert_frame_equal(last, expected) + + nth = grouped.nth(-1) + expected = df.iloc[[5, 7]] + tm.assert_frame_equal(nth, expected) + + nth = grouped.nth(1) + expected = df.iloc[[2, 3]] + tm.assert_frame_equal(nth, expected) + + # it works! + grouped["B"].first() + grouped["B"].last() + grouped["B"].nth(0) + + df = df.copy() + df.loc[df["A"] == "foo", "B"] = np.nan + grouped = df.groupby("A") + assert isna(grouped["B"].first()["foo"]) + assert isna(grouped["B"].last()["foo"]) + assert isna(grouped["B"].nth(0).iloc[0]) + + # v0.14.0 whatsnew + df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) + g = df.groupby("A") + result = g.first() + expected = df.iloc[[1, 2]].set_index("A") + tm.assert_frame_equal(result, expected) + + expected = df.iloc[[1, 2]] + result = g.nth(0, dropna="any") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["first", "last"]) +def test_first_last_with_na_object(method, nulls_fixture): + # https://github.com/pandas-dev/pandas/issues/32123 + groups = DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 3, nulls_fixture]}).groupby("a") + result = getattr(groups, method)() + + if method == "first": + values = [1, 3] + else: + values = [2, 3] + + values = np.array(values, dtype=result["b"].dtype) + idx = Index([1, 2], name="a") + expected = DataFrame({"b": values}, index=idx) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index", [0, -1]) +def test_nth_with_na_object(index, nulls_fixture): + # https://github.com/pandas-dev/pandas/issues/32123 + df = DataFrame({"a": [1, 1, 2, 2], "b": [1, 2, 3, nulls_fixture]}) + groups = df.groupby("a") + result = groups.nth(index) + expected = df.iloc[[0, 2]] if index == 0 else df.iloc[[1, 3]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["first", "last"]) +def test_first_last_with_None(method): + # https://github.com/pandas-dev/pandas/issues/32800 + # None should be preserved as object dtype + df = DataFrame.from_dict({"id": ["a"], "value": [None]}) + groups = df.groupby("id", as_index=False) + result = getattr(groups, method)() + + tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize("method", ["first", "last"]) +@pytest.mark.parametrize( + "df, expected", + [ + ( + DataFrame({"id": "a", "value": [None, "foo", np.nan]}), + DataFrame({"value": ["foo"]}, index=Index(["a"], name="id")), + ), + ( + DataFrame({"id": "a", "value": [np.nan]}, dtype=object), + DataFrame({"value": [None]}, index=Index(["a"], name="id")), + ), + ], +) +def test_first_last_with_None_expanded(method, df, expected): + # GH 32800, 38286 + result = getattr(df.groupby("id"), method)() + tm.assert_frame_equal(result, expected) + + +def test_first_last_nth_dtypes(): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.array(np.random.default_rng(2).standard_normal(8), dtype="float32"), + } + ) + df["E"] = True + df["F"] = 1 + + # tests for first / last / nth + grouped = df.groupby("A") + first = grouped.first() + expected = df.loc[[1, 0], ["B", "C", "D", "E", "F"]] + expected.index = Index(["bar", "foo"], name="A") + expected = expected.sort_index() + tm.assert_frame_equal(first, expected) + + last = grouped.last() + expected = df.loc[[5, 7], ["B", "C", "D", "E", "F"]] + expected.index = Index(["bar", "foo"], name="A") + expected = expected.sort_index() + tm.assert_frame_equal(last, expected) + + nth = grouped.nth(1) + expected = df.iloc[[2, 3]] + tm.assert_frame_equal(nth, expected) + + +def test_first_last_nth_dtypes2(): + # GH 2763, first/last shifting dtypes + idx = list(range(10)) + idx.append(9) + ser = Series(data=range(11), index=idx, name="IntCol") + assert ser.dtype == "int64" + f = ser.groupby(level=0).first() + assert f.dtype == "int64" + + +def test_first_last_nth_nan_dtype(): + # GH 33591 + df = DataFrame({"data": ["A"], "nans": Series([None], dtype=object)}) + grouped = df.groupby("data") + + expected = df.set_index("data").nans + tm.assert_series_equal(grouped.nans.first(), expected) + tm.assert_series_equal(grouped.nans.last(), expected) + + expected = df.nans + tm.assert_series_equal(grouped.nans.nth(-1), expected) + tm.assert_series_equal(grouped.nans.nth(0), expected) + + +def test_first_strings_timestamps(): + # GH 11244 + test = DataFrame( + { + Timestamp("2012-01-01 00:00:00"): ["a", "b"], + Timestamp("2012-01-02 00:00:00"): ["c", "d"], + "name": ["e", "e"], + "aaaa": ["f", "g"], + } + ) + result = test.groupby("name").first() + expected = DataFrame( + [["a", "c", "f"]], + columns=Index([Timestamp("2012-01-01"), Timestamp("2012-01-02"), "aaaa"]), + index=Index(["e"], name="name"), + ) + tm.assert_frame_equal(result, expected) + + +def test_nth(): + df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 2]]) + tm.assert_frame_equal(gb.nth(1), df.iloc[[1]]) + tm.assert_frame_equal(gb.nth(2), df.loc[[]]) + tm.assert_frame_equal(gb.nth(-1), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-2), df.iloc[[0]]) + tm.assert_frame_equal(gb.nth(-3), df.loc[[]]) + tm.assert_series_equal(gb.B.nth(0), df.B.iloc[[0, 2]]) + tm.assert_series_equal(gb.B.nth(1), df.B.iloc[[1]]) + tm.assert_frame_equal(gb[["B"]].nth(0), df[["B"]].iloc[[0, 2]]) + + tm.assert_frame_equal(gb.nth(0, dropna="any"), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-1, dropna="any"), df.iloc[[1, 2]]) + + tm.assert_frame_equal(gb.nth(7, dropna="any"), df.iloc[:0]) + tm.assert_frame_equal(gb.nth(2, dropna="any"), df.iloc[:0]) + + +def test_nth2(): + # out of bounds, regression from 0.13.1 + # GH 6621 + df = DataFrame( + { + "color": {0: "green", 1: "green", 2: "red", 3: "red", 4: "red"}, + "food": {0: "ham", 1: "eggs", 2: "eggs", 3: "ham", 4: "pork"}, + "two": { + 0: 1.5456590000000001, + 1: -0.070345000000000005, + 2: -2.4004539999999999, + 3: 0.46206000000000003, + 4: 0.52350799999999997, + }, + "one": { + 0: 0.56573799999999996, + 1: -0.9742360000000001, + 2: 1.033801, + 3: -0.78543499999999999, + 4: 0.70422799999999997, + }, + } + ).set_index(["color", "food"]) + + result = df.groupby(level=0, as_index=False).nth(2) + expected = df.iloc[[-1]] + tm.assert_frame_equal(result, expected) + + result = df.groupby(level=0, as_index=False).nth(3) + expected = df.loc[[]] + tm.assert_frame_equal(result, expected) + + +def test_nth3(): + # GH 7559 + # from the vbench + df = DataFrame(np.random.default_rng(2).integers(1, 10, (100, 2)), dtype="int64") + ser = df[1] + gb = df[0] + expected = ser.groupby(gb).first() + expected2 = ser.groupby(gb).apply(lambda x: x.iloc[0]) + tm.assert_series_equal(expected2, expected, check_names=False) + assert expected.name == 1 + assert expected2.name == 1 + + # validate first + v = ser[gb == 1].iloc[0] + assert expected.iloc[0] == v + assert expected2.iloc[0] == v + + with pytest.raises(ValueError, match="For a DataFrame"): + ser.groupby(gb, sort=False).nth(0, dropna=True) + + +def test_nth4(): + # doc example + df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) + gb = df.groupby("A") + result = gb.B.nth(0, dropna="all") + expected = df.B.iloc[[1, 2]] + tm.assert_series_equal(result, expected) + + +def test_nth5(): + # test multiple nth values + df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=["A", "B"]) + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0]), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0, 1]), df.iloc[[0, 1, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, -1]), df.iloc[[0, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([2]), df.iloc[[2]]) + tm.assert_frame_equal(gb.nth([3, 4]), df.loc[[]]) + + +def test_nth_bdays(unit): + business_dates = pd.date_range( + start="4/1/2014", end="6/30/2014", freq="B", unit=unit + ) + df = DataFrame(1, index=business_dates, columns=["a", "b"]) + # get the first, fourth and last two business days for each month + key = [df.index.year, df.index.month] + result = df.groupby(key, as_index=False).nth([0, 3, -2, -1]) + expected_dates = pd.to_datetime( + [ + "2014/4/1", + "2014/4/4", + "2014/4/29", + "2014/4/30", + "2014/5/1", + "2014/5/6", + "2014/5/29", + "2014/5/30", + "2014/6/2", + "2014/6/5", + "2014/6/27", + "2014/6/30", + ] + ).as_unit(unit) + expected = DataFrame(1, columns=["a", "b"], index=expected_dates) + tm.assert_frame_equal(result, expected) + + +def test_nth_multi_grouper(three_group): + # PR 9090, related to issue 8979 + # test nth on multiple groupers + grouped = three_group.groupby(["A", "B"]) + result = grouped.nth(0) + expected = three_group.iloc[[0, 3, 4, 7]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data, expected_first, expected_last", + [ + ( + { + "id": ["A"], + "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + { + "id": ["A"], + "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + { + "id": ["A"], + "time": Timestamp("2012-02-01 14:00:00", tz="US/Central"), + "foo": [1], + }, + ), + ( + { + "id": ["A", "B", "A"], + "time": [ + Timestamp("2012-01-01 13:00:00", tz="America/New_York"), + Timestamp("2012-02-01 14:00:00", tz="US/Central"), + Timestamp("2012-03-01 12:00:00", tz="Europe/London"), + ], + "foo": [1, 2, 3], + }, + { + "id": ["A", "B"], + "time": [ + Timestamp("2012-01-01 13:00:00", tz="America/New_York"), + Timestamp("2012-02-01 14:00:00", tz="US/Central"), + ], + "foo": [1, 2], + }, + { + "id": ["A", "B"], + "time": [ + Timestamp("2012-03-01 12:00:00", tz="Europe/London"), + Timestamp("2012-02-01 14:00:00", tz="US/Central"), + ], + "foo": [3, 2], + }, + ), + ], +) +def test_first_last_tz(data, expected_first, expected_last): + # GH15884 + # Test that the timezone is retained when calling first + # or last on groupby with as_index=False + + df = DataFrame(data) + + result = df.groupby("id", as_index=False).first() + expected = DataFrame(expected_first) + cols = ["id", "time", "foo"] + tm.assert_frame_equal(result[cols], expected[cols]) + + result = df.groupby("id", as_index=False)["time"].first() + tm.assert_frame_equal(result, expected[["id", "time"]]) + + result = df.groupby("id", as_index=False).last() + expected = DataFrame(expected_last) + cols = ["id", "time", "foo"] + tm.assert_frame_equal(result[cols], expected[cols]) + + result = df.groupby("id", as_index=False)["time"].last() + tm.assert_frame_equal(result, expected[["id", "time"]]) + + +@pytest.mark.parametrize( + "method, ts, alpha", + [ + ["first", Timestamp("2013-01-01", tz="US/Eastern"), "a"], + ["last", Timestamp("2013-01-02", tz="US/Eastern"), "b"], + ], +) +def test_first_last_tz_multi_column(method, ts, alpha, unit): + # GH 21603 + category_string = Series(list("abc")).astype("category") + dti = pd.date_range("20130101", periods=3, tz="US/Eastern", unit=unit) + df = DataFrame( + { + "group": [1, 1, 2], + "category_string": category_string, + "datetimetz": dti, + } + ) + result = getattr(df.groupby("group"), method)() + expected = DataFrame( + { + "category_string": pd.Categorical( + [alpha, "c"], dtype=category_string.dtype + ), + "datetimetz": [ts, Timestamp("2013-01-03", tz="US/Eastern")], + }, + index=Index([1, 2], name="group"), + ) + expected["datetimetz"] = expected["datetimetz"].dt.as_unit(unit) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + pd.array([True, False], dtype="boolean"), + pd.array([1, 2], dtype="Int64"), + pd.to_datetime(["2020-01-01", "2020-02-01"]), + pd.to_timedelta([1, 2], unit="D"), + ], +) +@pytest.mark.parametrize("function", ["first", "last", "min", "max"]) +def test_first_last_extension_array_keeps_dtype(values, function): + # https://github.com/pandas-dev/pandas/issues/33071 + # https://github.com/pandas-dev/pandas/issues/32194 + df = DataFrame({"a": [1, 2], "b": values}) + grouped = df.groupby("a") + idx = Index([1, 2], name="a") + expected_series = Series(values, name="b", index=idx) + expected_frame = DataFrame({"b": values}, index=idx) + + result_series = getattr(grouped["b"], function)() + tm.assert_series_equal(result_series, expected_series) + + result_frame = grouped.agg({"b": function}) + tm.assert_frame_equal(result_frame, expected_frame) + + +def test_nth_multi_index_as_expected(): + # PR 9090, related to issue 8979 + # test nth on MultiIndex + three_group = DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "C": [ + "dull", + "dull", + "shiny", + "dull", + "dull", + "shiny", + "shiny", + "dull", + "shiny", + "shiny", + "shiny", + ], + } + ) + grouped = three_group.groupby(["A", "B"]) + result = grouped.nth(0) + expected = three_group.iloc[[0, 3, 4, 7]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op, n, expected_rows", + [ + ("head", -1, [0]), + ("head", 0, []), + ("head", 1, [0, 2]), + ("head", 7, [0, 1, 2]), + ("tail", -1, [1]), + ("tail", 0, []), + ("tail", 1, [1, 2]), + ("tail", 7, [0, 1, 2]), + ], +) +@pytest.mark.parametrize("columns", [None, [], ["A"], ["B"], ["A", "B"]]) +@pytest.mark.parametrize("as_index", [True, False]) +def test_groupby_head_tail(op, n, expected_rows, columns, as_index): + df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) + g = df.groupby("A", as_index=as_index) + expected = df.iloc[expected_rows] + if columns is not None: + g = g[columns] + expected = expected[columns] + result = getattr(g, op)(n) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op, n, expected_cols", + [ + ("head", -1, [0]), + ("head", 0, []), + ("head", 1, [0, 2]), + ("head", 7, [0, 1, 2]), + ("tail", -1, [1]), + ("tail", 0, []), + ("tail", 1, [1, 2]), + ("tail", 7, [0, 1, 2]), + ], +) +def test_groupby_head_tail_axis_1(op, n, expected_cols): + # GH 9772 + df = DataFrame( + [[1, 2, 3], [1, 4, 5], [2, 6, 7], [3, 8, 9]], columns=["A", "B", "C"] + ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = df.groupby([0, 0, 1], axis=1) + expected = df.iloc[:, expected_cols] + result = getattr(g, op)(n) + tm.assert_frame_equal(result, expected) + + +def test_group_selection_cache(): + # GH 12839 nth, head, and tail should return same result consistently + df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) + expected = df.iloc[[0, 2]] + + g = df.groupby("A") + result1 = g.head(n=2) + result2 = g.nth(0) + tm.assert_frame_equal(result1, df) + tm.assert_frame_equal(result2, expected) + + g = df.groupby("A") + result1 = g.tail(n=2) + result2 = g.nth(0) + tm.assert_frame_equal(result1, df) + tm.assert_frame_equal(result2, expected) + + g = df.groupby("A") + result1 = g.nth(0) + result2 = g.head(n=2) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, df) + + g = df.groupby("A") + result1 = g.nth(0) + result2 = g.tail(n=2) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, df) + + +def test_nth_empty(): + # GH 16064 + df = DataFrame(index=[0], columns=["a", "b", "c"]) + result = df.groupby("a").nth(10) + expected = df.iloc[:0] + tm.assert_frame_equal(result, expected) + + result = df.groupby(["a", "b"]).nth(10) + expected = df.iloc[:0] + tm.assert_frame_equal(result, expected) + + +def test_nth_column_order(): + # GH 20760 + # Check that nth preserves column order + df = DataFrame( + [[1, "b", 100], [1, "a", 50], [1, "a", np.nan], [2, "c", 200], [2, "d", 150]], + columns=["A", "C", "B"], + ) + result = df.groupby("A").nth(0) + expected = df.iloc[[0, 3]] + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").nth(-1, dropna="any") + expected = df.iloc[[1, 4]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dropna", [None, "any", "all"]) +def test_nth_nan_in_grouper(dropna): + # GH 26011 + df = DataFrame( + { + "a": [np.nan, "a", np.nan, "b", np.nan], + "b": [0, 2, 4, 6, 8], + "c": [1, 3, 5, 7, 9], + } + ) + result = df.groupby("a").nth(0, dropna=dropna) + expected = df.iloc[[1, 3]] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dropna", [None, "any", "all"]) +def test_nth_nan_in_grouper_series(dropna): + # GH 26454 + df = DataFrame( + { + "a": [np.nan, "a", np.nan, "b", np.nan], + "b": [0, 2, 4, 6, 8], + } + ) + result = df.groupby("a")["b"].nth(0, dropna=dropna) + expected = df["b"].iloc[[1, 3]] + + tm.assert_series_equal(result, expected) + + +def test_first_categorical_and_datetime_data_nat(): + # GH 20520 + df = DataFrame( + { + "group": ["first", "first", "second", "third", "third"], + "time": 5 * [np.datetime64("NaT")], + "categories": Series(["a", "b", "c", "a", "b"], dtype="category"), + } + ) + result = df.groupby("group").first() + expected = DataFrame( + { + "time": 3 * [np.datetime64("NaT")], + "categories": Series(["a", "c", "a"]).astype( + pd.CategoricalDtype(["a", "b", "c"]) + ), + } + ) + expected.index = Index(["first", "second", "third"], name="group") + tm.assert_frame_equal(result, expected) + + +def test_first_multi_key_groupby_categorical(): + # GH 22512 + df = DataFrame( + { + "A": [1, 1, 1, 2, 2], + "B": [100, 100, 200, 100, 100], + "C": ["apple", "orange", "mango", "mango", "orange"], + "D": ["jupiter", "mercury", "mars", "venus", "venus"], + } + ) + df = df.astype({"D": "category"}) + result = df.groupby(by=["A", "B"]).first() + expected = DataFrame( + { + "C": ["apple", "mango", "mango"], + "D": Series(["jupiter", "mars", "venus"]).astype( + pd.CategoricalDtype(["jupiter", "mars", "mercury", "venus"]) + ), + } + ) + expected.index = MultiIndex.from_tuples( + [(1, 100), (1, 200), (2, 100)], names=["A", "B"] + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["first", "last", "nth"]) +def test_groupby_last_first_nth_with_none(method, nulls_fixture): + # GH29645 + expected = Series(["y"]) + data = Series( + [nulls_fixture, nulls_fixture, nulls_fixture, "y", nulls_fixture], + index=[0, 0, 0, 0, 0], + ).groupby(level=0) + + if method == "nth": + result = getattr(data, method)(3) + else: + result = getattr(data, method)() + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "arg, expected_rows", + [ + [slice(None, 3, 2), [0, 1, 4, 5]], + [slice(None, -2), [0, 2, 5]], + [[slice(None, 2), slice(-2, None)], [0, 1, 2, 3, 4, 6, 7]], + [[0, 1, slice(-2, None)], [0, 1, 2, 3, 4, 6, 7]], + ], +) +def test_slice(slice_test_df, slice_test_grouped, arg, expected_rows): + # Test slices GH #42947 + + result = slice_test_grouped.nth[arg] + equivalent = slice_test_grouped.nth(arg) + expected = slice_test_df.iloc[expected_rows] + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(equivalent, expected) + + +def test_nth_indexed(slice_test_df, slice_test_grouped): + # Test index notation GH #44688 + + result = slice_test_grouped.nth[0, 1, -2:] + equivalent = slice_test_grouped.nth([0, 1, slice(-2, None)]) + expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]] + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(equivalent, expected) + + +def test_invalid_argument(slice_test_grouped): + # Test for error on invalid argument + + with pytest.raises(TypeError, match="Invalid index"): + slice_test_grouped.nth(3.14) + + +def test_negative_step(slice_test_grouped): + # Test for error on negative slice step + + with pytest.raises(ValueError, match="Invalid step"): + slice_test_grouped.nth(slice(None, None, -1)) + + +def test_np_ints(slice_test_df, slice_test_grouped): + # Test np ints work + + result = slice_test_grouped.nth(np.array([0, 1])) + expected = slice_test_df.iloc[[0, 1, 2, 3, 4]] + tm.assert_frame_equal(result, expected) + + +def test_groupby_nth_with_column_axis(): + # GH43926 + df = DataFrame( + [ + [4, 5, 6], + [8, 8, 7], + ], + index=["z", "y"], + columns=["C", "B", "A"], + ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(df.iloc[1], axis=1) + result = gb.nth(0) + expected = df.iloc[:, [0, 2]] + tm.assert_frame_equal(result, expected) + + +def test_groupby_nth_interval(): + # GH#24205 + idx_result = MultiIndex( + [ + pd.CategoricalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]), + pd.CategoricalIndex([pd.Interval(0, 10), pd.Interval(10, 20)]), + ], + [[0, 0, 0, 1, 1], [0, 1, 1, 0, -1]], + ) + df_result = DataFrame({"col": range(len(idx_result))}, index=idx_result) + result = df_result.groupby(level=[0, 1], observed=False).nth(0) + val_expected = [0, 1, 3] + idx_expected = MultiIndex( + [ + pd.CategoricalIndex([pd.Interval(0, 1), pd.Interval(1, 2)]), + pd.CategoricalIndex([pd.Interval(0, 10), pd.Interval(10, 20)]), + ], + [[0, 0, 1], [0, 1, 0]], + ) + expected = DataFrame(val_expected, index=idx_expected, columns=["col"]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "start, stop, expected_values, expected_columns", + [ + (None, None, [0, 1, 2, 3, 4], list("ABCDE")), + (None, 1, [0, 3], list("AD")), + (None, 9, [0, 1, 2, 3, 4], list("ABCDE")), + (None, -1, [0, 1, 3], list("ABD")), + (1, None, [1, 2, 4], list("BCE")), + (1, -1, [1], list("B")), + (-1, None, [2, 4], list("CE")), + (-1, 2, [4], list("E")), + ], +) +@pytest.mark.parametrize("method", ["call", "index"]) +def test_nth_slices_with_column_axis( + start, stop, expected_values, expected_columns, method +): + df = DataFrame([range(5)], columns=[list("ABCDE")]) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([5, 5, 5, 6, 6], axis=1) + result = { + "call": lambda start, stop: gb.nth(slice(start, stop)), + "index": lambda start, stop: gb.nth[start:stop], + }[method](start, stop) + expected = DataFrame([expected_values], columns=[expected_columns]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings( + "ignore:invalid value encountered in remainder:RuntimeWarning" +) +def test_head_tail_dropna_true(): + # GH#45089 + df = DataFrame( + [["a", "z"], ["b", np.nan], ["c", np.nan], ["c", np.nan]], columns=["X", "Y"] + ) + expected = DataFrame([["a", "z"]], columns=["X", "Y"]) + + result = df.groupby(["X", "Y"]).head(n=1) + tm.assert_frame_equal(result, expected) + + result = df.groupby(["X", "Y"]).tail(n=1) + tm.assert_frame_equal(result, expected) + + result = df.groupby(["X", "Y"]).nth(n=0) + tm.assert_frame_equal(result, expected) + + +def test_head_tail_dropna_false(): + # GH#45089 + df = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"]) + expected = DataFrame([["a", "z"], ["b", np.nan], ["c", np.nan]], columns=["X", "Y"]) + + result = df.groupby(["X", "Y"], dropna=False).head(n=1) + tm.assert_frame_equal(result, expected) + + result = df.groupby(["X", "Y"], dropna=False).tail(n=1) + tm.assert_frame_equal(result, expected) + + result = df.groupby(["X", "Y"], dropna=False).nth(n=0) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("selection", ("b", ["b"], ["b", "c"])) +@pytest.mark.parametrize("dropna", ["any", "all", None]) +def test_nth_after_selection(selection, dropna): + # GH#11038, GH#53518 + df = DataFrame( + { + "a": [1, 1, 2], + "b": [np.nan, 3, 4], + "c": [5, 6, 7], + } + ) + gb = df.groupby("a")[selection] + result = gb.nth(0, dropna=dropna) + if dropna == "any" or (dropna == "all" and selection != ["b", "c"]): + locs = [1, 2] + else: + locs = [0, 2] + expected = df.loc[locs, selection] + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "data", + [ + ( + Timestamp("2011-01-15 12:50:28.502376"), + Timestamp("2011-01-20 12:50:28.593448"), + ), + (24650000000000001, 24650000000000002), + ], +) +def test_groupby_nth_int_like_precision(data): + # GH#6620, GH#9311 + df = DataFrame({"a": [1, 1], "b": data}) + + grouped = df.groupby("a") + result = grouped.nth(0) + expected = DataFrame({"a": 1, "b": [data[0]]}) + + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/93/936a6026d96d45e18ba90e0c8569ce3cfcbeeee4a745967a19e5ae8ee1783cd6/test_actuator.cpython-311.pyc b/shared/package-files/93/936a6026d96d45e18ba90e0c8569ce3cfcbeeee4a745967a19e5ae8ee1783cd6/test_actuator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af0b2f9eb13179e577accc3e75eaa35c8be4da94 Binary files /dev/null and b/shared/package-files/93/936a6026d96d45e18ba90e0c8569ce3cfcbeeee4a745967a19e5ae8ee1783cd6/test_actuator.cpython-311.pyc differ diff --git a/shared/package-files/93/93722ae1caf77599c6ca97c1b8e48183dc730dc99f0880647406fc8d36565039/big5hkscs.cpython-311.pyc b/shared/package-files/93/93722ae1caf77599c6ca97c1b8e48183dc730dc99f0880647406fc8d36565039/big5hkscs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99a711fdc9948e685bdb00b48fad09b153aafd49 Binary files /dev/null and b/shared/package-files/93/93722ae1caf77599c6ca97c1b8e48183dc730dc99f0880647406fc8d36565039/big5hkscs.cpython-311.pyc differ diff --git a/shared/package-files/93/9375e67beb34f90a982c90e5277c0b71b4a7c91368d708d10a6681ae37717085/gen_inplace_or_view_type.py b/shared/package-files/93/9375e67beb34f90a982c90e5277c0b71b4a7c91368d708d10a6681ae37717085/gen_inplace_or_view_type.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd882d00cf1ad9c817905ac8821ea5bbf998a1e --- /dev/null +++ b/shared/package-files/93/9375e67beb34f90a982c90e5277c0b71b4a7c91368d708d10a6681ae37717085/gen_inplace_or_view_type.py @@ -0,0 +1,673 @@ +# Generates ADInplaceOrViewType.h/cpp +# +# NOTE: If any changes are being made to the ADInplaceOrView codegen please also check +# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp +# The fallback is expected to mimick this codegen, so we should keep the two in sync. + +from __future__ import annotations + +from torchgen.api import cpp +from torchgen.api.autograd import ( + dispatch_strategy, + gen_differentiable_outputs, + NativeFunctionWithDifferentiabilityInfo, +) +from torchgen.api.types import ( + BaseCType, + Binding, + boolT, + ConstRefCType, + CType, + DispatcherSignature, + intArrayRefT, + longT, + OptionalCType, + symIntArrayRefT, + SymIntT, + tensorT, +) +from torchgen.code_template import CodeTemplate +from torchgen.context import with_native_function +from torchgen.model import ( + NativeFunction, + SchemaKind, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.utils import FileManager + +from .context import with_native_function_with_differentiability_info +from .gen_trace_type import ( + get_return_value, + MANUAL_AUTOGRAD, + tie_return_values, + type_wrapper_name, +) + + +# See NOTE [ Autograd View Variables ] in variable.h for details. +# If you update list VIEW_FUNCTIONS or RETURNS_VIEWS_OF_INPUT, +# you **MUST** also update the public list of view ops accordingly in +# docs/source/tensor_view.rst. Note not all ATen functions are exposed to public, +# e.g alias & sparse_coo_tensor_with_dims_and_tensors. +# +# A map: function name => name of the argument that all outputs are view of + +VIEW_FUNCTIONS_WITH_METADATA_CHANGE = [ + "view_as_complex", + "view_as_real", + "_conj", + "_neg_view", + "_nested_get_values", + "_nested_view_from_buffer", + "_nested_view_from_jagged", +] + +VIEW_FUNCTIONS = { + "numpy_T": "self", + "alias": "self", + "as_strided": "self", + "diagonal": "self", + "expand": "self", + "permute": "self", + "select": "self", + "slice": "self", + "slice_inverse": "self", + "split": "self", + "split_with_sizes": "self", + "squeeze": "self", + "t": "self", + "transpose": "self", + "unfold": "self", + "unsqueeze": "self", + "flatten": "self", + "view": "self", + "unbind": "self", + "_indices": "self", + "_values": "self", + "indices": "self", + "values": "self", + "crow_indices": "self", + "col_indices": "self", + "ccol_indices": "self", + "row_indices": "self", + # sparse_coo ctor output should really be views of both indices and values, + # but we only supports making as view of a single variable, and indices is + # discrete anyways. + # FIXME: clone indices on construction. + "sparse_coo_tensor_with_dims_and_tensors": "values", + "_reshape_alias": "self", + "_test_autograd_multiple_dispatch_view": "self", +} + +for key in VIEW_FUNCTIONS_WITH_METADATA_CHANGE: + VIEW_FUNCTIONS[key] = "self" + +# note: some VIEW_FUNCTIONS are just compositions of the view functions above +# this list contains both the root view functions and any that are purely composed +# of viewing functions, and is used by the JIT to determine when an operator +# may return a view of its inputs; however they may sometimes return a copy. +# (e.g. `contiguous`) +RETURNS_VIEWS_OF_INPUT = set(VIEW_FUNCTIONS.keys()).union( + { + "chunk", + "detach", + "contiguous", + "reshape", + "reshape_as", + "expand_as", + "view_as", + "real", + "imag", + "narrow", + "movedim", + "tensor_split", + "swapdims", + "swapaxes", + "mT", + "mH", + "adjoint", + "matrix_H", + } +) + +# These are the functions we consider views for the purposes of validating +# StorageImpl and TensorImpl in gen_variable_type. +# `_unsafe_view` is not included in VIEW_FUNCTIONS above because it is not a +# view for the purposes of ADInplaceOrView kernel, we do not want to call as_view +# See NOTE [Unsafe View] for more info. +ALL_VIEW_FUNCTIONS = { + **VIEW_FUNCTIONS, + "_unsafe_view": "self", +} + +ARRAYREF_TO_VEC = CodeTemplate( + """\ +auto ${vec} = ${arg}.vec(); +""" +) + +OPTIONAL_TO_VAL = CodeTemplate( + """\ +auto ${val} = ${arg}.value_or(${default}); +""" +) + +CALL_DISPATCH = CodeTemplate( + """\ +at::_ops::${unambiguous_name}::call(${unpacked_args})""" +) + +REVERSE_VIEW_DISPATCH = CodeTemplate( + """\ +${reverse_name}(${unpacked_args})""" +) + +MULTI_OUTPUT_VIEW_ITERATION = CodeTemplate( + """\ +for (auto ${view_idx} : c10::irange(${var}.size())) { + ${body} +} +""" +) + +SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE = CodeTemplate( + """\ +std::unique_ptr func(nullptr); +std::function rev_func=nullptr; +if (${is_view_with_metadata_change} || + !self.unsafeGetTensorImpl()->support_as_strided() || + self.unsafeGetTensorImpl()->is_python_dispatch() || + c10::AutogradState::get_tls_state().get_view_replay_enabled()) { + ${replay_view_func} + ${reverse_replay_view_func} +} +""" +) + +REPLAY_VIEW_FUNC = CodeTemplate( + """\ +func = std::make_unique<${view_func_name}>(${view_func_args}); +""" +) + +REVERSE_REPLAY_VIEW_LAMBDA_FUNC = CodeTemplate( + """\ +rev_func = [=](const at::Tensor& ${input_view}) { + return ${reverse_replay_view_call}; +}; +""" +) + +METHOD_DEFINITION = CodeTemplate( + """\ +${return_type} ${type_wrapper_name}(${formals}) { + ${type_definition_body} +} +""" +) + +WRAPPER_REGISTRATION = CodeTemplate( + """\ +m.impl("${unqual_operator_name_with_overload}", + TORCH_FN(${class_type}::${type_wrapper_name}) +); +""" +) + +AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION = CodeTemplate( + """\ +m.impl("${unqual_operator_name_with_overload}", torch::autograd::autogradNotImplementedFallback()); +""" +) + +INPLACE_REDISPATCH = CodeTemplate( + """\ +{ + at::AutoDispatchBelowADInplaceOrView guard; + at::_ops::${unambiguous_name}::redispatch(${unpacked_args}); +} +""" +) + +ASSIGN_RETURN_VALUE = CodeTemplate( + """\ +${return_values} = ${rhs_value}; +""" +) + +VIEW_REDISPATCH = CodeTemplate( + """\ +${assign_return_values} ([&]() { + at::AutoDispatchBelowADInplaceOrView guard; + return at::_ops::${unambiguous_name}::redispatch(${unpacked_args}); +})(); +""" +) + +TMP_VAR = "_tmp" + + +# FIXME: Ideally these functions should be methods on Type class, but we have a +# comment in codegen/model.py there saying these concepts are not well defined. +# Thus we put a version that commonly used by autograd codegen here. +def is_tensor_type(t: Type) -> bool: + # TODO: Should handle optional here? + return t.is_tensor_like() and t.is_list_like() is None + + +def is_tensor_list_type(t: Type) -> bool: + # TODO: Should handle optional here? + return t.is_tensor_like() and t.is_list_like() is not None + + +UNPACK_TENSOR = CodeTemplate( + """\ +auto${ref} ${arg_name}_ = unpack${suffix}(${arg_name}, "${arg_name}", ${arg_pos});""" +) + + +def unpacked_name(arg_name: str) -> str: + return arg_name + "_" + + +# e.g. select.int -> select_copy_int_inverse() +def inverse_view_name(f: NativeFunction) -> str: + copy_variant = f"{f.root_name}_copy" + overload = f"{f.func.name.overload_name}" + if overload != "": + overload = "_" + overload + return f"{copy_variant}{overload}_inverse" + + +def extract_bindings(f: NativeFunction) -> list[Binding]: + return [ + r + for a in f.func.schema_order_arguments() + for r in cpp.argument( + a, + method=False, + symint=True, + cpp_no_default_args=set(), + faithful=False, + has_tensor_options=False, + ) + ] + + +@with_native_function +def unpack_args(f: NativeFunction) -> tuple[list[str], list[Binding]]: + body: list[str] = [] + unpacked_bindings: list[Binding] = [] + + for i, binding in enumerate(extract_bindings(f)): + assert not isinstance(binding.argument, SelfArgument) + if isinstance(binding.argument, TensorOptionsArguments): + raise RuntimeError("VariableKernel shouldn't take TensorOptions") + + is_nullable = binding.argument.type.is_nullable() + if not binding.argument.type.is_tensor_like() or is_nullable: + unpacked_bindings.append(binding) + continue + + is_tensor_list = is_tensor_list_type(binding.argument.type) + ref = (not is_nullable) and not is_tensor_list + suffix = "_opt" if is_nullable and not is_tensor_list else "" + body.append( + UNPACK_TENSOR.substitute( + arg_name=binding.name, + arg_pos=i, + suffix=suffix, + ref="&" if ref else "", + ) + ) + unpacked_bindings.append( + Binding( + name=unpacked_name(binding.name), + nctype=binding.nctype, + argument=binding.argument, + default=binding.default, + ) + ) + + return body, unpacked_bindings + + +def get_base_name(f: NativeFunction) -> str: + return f.func.name.name.base # TODO: should be str(f.func.name.name)? + + +def get_view_info(f: NativeFunction) -> str | None: + base_name = get_base_name(f) + view_info = VIEW_FUNCTIONS.get(base_name, None) + if view_info is None and base_name in RETURNS_VIEWS_OF_INPUT: + view_info = "self" + return view_info + + +def emit_view_func( + f: NativeFunction, bindings: list[Binding], view_idx: str | None = None +) -> str: + """Generate an additional lambda function to recover views in backward when as_strided is not supported. + See Note [View + Inplace update for base tensor] and [View + Inplace update for view tensor] for more details. + """ + # TODO: Clean this logic up if we get rid of reverse view funcs or reify them. + input_base = "input_base" + replay_view_func = "" + updated_args: list[str] = [] + known_view_arg_simple_types: list[CType] = [ + BaseCType(longT), + OptionalCType(BaseCType(longT)), + BaseCType(SymIntT), + OptionalCType(BaseCType(SymIntT)), + BaseCType(boolT), + BaseCType(intArrayRefT), + BaseCType(symIntArrayRefT), + ConstRefCType(BaseCType(tensorT)), + ConstRefCType(OptionalCType(BaseCType(tensorT))), + ] + for binding in bindings: + arg, arg_type = binding.name, binding.nctype.type + if arg == "self": + updated_args.append(input_base) + continue + if arg_type not in known_view_arg_simple_types: + known_types_str = ", ".join([str(t) for t in known_view_arg_simple_types]) + raise TypeError( + f"You are adding an {arg_type} {arg} argument to op {cpp.name(f.func)} in addition to known types: " + f"{known_types_str}. Please update the list or materialize it so that it can be closed " + "over by value, also add a test in pytorch/xla/test/test_operations.py where this code " + "is exercised." + ) + if arg_type == BaseCType(intArrayRefT) or arg_type == BaseCType( + symIntArrayRefT + ): + # It's not safe to close over IntArrayRef by value, since this is a + # reference type, so materialize a vector to close over by value + arg_vec = arg + "_vec" + replay_view_func += ARRAYREF_TO_VEC.substitute(arg=arg, vec=arg_vec) + updated_args.append(arg_vec) + elif arg_type == OptionalCType(BaseCType(longT)): + # Materialize int64_t? to int64_t + arg_value = arg + "_val" + replay_view_func += OPTIONAL_TO_VAL.substitute( + arg=arg, val=arg_value, default="0" + ) + updated_args.append(arg_value) + elif arg_type == ConstRefCType(BaseCType(tensorT)) or arg_type == ConstRefCType( + OptionalCType(BaseCType(tensorT)) + ): + # NB: Closing over a tensor. If a user modifies this tensor, this will be silently + # incorrect. The proper thing to do is to store the version counter and copy on write. + updated_args.append(arg) + else: + updated_args.append(arg) + + from .gen_view_funcs import view_func_name + + view_func_args = [b.name for b in bindings if b.name != "self"] + if view_idx is not None: + view_func_args.append(f"{view_idx}") + replay_view_func += REPLAY_VIEW_FUNC.substitute( + view_func_name=view_func_name(f, include_namespace=True), + view_func_args=view_func_args, + ) + + input_view = "input_view" + reverse_unpacked_args = [ + "self", + f"{input_view}", + # inverse_return_mode= + "at::functionalization::InverseReturnMode::AlwaysView", + *(() if view_idx is None else (f"{view_idx}",)), + # skip input_base arg + *updated_args[1:], + ] + + from torchgen.api.functionalization import reverse_name + + reverse_replay_view_call = REVERSE_VIEW_DISPATCH.substitute( + reverse_name=reverse_name(f, include_namespace=True), + unpacked_args=reverse_unpacked_args, + ) + reverse_replay_view_func = REVERSE_REPLAY_VIEW_LAMBDA_FUNC.substitute( + input_view=input_view, reverse_replay_view_call=reverse_replay_view_call + ) + + is_view_with_metadata_change = ( + "true" if cpp.name(f.func) in VIEW_FUNCTIONS_WITH_METADATA_CHANGE else "false" + ) + + return SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE.substitute( + is_view_with_metadata_change=is_view_with_metadata_change, + replay_view_func=replay_view_func, + reverse_replay_view_func=reverse_replay_view_func, + ) + + +def emit_view_body( + fn: NativeFunctionWithDifferentiabilityInfo, var: str +) -> tuple[str, str]: + # See NOTE [ Autograd View Variables ] in variable.h for details. + f = fn.func + base_name = get_base_name(f) + view_info = get_view_info(f) + call = "" + differentiable_outputs = gen_differentiable_outputs(fn) + differentiable_output_vars = {r.name for r in differentiable_outputs} + if not isinstance(view_info, str): + raise TypeError( + f"The view info should be a string for {base_name}, but it is: {view_info}" + ) + if len(differentiable_output_vars) == 0: + # no output is differentiable (.indices() for SparseTensors for example) + rhs_value = ( + f"as_view({view_info}, {var}, " + f"/* is_bw_differentiable */ false, /* is_fw_differentiable */ false)" + ) + elif len(differentiable_output_vars) == 1: + # Single differentiable output (Tensor or Tensor[]) + return_info = differentiable_outputs[0] + # We only support simple Tensor or a TensorList for functions that return views + if not is_tensor_type(return_info.type) and not is_tensor_list_type( + return_info.type + ): + raise RuntimeError( + f"{base_name} that return differentiable views can only return Tensor or Tensor[]" + ) + + # See Note [ View + Inplace detection] + def get_creation_meta_in_mode(original: str) -> str: + creation_meta_with_grad_mode = f"(at::GradMode::is_enabled() ? {original} : CreationMeta::NO_GRAD_MODE)" + return f"InferenceMode::is_enabled() ? CreationMeta::INFERENCE_MODE : {creation_meta_with_grad_mode}" + + # Only allow rebasing of the history if we return a single Tensor + # If we are in a no grad block, raise a warning + # See NOTE [ View + Inplace detection ] for more details about this logic + if is_tensor_list_type(return_info.type): + creation_meta = get_creation_meta_in_mode("CreationMeta::MULTI_OUTPUT_NODE") + view_idx = "view_idx" + view_func = emit_view_func( + f, extract_bindings(f), view_idx=view_idx + ).strip() + as_view_call = ( + f"as_view(/* base */ {view_info}, /* output */ {var}[{view_idx}], " + "/* is_bw_differentiable */ true, /* is_fw_differentiable */ true, " + "/* view_func */ std::move(func), /* rev_view_func */ rev_func, " + f"/* creation_meta */ {creation_meta});" + ) + call += MULTI_OUTPUT_VIEW_ITERATION.substitute( + var=var, view_idx=view_idx, body=f"{view_func}\n{as_view_call}" + ) + rhs_value = f"std::move({var})" + else: + call += emit_view_func(f, extract_bindings(f), view_idx=None) + creation_meta = get_creation_meta_in_mode("CreationMeta::DEFAULT") + rhs_value = ( + f"as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, " + "/* is_fw_differentiable */ true, " + f"/* view_func */ std::move(func), /* rev_view_func */ rev_func, /* creation_meta */ {creation_meta})" + ) + else: + # This could be supported but we don't need it at the moment, so keeping things simple. + raise RuntimeError( + "Function that return multiple differentiable output " + "when at least one of them is view is not supported." + ) + return call, rhs_value + + +def modifies_arguments(f: NativeFunction) -> bool: + return f.func.kind() in [SchemaKind.inplace, SchemaKind.out] + + +@with_native_function_with_differentiability_info +def emit_inplace_or_view_body(fn: NativeFunctionWithDifferentiabilityInfo) -> list[str]: + f = fn.func + inplace_view_body: list[str] = [] + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + dispatcher_exprs = dispatcher_sig.exprs() + + # code-generated ADInplaceOrView kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + dispatch_key_set = "ks & c10::after_ADInplaceOrView_keyset" + redispatch_args = ", ".join([dispatch_key_set] + [a.expr for a in dispatcher_exprs]) + + # Note that this calls the slow, dispatching variants of manual_cpp_binding ops. + # We could probably work harder to ensure that the fast variants are called instead, but the perf benefit would be minimal. + if modifies_arguments(f): # inplace op + inplace_view_body.append( + INPLACE_REDISPATCH.substitute( + unambiguous_name=f.func.name.unambiguous_name(), + unpacked_args=redispatch_args, + ) + ) + for r in cpp.return_names(f): + inplace_view_body.append(f"increment_version({r});") + else: + assert get_view_info(f) is not None + inplace_view_body.append( + VIEW_REDISPATCH.substitute( + assign_return_values="auto " + TMP_VAR + " = ", + unambiguous_name=f.func.name.unambiguous_name(), + unpacked_args=redispatch_args, + ) + ) + call, rhs_value = emit_view_body(fn, TMP_VAR) + inplace_view_body.append(call) + assert rhs_value is not None + inplace_view_body.append( + ASSIGN_RETURN_VALUE.substitute( + return_values=tie_return_values(f), rhs_value=rhs_value + ) + ) + if f.func.returns: + inplace_view_body.append(f"return {get_return_value(f)};") + return inplace_view_body + + +@with_native_function +def gen_formals(f: NativeFunction) -> str: + return ", ".join( + # code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + ["c10::DispatchKeySet ks"] + + [ + f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}" + for a in f.func.schema_order_arguments() + ] + ) + + +@with_native_function_with_differentiability_info +def inplace_or_view_method_definition( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> str | None: + f = fn.func + if get_view_info(f) is None and ( + # For functions that modify their inputs but don't return them, + # we can't give them autograd support. + # See https://github.com/pytorch/pytorch/issues/53796 + not modifies_arguments(f) or len(f.func.returns) == 0 + ): + return None + return METHOD_DEFINITION.substitute( + return_type=cpp.returns_type(f.func.returns, symint=True).cpp_type(), + type_wrapper_name=type_wrapper_name(f), + formals=gen_formals(f), + type_definition_body=emit_inplace_or_view_body(fn), + ) + + +@with_native_function_with_differentiability_info +def inplace_or_view_method_registration( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> str | None: + f = fn.func + if get_view_info(f) is None and ( + not modifies_arguments(f) or len(f.func.returns) == 0 + ): + return None + return WRAPPER_REGISTRATION.substitute( + unqual_operator_name_with_overload=f.func.name, + type_wrapper_name=type_wrapper_name(f), + class_type="ADInplaceOrView", + ) + + +def use_derived(fn: NativeFunctionWithDifferentiabilityInfo) -> bool: + f = fn.func + name = cpp.name(f.func) + return name not in MANUAL_AUTOGRAD and dispatch_strategy(fn) == "use_derived" + + +def gen_inplace_or_view_type_env( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> dict[str, list[str]]: + definition = inplace_or_view_method_definition(fn) + registration = inplace_or_view_method_registration(fn) + + return { + "ops_headers": ( + [f"#include "] + if definition is not None + else [] + ), + "inplace_or_view_method_definitions": [definition] + if definition is not None + else [], + "inplace_or_view_wrapper_registrations": [registration] + if registration is not None + else [], + } + + +def gen_inplace_or_view_type( + out: str, + native_yaml_path: str, + tags_yaml_path: str, + fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo], + template_path: str, +) -> None: + # NOTE: see Note [Sharded File] at the top of the VariableType.cpp + # template regarding sharding of the generated files. + + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_sharded( + "ADInplaceOrViewType.cpp", + [fn for fn in fns_with_infos if use_derived(fn)], + key_fn=lambda fn: fn.func.root_name, + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/ADInplaceOrViewType.cpp", + }, + env_callable=gen_inplace_or_view_type_env, + num_shards=2, + sharded_keys={ + "ops_headers", + "inplace_or_view_method_definitions", + "inplace_or_view_wrapper_registrations", + }, + ) diff --git a/shared/package-files/93/93783cda348368538525f52a5e9a5a43a3de93caec26b6a030ecfb3aedf98b98/util.py b/shared/package-files/93/93783cda348368538525f52a5e9a5a43a3de93caec26b6a030ecfb3aedf98b98/util.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbe094cba1624c89e24acdd43bd9ae619f09fc8 --- /dev/null +++ b/shared/package-files/93/93783cda348368538525f52a5e9a5a43a3de93caec26b6a030ecfb3aedf98b98/util.py @@ -0,0 +1,159 @@ +"""Miscellaneous WSGI-related Utilities""" + +import posixpath + +__all__ = [ + 'FileWrapper', 'guess_scheme', 'application_uri', 'request_uri', + 'shift_path_info', 'setup_testing_defaults', +] + + +class FileWrapper: + """Wrapper to convert file-like objects to iterables""" + + def __init__(self, filelike, blksize=8192): + self.filelike = filelike + self.blksize = blksize + if hasattr(filelike,'close'): + self.close = filelike.close + + def __iter__(self): + return self + + def __next__(self): + data = self.filelike.read(self.blksize) + if data: + return data + raise StopIteration + +def guess_scheme(environ): + """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' + """ + if environ.get("HTTPS") in ('yes','on','1'): + return 'https' + else: + return 'http' + +def application_uri(environ): + """Return the application's base URI (no PATH_INFO or QUERY_STRING)""" + url = environ['wsgi.url_scheme']+'://' + from urllib.parse import quote + + if environ.get('HTTP_HOST'): + url += environ['HTTP_HOST'] + else: + url += environ['SERVER_NAME'] + + if environ['wsgi.url_scheme'] == 'https': + if environ['SERVER_PORT'] != '443': + url += ':' + environ['SERVER_PORT'] + else: + if environ['SERVER_PORT'] != '80': + url += ':' + environ['SERVER_PORT'] + + url += quote(environ.get('SCRIPT_NAME') or '/', encoding='latin1') + return url + +def request_uri(environ, include_query=True): + """Return the full request URI, optionally including the query string""" + url = application_uri(environ) + from urllib.parse import quote + path_info = quote(environ.get('PATH_INFO',''), safe='/;=,', encoding='latin1') + if not environ.get('SCRIPT_NAME'): + url += path_info[1:] + else: + url += path_info + if include_query and environ.get('QUERY_STRING'): + url += '?' + environ['QUERY_STRING'] + return url + +def shift_path_info(environ): + """Shift a name from PATH_INFO to SCRIPT_NAME, returning it + + If there are no remaining path segments in PATH_INFO, return None. + Note: 'environ' is modified in-place; use a copy if you need to keep + the original PATH_INFO or SCRIPT_NAME. + + Note: when PATH_INFO is just a '/', this returns '' and appends a trailing + '/' to SCRIPT_NAME, even though empty path segments are normally ignored, + and SCRIPT_NAME doesn't normally end in a '/'. This is intentional + behavior, to ensure that an application can tell the difference between + '/x' and '/x/' when traversing to objects. + """ + path_info = environ.get('PATH_INFO','') + if not path_info: + return None + + path_parts = path_info.split('/') + path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p != '.'] + name = path_parts[1] + del path_parts[1] + + script_name = environ.get('SCRIPT_NAME','') + script_name = posixpath.normpath(script_name+'/'+name) + if script_name.endswith('/'): + script_name = script_name[:-1] + if not name and not script_name.endswith('/'): + script_name += '/' + + environ['SCRIPT_NAME'] = script_name + environ['PATH_INFO'] = '/'.join(path_parts) + + # Special case: '/.' on PATH_INFO doesn't get stripped, + # because we don't strip the last element of PATH_INFO + # if there's only one path part left. Instead of fixing this + # above, we fix it here so that PATH_INFO gets normalized to + # an empty string in the environ. + if name=='.': + name = None + return name + +def setup_testing_defaults(environ): + """Update 'environ' with trivial defaults for testing purposes + + This adds various parameters required for WSGI, including HTTP_HOST, + SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO, + and all of the wsgi.* variables. It only supplies default values, + and does not replace any existing settings for these variables. + + This routine is intended to make it easier for unit tests of WSGI + servers and applications to set up dummy environments. It should *not* + be used by actual WSGI servers or applications, since the data is fake! + """ + + environ.setdefault('SERVER_NAME','127.0.0.1') + environ.setdefault('SERVER_PROTOCOL','HTTP/1.0') + + environ.setdefault('HTTP_HOST',environ['SERVER_NAME']) + environ.setdefault('REQUEST_METHOD','GET') + + if 'SCRIPT_NAME' not in environ and 'PATH_INFO' not in environ: + environ.setdefault('SCRIPT_NAME','') + environ.setdefault('PATH_INFO','/') + + environ.setdefault('wsgi.version', (1,0)) + environ.setdefault('wsgi.run_once', 0) + environ.setdefault('wsgi.multithread', 0) + environ.setdefault('wsgi.multiprocess', 0) + + from io import StringIO, BytesIO + environ.setdefault('wsgi.input', BytesIO()) + environ.setdefault('wsgi.errors', StringIO()) + environ.setdefault('wsgi.url_scheme',guess_scheme(environ)) + + if environ['wsgi.url_scheme']=='http': + environ.setdefault('SERVER_PORT', '80') + elif environ['wsgi.url_scheme']=='https': + environ.setdefault('SERVER_PORT', '443') + + + +_hoppish = { + 'connection', 'keep-alive', 'proxy-authenticate', + 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', + 'upgrade' +}.__contains__ + +def is_hop_by_hop(header_name): + """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" + return _hoppish(header_name.lower()) diff --git a/shared/package-files/93/937e5f32a53c641613f74947c2ef4e41757af0379f61310c7b330aa433ad2080/develop.cpython-311.pyc b/shared/package-files/93/937e5f32a53c641613f74947c2ef4e41757af0379f61310c7b330aa433ad2080/develop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92a51eaefce3d639e0bfb390b39fa01461122b2c Binary files /dev/null and b/shared/package-files/93/937e5f32a53c641613f74947c2ef4e41757af0379f61310c7b330aa433ad2080/develop.cpython-311.pyc differ diff --git a/shared/package-files/93/9381f4f340c1944e942f4501f015f59ac123493c104f8e1fa70a777ee2e9b8fd/ddp_fusion.py b/shared/package-files/93/9381f4f340c1944e942f4501f015f59ac123493c104f8e1fa70a777ee2e9b8fd/ddp_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..2d9409523c159f88dcfbdb8672b2ea5451989c06 --- /dev/null +++ b/shared/package-files/93/9381f4f340c1944e942f4501f015f59ac123493c104f8e1fa70a777ee2e9b8fd/ddp_fusion.py @@ -0,0 +1,586 @@ +# Owner(s): ["oncall: distributed"] +import collections +import inspect +import logging +import math +import operator +from collections.abc import Generator +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, cast, Optional, Union + +import torch +import torch.fx as fx +from torch._dynamo.utils import counters +from torch.fx.passes.graph_transform_observer import GraphTransformObserver +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten, tree_map, tree_unflatten + +from ..fx_utils import get_fake_args_kwargs +from ..virtualized import V + + +aten = torch.ops.aten +logger: logging.Logger = logging.getLogger("comm_fusion") + + +def move_block_after(block: list[fx.Node], target_node: fx.Node) -> None: + for node in block: + target_node.append(node) + target_node = node + + +def move_block_before(block: list[fx.Node], target_node: fx.Node) -> None: + for node in block: + target_node.prepend(node) + target_node = node + + +def call_function( + graph: fx.Graph, + target: Union[str, Callable[..., Any]], + args: Optional[tuple[fx.node.Argument, ...]] = None, + kwargs: Optional[dict[str, fx.node.Argument]] = None, +) -> fx.Node: + # We accept target as a str to avoid typing error as the type of + # a node.target is Union[str, Callable[..., Any]]. + # This also allows us to avoid writing check for every call. + if isinstance(target, str): + raise RuntimeError(f"Call function should not get a str target {target=}") + node = graph.call_function(target, args, kwargs) + _, args, kwargs = get_fake_args_kwargs(node) + with V.fake_mode: + node.meta["val"] = target(*args, **kwargs) + # node.meta["val"] may be a container. So we use tree_map here + # to recursively extract the tensor metadata. + node.meta["tensor_meta"] = tree_map( + _extract_tensor_metadata, (node.meta["val"],) + )[0] + return node + + +@dataclass(unsafe_hash=True) +class CommBlock: + shape: Union[torch.Size, list[torch.Size]] + node_list: list[fx.Node] + inputs: list[fx.Node] + wait_nodes: list[fx.Node] + comm_node: fx.Node + outputs: OrderedSet[fx.Node] + + +def get_comm_block(comm_node: fx.Node) -> Optional[CommBlock]: + """ + Given a collective node (e.g., allreduce), find out all the nodes belong to + this communcation. + + Args: + comm_node(fx.Node): The target communication/collective node. + Returns: + The CommBlock that encapsulates the related nodes (e.g., wait_node) of + the given comm_node. + """ + node_list = [] + wait_nodes = [] + inputs, _ = tree_flatten((comm_node.args, comm_node.kwargs)) + input_nodes = [inp for inp in inputs if isinstance(inp, fx.Node)] + # If the users of the wait node are following items, we consinder them + # to be a part of the output. + intermediate_outputs = ("split", "reshape", "getitem", "detach", "alias") + + first_user = next(iter(comm_node.users)) + if ( + len(comm_node.users) == 1 + and first_user.target == torch.ops._c10d_functional.wait_tensor.default + ): + # Collective with only one output + node_list = [comm_node, first_user] + wait_nodes.append(first_user) + elif len(comm_node.users) > 1 and first_user.target == operator.getitem: + # Collective with only more than one output + node_list.append(comm_node) + for user in comm_node.users: + if user.target != operator.getitem: + return None + if len(user.users) != 1: + return None + wait_node = next(iter(user.users)) + if wait_node.target != torch.ops._c10d_functional.wait_tensor.default: + return None + wait_nodes.append(wait_node) + node_list.append(user) + node_list.extend(wait_nodes) + else: + return None + + # Identify all the outputs of this collective block. + outputs = OrderedSet[fx.Node]() + nodes = collections.deque(wait_nodes) + while nodes: + node = nodes.popleft() + for user in node.users: + if isinstance(user, fx.Node) and user.name.startswith(intermediate_outputs): + nodes.append(user) + node_list.append(user) + else: + outputs.add(node) + break + + tensor_meta = input_nodes[0].meta["tensor_meta"] + shape: Union[torch.Size, list[torch.Size]] + if isinstance(tensor_meta, TensorMetadata): + shape = tensor_meta.shape + elif isinstance(tensor_meta, (list, tuple)): + shape = [tm.shape for tm in tensor_meta] + else: + logger.warning("Unexpected type of tensor_meta %s", type(tensor_meta)) + return None + + return CommBlock( + shape=shape, + node_list=node_list, + wait_nodes=wait_nodes, + comm_node=comm_node, + inputs=input_nodes, + outputs=outputs, + ) + + +def get_all_comm_blocks( + graph: fx.Graph, + comm_ops: tuple[torch._ops.OpOverload, ...], + comm_filter: Optional[Callable[..., bool]] = None, +) -> list[CommBlock]: + if comm_filter is None: + + def always_true(comm_block: CommBlock) -> bool: + return True + + comm_filter = always_true + + blocks = [] + for node in graph.nodes: + if node.target not in comm_ops: + continue + comm_block = get_comm_block(node) + if comm_block is not None and comm_filter(comm_block): + blocks.append(comm_block) + return blocks + + +def _fuse_allreduce_by_concat( + graph: fx.Graph, + last_input_node: fx.Node, + all_input_nodes: list[fx.Node], + last_comm_block: CommBlock, +) -> CommBlock: + """Given a list of inputs in order, create a fused allreduce using concat.""" + # Flatten all the inputs to the all_reduce nodes. + with graph.inserting_after(last_input_node): + cat_inputs = [] + for input_node in all_input_nodes: + assert isinstance(input_node.args[0], fx.Node) + input_node = input_node.args[0] + cat_inputs.append( + call_function(graph, aten.flatten.using_ints, (input_node,)) + ) + + # Concat all the flattened nodes. + with graph.inserting_after(cat_inputs[0]): + cat_node = call_function(graph, aten.cat, (cat_inputs,)) + + # Insert the fused div node and remove the input div nodes. + # This is an optimization and is not mandatory for fusion. + divisors = [div.args[1] for div in all_input_nodes] + assert all(divisor == divisors[0] for divisor in divisors) + with graph.inserting_after(cat_node): + div_node = call_function(graph, last_input_node.target, (cat_node, divisors[0])) + + # Create a new Comm/all_reduce node. + last_comm_node = last_comm_block.comm_node + last_wait_node = last_comm_block.wait_nodes[0] + with graph.inserting_after(div_node): + flatten_args, spec = tree_flatten((last_comm_node.args, last_comm_node.kwargs)) + flatten_args[0] = div_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_comm_node = call_function(graph, last_comm_node.target, args, kwargs) + + # Create a new Wait node. + with graph.inserting_after(fused_comm_node): + flatten_args, spec = tree_flatten((last_wait_node.args, last_wait_node.kwargs)) + flatten_args[0] = fused_comm_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_wait_node = call_function(graph, last_wait_node.target, args, kwargs) + + # Move the fused all_reduce and its args to right after the input node + nodes_to_move = cat_inputs + [cat_node, div_node, fused_comm_node, fused_wait_node] + move_block_after(nodes_to_move, last_input_node) + + return CommBlock( + shape=cast(TensorMetadata, cat_node.meta.get("tensor_meta")).shape, + node_list=[fused_comm_node, fused_wait_node], + wait_nodes=[fused_wait_node], + comm_node=fused_comm_node, + inputs=[div_node], + outputs=OrderedSet([fused_wait_node]), + ) + + +def _fuse_with_coalesced_op( + graph: fx.Graph, + last_input_node: fx.Node, + all_input_nodes: list[fx.Node], + last_comm_block: CommBlock, +) -> CommBlock: + """Given a list of inputs in order, create a fused allreduce by coalesced.""" + last_comm_node = last_comm_block.comm_node + last_wait_node = last_comm_block.wait_nodes[0] + + # Insert the fused div node and remove the input div nodes. + # This is an optimization and is not mandatory for fusion. + dividends = [div.args[0] for div in all_input_nodes] + divisors = [div.args[1] for div in all_input_nodes] + assert all(divisor == divisors[0] for divisor in divisors) + with graph.inserting_before(last_input_node): + last_input_node = call_function( + graph, aten._foreach_div.Scalar, (dividends, divisors[0]) + ) + input_node = last_input_node + + # Create a new Comm/all_reduce_coalesced node. + with graph.inserting_after(last_comm_node): + flatten_args, spec = tree_flatten((last_comm_node.args, last_comm_node.kwargs)) + flatten_args[0] = input_node + args, kwargs = tree_unflatten(flatten_args, spec) + fused_comm_node = call_function( + graph, torch.ops._c10d_functional.all_reduce_coalesced.default, args, kwargs + ) + + # Create a new wait node. + getitem_nodes = [] + wait_nodes = [] + flatten_args, spec = tree_flatten((last_wait_node.args, last_wait_node.kwargs)) + for idx in range(len(all_input_nodes)): + with graph.inserting_after(fused_comm_node): + gi_node = call_function(graph, operator.getitem, (fused_comm_node, idx)) + getitem_nodes.append(gi_node) + flatten_args[0] = gi_node + args, kwargs = tree_unflatten(flatten_args, spec) + with graph.inserting_after(gi_node): + wait_nodes.append(call_function(graph, last_wait_node.target, args, kwargs)) + + # Move the new all_reduce_coalesced and its args to right after the input node + nodes_to_move = [fused_comm_node] + getitem_nodes + wait_nodes + move_block_after(nodes_to_move, last_input_node) + + return CommBlock( + shape=[ + tm.shape + for tm in cast( + list[TensorMetadata], fused_comm_node.meta.get("tensor_meta") + ) + ], + node_list=[fused_comm_node] + getitem_nodes + wait_nodes, + wait_nodes=wait_nodes, + comm_node=fused_comm_node, + inputs=[input_node], + outputs=OrderedSet(wait_nodes), + ) + + +def _scatter_fused_allreduce_waits( + graph: fx.Graph, + fused_comm_block: CommBlock, + orig_comm_blocks: list[CommBlock], + node_indices: dict[fx.Node, int], + split_and_reshape: bool = True, +) -> None: + """ + Scatters the result of the fused communication node to the original users. + If the fused method is concat splitting the output and reshape will be inserted, + before inserting getitem. Otherwise getitem will be used as the users of the + wait node. + """ + + # Before we mass up the order, we need to get the index of the last wait node + # in orig_comm_blocks. This index will be later used to determinee what users + # nodes need to be move to maintain a correct topological sort order. + last_wait_node_idx = 0 + for node in graph.nodes: + last_wait_node_idx = max( + node_indices.get(node, last_wait_node_idx), last_wait_node_idx + ) + if node == orig_comm_blocks[-1].wait_nodes[0]: + break + + if split_and_reshape: + fused_wait_node = fused_comm_block.wait_nodes[0] + with graph.inserting_after(fused_wait_node): + split_node = call_function( + graph, + aten.split, + ( + fused_wait_node, + [math.prod(cast(list[int], cb.shape)) for cb in orig_comm_blocks], + ), + ) + with graph.inserting_after(split_node): + fused_outputs = [] + for idx, comm_block in enumerate(orig_comm_blocks): + split_idx_node = call_function( + graph, operator.getitem, (split_node, idx) + ) + with graph.inserting_after(split_idx_node): + fused_outputs.append( + call_function( + graph, aten.reshape, (split_idx_node, comm_block.shape) + ) + ) + else: + fused_outputs = fused_comm_block.wait_nodes + + # Scatter the fused outputs. + incorrect_order_nodes = [] + for comm_block, fused_output in zip(orig_comm_blocks, fused_outputs): + # Some descendant users of the orig_comm_blocks may be scheduled before + # the fused all_reduce. For example, the user nodes of the very first + # all_reduce may be scheduled before the second all_reduce. Since the + # fused all_reduce is inserted right after the last all_reudce, the + # order can be wrong. + # `incorrect_order_nodes` records these nodes. + + orig_wait = comm_block.wait_nodes[0] + nodes = collections.deque(list(orig_wait.users)) + while nodes: + user_node = nodes.popleft() + if not isinstance(user_node, fx.Node): + continue + if node_indices[user_node] < last_wait_node_idx: + incorrect_order_nodes.append(user_node) + nodes.extend(list(user_node.users)) + + orig_wait.replace_all_uses_with(fused_output) + + last_fused_result = fused_outputs[0] + fused_outputs_set = OrderedSet(fused_outputs) + for node in graph.nodes: + if node in fused_outputs_set: + last_fused_result = node + + # Move the incorrect_order_nodes to right after the last fused_result. + incorrect_order_nodes = sorted( + incorrect_order_nodes, key=lambda node: node_indices[node] + ) + move_block_after(incorrect_order_nodes, last_fused_result) + + +def _fuse_allreduce( + graph: fx.Graph, + comm_blocks: list[CommBlock], + node_indices: dict[fx.Node, int], + use_concat: bool, +) -> CommBlock: + """Given a list of allreduce CommBlock, fuse the CommBlocks into one CommBlock.""" + + if len(comm_blocks) == 1: + return comm_blocks[0] + + # Find the last input node of all the CommBlocks. This node will be served + # as the inserting point of the new collective op. + last_input_node = comm_blocks[0].inputs[0] + last_input_index = -1 + all_input_nodes = [] + for comm_block in comm_blocks: + input_node = comm_block.inputs[0] + all_input_nodes.append(input_node) + index = node_indices[input_node] + if index >= last_input_index: + assert index != last_input_index + last_input_node = input_node + last_input_index = index + + if use_concat: + fused_comm_block = _fuse_allreduce_by_concat( + graph, last_input_node, all_input_nodes, comm_blocks[-1] + ) + else: + fused_comm_block = _fuse_with_coalesced_op( + graph, last_input_node, all_input_nodes, comm_blocks[-1] + ) + + _scatter_fused_allreduce_waits( + graph, fused_comm_block, comm_blocks, node_indices, split_and_reshape=use_concat + ) + + for comm_block in comm_blocks: + for wait in comm_block.wait_nodes: + graph.erase_node(wait) + graph.erase_node(comm_block.comm_node) + graph.eliminate_dead_code() + + return fused_comm_block + + +def _bucket_size_fusion( + graph: fx.Graph, comm_blocks: list[CommBlock], bucket_size_mb: int +) -> Generator[list[CommBlock], None, None]: + MB = 1024**2 + bucket_size = 1 * MB + bucket_cap_size = bucket_size_mb * MB + curr_size = 0 + curr_blocks = [] + + count = 0 + fuse_count = 0 + for i, block in enumerate(comm_blocks): + curr_blocks.append(block) + itemsize = block.comm_node.meta["tensor_meta"].dtype.itemsize + curr_size += cast(torch.Size, block.shape).numel() * itemsize + count += 1 + if curr_size < bucket_size and i != len(comm_blocks) - 1: + continue + + fuse_count += 1 + if torch.distributed.get_rank() == 0: + logger.info( + "DDP bucketing: block%d, count=%d, curr_size=%d, bucket_size=%d", + fuse_count, + count, + curr_size, + bucket_size, + ) + + # Set the debug counters + counters["inductor"]["ddp_buckets"] = fuse_count + yield curr_blocks + + bucket_size = bucket_cap_size + curr_blocks = [] + curr_size = 0 + count = 0 + + +def _fuse_ddp_communication( + graph: fx.Graph, algorithm_fn: Callable[..., Any], fusion_fn: Callable[..., Any] +) -> None: + for output in reversed(graph.nodes): + if output.op == "output": + break + + def ddp_reducer_filter(block: CommBlock) -> bool: + if ( + not isinstance(block.comm_node.args[0], fx.Node) + or block.comm_node.args[0].target != aten.div.Tensor + ): + return False + + if len(block.wait_nodes[0].users) != 1: + # gradient/wait node should only be used by one user + return False + + # Two cases: + # 1. gradient/wait node should be directly used by the output + # if gradient is None before bwd. + # 2. gradient/wait node should be directly used by copy_. + if ( + output not in block.wait_nodes[0].users + and next(iter(block.wait_nodes[0].users)).target != aten.copy_.default + ): + return False + + return True + + ops = ( + torch.ops._c10d_functional.all_reduce_.default, + torch.ops._c10d_functional.all_reduce.default, + ) + comm_blocks = get_all_comm_blocks(graph, ops, comm_filter=ddp_reducer_filter) + node_indices = {node: i for i, node in enumerate(graph.nodes)} + + for block in algorithm_fn(graph, comm_blocks): + fusion_fn(graph, block, node_indices) + + +def fuse_ddp_with_coalesced_op(graph: fx.Graph, bucket_size_mb: int) -> None: + _fuse_ddp_communication( + graph, + partial(_bucket_size_fusion, bucket_size_mb=bucket_size_mb), + partial(_fuse_allreduce, use_concat=False), + ) + + +def fuse_ddp_with_concat_op(graph: fx.Graph, bucket_size_mb: int) -> None: + _fuse_ddp_communication( + graph, + partial(_bucket_size_fusion, bucket_size_mb=bucket_size_mb), + partial(_fuse_allreduce, use_concat=True), + ) + + +def schedule_comm_wait(graph: fx.Graph) -> None: + """ + Delay the execution of wait tensors of allreduce until its first user. + + This algorithm considers the intermediate users, like split, getitem, + of the wait node and schedule those intermediate users as well. + This will result in a better overlapping result. + """ + ops = ( + torch.ops._c10d_functional.all_reduce_.default, + torch.ops._c10d_functional.all_reduce.default, + torch.ops._c10d_functional.all_reduce_coalesced.default, + torch.ops._c10d_functional.all_reduce_coalesced_.default, + ) + comm_blocks = get_all_comm_blocks(graph, ops) + if not comm_blocks: + return + + # Find all the end users. + allreduce_users = OrderedSet[fx.Node]() + for allreduce in comm_blocks: + for output in allreduce.outputs: + allreduce_users.update(output.users) + + node_indices = {node: i for i, node in enumerate(graph.nodes)} + for allreduce in comm_blocks: + # Find the earliest/first user -- target_node. + assert len(allreduce.outputs) >= 1, ( + f"Found a allreduce that has zero outputs/users -- {allreduce}." + ) + # Initialize the target node to avoid typing issues. + target_node = next(iter(next(iter(allreduce.outputs)).users)) + target_node_index = 2**31 + for user in (user for output in allreduce.outputs for user in output.users): + index = node_indices[user] + if index < target_node_index: + target_node = user + target_node_index = index + + # Move wait nodes and all the subsequent nodes in the comm_block to + # before the first user -- target_node. + wait_idx = -1 + for wait_idx, node in enumerate(allreduce.node_list): + if node == allreduce.wait_nodes[0]: + break + assert wait_idx >= 0 + move_block_before(allreduce.node_list[wait_idx:], target_node) + + +def fuse_ddp_communication( + graph: fx.Graph, passes: list[Union[Callable[..., None], str]], bucket_size_mb: int +) -> None: + for i, pa in enumerate(passes): + with GraphTransformObserver( + graph.owning_module, f"fuse_ddp_communication_pass_{i}" + ): + if isinstance(pa, str): + func = globals()[pa] + else: + func = pa + if "bucket_size_mb" in OrderedSet( + v.name for v in inspect.signature(func).parameters.values() + ): + func(graph, bucket_size_mb=bucket_size_mb) + else: + func(graph) diff --git a/shared/package-files/93/9383eb00c30887cc6adf06ab6c5765e214234a92cb85ff8ce1c20cd0461c5c30/base64_codec.cpython-311.pyc b/shared/package-files/93/9383eb00c30887cc6adf06ab6c5765e214234a92cb85ff8ce1c20cd0461c5c30/base64_codec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c619a619b867e8c00638ca7015e88123f6d6c91 Binary files /dev/null and b/shared/package-files/93/9383eb00c30887cc6adf06ab6c5765e214234a92cb85ff8ce1c20cd0461c5c30/base64_codec.cpython-311.pyc differ diff --git a/shared/package-files/93/93854d4abd032f7328062d9bace70cfacd20984044bd95fd25da9dd4f598d9fe/test_point.cpython-311.pyc b/shared/package-files/93/93854d4abd032f7328062d9bace70cfacd20984044bd95fd25da9dd4f598d9fe/test_point.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68cbb3c96024b8d683f275c5ddc3f64f39e9c067 Binary files /dev/null and b/shared/package-files/93/93854d4abd032f7328062d9bace70cfacd20984044bd95fd25da9dd4f598d9fe/test_point.cpython-311.pyc differ diff --git a/shared/package-files/93/93866a94492ee70bf55c88e636820e473c7dfb99c9df799ea4f3a1e4a28f0b07/lindenmayer.cpython-311.pyc b/shared/package-files/93/93866a94492ee70bf55c88e636820e473c7dfb99c9df799ea4f3a1e4a28f0b07/lindenmayer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1906bef296696c2f6c676e01aa4ca65f9737086 Binary files /dev/null and b/shared/package-files/93/93866a94492ee70bf55c88e636820e473c7dfb99c9df799ea4f3a1e4a28f0b07/lindenmayer.cpython-311.pyc differ diff --git a/shared/package-files/93/938908b960df11b8482dd6fbd53a46ad5af55aeced44ac1a0cec1d8d49662251/special_gammaincc_ops.h b/shared/package-files/93/938908b960df11b8482dd6fbd53a46ad5af55aeced44ac1a0cec1d8d49662251/special_gammaincc_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f6ce5980428a5a45448d9ce353adf9f764d79e2e --- /dev/null +++ b/shared/package-files/93/938908b960df11b8482dd6fbd53a46ad5af55aeced44ac1a0cec1d8d49662251/special_gammaincc_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_gammaincc_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_gammaincc"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "special_gammaincc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +struct TORCH_API special_gammaincc { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_gammaincc"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "special_gammaincc(Tensor self, Tensor other) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/93/938a0b9a80dc55e2ca8605f2157fb3b3aca821aa9c3064097f85ae4b44f2ef02/_ordered_set.py b/shared/package-files/93/938a0b9a80dc55e2ca8605f2157fb3b3aca821aa9c3064097f85ae4b44f2ef02/_ordered_set.py new file mode 100644 index 0000000000000000000000000000000000000000..29373289c42606c2f3fd08120cc59af8dcf25b1c --- /dev/null +++ b/shared/package-files/93/938a0b9a80dc55e2ca8605f2157fb3b3aca821aa9c3064097f85ae4b44f2ef02/_ordered_set.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +from collections.abc import ( + Iterable, + Iterator, + MutableSet, + Reversible, + Set as AbstractSet, +) +from typing import Any, cast, Optional, TypeVar + + +T = TypeVar("T") +T_co = TypeVar("T_co", covariant=True) + +__all__ = ["OrderedSet"] + + +class OrderedSet(MutableSet[T], Reversible[T]): + """ + Insertion ordered set, similar to OrderedDict. + """ + + __slots__ = ("_dict",) + + def __init__(self, iterable: Optional[Iterable[T]] = None): + self._dict = dict.fromkeys(iterable, None) if iterable is not None else {} + + @staticmethod + def _from_dict(dict_inp: dict[T, None]) -> OrderedSet[T]: + s: OrderedSet[T] = OrderedSet() + s._dict = dict_inp + return s + + # + # Required overriden abstract methods + # + def __contains__(self, elem: object) -> bool: + return elem in self._dict + + def __iter__(self) -> Iterator[T]: + return iter(self._dict) + + def __len__(self) -> int: + return len(self._dict) + + def __reversed__(self) -> Iterator[T]: + return reversed(self._dict) + + def add(self, elem: T) -> None: + self._dict[elem] = None + + def discard(self, elem: T) -> None: + self._dict.pop(elem, None) + + def clear(self) -> None: + # overridden because MutableSet impl is slow + self._dict.clear() + + # Unimplemented set() methods in _collections_abc.MutableSet + + @classmethod + def _wrap_iter_in_set(cls, other: Any) -> Any: + """ + Wrap non-Set Iterables in OrderedSets + + Some of the magic methods are more strict on input types than + the public apis, so we need to wrap inputs in sets. + """ + + if not isinstance(other, AbstractSet) and isinstance(other, Iterable): + return cls(other) + else: + return other + + def pop(self) -> T: + if not self: + raise KeyError("pop from an empty set") + return self._dict.popitem()[0] + + def copy(self) -> OrderedSet[T]: + return OrderedSet._from_dict(self._dict.copy()) + + def difference(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + res.difference_update(*others) + return res + + def difference_update(self, *others: Iterable[T]) -> None: + for other in others: + self -= other # type: ignore[arg-type] + + def update(self, *others: Iterable[T]) -> None: + for other in others: + self |= other + + def intersection(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + for other in others: + if other is not self: + res &= other # type: ignore[arg-type] + return res + + def intersection_update(self, *others: Iterable[T]) -> None: + for other in others: + self &= other # type: ignore[arg-type] + + def issubset(self, other: Iterable[T]) -> bool: + return self <= self._wrap_iter_in_set(other) + + def issuperset(self, other: Iterable[T]) -> bool: + return self >= self._wrap_iter_in_set(other) + + def symmetric_difference(self, other: Iterable[T]) -> OrderedSet[T]: + return self ^ other # type: ignore[operator] + + def symmetric_difference_update(self, other: Iterable[T]) -> None: + self ^= other # type: ignore[arg-type] + + def union(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + for other in others: + if other is self: + continue + res |= other + return res + + # Specify here for correct type inference, otherwise would + # return AbstractSet[T] + def __sub__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + # following cpython set impl optimization + if isinstance(other, OrderedSet) and (len(self) * 4) > len(other): + out = self.copy() + out -= other + return out + return cast(OrderedSet[T], super().__sub__(other)) + + def __ior__(self, other: Iterable[T]) -> OrderedSet[T]: # type: ignore[misc, override] # noqa: PYI034 + if isinstance(other, OrderedSet): + self._dict.update(other._dict) + return self + return super().__ior__(other) # type: ignore[arg-type] + + def __eq__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self._dict == other._dict + return super().__eq__(other) + + def __ne__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self._dict != other._dict + return super().__ne__(other) + + def __or__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + return cast(OrderedSet[T], super().__or__(other)) + + def __and__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + # MutableSet impl will iterate over other, iter over smaller of two sets + if isinstance(other, OrderedSet) and len(self) < len(other): + return other & self + return cast(OrderedSet[T], super().__and__(other)) + + def __xor__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + return cast(OrderedSet[T], super().__xor__(other)) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({list(self)})" + + def __getstate__(self) -> list[T]: + return list(self._dict.keys()) + + def __setstate__(self, state: list[T]) -> None: + self._dict = dict.fromkeys(state, None) + + def __reduce__(self) -> tuple[type[OrderedSet[T]], tuple[list[T]]]: + return (OrderedSet, (list(self),)) diff --git a/shared/package-files/93/938f8a58d907546756216b92f448748f7b422ccfd0e56bea515b98f27beff754/test_iterrows.cpython-311.pyc b/shared/package-files/93/938f8a58d907546756216b92f448748f7b422ccfd0e56bea515b98f27beff754/test_iterrows.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8401e889a76fb4d645f2add0f75b6e012307a4f Binary files /dev/null and b/shared/package-files/93/938f8a58d907546756216b92f448748f7b422ccfd0e56bea515b98f27beff754/test_iterrows.cpython-311.pyc differ diff --git a/shared/package-files/93/9395ef218aa0d7362bc623fe4db484b24182302ae29c4aa2d1f311d234fd7675/associative_scan.py b/shared/package-files/93/9395ef218aa0d7362bc623fe4db484b24182302ae29c4aa2d1f311d234fd7675/associative_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..55f9d0dcc319a945f520eb2d459a99e526e42a33 --- /dev/null +++ b/shared/package-files/93/9395ef218aa0d7362bc623fe4db484b24182302ae29c4aa2d1f311d234fd7675/associative_scan.py @@ -0,0 +1,461 @@ +# mypy: allow-untyped-defs +import functools +import itertools +from typing import Any, Callable + +import torch +import torch._prims_common as utils +import torch._subclasses.functional_tensor +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _maybe_run_with_interpreter, + _set_compilation_env, + autograd_not_implemented, + first_slice_copy, + reenter_make_fx, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +aten = torch._ops.ops.aten + + +def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves): + assert len(args) == 2 * num_leaves + lhs = pytree.tree_unflatten(args[:num_leaves], spec) + rhs = pytree.tree_unflatten(args[num_leaves:], spec) + combined = combine_fn(lhs, rhs) + combined_leaves = pytree.tree_leaves(combined) + assert num_leaves == len(combined_leaves) + return combined_leaves + + +def _interleave(a, b, dim=0): + # https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors + if b_trunc := (a.shape[dim] == b.shape[dim] + 1): + pad = ( + [0] * ((b.ndim - dim - 1) * 2 + 1) + + [1] + + [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2)) + ) + b = torch.nn.functional.pad(b, pad) + + stacked = torch.stack([a, b], dim=dim + 1) + interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1) + if b_trunc: + # TODO: find torch alternative for slice_along dim for torch.jit.script to work + interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1) + return interleaved + + +def safe_map(f, *args): + args = list(map(list, args)) + n = len(args[0]) + for arg in args[1:]: + if len(arg) != n: + raise ValueError("length mismatch: {list(map(len, args))}") + + def nf(a): + return f(*a) + + return list(map(nf, zip(*args))) + + +class AssociativeScanOp(HigherOrderOperator): + def __init__(self): + super().__init__("associative_scan") + + def __call__(self, combine_fn, xs, additional_inputs): + # There is currently an issue that the ScanOp is sometimes called with + # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785 + # Once this issue is resolved, the assertion should only allow tuples + # and the tuple cast should be removed + assert isinstance( + additional_inputs, (tuple, list) + ), "additional_inputs must be a tuple." + validate_subgraph_args_types(additional_inputs) + return super().__call__(combine_fn, xs, additional_inputs) + + +associative_scan_op = AssociativeScanOp() + + +def associative_scan( + combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree], + xs: pytree.PyTree, + dim: int, + reverse: bool = False, + combine_mode: str = "pointwise", +) -> torch.Tensor: + r""" + Performs an inclusive scan with an associative combine function. + + .. warning:: + `torch.associative_scan` is a prototype feature in PyTorch. It currently + does not support autograd and you may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + This operator requires runtime code generation and so requires support for + ``torch.compile``. Further, only CUDA device codegen is supported at the moment. + + Args: + combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, i.e., no lifted arguments are supported at the moment, + satisfy the associative property and have no side-effects. + xs (torch.Tensor): The input tensor, or nested pytree of tensors. + All inputs are expected to have the same shape. + dim (int): the dimension to scan over + reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``. + combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``. + If ``combine_mode=pointwise``, ``combine_fn`` must be pure, may only contain pointwise operations + and ``xs`` must be CUDA tensors. + In all other cases ``combine_mode=generic`` should be used. + Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``. + + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + cumsum = associative_scan(add, x, dim) + + """ + if not callable(combine_fn): + raise ValueError("Combine_fn must be a callable, but got {combine_fn}") + if not isinstance(dim, int): + raise ValueError("Dim must be an int, but got " + str(type(dim))) + if combine_mode not in ["pointwise", "generic"]: + raise ValueError( + "Combine_mode must either 'pointwise' or 'generic', but got {combine_mode}" + ) + + if not torch.compiler.is_compiling(): + with _set_compilation_env(), torch._dynamo.utils.disable_cache_limit(): + return torch.compile(associative_scan, fullgraph=True, backend="eager")( + combine_fn, xs, dim, reverse=reverse, combine_mode=combine_mode + ) + + leaves, spec = pytree.tree_flatten(xs) + + if combine_mode == "pointwise" and not all(l.device.type == "cuda" for l in leaves): + raise ValueError( + "For combine_mode='pointwise', all input tensors need to be on CUDA" + ) + + if len(leaves) == 0: + raise ValueError("Expected at least 1 xs leaf") + if any(not isinstance(x, torch.Tensor) for x in leaves): + raise ValueError("xs leaves must be a Tensor") + if any(x.is_sparse for x in leaves): + raise ValueError("xs leaves must dense Tensors, consider using `to_dense()`") + if any(x.ndim <= dim for x in leaves): + raise ValueError( + "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0" + ) + if any(x.shape[dim] == 0 for x in leaves): + raise ValueError( + "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0" + ) + + if reverse: + leaves = [torch.flip(elem, [dim]) for elem in leaves] + + ndim = leaves[0].ndim + orig_scan_dim = utils.canonicalize_dim(ndim, dim) + leaves = [torch.movedim(elem, dim, 0) for elem in leaves] + + # Call the combine_fn with only a slice along the scan dim + # and check whether the output leaves have the same slice dimensions + sliced_leaves = [first_slice_copy(leaf) for leaf in leaves] + + out = combine_fn( + pytree.tree_unflatten(sliced_leaves, spec), + pytree.tree_unflatten(sliced_leaves, spec), + ) + out_leaves = pytree.tree_leaves(out) + if len(leaves) != len(out_leaves): + raise RuntimeError( + "The number of leaves of the pytree of the output of the operator needs to match the length of the pytree of the input" + ) + if any( + x.shape != x_sliced.shape + or x.dtype != x_sliced.dtype + or x.device != x_sliced.device + or x.stride() != x_sliced.stride() + for x, x_sliced in zip(out_leaves, sliced_leaves) + ): + raise RuntimeError( + f"The metadata of the output of the operator needs to match the meta data of the xs pytree" + f"\n xs metadata : {[(x.shape, x.dtype, x.device, x.stride()) for x in sliced_leaves]}" + f"\n operator output metadata: {[(x.shape, x.dtype, x.device, x.stride()) for x in out_leaves]}" + ) + + if combine_mode == "generic": + # The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension + # For example, consider: + # def add(x: torch.Tensor, y: torch.Tensor): + # return x + y + # leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0] + # [0.0, 1.0, 2.0, 3.0]]) + # which has shape 2 x 4; + # dim = 1; + # In the first iteration of `_scan` the combine_fn gets invoked with + # combine_fn([torch.tensor([[0.0, 2.0], + # [0.0, 2.0]])], + # [torch.tensor([[1.0, 3.0], + # [1.0, 3.0]])]) + # The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension. + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=torch.vmap( + combine_fn, + in_dims=( + pytree.tree_unflatten([0] * len(leaves), spec), + pytree.tree_unflatten([0] * len(leaves), spec), + ), + out_dims=0, + ), + spec=spec, + num_leaves=len(leaves), + ) + result_flat = generic_associative_scan(combine_fn, leaves, additional_inputs=()) + else: + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=combine_fn, + spec=spec, + num_leaves=len(leaves), + ) + result_flat = associative_scan_op(combine_fn, leaves, additional_inputs=()) + + if reverse: + result_flat = [torch.flip(elem, [0]) for elem in result_flat] + + result_flat = [torch.movedim(elem, 0, orig_scan_dim) for elem in result_flat] + + return pytree.tree_unflatten(result_flat, spec) + + +def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()): + r""" + This function performs the associative_scan operation. + The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently + applying the ``operator`` on all pairs in parallel along ``dim``. + The results of the recursive calls are later combined. + + Args: + operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, pointwise, and satisfy the associative property. + leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of + ``xs`` provided to ``associative_scan``. + All inputs are expected to have the same shape. + dim (int): the dimension to scan over + additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope. + This parameter will be populated internally. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + leaves = torch.tensor([0.0, 1.0, 2.0, 3.0]) + + First iteration of _scan -> + # odd_elems -> apply operator on all neighbours + # odd_elems = operator([torch.tensor([0.0, 2.0])], + # [torch.tensor([1.0, 3.0])]) + odd_elems = torch.tensor([1.0, 5.0]) + Second iteration of _scan -> + # odd_elems = operator([torch.tensor([1.0])], + # [torch.tensor([5.0])]) + odd_elems = torch.tensor([6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [1.0] + # Merges odd_elems and even_elems + res = torch.tensor([1.0, 6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [0.0, 3.0] + # Merges odd_elems and even_elems + res = torch.tensor([0.0, 1.0, 3.0, 6.0]) + + """ + + def _scan(elems): + """Perform the actual recursive scan on ``elems``.""" + num_elems = elems[0].shape[dim] + + if num_elems < 2: + return elems + + reduced_elems = operator( + *[aten.slice(elem, dim, 0, -1, 2) for elem in elems], + *[aten.slice(elem, dim, 1, None, 2) for elem in elems], + *additional_inputs, + ) + + # Recursively compute scan for partially reduced tensors. + odd_elems = _scan(reduced_elems) + + if num_elems % 2 == 0: + even_elems = operator( + *[aten.slice(e, dim, 0, -1) for e in odd_elems], + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + else: + even_elems = operator( + *odd_elems, + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + + # The first element of a scan is the same as the first element + # of the original `elems`. + even_elems = [ + torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim) + if result.shape.numel() > 0 and elem.shape[dim] > 0 + else result + if result.shape.numel() > 0 + else aten.slice( + elem, dim, 0, 1 + ) # Jax allows/ignores concat with 0-dim, Pytorch does not + for (elem, result) in zip(elems, even_elems) + ] + + return list( + safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems) + ) + + scans = _scan(leaves) + + return scans + + +def trace_associative_scan( + proxy_mode, + func_overload, + combine_fn: Callable, + xs: list[torch.Tensor], + additional_inputs: tuple[torch.Tensor], +): + with disable_proxy_modes_tracing(): + sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)] + combine_graph = reenter_make_fx(combine_fn)(*sample_xs, *additional_inputs) + + outputs = None + for node in combine_graph.graph.nodes: + if node.op == "output": + assert outputs is None + assert len(node.args) == 1 + outputs = node.args[0] + + assert outputs is not None + assert len(outputs) == len( + xs + ), f"expected combine_fn to return {len(xs)} results but got {len(outputs)}" + + for i, o in zip(xs, outputs): + o_meta = o.meta["tensor_meta"] + assert o_meta.dtype == i.dtype, ( + f"combine_fn output type mismatch, expected {i.dtype} " + + f"but got {o_meta.dtype}" + ) + + _, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph") + + proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph) + + args = (combine_graph, xs, additional_inputs) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="associative_scan" + ) + + with disable_proxy_modes_tracing(): + out = tuple(aten.clone(x) for x in xs) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def associative_scan_op_dense(combine_fn, xs, additional_inputs): + return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs) + + +associative_scan_op.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(associative_scan_op, deferred_error=True) +) + + +@associative_scan_op.py_impl(ProxyTorchDispatchMode) +def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs): + return trace_associative_scan( + mode, associative_scan_op, combine_fn, xs, additional_inputs + ) + + +@associative_scan_op.py_impl(FakeTensorMode) +def assoiciative_scan_fake_tensor_mode(mode, combine_fn, xs, additional_inputs): + with mode: + return tuple(x.clone() for x in xs) + + +@associative_scan_op.py_functionalize_impl +def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs): + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + with ctx.redispatch_to_next(): + functional_combine_fn = ctx.functionalize( + _maybe_run_with_interpreter(combine_fn) + ) + ret = associative_scan_op( + functional_combine_fn, + unwrapped_xs, + unwrapped_additional_inputs, + ) + return ctx.wrap_tensors(ret) + + +def _fake_associative_scan(combine_fn, xs, dim, reverse=False): + inp_leaves, spec = pytree.tree_flatten(xs) + result_flat: list[Any] = [] + num_leaves = len(inp_leaves) + op = reversed if reverse else lambda x: x + + for ind in op(range(inp_leaves[0].size(dim))): + r = [ + inp_leaves[leave_ind][(slice(None),) * dim + (ind,)] + for leave_ind in range(num_leaves) + ] + if (ind > 0 and not reverse) or ( + ind < (inp_leaves[0].size(dim) - 1) and reverse + ): + r = combine_fn( + pytree.tree_unflatten(result_flat[-1], spec), + pytree.tree_unflatten(r, spec), + ) + r_flat, _ = pytree.tree_flatten(r) + result_flat.append(r_flat) + + results = [ + torch.stack([e[leave_ind] for e in op(result_flat)], dim) + for leave_ind in range(num_leaves) + ] + return pytree.tree_unflatten(results, spec) diff --git a/shared/package-files/93/939c1f1092e33ff87c50e40f2745225e2d2a3bad4a7c341a7ff8134cb08e4408/python_fft_functions.h b/shared/package-files/93/939c1f1092e33ff87c50e40f2745225e2d2a3bad4a7c341a7ff8134cb08e4408/python_fft_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..1ce94653e1cba2e4b21b2cf314ad3e9e502aaf8d --- /dev/null +++ b/shared/package-files/93/939c1f1092e33ff87c50e40f2745225e2d2a3bad4a7c341a7ff8134cb08e4408/python_fft_functions.h @@ -0,0 +1,8 @@ +#pragma once +#include + +namespace torch::autograd { + +void initFFTFunctions(PyObject* module); + +} diff --git a/shared/package-files/93/93a20c4601fa982b49841aa6a4f19f197a02d98f1116a0f30013e6da0963272b/simple_paths.cpython-311.pyc b/shared/package-files/93/93a20c4601fa982b49841aa6a4f19f197a02d98f1116a0f30013e6da0963272b/simple_paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cdb97231c7dd71a6d637d4cbe9a4c2b4b1680b2 Binary files /dev/null and b/shared/package-files/93/93a20c4601fa982b49841aa6a4f19f197a02d98f1116a0f30013e6da0963272b/simple_paths.cpython-311.pyc differ diff --git a/shared/package-files/93/93a2e346a265b4b75f6fa4bb536a5ef9ec20f6dce031e9339567ed727f6c3424/test_return_logical.cpython-311.pyc b/shared/package-files/93/93a2e346a265b4b75f6fa4bb536a5ef9ec20f6dce031e9339567ed727f6c3424/test_return_logical.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc89435f1eaf7e783c2e79c0330576a6c3a2feb0 Binary files /dev/null and b/shared/package-files/93/93a2e346a265b4b75f6fa4bb536a5ef9ec20f6dce031e9339567ed727f6c3424/test_return_logical.cpython-311.pyc differ diff --git a/shared/package-files/93/93a82c91bd1eca95ddaca251c51de5ffbe665639880869da3b2ec57513301bc1/modularinteger.py b/shared/package-files/93/93a82c91bd1eca95ddaca251c51de5ffbe665639880869da3b2ec57513301bc1/modularinteger.py new file mode 100644 index 0000000000000000000000000000000000000000..39a0237563c69a77e4736466d1ebcaa7ca39485f --- /dev/null +++ b/shared/package-files/93/93a82c91bd1eca95ddaca251c51de5ffbe665639880869da3b2ec57513301bc1/modularinteger.py @@ -0,0 +1,237 @@ +"""Implementation of :class:`ModularInteger` class. """ + +from __future__ import annotations +from typing import Any + +import operator + +from sympy.polys.polyutils import PicklableWithSlots +from sympy.polys.polyerrors import CoercionFailed +from sympy.polys.domains.domainelement import DomainElement + +from sympy.utilities import public +from sympy.utilities.exceptions import sympy_deprecation_warning + +@public +class ModularInteger(PicklableWithSlots, DomainElement): + """A class representing a modular integer. """ + + mod, dom, sym, _parent = None, None, None, None + + __slots__ = ('val',) + + def parent(self): + return self._parent + + def __init__(self, val): + if isinstance(val, self.__class__): + self.val = val.val % self.mod + else: + self.val = self.dom.convert(val) % self.mod + + def modulus(self): + return self.mod + + def __hash__(self): + return hash((self.val, self.mod)) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, self.val) + + def __str__(self): + return "%s mod %s" % (self.val, self.mod) + + def __int__(self): + return int(self.val) + + def to_int(self): + + sympy_deprecation_warning( + """ModularInteger.to_int() is deprecated. + + Use int(a) or K = GF(p) and K.to_int(a) instead of a.to_int(). + """, + deprecated_since_version="1.13", + active_deprecations_target="modularinteger-to-int", + ) + + if self.sym: + if self.val <= self.mod // 2: + return self.val + else: + return self.val - self.mod + else: + return self.val + + def __pos__(self): + return self + + def __neg__(self): + return self.__class__(-self.val) + + @classmethod + def _get_val(cls, other): + if isinstance(other, cls): + return other.val + else: + try: + return cls.dom.convert(other) + except CoercionFailed: + return None + + def __add__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val + val) + else: + return NotImplemented + + def __radd__(self, other): + return self.__add__(other) + + def __sub__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val - val) + else: + return NotImplemented + + def __rsub__(self, other): + return (-self).__add__(other) + + def __mul__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val * val) + else: + return NotImplemented + + def __rmul__(self, other): + return self.__mul__(other) + + def __truediv__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val * self._invert(val)) + else: + return NotImplemented + + def __rtruediv__(self, other): + return self.invert().__mul__(other) + + def __mod__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(self.val % val) + else: + return NotImplemented + + def __rmod__(self, other): + val = self._get_val(other) + + if val is not None: + return self.__class__(val % self.val) + else: + return NotImplemented + + def __pow__(self, exp): + if not exp: + return self.__class__(self.dom.one) + + if exp < 0: + val, exp = self.invert().val, -exp + else: + val = self.val + + return self.__class__(pow(val, int(exp), self.mod)) + + def _compare(self, other, op): + val = self._get_val(other) + + if val is None: + return NotImplemented + + return op(self.val, val % self.mod) + + def _compare_deprecated(self, other, op): + val = self._get_val(other) + + if val is None: + return NotImplemented + + sympy_deprecation_warning( + """Ordered comparisons with modular integers are deprecated. + + Use e.g. int(a) < int(b) instead of a < b. + """, + deprecated_since_version="1.13", + active_deprecations_target="modularinteger-compare", + stacklevel=4, + ) + + return op(self.val, val % self.mod) + + def __eq__(self, other): + return self._compare(other, operator.eq) + + def __ne__(self, other): + return self._compare(other, operator.ne) + + def __lt__(self, other): + return self._compare_deprecated(other, operator.lt) + + def __le__(self, other): + return self._compare_deprecated(other, operator.le) + + def __gt__(self, other): + return self._compare_deprecated(other, operator.gt) + + def __ge__(self, other): + return self._compare_deprecated(other, operator.ge) + + def __bool__(self): + return bool(self.val) + + @classmethod + def _invert(cls, value): + return cls.dom.invert(value, cls.mod) + + def invert(self): + return self.__class__(self._invert(self.val)) + +_modular_integer_cache: dict[tuple[Any, Any, Any], type[ModularInteger]] = {} + +def ModularIntegerFactory(_mod, _dom, _sym, parent): + """Create custom class for specific integer modulus.""" + try: + _mod = _dom.convert(_mod) + except CoercionFailed: + ok = False + else: + ok = True + + if not ok or _mod < 1: + raise ValueError("modulus must be a positive integer, got %s" % _mod) + + key = _mod, _dom, _sym + + try: + cls = _modular_integer_cache[key] + except KeyError: + class cls(ModularInteger): + mod, dom, sym = _mod, _dom, _sym + _parent = parent + + if _sym: + cls.__name__ = "SymmetricModularIntegerMod%s" % _mod + else: + cls.__name__ = "ModularIntegerMod%s" % _mod + + _modular_integer_cache[key] = cls + + return cls diff --git a/shared/package-files/93/93a8ddaea72cfe1f9ec0ceb109c30ba67205deeaaff3fafd808429ac87d11a7f/__init__.py b/shared/package-files/93/93a8ddaea72cfe1f9ec0ceb109c30ba67205deeaaff3fafd808429ac87d11a7f/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a05d8bde0f67433a2e8b621df5dfb47451bd1d --- /dev/null +++ b/shared/package-files/93/93a8ddaea72cfe1f9ec0ceb109c30ba67205deeaaff3fafd808429ac87d11a7f/__init__.py @@ -0,0 +1,7 @@ +# flake8: noqa: F401 +r"""QAT Dynamic Modules. + +This package is in the process of being deprecated. +Please, use `torch.ao.nn.qat.dynamic` instead. +""" +from torch.nn.qat.dynamic.modules import * # noqa: F403 diff --git a/shared/package-files/93/93ab4ec9cf78dc77d02f08e3d845537c82c31b3b7527fe460192c21a36aa8726/test_operator.cpython-311.pyc b/shared/package-files/93/93ab4ec9cf78dc77d02f08e3d845537c82c31b3b7527fe460192c21a36aa8726/test_operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..447ff96da76e010aa5b2a353193f1c0360e78833 Binary files /dev/null and b/shared/package-files/93/93ab4ec9cf78dc77d02f08e3d845537c82c31b3b7527fe460192c21a36aa8726/test_operator.cpython-311.pyc differ diff --git a/shared/package-files/93/93aec712aa0f1899597c52697d859cf26c63163ee355e456f0e20b984dcfdfdf/help_about.py b/shared/package-files/93/93aec712aa0f1899597c52697d859cf26c63163ee355e456f0e20b984dcfdfdf/help_about.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1c352897f9e7c137057a8d279a86ac8fbe6cc1 --- /dev/null +++ b/shared/package-files/93/93aec712aa0f1899597c52697d859cf26c63163ee355e456f0e20b984dcfdfdf/help_about.py @@ -0,0 +1,207 @@ +"""About Dialog for IDLE + +""" +import os +import sys +import webbrowser +from platform import python_version, architecture + +from tkinter import Toplevel, Frame, Label, Button, PhotoImage +from tkinter import SUNKEN, TOP, BOTTOM, LEFT, X, BOTH, W, EW, NSEW, E + +from idlelib import textview + +pyver = python_version() + +if sys.platform == 'darwin': + bits = '64' if sys.maxsize > 2**32 else '32' +else: + bits = architecture()[0][:2] + + +class AboutDialog(Toplevel): + """Modal about dialog for idle + + """ + def __init__(self, parent, title=None, *, _htest=False, _utest=False): + """Create popup, do not return until tk widget destroyed. + + parent - parent of this dialog + title - string which is title of popup dialog + _htest - bool, change box location when running htest + _utest - bool, don't wait_window when running unittest + """ + Toplevel.__init__(self, parent) + self.configure(borderwidth=5) + # place dialog below parent if running htest + self.geometry("+%d+%d" % ( + parent.winfo_rootx()+30, + parent.winfo_rooty()+(30 if not _htest else 100))) + self.bg = "#bbbbbb" + self.fg = "#000000" + self.create_widgets() + self.resizable(height=False, width=False) + self.title(title or + f'About IDLE {pyver} ({bits} bit)') + self.transient(parent) + self.grab_set() + self.protocol("WM_DELETE_WINDOW", self.ok) + self.parent = parent + self.button_ok.focus_set() + self.bind('', self.ok) # dismiss dialog + self.bind('', self.ok) # dismiss dialog + self._current_textview = None + self._utest = _utest + + if not _utest: + self.deiconify() + self.wait_window() + + def create_widgets(self): + frame = Frame(self, borderwidth=2, relief=SUNKEN) + frame_buttons = Frame(self) + frame_buttons.pack(side=BOTTOM, fill=X) + frame.pack(side=TOP, expand=True, fill=BOTH) + self.button_ok = Button(frame_buttons, text='Close', + command=self.ok) + self.button_ok.pack(padx=5, pady=5) + + frame_background = Frame(frame, bg=self.bg) + frame_background.pack(expand=True, fill=BOTH) + + header = Label(frame_background, text='IDLE', fg=self.fg, + bg=self.bg, font=('courier', 24, 'bold')) + header.grid(row=0, column=0, sticky=E, padx=10, pady=10) + + tkpatch = self._root().getvar('tk_patchLevel') + ext = '.png' if tkpatch >= '8.6' else '.gif' + icon = os.path.join(os.path.abspath(os.path.dirname(__file__)), + 'Icons', f'idle_48{ext}') + self.icon_image = PhotoImage(master=self._root(), file=icon) + logo = Label(frame_background, image=self.icon_image, bg=self.bg) + logo.grid(row=0, column=0, sticky=W, rowspan=2, padx=10, pady=10) + + byline_text = "Python's Integrated Development\nand Learning Environment" + 5*'\n' + byline = Label(frame_background, text=byline_text, justify=LEFT, + fg=self.fg, bg=self.bg) + byline.grid(row=2, column=0, sticky=W, columnspan=3, padx=10, pady=5) + email = Label(frame_background, text='email: idle-dev@python.org', + justify=LEFT, fg=self.fg, bg=self.bg) + email.grid(row=6, column=0, columnspan=2, sticky=W, padx=10, pady=0) + docs_url = ("https://docs.python.org/%d.%d/library/idle.html" % + sys.version_info[:2]) + docs = Label(frame_background, text=docs_url, + justify=LEFT, fg=self.fg, bg=self.bg) + docs.grid(row=7, column=0, columnspan=2, sticky=W, padx=10, pady=0) + docs.bind("", lambda event: webbrowser.open(docs['text'])) + + Frame(frame_background, borderwidth=1, relief=SUNKEN, + height=2, bg=self.bg).grid(row=8, column=0, sticky=EW, + columnspan=3, padx=5, pady=5) + + tclver = str(self.info_patchlevel()) + tkver = ' and ' + tkpatch if tkpatch != tclver else '' + versions = f"Python {pyver} with tcl/tk {tclver}{tkver}" + vers = Label(frame_background, text=versions, fg=self.fg, bg=self.bg) + vers.grid(row=9, column=0, sticky=W, padx=10, pady=0) + py_buttons = Frame(frame_background, bg=self.bg) + py_buttons.grid(row=10, column=0, columnspan=2, sticky=NSEW) + self.py_license = Button(py_buttons, text='License', width=8, + highlightbackground=self.bg, + command=self.show_py_license) + self.py_license.pack(side=LEFT, padx=10, pady=10) + self.py_copyright = Button(py_buttons, text='Copyright', width=8, + highlightbackground=self.bg, + command=self.show_py_copyright) + self.py_copyright.pack(side=LEFT, padx=10, pady=10) + self.py_credits = Button(py_buttons, text='Credits', width=8, + highlightbackground=self.bg, + command=self.show_py_credits) + self.py_credits.pack(side=LEFT, padx=10, pady=10) + + Frame(frame_background, borderwidth=1, relief=SUNKEN, + height=2, bg=self.bg).grid(row=11, column=0, sticky=EW, + columnspan=3, padx=5, pady=5) + + idle = Label(frame_background, + text='IDLE', + fg=self.fg, bg=self.bg) + idle.grid(row=12, column=0, sticky=W, padx=10, pady=0) + idle_buttons = Frame(frame_background, bg=self.bg) + idle_buttons.grid(row=13, column=0, columnspan=3, sticky=NSEW) + self.readme = Button(idle_buttons, text='Readme', width=8, + highlightbackground=self.bg, + command=self.show_readme) + self.readme.pack(side=LEFT, padx=10, pady=10) + self.idle_news = Button(idle_buttons, text='News', width=8, + highlightbackground=self.bg, + command=self.show_idle_news) + self.idle_news.pack(side=LEFT, padx=10, pady=10) + self.idle_credits = Button(idle_buttons, text='Credits', width=8, + highlightbackground=self.bg, + command=self.show_idle_credits) + self.idle_credits.pack(side=LEFT, padx=10, pady=10) + + # License, copyright, and credits are of type _sitebuiltins._Printer + def show_py_license(self): + "Handle License button event." + self.display_printer_text('About - License', license) + + def show_py_copyright(self): + "Handle Copyright button event." + self.display_printer_text('About - Copyright', copyright) + + def show_py_credits(self): + "Handle Python Credits button event." + self.display_printer_text('About - Python Credits', credits) + + # Encode CREDITS.txt to utf-8 for proper version of Loewis. + # Specify others as ascii until need utf-8, so catch errors. + def show_idle_credits(self): + "Handle Idle Credits button event." + self.display_file_text('About - Credits', 'CREDITS.txt', 'utf-8') + + def show_readme(self): + "Handle Readme button event." + self.display_file_text('About - Readme', 'README.txt', 'ascii') + + def show_idle_news(self): + "Handle News button event." + self.display_file_text('About - News', 'News3.txt', 'utf-8') + + def display_printer_text(self, title, printer): + """Create textview for built-in constants. + + Built-in constants have type _sitebuiltins._Printer. The + text is extracted from the built-in and then sent to a text + viewer with self as the parent and title as the title of + the popup. + """ + printer._Printer__setup() + text = '\n'.join(printer._Printer__lines) + self._current_textview = textview.view_text( + self, title, text, _utest=self._utest) + + def display_file_text(self, title, filename, encoding=None): + """Create textview for filename. + + The filename needs to be in the current directory. The path + is sent to a text viewer with self as the parent, title as + the title of the popup, and the file encoding. + """ + fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), filename) + self._current_textview = textview.view_file( + self, title, fn, encoding, _utest=self._utest) + + def ok(self, event=None): + "Dismiss help_about dialog." + self.grab_release() + self.destroy() + + +if __name__ == '__main__': + from unittest import main + main('idlelib.idle_test.test_help_about', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(AboutDialog) diff --git a/shared/package-files/93/93b7913d58c53ff0ac37fd81a65699f0996c1ac50fc30c714a1a715836664263/vec_qint.h b/shared/package-files/93/93b7913d58c53ff0ac37fd81a65699f0996c1ac50fc30c714a1a715836664263/vec_qint.h new file mode 100644 index 0000000000000000000000000000000000000000..96e201ef36a2196fb3b09cd221766013e3223c64 --- /dev/null +++ b/shared/package-files/93/93b7913d58c53ff0ac37fd81a65699f0996c1ac50fc30c714a1a715836664263/vec_qint.h @@ -0,0 +1,567 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with SVE] + +#include +#include +#include +#include +#include +#include + +#include + +// This file defines Vectorized<> for the quantized types. +// +// +// Currently, we simply use these classes as efficient converters between +// the quantized types and Vectorized, usually in bandwidth-bound cases +// where doing the arithmetic in full-precision is acceptable (e.g. +// elementwise operators). +// +// +// Conversions are as follows: +// Vectorized -> 4x Vectorized +// Vectorized -> 4x Vectorized +// Vectorized -> 1x Vectorized +// +// The size of the returned float vector is specified by the special +// constexpr function float_num_vecs. The type of the value returned +// from dequantize (and expected as an argument to quantize) is +// specified by float_vec_return_type. +// +// When writing kernels with these vectors, it is expected that floating- +// point operations will be carried out in a loop over Vectorized::float_num_vecs +// iterations. + + +namespace at::vec { +// Note [CPU_CAPABILITY namespace] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// This header, and all of its subheaders, will be compiled with +// different architecture flags for each supported set of vector +// intrinsics. So we need to make sure they aren't inadvertently +// linked together. We do this by declaring objects in an `inline +// namespace` which changes the name mangling, but can still be +// accessed as `at::vec`. +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_SVE) + +// NOTE: These are low-performance implementations that we fall back on +// if we are not building with SVE. This may not be an issue, because +// currently for quantization we assume the user has at least SVE +// installed, so these can simply act as a reference implementation. +// +// If in the future we relax this requirement (SVE+), we should probably +// revisit these implementations + +template < + typename T, + typename float_vec_return_type_, + typename int_vec_return_type_, + int size_> +struct VectorizedQuantizedConverter { + using size_type = int; + static constexpr size_type size() { + return size_; + } + + static constexpr int float_num_vecs() { + return size() / Vectorized::size(); + } + + static constexpr int int_num_vecs() { + return size() / Vectorized::size(); + } + + using float_vec_return_type = float_vec_return_type_; + using int_vec_return_type = int_vec_return_type_; + + using value_type = typename T::underlying; + std::array vals; + + VectorizedQuantizedConverter(T val) { + for (size_t i = 0; i < size(); ++i) { + vals[i] = val.val_; + } + } + + VectorizedQuantizedConverter(const void* ptr) { + memcpy(vals.data(), ptr, sizeof(value_type) * size()); + } + + void store(void* ptr, int count = size()) const { + memcpy(ptr, vals.data(), count * sizeof(value_type)); + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + float_vec_return_type rv; + float tmp_scale[Vectorized::size()]; + float tmp_zero_point[Vectorized::size()]; + scale.store(tmp_scale); + zero_point.store(tmp_zero_point); + for (int i = 0; i < float_num_vecs(); ++i) { + float tmp_vals[Vectorized::size()]; + for (int j = 0; j < Vectorized::size(); ++j) { + tmp_vals[j] = + at::native::dequantize_val(tmp_scale[j], tmp_zero_point[j], T(vals[Vectorized::size() * i + j])); + } + rv[i] = Vectorized::loadu(tmp_vals); + } + return rv; + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { + float_vec_return_type rv; + float tmp_scale[Vectorized::size()]; + float tmp_zero_point[Vectorized::size()]; + scale.store(tmp_scale); + zero_point.store(tmp_zero_point); + for (int i = 0; i < float_num_vecs(); ++i) { + float tmp_vals[Vectorized::size()]; + for (int j = 0; j < Vectorized::size(); ++j) { + tmp_vals[j] = + at::native::dequantize_val(tmp_scale[j], tmp_zero_point[j], T(vals[Vectorized::size() * i + j])); + } + rv[i] = Vectorized::loadu(tmp_vals); + } + return rv; + } + + protected: + VectorizedQuantizedConverter() {} +}; + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + VECTOR_WIDTH / 4> { + Vectorized() + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + VECTOR_WIDTH / 4>() {} + Vectorized(c10::qint32 val) + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + VECTOR_WIDTH / 4>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + VECTOR_WIDTH / 4>(ptr) {} +#if 1 + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + __at_align__ value_type tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, reinterpret_cast(ptr), count * sizeof(value_type)); + return loadu(tmp_values); + } +#else + static Vectorized loadu(const void* ptr, int64_t count = size()) { + if (count == size()) + return svld1_s32(ptrue, reinterpret_cast(ptr)); + svbool_t pg = svwhilelt_b32(0ull, count); + return svld1_s32(pg, reinterpret_cast(ptr)); + } +#endif + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + std::array qvals; + std::array::size()> float_vals; + + for (int i = 0; i < float_num_vecs(); ++i) { + rhs[i].store(&float_vals[i * Vectorized::size()], Vectorized::size()); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::qint32*)qvals.data(), + Vectorized::size() * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + for (size_t i = 0; i < size(); ++i) { + retval[0].vals[i] = vals[i] - b.vals[i]; + } + return retval; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = + nearbyint(static_cast(inp[0].vals[i]) * multiplier) + + zero_point; + } + return retval; + } +}; + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return a.maximum(b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + Vectorized retval; + for (size_t i = 0; i < std::decay_t::size(); ++i) { + retval.vals[i] = a.vals[i] * b.vals[i]; + } + return retval; +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + Vectorized retval; + for (size_t i = 0; i < std::decay_t::size(); ++i) { + retval.vals[i] = a.vals[i] + b.vals[i]; + } + return retval; +} + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH> { + Vectorized() + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>() {} + Vectorized(c10::qint8 val) + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>(ptr) {} + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + __at_align__ value_type tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, reinterpret_cast(ptr), count * sizeof(value_type)); + return loadu(tmp_values); + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + std::array qvals; + std::array::size()> float_vals; + + for (int i = 0; i < float_num_vecs(); ++i) { + rhs[i].store(&float_vals[i * Vectorized::size()], Vectorized::size()); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::qint8*)qvals.data(), + Vectorized::size() * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + constexpr int elem_per_int_vec = size() / int_num_vecs(); + for (size_t i = 0; i < int_num_vecs(); ++i) { + for (size_t j = 0; j < elem_per_int_vec; ++j) { + retval[i].vals[j] = + static_cast(vals[i * elem_per_int_vec + j]) - + static_cast(b.vals[i * elem_per_int_vec + j]); + } + } + return retval; + } + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + constexpr int elem_per_int_vec = size() / int_num_vecs(); + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + Vectorized retval; + for (size_t i = 0; i < int_num_vecs(); ++i) { + for (size_t j = 0; j < elem_per_int_vec; ++j) { + int32_t rounded = + nearbyint(static_cast(inp[i].vals[j]) * multiplier) + + zero_point; + retval.vals[i * elem_per_int_vec + j] = + std::min(std::max(rounded, min_val), max_val); + } + } + return retval; + } +}; + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return a.maximum(b); +} + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH> { + Vectorized() + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>() {} + Vectorized(c10::quint8 val) + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + VECTOR_WIDTH>(ptr) {} +#if 1 + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + __at_align__ value_type tmp_values[size()]; + // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502 + // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two + // instructions while a loop would be compiled to one instruction. + for (const auto i : c10::irange(size())) { + tmp_values[i] = 0; + } + std::memcpy(tmp_values, reinterpret_cast(ptr), count * sizeof(value_type)); + return loadu(tmp_values); + } +#else + static Vectorized loadu(const void* ptr, int64_t count = size()) { + if (count == size()) + return svld1_u8(ptrue, reinterpret_cast(ptr)); + svbool_t pg = svwhilelt_b8(0ull, count); + return svld1_u8(pg, reinterpret_cast(ptr)); + } +#endif + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + std::array qvals; + std::array::size()> float_vals; + + for (int i = 0; i < float_num_vecs(); ++i) { + rhs[i].store(&float_vals[i * Vectorized::size()], Vectorized::size()); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::quint8*)qvals.data(), + Vectorized::size() * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (size_t i = 0; i < size(); ++i) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + constexpr int elem_per_int_vec = size() / int_num_vecs(); + for (size_t i = 0; i < int_num_vecs(); ++i) { + for (size_t j = 0; j < elem_per_int_vec; ++j) { + retval[i].vals[j] = + static_cast(vals[i * elem_per_int_vec + j]) - + static_cast(b.vals[i * elem_per_int_vec + j]); + } + } + return retval; + } + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + constexpr int elem_per_int_vec = size() / int_num_vecs(); + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + Vectorized retval; + for (size_t i = 0; i < int_num_vecs(); ++i) { + for (size_t j = 0; j < elem_per_int_vec; ++j) { + int32_t rounded = + nearbyint(static_cast(inp[i].vals[j]) * multiplier) + + zero_point; + retval.vals[i * elem_per_int_vec + j] = + std::min(std::max(rounded, min_val), max_val); + } + } + return retval; + } +}; + +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + return a.maximum(b); +} + +#endif // defined(CPU_CAPABILITY_SVE) + +}} diff --git a/shared/package-files/93/93b82d1ac1a4f266a421a6da715ac725ef77c19c931e288dd18ee7aaaeb03f98/_assert_tensor_metadata_compositeexplicitautograd_dispatch.h b/shared/package-files/93/93b82d1ac1a4f266a421a6da715ac725ef77c19c931e288dd18ee7aaaeb03f98/_assert_tensor_metadata_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..71f16ffd326f58e7f58131814a1090c9dd0c6843 --- /dev/null +++ b/shared/package-files/93/93b82d1ac1a4f266a421a6da715ac725ef77c19c931e288dd18ee7aaaeb03f98/_assert_tensor_metadata_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _assert_tensor_metadata(const at::Tensor & a, at::OptionalIntArrayRef size=::std::nullopt, at::OptionalIntArrayRef stride=::std::nullopt, ::std::optional dtype=::std::nullopt, ::std::optional device=::std::nullopt, ::std::optional layout=::std::nullopt); +TORCH_API void _assert_tensor_metadata_symint(const at::Tensor & a, at::OptionalSymIntArrayRef size=::std::nullopt, at::OptionalSymIntArrayRef stride=::std::nullopt, ::std::optional dtype=::std::nullopt, ::std::optional device=::std::nullopt, ::std::optional layout=::std::nullopt); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/93/93bc5cabb0fb6c47a18316ab6f0f9d5b702d98664e46acfc1e3291e85189de39/test.py b/shared/package-files/93/93bc5cabb0fb6c47a18316ab6f0f9d5b702d98664e46acfc1e3291e85189de39/test.py new file mode 100644 index 0000000000000000000000000000000000000000..341b11a20eb2cce98cdeeebea9ba2de0282d5d38 --- /dev/null +++ b/shared/package-files/93/93bc5cabb0fb6c47a18316ab6f0f9d5b702d98664e46acfc1e3291e85189de39/test.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from setuptools import Command +from setuptools.warnings import SetuptoolsDeprecationWarning + + +# Would restrict to Literal["test"], but mypy doesn't support it: https://github.com/python/mypy/issues/8203 +def __getattr__(name: str) -> type[_test]: + if name == 'test': + SetuptoolsDeprecationWarning.emit( + "The test command is disabled and references to it are deprecated.", + "Please remove any references to `setuptools.command.test` in all " + "supported versions of the affected package.", + due_date=(2024, 11, 15), + stacklevel=2, + ) + return _test + raise AttributeError(name) + + +class _test(Command): + """ + Stub to warn when test command is referenced or used. + """ + + description = "stub for old test command (do not use)" + + user_options = [ + ('test-module=', 'm', "Run 'test_suite' in specified module"), + ( + 'test-suite=', + 's', + "Run single test, case or suite (e.g. 'module.test_suite')", + ), + ('test-runner=', 'r', "Test runner to use"), + ] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + raise RuntimeError("Support for the test command was removed in Setuptools 72") diff --git a/shared/package-files/93/93be60f359140cf3ca43b1b2e8fcf03ce9402ef01d6e3849931ec39391d5cb66/printers.py b/shared/package-files/93/93be60f359140cf3ca43b1b2e8fcf03ce9402ef01d6e3849931ec39391d5cb66/printers.py new file mode 100644 index 0000000000000000000000000000000000000000..996c68a8bb7a60824c3ad05f061f9226d8cdc733 --- /dev/null +++ b/shared/package-files/93/93be60f359140cf3ca43b1b2e8fcf03ce9402ef01d6e3849931ec39391d5cb66/printers.py @@ -0,0 +1,477 @@ +import sys +from typing import Optional + +import sympy +from sympy.printing.precedence import PRECEDENCE, precedence +from sympy.printing.str import StrPrinter + + +INDEX_TYPE = "int64_t" + + +# This printer contains rules that are supposed to be generic for both C/C++ and +# Python +class ExprPrinter(StrPrinter): + # override this so that _print_FloorDiv is used + printmethod = "_torch_sympystr" + + def _print_Mul(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, "*", precedence(expr)) + + def _print_Add(self, expr: sympy.Expr, order: Optional[str] = None) -> str: + return self.stringify(expr.args, " + ", precedence(expr)) + + def _print_Relational(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, f" {expr.rel_op} ", precedence(expr)) + + def _print_BitwiseFn_bitwise_and(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"]) + + def _print_BitwiseFn_bitwise_or(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) + + # NB: this is OK to put here, because Mod is only defined for positive + # numbers, and so across C/Python its behavior is consistent + def _print_Mod(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5) + + def _print_FloatTrueDiv(self, expr: sympy.Expr) -> str: + s = self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5) + return f"({s})" + + def _print_CleanDiv(self, expr: sympy.Expr) -> str: + return self._print_FloorDiv(expr) + + def _print_Identity(self, expr: sympy.Expr) -> str: + return self._print(expr.args[0]) + + # This must be implemented because sympy will collect x * x into Pow(x, 2), without + # any explicit intervention. We print it just like x * x, notably, we + # never generate sympy.Pow with floats. + # + # NB: this pow by natural, you should never have used builtin sympy.pow + # for FloatPow, and a symbolic exponent should be PowByNatural. These + # means exp is guaranteed to be integer. + def _print_Pow(self, expr: sympy.Expr) -> str: + base, exp = expr.args + assert exp == int(exp), exp + exp = int(exp) + assert exp >= 0 + if exp > 0: + return self.stringify([base] * exp, "*", PRECEDENCE["Mul"]) + return "1" + + # Explicit NotImplemented functions are to prevent default sympy printing + # behavior, which will just barf out ToFloat(...) to your IR. The error + # message is better here because it tells you which printer class it needs + # to go in. + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_ToFloat not implemented for {type(self)}") + + def _print_Infinity(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_Infinity not implemented for {type(self)}") + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_NegativeInfinity not implemented for {type(self)}" + ) + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_FloorDiv not implemented for {type(self)}") + + def _print_PythonMod(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_PythonMod not implemented for {type(self)}") + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_IntTrueDiv not implemented for {type(self)}") + + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_PowByNatural not implemented for {type(self)}" + ) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_FloatPow not implemented for {type(self)}") + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_TruncToInt not implemented for {type(self)}") + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_RoundToInt not implemented for {type(self)}") + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_RoundDecimal not implemented for {type(self)}" + ) + + # NB: Some float operations are INTENTIONALLY not implemented for + # printers. You can implement them as a quick unblock, but it is better + # to ask yourself why we haven't done this computation in the Tensor + # universe instead + + def _print_TruncToFloat(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_TruncToFloat not implemented for {type(self)}" + ) + + +class PythonPrinter(ExprPrinter): + def _print_ToFloat(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + # NB: We use sym_float here because the printer is used for cache + # serialization, and cache guards get evaluated with SymInt to + # propagate guards to the parent ShapeEnv. However, this comes at a + # runtime cost for guards involving float. If this is unacceptable + # overhead, what you want to do is have two separate printers for + # SymInt, one for when the inputs are guaranteed to be int, and + # another for when they could be SymInt. + # + # NB: sym_min/sym_max also have this problem, but I chose not to fix + # those. + # + # See https://github.com/pytorch/pytorch/issues/142507 for more + # context. + return f"torch.sym_float({self._print(expr.args[0])})" + + def _print_And(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " and ", precedence(expr)) + + def _print_Or(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " or ", precedence(expr)) + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + if div != "1": + x = f"({x} // {div})" + return f"({x} % {mod})" + + def _print_Infinity(self, expr: sympy.Expr) -> str: + return "math.inf" + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + return "-math.inf" + + # WARNING: this is dangerous for Triton, which has C-style modulus + def _print_PythonMod(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5) + + # WARNING: this is dangerous for Triton, which has C-style modulus + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = (self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args) + return f"{x} // {div}" + + # WARNING: this is dangerous for Triton, when lhs, rhs > 2**53, Python + # does a special algorithm + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5) + + def _helper_sqrt(self, expr: sympy.Expr) -> str: + return f"math.sqrt({self._print(expr)})" + + def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str: + return self._helper_sqrt(expr.args[0]) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"]) + + # TODO: Not sure this works with Triton, even when base/exp are integral + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"]) + + def _print_floor(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.floor({self._print(expr.args[0])})" + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.floor({self._print(expr.args[0])})" + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + # This also could have been int(), they'll do the same thing for float + return f"math.trunc({self._print(expr.args[0])})" + + def _print_ceiling(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.ceil({self._print(expr.args[0])})" + + def _print_CeilToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.ceil({self._print(expr.args[0])})" + + def _print_Abs(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"abs({self._print(expr.args[0])})" + + # NB: It's expected that we've made explicit any promotion in the sympy + # expression, so it doesn't matter that Python max/min doesn't perform + # promotion + def _print_Max(self, expr: sympy.Expr) -> str: + assert len(expr.args) >= 2 + return f"max({', '.join(map(self._print, expr.args))})" + + def _print_Min(self, expr: sympy.Expr) -> str: + assert len(expr.args) >= 2 + return f"min({', '.join(map(self._print, expr.args))})" + + def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"math.atan({self._print(expr.args[0])})" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"round({self._print(expr.args[0])})" + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 2 + number, ndigits = expr.args + assert isinstance(ndigits, sympy.Integer) + return f"round({self._print(number)}, {ndigits})" + + +class CppPrinter(ExprPrinter): + def _print_Integer(self, expr: sympy.Expr) -> str: + return ( + f"{int(expr)}LL" if sys.platform in ["darwin", "win32"] else f"{int(expr)}L" + ) + + def _print_Where(self, expr: sympy.Expr) -> str: + c, p, q = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + return f"{c} ? {p} : {q}" + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = expr.args + x = self.doprint(x) + if div != 1: + div = self.doprint(div) + if expr.is_integer: + x = f"c10::div_floor_integer(static_cast({x}), static_cast({div}))" + else: + x = f"c10::div_floor_floating(static_cast({x}), static_cast({div}))" + mod = self.doprint(mod) + return f"(static_cast<{INDEX_TYPE}>({x}) % static_cast<{INDEX_TYPE}>({mod}))" + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + if expr.is_integer: + return f"c10::div_floor_integer(static_cast({x}), static_cast({div}))" + return f"c10::div_floor_floating(static_cast({x}), static_cast({div}))" + + def _print_floor(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + r = f"std::floor({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + r = f"std::floor({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + r = f"std::trunc({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" + + def _print_TruncToFloat(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::trunc({self._print(expr.args[0])})" + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"static_cast({self._print(expr.args[0])})" + + def _print_PythonMod(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + return f"c10::div_mod({x}, {div})" + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + lhs, rhs = expr.args + # TODO: This is only accurate up to 2**53 + return f"static_cast({self._print(lhs)}) / static_cast({self._print(rhs)})" + + # TODO: PowByNatural: we need to implement our own int-int pow. Do NOT + # use std::pow, that operates on floats + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_PowByNatural not implemented for {type(self)}" + ) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + base, exp = expr.args + return f"std::pow({self._print(base)}, {self._print(exp)})" + + def _print_Pow(self, expr: sympy.Expr) -> str: + # Uses float constants to perform FP div + base, exp = expr.args + + if exp == 0.5 or exp == -0.5: + base = self._print(base) + return f"std::sqrt({base})" if exp == 0.5 else f"1.0/std::sqrt({base})" + if exp.is_integer: + exp = int(exp) + if exp > 0: + r = self.stringify([base] * exp, "*", PRECEDENCE["Mul"]) + elif exp < -1: + r = ( + "1.0/(" + + self.stringify([base] * abs(exp), "*", PRECEDENCE["Mul"]) + + ")" + ) + elif exp == -1: + r = "1.0/" + self._print(base) + else: # exp == 0 + r = "1.0" + + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + else: + # TODO: float vs double + return f"std::pow({base}, {float(exp)})" + + def _print_Rational(self, expr: sympy.Expr) -> str: + # Uses float constants to perform FP div + if expr.q == 1: + r = f"{expr.p}" + else: + r = f"{expr.p}.0/{expr.q}.0" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_ceiling(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + r = f"std::ceil({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_CeilToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + r = f"std::ceil({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_Min(self, expr: sympy.Expr) -> str: + args = [self._print(a) for a in expr.args] + if len(args) == 2: + return f"std::min(static_cast<{INDEX_TYPE}>({args[0]}), static_cast<{INDEX_TYPE}>({args[1]}))" + else: + # Initializer list overload + il = "{" + ", ".join(args) + "}" + return f"std::min({il})" + + def _print_Max(self, expr: sympy.Expr) -> str: + args = [self._print(a) for a in expr.args] + if len(args) == 2: + return f"std::max(static_cast<{INDEX_TYPE}>({args[0]}), static_cast<{INDEX_TYPE}>({args[1]}))" + else: + # Initializer list overload + il = "{" + ", ".join(args) + "}" + return f"std::max({il})" + + def _print_Abs(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::abs({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + return f"std::atan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str: + return f"std::sqrt({self._print(expr.args[0])})" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 1 + # TODO: dispatch to llrint depending on index type + return f"std::lrint({self._print(expr.args[0])})" + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + assert len(expr.args) == 2 + number, ndigits = expr.args + if number.is_integer: + # ndigits < 0 should have been filtered by the sympy function + assert ndigits < 0 + raise ValueError( + f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}." + ) + number_str = self.parenthesize(number, PRECEDENCE["Mul"]) + return f"static_cast(std::nearbyint(1e{ndigits} * {number_str}) * 1e{-ndigits})" + + def _print_BooleanTrue(self, expr: sympy.Expr) -> str: + return "true" + + def _print_BooleanFalse(self, expr: sympy.Expr) -> str: + return "false" + + def _print_Infinity(self, expr: sympy.Expr) -> str: + return "std::numeric_limits::infinity()" + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + return f"-{self._print_Infinity(expr)}" diff --git a/shared/package-files/93/93c0fde218f204aff46ef8091bb35fd5c4af0b9601d16bc850951d21c2a7ef43/test_assert_numpy_array_equal.cpython-311.pyc b/shared/package-files/93/93c0fde218f204aff46ef8091bb35fd5c4af0b9601d16bc850951d21c2a7ef43/test_assert_numpy_array_equal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4465d96e6b1da0110bb8d0c6f9ff0420d80f0e40 Binary files /dev/null and b/shared/package-files/93/93c0fde218f204aff46ef8091bb35fd5c4af0b9601d16bc850951d21c2a7ef43/test_assert_numpy_array_equal.cpython-311.pyc differ diff --git a/shared/package-files/93/93c3077962745373ee567a4dc557b3800bcf6acc70d41ddd73376f8f4df3bbf5/iterators.cpython-311.pyc b/shared/package-files/93/93c3077962745373ee567a4dc557b3800bcf6acc70d41ddd73376f8f4df3bbf5/iterators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c54d99c3100bb8df3043b4ff557a2d9422b0f14 Binary files /dev/null and b/shared/package-files/93/93c3077962745373ee567a4dc557b3800bcf6acc70d41ddd73376f8f4df3bbf5/iterators.cpython-311.pyc differ diff --git a/shared/package-files/93/93c44edacc2f5abd9fa745d43c1618541f671ddcbef9ba12983bca26f65112e1/stateful.cpython-311.pyc b/shared/package-files/93/93c44edacc2f5abd9fa745d43c1618541f671ddcbef9ba12983bca26f65112e1/stateful.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06f35d97ec91fe6f0cfeea7a0da629ab0d45183e Binary files /dev/null and b/shared/package-files/93/93c44edacc2f5abd9fa745d43c1618541f671ddcbef9ba12983bca26f65112e1/stateful.cpython-311.pyc differ diff --git a/shared/package-files/93/93c5b13e36d905b69e7354552c4c2d0439050d7edcaed5f5f59ee195b6dc78d0/refine_names_ops.h b/shared/package-files/93/93c5b13e36d905b69e7354552c4c2d0439050d7edcaed5f5f59ee195b6dc78d0/refine_names_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5790edb99adc2ad391a85d91cf84a92b0f0a1c6d --- /dev/null +++ b/shared/package-files/93/93c5b13e36d905b69e7354552c4c2d0439050d7edcaed5f5f59ee195b6dc78d0/refine_names_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API refine_names { + using schema = at::Tensor (const at::Tensor &, at::DimnameList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::refine_names"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "refine_names(Tensor(a) self, Dimname[] names) -> Tensor(a)"; + static at::Tensor call(const at::Tensor & self, at::DimnameList names); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::DimnameList names); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/93/93c79410122b46b18cb0163938e6835dd1a7414286c0321f43276e07a603dcdb/mv.py b/shared/package-files/93/93c79410122b46b18cb0163938e6835dd1a7414286c0321f43276e07a603dcdb/mv.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6caa3de815e024fa84de2acecc986c823ed29 --- /dev/null +++ b/shared/package-files/93/93c79410122b46b18cb0163938e6835dd1a7414286c0321f43276e07a603dcdb/mv.py @@ -0,0 +1,57 @@ +import os + +import pytest + +import fsspec + + +def test_move_raises_error_with_tmpdir(tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Define a destination that simulates a protected or invalid path + destination = tmpdir.join("non_existent_directory/destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Use the actual file paths as string + with pytest.raises(FileNotFoundError): + fs.mv(str(source), str(destination)) + + +@pytest.mark.parametrize("recursive", (True, False)) +def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Create a protected directory (non-writable) + protected_dir = tmpdir.mkdir("protected_directory") + protected_path = str(protected_dir) + + # Set the directory to read-only + if os.name == "nt": + os.system(f'icacls "{protected_path}" /deny Everyone:(W)') + else: + os.chmod(protected_path, 0o555) # Sets the directory to read-only + + # Define a destination inside the protected directory + destination = protected_dir.join("destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Try to move the file to the read-only directory, expecting a permission error + with pytest.raises(PermissionError): + fs.mv(str(source), str(destination), recursive=recursive) + + # Assert the file was not created in the destination + assert not os.path.exists(destination) + + # Cleanup: Restore permissions so the directory can be cleaned up + if os.name == "nt": + os.system(f'icacls "{protected_path}" /remove:d Everyone') + else: + os.chmod(protected_path, 0o755) # Restore write permission for cleanup diff --git a/shared/package-files/93/93c8d00e93fdce66c88ae1923fc0a0e2a8e8f2d22a54b17213e203a0d194372e/_sparse_csr_sum.h b/shared/package-files/93/93c8d00e93fdce66c88ae1923fc0a0e2a8e8f2d22a54b17213e203a0d194372e/_sparse_csr_sum.h new file mode 100644 index 0000000000000000000000000000000000000000..e89bf8ab93c5afa62183df6755186bca73431a02 --- /dev/null +++ b/shared/package-files/93/93c8d00e93fdce66c88ae1923fc0a0e2a8e8f2d22a54b17213e203a0d194372e/_sparse_csr_sum.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_sparse_csr_sum.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor +inline at::Tensor _sparse_csr_sum(const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false, ::std::optional dtype=::std::nullopt) { + return at::_ops::_sparse_csr_sum_dim_dtype::call(self, dim, keepdim, dtype); +} + +// aten::_sparse_csr_sum.dim_dtype_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _sparse_csr_sum_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dim, bool keepdim=false, ::std::optional dtype=::std::nullopt) { + return at::_ops::_sparse_csr_sum_dim_dtype_out::call(self, dim, keepdim, dtype, out); +} +// aten::_sparse_csr_sum.dim_dtype_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _sparse_csr_sum_outf(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, ::std::optional dtype, at::Tensor & out) { + return at::_ops::_sparse_csr_sum_dim_dtype_out::call(self, dim, keepdim, dtype, out); +} + +} diff --git a/shared/package-files/93/93caaf204e8fbf3dd78177a55b8b583235b7813f8aa5f4ba2cf8fe46065f5113/__init__.cpython-311.pyc b/shared/package-files/93/93caaf204e8fbf3dd78177a55b8b583235b7813f8aa5f4ba2cf8fe46065f5113/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24d680ed8f931b7cfab43a7b5dd22b00a3320a5d Binary files /dev/null and b/shared/package-files/93/93caaf204e8fbf3dd78177a55b8b583235b7813f8aa5f4ba2cf8fe46065f5113/__init__.cpython-311.pyc differ diff --git a/shared/package-files/93/93cd37d89e08b59e1a14778eada3a9885f32e1a3e6d8ed60e3852f51fad02608/test_temporalisomorphvf2.py b/shared/package-files/93/93cd37d89e08b59e1a14778eada3a9885f32e1a3e6d8ed60e3852f51fad02608/test_temporalisomorphvf2.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe70a42869e4fd1501ae90b849bfb4de50eda2e --- /dev/null +++ b/shared/package-files/93/93cd37d89e08b59e1a14778eada3a9885f32e1a3e6d8ed60e3852f51fad02608/test_temporalisomorphvf2.py @@ -0,0 +1,212 @@ +""" +Tests for the temporal aspect of the Temporal VF2 isomorphism algorithm. +""" + +from datetime import date, datetime, timedelta + +import networkx as nx +from networkx.algorithms import isomorphism as iso + + +def provide_g1_edgelist(): + return [(0, 1), (0, 2), (1, 2), (2, 4), (1, 3), (3, 4), (4, 5)] + + +def put_same_time(G, att_name): + for e in G.edges(data=True): + e[2][att_name] = date(2015, 1, 1) + return G + + +def put_same_datetime(G, att_name): + for e in G.edges(data=True): + e[2][att_name] = datetime(2015, 1, 1) + return G + + +def put_sequence_time(G, att_name): + current_date = date(2015, 1, 1) + for e in G.edges(data=True): + current_date += timedelta(days=1) + e[2][att_name] = current_date + return G + + +def put_time_config_0(G, att_name): + G[0][1][att_name] = date(2015, 1, 2) + G[0][2][att_name] = date(2015, 1, 2) + G[1][2][att_name] = date(2015, 1, 3) + G[1][3][att_name] = date(2015, 1, 1) + G[2][4][att_name] = date(2015, 1, 1) + G[3][4][att_name] = date(2015, 1, 3) + G[4][5][att_name] = date(2015, 1, 3) + return G + + +def put_time_config_1(G, att_name): + G[0][1][att_name] = date(2015, 1, 2) + G[0][2][att_name] = date(2015, 1, 1) + G[1][2][att_name] = date(2015, 1, 3) + G[1][3][att_name] = date(2015, 1, 1) + G[2][4][att_name] = date(2015, 1, 2) + G[3][4][att_name] = date(2015, 1, 4) + G[4][5][att_name] = date(2015, 1, 3) + return G + + +def put_time_config_2(G, att_name): + G[0][1][att_name] = date(2015, 1, 1) + G[0][2][att_name] = date(2015, 1, 1) + G[1][2][att_name] = date(2015, 1, 3) + G[1][3][att_name] = date(2015, 1, 2) + G[2][4][att_name] = date(2015, 1, 2) + G[3][4][att_name] = date(2015, 1, 3) + G[4][5][att_name] = date(2015, 1, 2) + return G + + +class TestTimeRespectingGraphMatcher: + """ + A test class for the undirected temporal graph matcher. + """ + + def provide_g1_topology(self): + G1 = nx.Graph() + G1.add_edges_from(provide_g1_edgelist()) + return G1 + + def provide_g2_path_3edges(self): + G2 = nx.Graph() + G2.add_edges_from([(0, 1), (1, 2), (2, 3)]) + return G2 + + def test_timdelta_zero_timeRespecting_returnsTrue(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_same_time(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + assert gm.subgraph_is_isomorphic() + + def test_timdelta_zero_datetime_timeRespecting_returnsTrue(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_same_datetime(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + assert gm.subgraph_is_isomorphic() + + def test_attNameStrange_timdelta_zero_timeRespecting_returnsTrue(self): + G1 = self.provide_g1_topology() + temporal_name = "strange_name" + G1 = put_same_time(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + assert gm.subgraph_is_isomorphic() + + def test_notTimeRespecting_returnsFalse(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_sequence_time(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + assert not gm.subgraph_is_isomorphic() + + def test_timdelta_one_config0_returns_no_embeddings(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_0(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 0 + + def test_timdelta_one_config1_returns_four_embedding(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_1(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 4 + + def test_timdelta_one_config2_returns_ten_embeddings(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_2(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingGraphMatcher(G1, G2, temporal_name, d) + L = list(gm.subgraph_isomorphisms_iter()) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 10 + + +class TestDiTimeRespectingGraphMatcher: + """ + A test class for the directed time-respecting graph matcher. + """ + + def provide_g1_topology(self): + G1 = nx.DiGraph() + G1.add_edges_from(provide_g1_edgelist()) + return G1 + + def provide_g2_path_3edges(self): + G2 = nx.DiGraph() + G2.add_edges_from([(0, 1), (1, 2), (2, 3)]) + return G2 + + def test_timdelta_zero_same_dates_returns_true(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_same_time(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d) + assert gm.subgraph_is_isomorphic() + + def test_attNameStrange_timdelta_zero_same_dates_returns_true(self): + G1 = self.provide_g1_topology() + temporal_name = "strange" + G1 = put_same_time(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta() + gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d) + assert gm.subgraph_is_isomorphic() + + def test_timdelta_one_config0_returns_no_embeddings(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_0(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 0 + + def test_timdelta_one_config1_returns_one_embedding(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_1(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 1 + + def test_timdelta_one_config2_returns_two_embeddings(self): + G1 = self.provide_g1_topology() + temporal_name = "date" + G1 = put_time_config_2(G1, temporal_name) + G2 = self.provide_g2_path_3edges() + d = timedelta(days=1) + gm = iso.TimeRespectingDiGraphMatcher(G1, G2, temporal_name, d) + count_match = len(list(gm.subgraph_isomorphisms_iter())) + assert count_match == 2 diff --git a/shared/package-files/93/93cd72ee4e6332401f9c38a7d93844df4b6dad281cee71c527bb5aff7480b7ed/__init__.cpython-311.pyc b/shared/package-files/93/93cd72ee4e6332401f9c38a7d93844df4b6dad281cee71c527bb5aff7480b7ed/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..975eff281e90009b5984f705ed83a79dcfcc3f8d Binary files /dev/null and b/shared/package-files/93/93cd72ee4e6332401f9c38a7d93844df4b6dad281cee71c527bb5aff7480b7ed/__init__.cpython-311.pyc differ diff --git a/shared/package-files/93/93d95def074fab99274ba723a348636bc6962fe71dc582864690d4d33ddcbcd2/test_wiener.py b/shared/package-files/93/93d95def074fab99274ba723a348636bc6962fe71dc582864690d4d33ddcbcd2/test_wiener.py new file mode 100644 index 0000000000000000000000000000000000000000..aded95143ca53e0031189dfabeacf5df0f887120 --- /dev/null +++ b/shared/package-files/93/93d95def074fab99274ba723a348636bc6962fe71dc582864690d4d33ddcbcd2/test_wiener.py @@ -0,0 +1,123 @@ +import networkx as nx + + +def test_wiener_index_of_disconnected_graph(): + assert nx.wiener_index(nx.empty_graph(2)) == float("inf") + + +def test_wiener_index_of_directed_graph(): + G = nx.complete_graph(3) + H = nx.DiGraph(G) + assert (2 * nx.wiener_index(G)) == nx.wiener_index(H) + + +def test_wiener_index_of_complete_graph(): + n = 10 + G = nx.complete_graph(n) + assert nx.wiener_index(G) == (n * (n - 1) / 2) + + +def test_wiener_index_of_path_graph(): + # In P_n, there are n - 1 pairs of vertices at distance one, n - + # 2 pairs at distance two, n - 3 at distance three, ..., 1 at + # distance n - 1, so the Wiener index should be + # + # 1 * (n - 1) + 2 * (n - 2) + ... + (n - 2) * 2 + (n - 1) * 1 + # + # For example, in P_5, + # + # 1 * 4 + 2 * 3 + 3 * 2 + 4 * 1 = 2 (1 * 4 + 2 * 3) + # + # and in P_6, + # + # 1 * 5 + 2 * 4 + 3 * 3 + 4 * 2 + 5 * 1 = 2 (1 * 5 + 2 * 4) + 3 * 3 + # + # assuming n is *odd*, this gives the formula + # + # 2 \sum_{i = 1}^{(n - 1) / 2} [i * (n - i)] + # + # assuming n is *even*, this gives the formula + # + # 2 \sum_{i = 1}^{n / 2} [i * (n - i)] - (n / 2) ** 2 + # + n = 9 + G = nx.path_graph(n) + expected = 2 * sum(i * (n - i) for i in range(1, (n // 2) + 1)) + actual = nx.wiener_index(G) + assert expected == actual + + +def test_schultz_and_gutman_index_of_disconnected_graph(): + n = 4 + G = nx.Graph() + G.add_nodes_from(list(range(1, n + 1))) + expected = float("inf") + + G.add_edge(1, 2) + G.add_edge(3, 4) + + actual_1 = nx.schultz_index(G) + actual_2 = nx.gutman_index(G) + + assert expected == actual_1 + assert expected == actual_2 + + +def test_schultz_and_gutman_index_of_complete_bipartite_graph_1(): + n = 3 + m = 3 + cbg = nx.complete_bipartite_graph(n, m) + + expected_1 = n * m * (n + m) + 2 * n * (n - 1) * m + 2 * m * (m - 1) * n + actual_1 = nx.schultz_index(cbg) + + expected_2 = n * m * (n * m) + n * (n - 1) * m * m + m * (m - 1) * n * n + actual_2 = nx.gutman_index(cbg) + + assert expected_1 == actual_1 + assert expected_2 == actual_2 + + +def test_schultz_and_gutman_index_of_complete_bipartite_graph_2(): + n = 2 + m = 5 + cbg = nx.complete_bipartite_graph(n, m) + + expected_1 = n * m * (n + m) + 2 * n * (n - 1) * m + 2 * m * (m - 1) * n + actual_1 = nx.schultz_index(cbg) + + expected_2 = n * m * (n * m) + n * (n - 1) * m * m + m * (m - 1) * n * n + actual_2 = nx.gutman_index(cbg) + + assert expected_1 == actual_1 + assert expected_2 == actual_2 + + +def test_schultz_and_gutman_index_of_complete_graph(): + n = 5 + cg = nx.complete_graph(n) + + expected_1 = n * (n - 1) * (n - 1) + actual_1 = nx.schultz_index(cg) + + assert expected_1 == actual_1 + + expected_2 = n * (n - 1) * (n - 1) * (n - 1) / 2 + actual_2 = nx.gutman_index(cg) + + assert expected_2 == actual_2 + + +def test_schultz_and_gutman_index_of_odd_cycle_graph(): + k = 5 + n = 2 * k + 1 + ocg = nx.cycle_graph(n) + + expected_1 = 2 * n * k * (k + 1) + actual_1 = nx.schultz_index(ocg) + + expected_2 = 2 * n * k * (k + 1) + actual_2 = nx.gutman_index(ocg) + + assert expected_1 == actual_1 + assert expected_2 == actual_2 diff --git a/shared/package-files/93/93dd252108b095353f1c031c8f821531fabf6a400cfa6ea42bb0f2ccc10eca4b/test_nunique.cpython-311.pyc b/shared/package-files/93/93dd252108b095353f1c031c8f821531fabf6a400cfa6ea42bb0f2ccc10eca4b/test_nunique.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ced1997f4523f09803f8336a9d10d61be5160aaa Binary files /dev/null and b/shared/package-files/93/93dd252108b095353f1c031c8f821531fabf6a400cfa6ea42bb0f2ccc10eca4b/test_nunique.cpython-311.pyc differ diff --git a/shared/package-files/93/93e298b8f88c3005f23dec1cf1619a56d1c80aa0d5097cc1201b044c94cc34ae/init.h b/shared/package-files/93/93e298b8f88c3005f23dec1cf1619a56d1c80aa0d5097cc1201b044c94cc34ae/init.h new file mode 100644 index 0000000000000000000000000000000000000000..a14cc213e8ff74b5633beaf279f0872367f848eb --- /dev/null +++ b/shared/package-files/93/93e298b8f88c3005f23dec1cf1619a56d1c80aa0d5097cc1201b044c94cc34ae/init.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +#include +#include + +namespace pybind11::detail { +using torch::profiler::impl::TensorID; + +#define STRONG_POINTER_TYPE_CASTER(T) \ + template <> \ + struct type_caster : public strong_pointer_type_caster {}; + +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::StorageImplData) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::AllocationID) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::TensorImplAddress) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleSelf) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyModuleCls) +STRONG_POINTER_TYPE_CASTER(torch::profiler::impl::PyOptimizerSelf) +#undef STRONG_POINTER_TYPE_CASTER + +template <> +struct type_caster : public strong_uint_type_caster {}; +} // namespace pybind11::detail + +namespace torch::profiler { + +void initPythonBindings(PyObject* module); + +} // namespace torch::profiler diff --git a/shared/package-files/93/93e45d09064c826f236d090642ad11044a8390fa8a9c9c0c731c0f13cefbce2c/index_propagation.cpython-311.pyc b/shared/package-files/93/93e45d09064c826f236d090642ad11044a8390fa8a9c9c0c731c0f13cefbce2c/index_propagation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d193816e9d71a156ab2fea92ca9ba19e6bbf9ca Binary files /dev/null and b/shared/package-files/93/93e45d09064c826f236d090642ad11044a8390fa8a9c9c0c731c0f13cefbce2c/index_propagation.cpython-311.pyc differ diff --git a/shared/package-files/93/93ea15db35d0d605228826b9c110e450399015f7a74adbdb32a194599d0dda0e/module.py b/shared/package-files/93/93ea15db35d0d605228826b9c110e450399015f7a74adbdb32a194599d0dda0e/module.py new file mode 100644 index 0000000000000000000000000000000000000000..4840eff28221642f6c5b325b9836b4089ab1e6ad --- /dev/null +++ b/shared/package-files/93/93ea15db35d0d605228826b9c110e450399015f7a74adbdb32a194599d0dda0e/module.py @@ -0,0 +1,3003 @@ +# mypy: allow-untyped-defs + +import functools +import inspect +import itertools +import warnings +import weakref +from collections import namedtuple, OrderedDict +from collections.abc import Iterator, Mapping +from typing import Any, Callable, Optional, overload, TypeVar, Union +from typing_extensions import Self + +import torch +from torch import device, dtype, Tensor +from torch._prims_common import DeviceLikeType +from torch.nn.parameter import Buffer, Parameter +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils.hooks import BackwardHook, RemovableHandle + + +__all__ = [ + "register_module_forward_pre_hook", + "register_module_forward_hook", + "register_module_full_backward_pre_hook", + "register_module_backward_hook", + "register_module_full_backward_hook", + "register_module_buffer_registration_hook", + "register_module_module_registration_hook", + "register_module_parameter_registration_hook", + "Module", +] + +_grad_t = Union[tuple[Tensor, ...], Tensor] +# See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use +# of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be +# the type of the subclass, not the looser type of `Module`. +T = TypeVar("T", bound="Module") + + +class _IncompatibleKeys( + namedtuple("IncompatibleKeys", ["missing_keys", "unexpected_keys"]), +): + __slots__ = () + + def __repr__(self): + if not self.missing_keys and not self.unexpected_keys: + return "" + return super().__repr__() + + __str__ = __repr__ + + +def _addindent(s_, numSpaces): + s = s_.split("\n") + # don't do anything for single-line stuff + if len(s) == 1: + return s_ + first = s.pop(0) + s = [(numSpaces * " ") + line for line in s] + s = "\n".join(s) + s = first + "\n" + s + return s + + +r"""This tracks hooks common to all modules that are executed immediately before +.registering the buffer/module/parameter""" +_global_buffer_registration_hooks: dict[int, Callable] = OrderedDict() +_global_module_registration_hooks: dict[int, Callable] = OrderedDict() +_global_parameter_registration_hooks: dict[int, Callable] = OrderedDict() + + +class _WrappedHook: + def __init__(self, hook: Callable, module: Optional["Module"] = None): + self.hook: Callable = hook + functools.update_wrapper(self, hook) + + self.with_module: bool = False + + if module is not None: + self.module: weakref.ReferenceType[Module] = weakref.ref(module) + self.with_module = True + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if self.with_module: + module = self.module() + if module is None: + raise RuntimeError("You are trying to call the hook of a dead Module!") + return self.hook(module, *args, **kwargs) + return self.hook(*args, **kwargs) + + def __getstate__(self) -> dict: + result = {"hook": self.hook, "with_module": self.with_module} + if self.with_module: + result["module"] = self.module() + + return result + + def __setstate__(self, state: dict): + self.hook = state["hook"] + self.with_module = state["with_module"] + + if self.with_module: + if state["module"] is None: + raise RuntimeError( + "You are trying to revive the hook of a dead Module!" + ) + self.module = weakref.ref(state["module"]) + + +r"""This tracks hooks common to all modules that are executed before/after +calling forward and backward. This is global state used for debugging/profiling +purposes""" +_global_backward_pre_hooks: dict[int, Callable] = OrderedDict() +_global_backward_hooks: dict[int, Callable] = OrderedDict() +_global_is_full_backward_hook: Optional[bool] = None +_global_forward_pre_hooks: dict[int, Callable] = OrderedDict() +_global_forward_hooks: dict[int, Callable] = OrderedDict() +_global_forward_hooks_always_called: dict[int, bool] = OrderedDict() +_global_forward_hooks_with_kwargs: dict[int, bool] = OrderedDict() + +_EXTRA_STATE_KEY_SUFFIX = "_extra_state" + + +def register_module_buffer_registration_hook( + hook: Callable[..., None], +) -> RemovableHandle: + r"""Register a buffer registration hook common to all modules. + + .. warning :: + + This adds global state to the `nn.Module` module + + The hook will be called every time :func:`register_buffer` is invoked. + It should have the following signature:: + + hook(module, name, buffer) -> None or new buffer + + The hook can modify the input or return a single modified value in the hook. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle(_global_buffer_registration_hooks) + _global_buffer_registration_hooks[handle.id] = hook + return handle + + +def register_module_module_registration_hook( + hook: Callable[..., None], +) -> RemovableHandle: + r"""Register a module registration hook common to all modules. + + .. warning :: + + This adds global state to the `nn.Module` module + + The hook will be called every time :func:`register_module` is invoked. + It should have the following signature:: + + hook(module, name, submodule) -> None or new submodule + + The hook can modify the input or return a single modified value in the hook. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle(_global_module_registration_hooks) + _global_module_registration_hooks[handle.id] = hook + return handle + + +def register_module_parameter_registration_hook( + hook: Callable[..., None], +) -> RemovableHandle: + r"""Register a parameter registration hook common to all modules. + + .. warning :: + + This adds global state to the `nn.Module` module + + The hook will be called every time :func:`register_parameter` is invoked. + It should have the following signature:: + + hook(module, name, param) -> None or new parameter + + The hook can modify the input or return a single modified value in the hook. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle(_global_parameter_registration_hooks) + _global_parameter_registration_hooks[handle.id] = hook + return handle + + +def register_module_forward_pre_hook(hook: Callable[..., None]) -> RemovableHandle: + r"""Register a forward pre-hook common to all modules. + + .. warning :: + + This adds global state to the `nn.module` module + and it is only intended for debugging/profiling purposes. + + The hook will be called every time before :func:`forward` is invoked. + It should have the following signature:: + + hook(module, input) -> None or modified input + + The input contains only the positional arguments given to the module. + Keyword arguments won't be passed to the hooks and only to the ``forward``. + The hook can modify the input. User can either return a tuple or a + single modified value in the hook. We will wrap the value into a tuple + if a single value is returned(unless that value is already a tuple). + + This hook has precedence over the specific module hooks registered with + ``register_forward_pre_hook``. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle(_global_forward_pre_hooks) + _global_forward_pre_hooks[handle.id] = hook + return handle + + +def register_module_forward_hook( + hook: Callable[..., None], + *, + with_kwargs: bool = False, + always_call: bool = False, +) -> RemovableHandle: + r"""Register a global forward hook for all the modules. + + .. warning :: + + This adds global state to the `nn.module` module + and it is only intended for debugging/profiling purposes. + + The hook will be called every time after :func:`forward` has computed an output. + It should have the following signature:: + + hook(module, input, output) -> None or modified output + + The input contains only the positional arguments given to the module. + Keyword arguments won't be passed to the hooks and only to the ``forward``. + You can optionally modify the output of the module by returning a new value + that will replace the output from the :func:`forward` function. + + Parameters: + hook (Callable): The user defined hook to be registered. + always_call (bool): If ``True`` the ``hook`` will be run regardless of + whether an exception is raised while calling the Module. + Default: ``False`` + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + This hook will be executed before specific module hooks registered with + ``register_forward_hook``. + """ + handle = RemovableHandle( + _global_forward_hooks, extra_dict=_global_forward_hooks_always_called + ) + _global_forward_hooks[handle.id] = hook + if with_kwargs: + _global_forward_hooks_with_kwargs[handle.id] = True + if always_call: + _global_forward_hooks_always_called[handle.id] = True + return handle + + +def register_module_backward_hook( + hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]], +) -> RemovableHandle: + r"""Register a backward hook common to all the modules. + + This function is deprecated in favor of + :func:`torch.nn.modules.module.register_module_full_backward_hook` + and the behavior of this function will change in future versions. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + global _global_is_full_backward_hook + if _global_is_full_backward_hook is True: + raise RuntimeError( + "Cannot use both regular backward hooks and full backward hooks as a " + "global Module hook. Please use only one of them." + ) + + _global_is_full_backward_hook = False + + handle = RemovableHandle(_global_backward_hooks) + _global_backward_hooks[handle.id] = hook + return handle + + +def register_module_full_backward_pre_hook( + hook: Callable[["Module", _grad_t], Union[None, _grad_t]], +) -> RemovableHandle: + r"""Register a backward pre-hook common to all the modules. + + .. warning :: + This adds global state to the `nn.module` module + and it is only intended for debugging/profiling purposes. + + Hooks registered using this function behave in the same way as those + registered by :meth:`torch.nn.Module.register_full_backward_pre_hook`. + Refer to its documentation for more details. + + Hooks registered using this function will be called before hooks registered + using :meth:`torch.nn.Module.register_full_backward_pre_hook`. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + handle = RemovableHandle(_global_backward_pre_hooks) + _global_backward_pre_hooks[handle.id] = hook + return handle + + +def register_module_full_backward_hook( + hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]], +) -> RemovableHandle: + r"""Register a backward hook common to all the modules. + + .. warning :: + This adds global state to the `nn.module` module + and it is only intended for debugging/profiling purposes. + + Hooks registered using this function behave in the same way as those + registered by :meth:`torch.nn.Module.register_full_backward_hook`. + Refer to its documentation for more details. + + Hooks registered using this function will be called before hooks registered + using :meth:`torch.nn.Module.register_full_backward_hook`. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + global _global_is_full_backward_hook + if _global_is_full_backward_hook is False: + raise RuntimeError( + "Cannot use both regular backward hooks and full backward hooks as a " + "global Module hook. Please use only one of them." + ) + + _global_is_full_backward_hook = True + + handle = RemovableHandle(_global_backward_hooks) + _global_backward_hooks[handle.id] = hook + return handle + + +# Trick mypy into not applying contravariance rules to inputs by defining +# forward as a value, rather than a function. See also +# https://github.com/python/mypy/issues/8795 +def _forward_unimplemented(self, *input: Any) -> None: + r"""Define the computation performed at every call. + + Should be overridden by all subclasses. + + .. note:: + Although the recipe for forward pass needs to be defined within + this function, one should call the :class:`Module` instance afterwards + instead of this since the former takes care of running the + registered hooks while the latter silently ignores them. + """ + raise NotImplementedError( + f'Module [{type(self).__name__}] is missing the required "forward" function' + ) + + +class Module: + r"""Base class for all neural network modules. + + Your models should also subclass this class. + + Modules can also contain other Modules, allowing them to be nested in + a tree structure. You can assign the submodules as regular attributes:: + + import torch.nn as nn + import torch.nn.functional as F + + class Model(nn.Module): + def __init__(self) -> None: + super().__init__() + self.conv1 = nn.Conv2d(1, 20, 5) + self.conv2 = nn.Conv2d(20, 20, 5) + + def forward(self, x): + x = F.relu(self.conv1(x)) + return F.relu(self.conv2(x)) + + Submodules assigned in this way will be registered, and will also have their + parameters converted when you call :meth:`to`, etc. + + .. note:: + As per the example above, an ``__init__()`` call to the parent class + must be made before assignment on the child. + + :ivar training: Boolean represents whether this module is in training or + evaluation mode. + :vartype training: bool + """ + + dump_patches: bool = False + + _version: int = 1 + r"""This allows better BC support for :meth:`load_state_dict`. In + :meth:`state_dict`, the version number will be saved as in the attribute + `_metadata` of the returned state dict, and thus pickled. `_metadata` is a + dictionary with keys that follow the naming convention of state dict. See + ``_load_from_state_dict`` on how to use this information in loading. + + If new parameters/buffers are added/removed from a module, this number shall + be bumped, and the module's `_load_from_state_dict` method can compare the + version number and do appropriate changes if the state dict is from before + the change.""" + + training: bool + _parameters: dict[str, Optional[Parameter]] + _buffers: dict[str, Optional[Tensor]] + _non_persistent_buffers_set: set[str] + _backward_pre_hooks: dict[int, Callable] + _backward_hooks: dict[int, Callable] + _is_full_backward_hook: Optional[bool] + _forward_hooks: dict[int, Callable] + # Marks whether the corresponding _forward_hooks accept kwargs or not. + # As JIT does not support set[int], this dict is used as a set, where all + # hooks represented in this dict accept kwargs. + _forward_hooks_with_kwargs: dict[int, bool] + # forward hooks that should always be called even if an exception is raised + _forward_hooks_always_called: dict[int, bool] + _forward_pre_hooks: dict[int, Callable] + # Marks whether the corresponding _forward_hooks accept kwargs or not. + # As JIT does not support set[int], this dict is used as a set, where all + # hooks represented in this dict accept kwargs. + _forward_pre_hooks_with_kwargs: dict[int, bool] + _state_dict_hooks: dict[int, Callable] + _load_state_dict_pre_hooks: dict[int, Callable] + _state_dict_pre_hooks: dict[int, Callable] + _load_state_dict_post_hooks: dict[int, Callable] + _modules: dict[str, Optional["Module"]] + call_super_init: bool = False + _compiled_call_impl: Optional[Callable] = None + + def __init__(self, *args, **kwargs) -> None: + """Initialize internal Module state, shared by both nn.Module and ScriptModule.""" + torch._C._log_api_usage_once("python.nn_module") + + # Backward compatibility: no args used to be allowed when call_super_init=False + if self.call_super_init is False and bool(kwargs): + raise TypeError( + f"{type(self).__name__}.__init__() got an unexpected keyword argument '{next(iter(kwargs))}'" + "" + ) + + if self.call_super_init is False and bool(args): + raise TypeError( + f"{type(self).__name__}.__init__() takes 1 positional argument but {len(args) + 1} were" + " given" + ) + + """ + Calls super().__setattr__('a', a) instead of the typical self.a = a + to avoid Module.__setattr__ overhead. Module's __setattr__ has special + handling for parameters, submodules, and buffers but simply calls into + super().__setattr__ for all other attributes. + """ + super().__setattr__("training", True) + super().__setattr__("_parameters", {}) + super().__setattr__("_buffers", {}) + super().__setattr__("_non_persistent_buffers_set", set()) + super().__setattr__("_backward_pre_hooks", OrderedDict()) + super().__setattr__("_backward_hooks", OrderedDict()) + super().__setattr__("_is_full_backward_hook", None) + super().__setattr__("_forward_hooks", OrderedDict()) + super().__setattr__("_forward_hooks_with_kwargs", OrderedDict()) + super().__setattr__("_forward_hooks_always_called", OrderedDict()) + super().__setattr__("_forward_pre_hooks", OrderedDict()) + super().__setattr__("_forward_pre_hooks_with_kwargs", OrderedDict()) + super().__setattr__("_state_dict_hooks", OrderedDict()) + super().__setattr__("_state_dict_pre_hooks", OrderedDict()) + super().__setattr__("_load_state_dict_pre_hooks", OrderedDict()) + super().__setattr__("_load_state_dict_post_hooks", OrderedDict()) + super().__setattr__("_modules", {}) + + if self.call_super_init: + super().__init__(*args, **kwargs) + + forward: Callable[..., Any] = _forward_unimplemented + + def register_buffer( + self, name: str, tensor: Optional[Tensor], persistent: bool = True + ) -> None: + r"""Add a buffer to the module. + + This is typically used to register a buffer that should not to be + considered a model parameter. For example, BatchNorm's ``running_mean`` + is not a parameter, but is part of the module's state. Buffers, by + default, are persistent and will be saved alongside parameters. This + behavior can be changed by setting :attr:`persistent` to ``False``. The + only difference between a persistent buffer and a non-persistent buffer + is that the latter will not be a part of this module's + :attr:`state_dict`. + + Buffers can be accessed as attributes using given names. + + Args: + name (str): name of the buffer. The buffer can be accessed + from this module using the given name + tensor (Tensor or None): buffer to be registered. If ``None``, then operations + that run on buffers, such as :attr:`cuda`, are ignored. If ``None``, + the buffer is **not** included in the module's :attr:`state_dict`. + persistent (bool): whether the buffer is part of this module's + :attr:`state_dict`. + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> self.register_buffer('running_mean', torch.zeros(num_features)) + + """ + if persistent is False and isinstance(self, torch.jit.ScriptModule): + raise RuntimeError("ScriptModule does not support non-persistent buffers") + + if "_buffers" not in self.__dict__: + raise AttributeError("cannot assign buffer before Module.__init__() call") + elif not isinstance(name, str): + raise TypeError( + f"buffer name should be a string. Got {torch.typename(name)}" + ) + elif "." in name: + raise KeyError('buffer name can\'t contain "."') + elif name == "": + raise KeyError('buffer name can\'t be empty string ""') + elif hasattr(self, name) and name not in self._buffers: + raise KeyError(f"attribute '{name}' already exists") + elif tensor is not None and not isinstance(tensor, torch.Tensor): + raise TypeError( + f"cannot assign '{torch.typename(tensor)}' object to buffer '{name}' " + "(torch Tensor or None required)" + ) + else: + for hook in _global_buffer_registration_hooks.values(): + output = hook(self, name, tensor) + if output is not None: + tensor = output + self._buffers[name] = tensor + if persistent: + self._non_persistent_buffers_set.discard(name) + else: + self._non_persistent_buffers_set.add(name) + + def register_parameter(self, name: str, param: Optional[Parameter]) -> None: + r"""Add a parameter to the module. + + The parameter can be accessed as an attribute using given name. + + Args: + name (str): name of the parameter. The parameter can be accessed + from this module using the given name + param (Parameter or None): parameter to be added to the module. If + ``None``, then operations that run on parameters, such as :attr:`cuda`, + are ignored. If ``None``, the parameter is **not** included in the + module's :attr:`state_dict`. + """ + if "_parameters" not in self.__dict__: + raise AttributeError( + "cannot assign parameter before Module.__init__() call" + ) + + elif not isinstance(name, str): + raise TypeError( + f"parameter name should be a string. Got {torch.typename(name)}" + ) + elif "." in name: + raise KeyError('parameter name can\'t contain "."') + elif name == "": + raise KeyError('parameter name can\'t be empty string ""') + elif hasattr(self, name) and name not in self._parameters: + raise KeyError(f"attribute '{name}' already exists") + + if param is None: + self._parameters[name] = None + elif not isinstance(param, Parameter): + raise TypeError( + f"cannot assign '{torch.typename(param)}' object to parameter '{name}' " + "(torch.nn.Parameter or None required)" + ) + elif param.grad_fn: + raise ValueError( + f"Cannot assign non-leaf Tensor to parameter '{name}'. Model " + f"parameters must be created explicitly. To express '{name}' " + "as a function of another Tensor, compute the value in " + "the forward() method." + ) + else: + for hook in _global_parameter_registration_hooks.values(): + output = hook(self, name, param) + if output is not None: + param = output + self._parameters[name] = param + + def add_module(self, name: str, module: Optional["Module"]) -> None: + r"""Add a child module to the current module. + + The module can be accessed as an attribute using the given name. + + Args: + name (str): name of the child module. The child module can be + accessed from this module using the given name + module (Module): child module to be added to the module. + """ + if not isinstance(module, Module) and module is not None: + raise TypeError(f"{torch.typename(module)} is not a Module subclass") + elif not isinstance(name, str): + raise TypeError( + f"module name should be a string. Got {torch.typename(name)}" + ) + elif hasattr(self, name) and name not in self._modules: + raise KeyError(f"attribute '{name}' already exists") + elif "." in name: + raise KeyError(f'module name can\'t contain ".", got: {name}') + elif name == "": + raise KeyError('module name can\'t be empty string ""') + for hook in _global_module_registration_hooks.values(): + output = hook(self, name, module) + if output is not None: + module = output + self._modules[name] = module + + def register_module(self, name: str, module: Optional["Module"]) -> None: + r"""Alias for :func:`add_module`.""" + self.add_module(name, module) + + def get_submodule(self, target: str) -> "Module": + """Return the submodule given by ``target`` if it exists, otherwise throw an error. + + For example, let's say you have an ``nn.Module`` ``A`` that + looks like this: + + .. code-block:: text + + A( + (net_b): Module( + (net_c): Module( + (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) + ) + (linear): Linear(in_features=100, out_features=200, bias=True) + ) + ) + + (The diagram shows an ``nn.Module`` ``A``. ``A`` which has a nested + submodule ``net_b``, which itself has two submodules ``net_c`` + and ``linear``. ``net_c`` then has a submodule ``conv``.) + + To check whether or not we have the ``linear`` submodule, we + would call ``get_submodule("net_b.linear")``. To check whether + we have the ``conv`` submodule, we would call + ``get_submodule("net_b.net_c.conv")``. + + The runtime of ``get_submodule`` is bounded by the degree + of module nesting in ``target``. A query against + ``named_modules`` achieves the same result, but it is O(N) in + the number of transitive modules. So, for a simple check to see + if some submodule exists, ``get_submodule`` should always be + used. + + Args: + target: The fully-qualified string name of the submodule + to look for. (See above example for how to specify a + fully-qualified string.) + + Returns: + torch.nn.Module: The submodule referenced by ``target`` + + Raises: + AttributeError: If at any point along the path resulting from + the target string the (sub)path resolves to a non-existent + attribute name or an object that is not an instance of ``nn.Module``. + """ + if target == "": + return self + + atoms: list[str] = target.split(".") + mod: torch.nn.Module = self + + for item in atoms: + if not hasattr(mod, item): + raise AttributeError( + mod._get_name() + " has no attribute `" + item + "`" + ) + + mod = getattr(mod, item) + + if not isinstance(mod, torch.nn.Module): + raise AttributeError("`" + item + "` is not an nn.Module") + + return mod + + def set_submodule( + self, target: str, module: "Module", strict: bool = False + ) -> None: + """ + Set the submodule given by ``target`` if it exists, otherwise throw an error. + + .. note:: + If ``strict`` is set to ``False`` (default), the method will replace an existing submodule + or create a new submodule if the parent module exists. If ``strict`` is set to ``True``, + the method will only attempt to replace an existing submodule and throw an error if + the submodule does not exist. + + For example, let's say you have an ``nn.Module`` ``A`` that + looks like this: + + .. code-block:: text + + A( + (net_b): Module( + (net_c): Module( + (conv): Conv2d(3, 3, 3) + ) + (linear): Linear(3, 3) + ) + ) + + (The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested + submodule ``net_b``, which itself has two submodules ``net_c`` + and ``linear``. ``net_c`` then has a submodule ``conv``.) + + To override the ``Conv2d`` with a new submodule ``Linear``, you + could call ``set_submodule("net_b.net_c.conv", nn.Linear(1, 1))`` + where ``strict`` could be ``True`` or ``False`` + + To add a new submodule ``Conv2d`` to the existing ``net_b`` module, + you would call ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1))``. + + In the above if you set ``strict=True`` and call + ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True)``, an AttributeError + will be raised because ``net_b`` does not have a submodule named ``conv``. + + Args: + target: The fully-qualified string name of the submodule + to look for. (See above example for how to specify a + fully-qualified string.) + module: The module to set the submodule to. + strict: If ``False``, the method will replace an existing submodule + or create a new submodule if the parent module exists. If ``True``, + the method will only attempt to replace an existing submodule and throw an error + if the submodule doesn't already exist. + + Raises: + ValueError: If the ``target`` string is empty or if ``module`` is not an instance of ``nn.Module``. + AttributeError: If at any point along the path resulting from + the ``target`` string the (sub)path resolves to a non-existent + attribute name or an object that is not an instance of ``nn.Module``. + """ + if target == "": + raise ValueError("Cannot set the submodule without a target name!") + + atoms: list[str] = target.split(".") + if not isinstance(module, torch.nn.Module): + raise ValueError( + "`" + "module" + f"` is not an nn.Module, found {type(module)}" + ) + if len(atoms) == 1: + parent: torch.nn.Module = self + else: + parent_key = ".".join(atoms[:-1]) + parent = self.get_submodule(parent_key) + + if strict and not hasattr(parent, atoms[-1]): + raise AttributeError( + parent._get_name() + " has no attribute `" + atoms[-1] + "`" + ) + if hasattr(parent, atoms[-1]): + mod = getattr(parent, atoms[-1]) + if not isinstance(mod, torch.nn.Module): + raise AttributeError("`" + atoms[-1] + "` is not an nn.Module") + setattr(parent, atoms[-1], module) + + def get_parameter(self, target: str) -> "Parameter": + """Return the parameter given by ``target`` if it exists, otherwise throw an error. + + See the docstring for ``get_submodule`` for a more detailed + explanation of this method's functionality as well as how to + correctly specify ``target``. + + Args: + target: The fully-qualified string name of the Parameter + to look for. (See ``get_submodule`` for how to specify a + fully-qualified string.) + + Returns: + torch.nn.Parameter: The Parameter referenced by ``target`` + + Raises: + AttributeError: If the target string references an invalid + path or resolves to something that is not an + ``nn.Parameter`` + """ + module_path, _, param_name = target.rpartition(".") + + mod: torch.nn.Module = self.get_submodule(module_path) + + if not hasattr(mod, param_name): + raise AttributeError( + mod._get_name() + " has no attribute `" + param_name + "`" + ) + + param: torch.nn.Parameter = getattr(mod, param_name) + + if not isinstance(param, torch.nn.Parameter): + raise AttributeError("`" + param_name + "` is not an nn.Parameter") + + return param + + def get_buffer(self, target: str) -> "Tensor": + """Return the buffer given by ``target`` if it exists, otherwise throw an error. + + See the docstring for ``get_submodule`` for a more detailed + explanation of this method's functionality as well as how to + correctly specify ``target``. + + Args: + target: The fully-qualified string name of the buffer + to look for. (See ``get_submodule`` for how to specify a + fully-qualified string.) + + Returns: + torch.Tensor: The buffer referenced by ``target`` + + Raises: + AttributeError: If the target string references an invalid + path or resolves to something that is not a + buffer + """ + module_path, _, buffer_name = target.rpartition(".") + + mod: torch.nn.Module = self.get_submodule(module_path) + + if not hasattr(mod, buffer_name): + raise AttributeError( + mod._get_name() + " has no attribute `" + buffer_name + "`" + ) + + buffer: torch.Tensor = getattr(mod, buffer_name) + + if buffer_name not in mod._buffers: + raise AttributeError("`" + buffer_name + "` is not a buffer") + + return buffer + + def get_extra_state(self) -> Any: + """Return any extra state to include in the module's state_dict. + + Implement this and a corresponding :func:`set_extra_state` for your module + if you need to store extra state. This function is called when building the + module's `state_dict()`. + + Note that extra state should be picklable to ensure working serialization + of the state_dict. We only provide backwards compatibility guarantees + for serializing Tensors; other objects may break backwards compatibility if + their serialized pickled form changes. + + Returns: + object: Any extra state to store in the module's state_dict + """ + raise RuntimeError( + "Reached a code path in Module.get_extra_state() that should never be called. " + "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml " + "to report this bug." + ) + + def set_extra_state(self, state: Any) -> None: + """Set extra state contained in the loaded `state_dict`. + + This function is called from :func:`load_state_dict` to handle any extra state + found within the `state_dict`. Implement this function and a corresponding + :func:`get_extra_state` for your module if you need to store extra state within its + `state_dict`. + + Args: + state (dict): Extra state from the `state_dict` + """ + raise RuntimeError( + "Reached a code path in Module.set_extra_state() that should never be called. " + "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml " + "to report this bug." + ) + + def _apply(self, fn, recurse=True): + if recurse: + for module in self.children(): + module._apply(fn) + + def compute_should_use_set_data(tensor, tensor_applied): + if torch._has_compatible_shallow_copy_type(tensor, tensor_applied): + # If the new tensor has compatible tensor type as the existing tensor, + # the current behavior is to change the tensor in-place using `.data =`, + # and the future behavior is to overwrite the existing tensor. However, + # changing the current behavior is a BC-breaking change, and we want it + # to happen in future releases. So for now we introduce the + # `torch.__future__.get_overwrite_module_params_on_conversion()` + # global flag to let the user control whether they want the future + # behavior of overwriting the existing tensor or not. + return not torch.__future__.get_overwrite_module_params_on_conversion() + else: + return False + + should_use_swap_tensors = ( + torch.__future__.get_swap_module_params_on_conversion() + ) + + for key, param in self._parameters.items(): + if param is None: + continue + # Tensors stored in modules are graph leaves, and we don't want to + # track autograd history of `param_applied`, so we have to use + # `with torch.no_grad():` + with torch.no_grad(): + param_applied = fn(param) + p_should_use_set_data = compute_should_use_set_data(param, param_applied) + + # subclasses may have multiple child tensors so we need to use swap_tensors + p_should_use_swap_tensors = ( + should_use_swap_tensors or is_traceable_wrapper_subclass(param_applied) + ) + + param_grad = param.grad + if p_should_use_swap_tensors: + try: + if param_grad is not None: + # Accessing param.grad makes its at::Tensor's use_count 2, which will prevent swapping. + # Decrement use count of the gradient by setting to None + param.grad = None + param_applied = torch.nn.Parameter( + param_applied, requires_grad=param.requires_grad + ) + torch.utils.swap_tensors(param, param_applied) + except Exception as e: + if param_grad is not None: + param.grad = param_grad + raise RuntimeError( + f"_apply(): Couldn't swap {self._get_name()}.{key}" + ) from e + out_param = param + elif p_should_use_set_data: + param.data = param_applied + out_param = param + else: + assert isinstance(param, Parameter) + assert param.is_leaf + out_param = Parameter(param_applied, param.requires_grad) + self._parameters[key] = out_param + + if param_grad is not None: + with torch.no_grad(): + grad_applied = fn(param_grad) + g_should_use_set_data = compute_should_use_set_data( + param_grad, grad_applied + ) + if p_should_use_swap_tensors: + grad_applied.requires_grad_(param_grad.requires_grad) + try: + torch.utils.swap_tensors(param_grad, grad_applied) + except Exception as e: + raise RuntimeError( + f"_apply(): Couldn't swap {self._get_name()}.{key}.grad" + ) from e + out_param.grad = param_grad + elif g_should_use_set_data: + assert out_param.grad is not None + out_param.grad.data = grad_applied + else: + assert param_grad.is_leaf + out_param.grad = grad_applied.requires_grad_( + param_grad.requires_grad + ) + + for key, buf in self._buffers.items(): + if buf is not None: + self._buffers[key] = fn(buf) + + return self + + def apply(self: T, fn: Callable[["Module"], None]) -> T: + r"""Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. + + Typical use includes initializing the parameters of a model + (see also :ref:`nn-init-doc`). + + Args: + fn (:class:`Module` -> None): function to be applied to each submodule + + Returns: + Module: self + + Example:: + + >>> @torch.no_grad() + >>> def init_weights(m): + >>> print(m) + >>> if type(m) == nn.Linear: + >>> m.weight.fill_(1.0) + >>> print(m.weight) + >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) + >>> net.apply(init_weights) + Linear(in_features=2, out_features=2, bias=True) + Parameter containing: + tensor([[1., 1.], + [1., 1.]], requires_grad=True) + Linear(in_features=2, out_features=2, bias=True) + Parameter containing: + tensor([[1., 1.], + [1., 1.]], requires_grad=True) + Sequential( + (0): Linear(in_features=2, out_features=2, bias=True) + (1): Linear(in_features=2, out_features=2, bias=True) + ) + + """ + for module in self.children(): + module.apply(fn) + fn(self) + return self + + def cuda(self: T, device: Optional[Union[int, device]] = None) -> T: + r"""Move all model parameters and buffers to the GPU. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing the optimizer if the module will + live on GPU while being optimized. + + .. note:: + This method modifies the module in-place. + + Args: + device (int, optional): if specified, all parameters will be + copied to that device + + Returns: + Module: self + """ + return self._apply(lambda t: t.cuda(device)) + + def ipu(self: T, device: Optional[Union[int, device]] = None) -> T: + r"""Move all model parameters and buffers to the IPU. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing the optimizer if the module will + live on IPU while being optimized. + + .. note:: + This method modifies the module in-place. + + Arguments: + device (int, optional): if specified, all parameters will be + copied to that device + + Returns: + Module: self + """ + return self._apply(lambda t: t.ipu(device)) + + def xpu(self: T, device: Optional[Union[int, device]] = None) -> T: + r"""Move all model parameters and buffers to the XPU. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing optimizer if the module will + live on XPU while being optimized. + + .. note:: + This method modifies the module in-place. + + Arguments: + device (int, optional): if specified, all parameters will be + copied to that device + + Returns: + Module: self + """ + return self._apply(lambda t: t.xpu(device)) + + def mtia(self: T, device: Optional[Union[int, device]] = None) -> T: + r"""Move all model parameters and buffers to the MTIA. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing the optimizer if the module will + live on MTIA while being optimized. + + .. note:: + This method modifies the module in-place. + + Arguments: + device (int, optional): if specified, all parameters will be + copied to that device + + Returns: + Module: self + """ + return self._apply(lambda t: t.mtia(device)) + + def cpu(self: T) -> T: + r"""Move all model parameters and buffers to the CPU. + + .. note:: + This method modifies the module in-place. + + Returns: + Module: self + """ + return self._apply(lambda t: t.cpu()) + + def type(self: T, dst_type: Union[dtype, str]) -> T: + r"""Casts all parameters and buffers to :attr:`dst_type`. + + .. note:: + This method modifies the module in-place. + + Args: + dst_type (type or string): the desired type + + Returns: + Module: self + """ + return self._apply(lambda t: t.type(dst_type)) + + def float(self: T) -> T: + r"""Casts all floating point parameters and buffers to ``float`` datatype. + + .. note:: + This method modifies the module in-place. + + Returns: + Module: self + """ + return self._apply(lambda t: t.float() if t.is_floating_point() else t) + + def double(self: T) -> T: + r"""Casts all floating point parameters and buffers to ``double`` datatype. + + .. note:: + This method modifies the module in-place. + + Returns: + Module: self + """ + return self._apply(lambda t: t.double() if t.is_floating_point() else t) + + def half(self: T) -> T: + r"""Casts all floating point parameters and buffers to ``half`` datatype. + + .. note:: + This method modifies the module in-place. + + Returns: + Module: self + """ + return self._apply(lambda t: t.half() if t.is_floating_point() else t) + + def bfloat16(self: T) -> T: + r"""Casts all floating point parameters and buffers to ``bfloat16`` datatype. + + .. note:: + This method modifies the module in-place. + + Returns: + Module: self + """ + return self._apply(lambda t: t.bfloat16() if t.is_floating_point() else t) + + def to_empty( + self: T, *, device: Optional[DeviceLikeType], recurse: bool = True + ) -> T: + r"""Move the parameters and buffers to the specified device without copying storage. + + Args: + device (:class:`torch.device`): The desired device of the parameters + and buffers in this module. + recurse (bool): Whether parameters and buffers of submodules should + be recursively moved to the specified device. + + Returns: + Module: self + """ + return self._apply( + lambda t: torch.empty_like(t, device=device), recurse=recurse + ) + + @overload + def to( + self, + device: Optional[DeviceLikeType] = ..., + dtype: Optional[dtype] = ..., + non_blocking: bool = ..., + ) -> Self: + ... + + @overload + def to(self, dtype: dtype, non_blocking: bool = ...) -> Self: + ... + + @overload + def to(self, tensor: Tensor, non_blocking: bool = ...) -> Self: + ... + + def to(self, *args, **kwargs): + r"""Move and/or cast the parameters and buffers. + + This can be called as + + .. function:: to(device=None, dtype=None, non_blocking=False) + :noindex: + + .. function:: to(dtype, non_blocking=False) + :noindex: + + .. function:: to(tensor, non_blocking=False) + :noindex: + + .. function:: to(memory_format=torch.channels_last) + :noindex: + + Its signature is similar to :meth:`torch.Tensor.to`, but only accepts + floating point or complex :attr:`dtype`\ s. In addition, this method will + only cast the floating point or complex parameters and buffers to :attr:`dtype` + (if given). The integral parameters and buffers will be moved + :attr:`device`, if that is given, but with dtypes unchanged. When + :attr:`non_blocking` is set, it tries to convert/move asynchronously + with respect to the host if possible, e.g., moving CPU Tensors with + pinned memory to CUDA devices. + + See below for examples. + + .. note:: + This method modifies the module in-place. + + Args: + device (:class:`torch.device`): the desired device of the parameters + and buffers in this module + dtype (:class:`torch.dtype`): the desired floating point or complex dtype of + the parameters and buffers in this module + tensor (torch.Tensor): Tensor whose dtype and device are the desired + dtype and device for all parameters and buffers in this module + memory_format (:class:`torch.memory_format`): the desired memory + format for 4D parameters and buffers in this module (keyword + only argument) + + Returns: + Module: self + + Examples:: + + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> linear = nn.Linear(2, 2) + >>> linear.weight + Parameter containing: + tensor([[ 0.1913, -0.3420], + [-0.5113, -0.2325]]) + >>> linear.to(torch.double) + Linear(in_features=2, out_features=2, bias=True) + >>> linear.weight + Parameter containing: + tensor([[ 0.1913, -0.3420], + [-0.5113, -0.2325]], dtype=torch.float64) + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) + >>> gpu1 = torch.device("cuda:1") + >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) + Linear(in_features=2, out_features=2, bias=True) + >>> linear.weight + Parameter containing: + tensor([[ 0.1914, -0.3420], + [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') + >>> cpu = torch.device("cpu") + >>> linear.to(cpu) + Linear(in_features=2, out_features=2, bias=True) + >>> linear.weight + Parameter containing: + tensor([[ 0.1914, -0.3420], + [-0.5112, -0.2324]], dtype=torch.float16) + + >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) + >>> linear.weight + Parameter containing: + tensor([[ 0.3741+0.j, 0.2382+0.j], + [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) + >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) + tensor([[0.6122+0.j, 0.1150+0.j], + [0.6122+0.j, 0.1150+0.j], + [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128) + + """ + device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to( + *args, **kwargs + ) + + if dtype is not None: + if not (dtype.is_floating_point or dtype.is_complex): + raise TypeError( + "nn.Module.to only accepts floating point or complex " + f"dtypes, but got desired dtype={dtype}" + ) + if dtype.is_complex: + warnings.warn( + "Complex modules are a new feature under active development whose design may change, " + "and some modules might not work as expected when using complex tensors as parameters or buffers. " + "Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml " + "if a complex module does not work as expected." + ) + + def convert(t): + try: + if convert_to_format is not None and t.dim() in (4, 5): + return t.to( + device, + dtype if t.is_floating_point() or t.is_complex() else None, + non_blocking, + memory_format=convert_to_format, + ) + return t.to( + device, + dtype if t.is_floating_point() or t.is_complex() else None, + non_blocking, + ) + except NotImplementedError as e: + if str(e) == "Cannot copy out of meta tensor; no data!": + raise NotImplementedError( + f"{e} Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() " + f"when moving module from meta to a different device." + ) from None + else: + raise + + return self._apply(convert) + + def register_full_backward_pre_hook( + self, + hook: Callable[["Module", _grad_t], Union[None, _grad_t]], + prepend: bool = False, + ) -> RemovableHandle: + r"""Register a backward pre-hook on the module. + + The hook will be called every time the gradients for the module are computed. + The hook should have the following signature:: + + hook(module, grad_output) -> tuple[Tensor] or None + + The :attr:`grad_output` is a tuple. The hook should + not modify its arguments, but it can optionally return a new gradient with + respect to the output that will be used in place of :attr:`grad_output` in + subsequent computations. Entries in :attr:`grad_output` will be ``None`` for + all non-Tensor arguments. + + For technical reasons, when this hook is applied to a Module, its forward function will + receive a view of each Tensor passed to the Module. Similarly the caller will receive a view + of each Tensor returned by the Module's forward function. + + .. warning :: + Modifying inputs inplace is not allowed when using backward hooks and + will raise an error. + + Args: + hook (Callable): The user-defined hook to be registered. + prepend (bool): If true, the provided ``hook`` will be fired before + all existing ``backward_pre`` hooks on this + :class:`torch.nn.Module`. Otherwise, the provided + ``hook`` will be fired after all existing ``backward_pre`` hooks + on this :class:`torch.nn.Module`. Note that global + ``backward_pre`` hooks registered with + :func:`register_module_full_backward_pre_hook` will fire before + all hooks registered by this method. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + handle = RemovableHandle(self._backward_pre_hooks) + self._backward_pre_hooks[handle.id] = hook + if prepend: + self._backward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined] + return handle + + def register_backward_hook( + self, hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]] + ) -> RemovableHandle: + r"""Register a backward hook on the module. + + This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and + the behavior of this function will change in future versions. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + if self._is_full_backward_hook is True: + raise RuntimeError( + "Cannot use both regular backward hooks and full backward hooks on a " + "single Module. Please use only one of them." + ) + + self._is_full_backward_hook = False + + handle = RemovableHandle(self._backward_hooks) + self._backward_hooks[handle.id] = hook + return handle + + def register_full_backward_hook( + self, + hook: Callable[["Module", _grad_t, _grad_t], Union[None, _grad_t]], + prepend: bool = False, + ) -> RemovableHandle: + r"""Register a backward hook on the module. + + The hook will be called every time the gradients with respect to a module + are computed, i.e. the hook will execute if and only if the gradients with + respect to module outputs are computed. The hook should have the following + signature:: + + hook(module, grad_input, grad_output) -> tuple(Tensor) or None + + The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients + with respect to the inputs and outputs respectively. The hook should + not modify its arguments, but it can optionally return a new gradient with + respect to the input that will be used in place of :attr:`grad_input` in + subsequent computations. :attr:`grad_input` will only correspond to the inputs given + as positional arguments and all kwarg arguments are ignored. Entries + in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor + arguments. + + For technical reasons, when this hook is applied to a Module, its forward function will + receive a view of each Tensor passed to the Module. Similarly the caller will receive a view + of each Tensor returned by the Module's forward function. + + .. warning :: + Modifying inputs or outputs inplace is not allowed when using backward hooks and + will raise an error. + + Args: + hook (Callable): The user-defined hook to be registered. + prepend (bool): If true, the provided ``hook`` will be fired before + all existing ``backward`` hooks on this + :class:`torch.nn.Module`. Otherwise, the provided + ``hook`` will be fired after all existing ``backward`` hooks on + this :class:`torch.nn.Module`. Note that global + ``backward`` hooks registered with + :func:`register_module_full_backward_hook` will fire before + all hooks registered by this method. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + + """ + if self._is_full_backward_hook is False: + raise RuntimeError( + "Cannot use both regular backward hooks and full backward hooks on a " + "single Module. Please use only one of them." + ) + + self._is_full_backward_hook = True + + handle = RemovableHandle(self._backward_hooks) + self._backward_hooks[handle.id] = hook + if prepend: + self._backward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined] + return handle + + def _get_backward_hooks(self): + r"""Return the backward hooks for use in the call function. + + It returns two lists, one with the full backward hooks and one with the non-full + backward hooks. + """ + full_backward_hooks: list[Callable] = [] + if _global_is_full_backward_hook is True: + full_backward_hooks += _global_backward_hooks.values() + if self._is_full_backward_hook is True: + full_backward_hooks += self._backward_hooks.values() + + non_full_backward_hooks: list[Callable] = [] + if _global_is_full_backward_hook is False: + non_full_backward_hooks += _global_backward_hooks.values() + if self._is_full_backward_hook is False: + non_full_backward_hooks += self._backward_hooks.values() + + return full_backward_hooks, non_full_backward_hooks + + def _get_backward_pre_hooks(self): + backward_pre_hooks: list[Callable] = [] + backward_pre_hooks += _global_backward_pre_hooks.values() + backward_pre_hooks += self._backward_pre_hooks.values() + + return backward_pre_hooks + + def _maybe_warn_non_full_backward_hook(self, inputs, result, grad_fn): + if not isinstance(result, torch.Tensor): + if not ( + isinstance(result, tuple) + and all(isinstance(r, torch.Tensor) for r in result) + ): + warnings.warn( + "Using non-full backward hooks on a Module that does not return a " + "single Tensor or a tuple of Tensors is deprecated and will be removed " + "in future versions. This hook will be missing some of the grad_output. " + "Please use register_full_backward_hook to get the documented behavior.", + FutureWarning, + stacklevel=2, + ) + return + else: + result = (result,) + + if not isinstance(inputs, torch.Tensor): + if not ( + isinstance(inputs, tuple) + and all(isinstance(i, torch.Tensor) for i in inputs) + ): + warnings.warn( + "Using non-full backward hooks on a Module that does not take as input a " + "single Tensor or a tuple of Tensors is deprecated and will be removed " + "in future versions. This hook will be missing some of the grad_input. " + "Please use register_full_backward_hook to get the documented behavior.", + FutureWarning, + stacklevel=2, + ) + return + else: + inputs = (inputs,) + + # At this point we are sure that inputs and result are tuple of Tensors + out_grad_fn = {r.grad_fn for r in result if r.grad_fn is not None} + if len(out_grad_fn) == 0 or ( + len(out_grad_fn) == 1 and grad_fn not in out_grad_fn + ): + warnings.warn( + "Using a non-full backward hook when outputs are nested in python data structure " + "is deprecated and will be removed in future versions. This hook will be missing " + "some grad_output.", + FutureWarning, + stacklevel=2, + ) + elif len(out_grad_fn) > 1: + warnings.warn( + "Using a non-full backward hook when outputs are generated by different autograd Nodes " + "is deprecated and will be removed in future versions. This hook will be missing " + "some grad_output. Please use register_full_backward_hook to get the documented behavior.", + FutureWarning, + stacklevel=2, + ) + else: + # At this point the grad_output part of the hook will most likely be correct + inputs_grad_fn = {i.grad_fn for i in inputs if i.grad_fn is not None} + + next_functions = {n[0] for n in grad_fn.next_functions} + + if inputs_grad_fn != next_functions: + warnings.warn( + "Using a non-full backward hook when the forward contains multiple autograd Nodes " + "is deprecated and will be removed in future versions. This hook will be missing " + "some grad_input. Please use register_full_backward_hook to get the documented " + "behavior.", + FutureWarning, + stacklevel=2, + ) + + def register_forward_pre_hook( + self, + hook: Union[ + Callable[[T, tuple[Any, ...]], Optional[Any]], + Callable[ + [T, tuple[Any, ...], dict[str, Any]], + Optional[tuple[Any, dict[str, Any]]], + ], + ], + *, + prepend: bool = False, + with_kwargs: bool = False, + ) -> RemovableHandle: + r"""Register a forward pre-hook on the module. + + The hook will be called every time before :func:`forward` is invoked. + + + If ``with_kwargs`` is false or not specified, the input contains only + the positional arguments given to the module. Keyword arguments won't be + passed to the hooks and only to the ``forward``. The hook can modify the + input. User can either return a tuple or a single modified value in the + hook. We will wrap the value into a tuple if a single value is returned + (unless that value is already a tuple). The hook should have the + following signature:: + + hook(module, args) -> None or modified input + + If ``with_kwargs`` is true, the forward pre-hook will be passed the + kwargs given to the forward function. And if the hook modifies the + input, both the args and kwargs should be returned. The hook should have + the following signature:: + + hook(module, args, kwargs) -> None or a tuple of modified input and kwargs + + Args: + hook (Callable): The user defined hook to be registered. + prepend (bool): If true, the provided ``hook`` will be fired before + all existing ``forward_pre`` hooks on this + :class:`torch.nn.Module`. Otherwise, the provided + ``hook`` will be fired after all existing ``forward_pre`` hooks + on this :class:`torch.nn.Module`. Note that global + ``forward_pre`` hooks registered with + :func:`register_module_forward_pre_hook` will fire before all + hooks registered by this method. + Default: ``False`` + with_kwargs (bool): If true, the ``hook`` will be passed the kwargs + given to the forward function. + Default: ``False`` + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle( + self._forward_pre_hooks, extra_dict=self._forward_pre_hooks_with_kwargs + ) + self._forward_pre_hooks[handle.id] = hook + if with_kwargs: + self._forward_pre_hooks_with_kwargs[handle.id] = True + + if prepend: + self._forward_pre_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined] + return handle + + def register_forward_hook( + self, + hook: Union[ + Callable[[T, tuple[Any, ...], Any], Optional[Any]], + Callable[[T, tuple[Any, ...], dict[str, Any], Any], Optional[Any]], + ], + *, + prepend: bool = False, + with_kwargs: bool = False, + always_call: bool = False, + ) -> RemovableHandle: + r"""Register a forward hook on the module. + + The hook will be called every time after :func:`forward` has computed an output. + + If ``with_kwargs`` is ``False`` or not specified, the input contains only + the positional arguments given to the module. Keyword arguments won't be + passed to the hooks and only to the ``forward``. The hook can modify the + output. It can modify the input inplace but it will not have effect on + forward since this is called after :func:`forward` is called. The hook + should have the following signature:: + + hook(module, args, output) -> None or modified output + + If ``with_kwargs`` is ``True``, the forward hook will be passed the + ``kwargs`` given to the forward function and be expected to return the + output possibly modified. The hook should have the following signature:: + + hook(module, args, kwargs, output) -> None or modified output + + Args: + hook (Callable): The user defined hook to be registered. + prepend (bool): If ``True``, the provided ``hook`` will be fired + before all existing ``forward`` hooks on this + :class:`torch.nn.Module`. Otherwise, the provided + ``hook`` will be fired after all existing ``forward`` hooks on + this :class:`torch.nn.Module`. Note that global + ``forward`` hooks registered with + :func:`register_module_forward_hook` will fire before all hooks + registered by this method. + Default: ``False`` + with_kwargs (bool): If ``True``, the ``hook`` will be passed the + kwargs given to the forward function. + Default: ``False`` + always_call (bool): If ``True`` the ``hook`` will be run regardless of + whether an exception is raised while calling the Module. + Default: ``False`` + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle( + self._forward_hooks, + extra_dict=[ + self._forward_hooks_with_kwargs, + self._forward_hooks_always_called, + ], + ) + self._forward_hooks[handle.id] = hook + if with_kwargs: + self._forward_hooks_with_kwargs[handle.id] = True + if always_call: + self._forward_hooks_always_called[handle.id] = True + if prepend: + self._forward_hooks.move_to_end(handle.id, last=False) # type: ignore[attr-defined] + return handle + + def _slow_forward(self, *input, **kwargs): + tracing_state = torch._C._get_tracing_state() + if not tracing_state or isinstance(self.forward, torch._C.ScriptMethod): + return self.forward(*input, **kwargs) + recording_scopes = torch.jit._trace._trace_module_map is not None + if recording_scopes: + # type ignore was added because at this point one knows that + # torch.jit._trace._trace_module_map is not Optional and has type Dict[Any, Any] + name = torch.jit._trace._trace_module_map[self] if self in torch.jit._trace._trace_module_map else None # type: ignore[index, operator] # noqa: B950 + if name: + tracing_state.push_scope(name) + else: + recording_scopes = False + try: + result = self.forward(*input, **kwargs) + finally: + if recording_scopes: + tracing_state.pop_scope() + return result + + def _wrapped_call_impl(self, *args, **kwargs): + if self._compiled_call_impl is not None: + return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc] + else: + return self._call_impl(*args, **kwargs) + + # torchrec tests the code consistency with the following code + # fmt: off + def _call_impl(self, *args, **kwargs): + forward_call = (self._slow_forward if torch._C._get_tracing_state() else self.forward) + # If we don't have any hooks, we want to skip the rest of the logic in + # this function, and just call forward. + if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks + or _global_backward_pre_hooks or _global_backward_hooks + or _global_forward_hooks or _global_forward_pre_hooks): + return forward_call(*args, **kwargs) + + result = None + called_always_called_hooks = set() + + def inner(): + nonlocal result, args, kwargs + + full_backward_hooks, non_full_backward_hooks = [], [] + backward_pre_hooks = [] + if self._backward_pre_hooks or _global_backward_pre_hooks: + backward_pre_hooks = self._get_backward_pre_hooks() + + if self._backward_hooks or _global_backward_hooks: + full_backward_hooks, non_full_backward_hooks = self._get_backward_hooks() + + if _global_forward_pre_hooks or self._forward_pre_hooks: + for hook_id, hook in ( + *_global_forward_pre_hooks.items(), + *self._forward_pre_hooks.items(), + ): + if hook_id in self._forward_pre_hooks_with_kwargs: + args_kwargs_result = hook(self, args, kwargs) # type: ignore[misc] + if args_kwargs_result is not None: + if isinstance(args_kwargs_result, tuple) and len(args_kwargs_result) == 2: + args, kwargs = args_kwargs_result + else: + raise RuntimeError( + "forward pre-hook must return None or a tuple " + f"of (new_args, new_kwargs), but got {args_kwargs_result}." + ) + else: + args_result = hook(self, args) + if args_result is not None: + if not isinstance(args_result, tuple): + args_result = (args_result,) + args = args_result + + bw_hook = None + if full_backward_hooks or backward_pre_hooks: + bw_hook = BackwardHook(self, full_backward_hooks, backward_pre_hooks) + args = bw_hook.setup_input_hook(args) + + result = forward_call(*args, **kwargs) + if _global_forward_hooks or self._forward_hooks: + for hook_id, hook in ( + *_global_forward_hooks.items(), + *self._forward_hooks.items(), + ): + # mark that always called hook is run + if hook_id in self._forward_hooks_always_called or hook_id in _global_forward_hooks_always_called: + called_always_called_hooks.add(hook_id) + + if hook_id in self._forward_hooks_with_kwargs or hook_id in _global_forward_hooks_with_kwargs: + hook_result = hook(self, args, kwargs, result) + else: + hook_result = hook(self, args, result) + + if hook_result is not None: + result = hook_result + + if bw_hook: + if not isinstance(result, (torch.Tensor, tuple)): + warnings.warn("For backward hooks to be called," + " module output should be a Tensor or a tuple of Tensors" + f" but received {type(result)}") + result = bw_hook.setup_output_hook(result) + + # Handle the non-full backward hooks + if non_full_backward_hooks: + var = result + while not isinstance(var, torch.Tensor): + if isinstance(var, dict): + var = next(v for v in var.values() if isinstance(v, torch.Tensor)) + else: + var = var[0] + grad_fn = var.grad_fn + if grad_fn is not None: + for hook in non_full_backward_hooks: + grad_fn.register_hook(_WrappedHook(hook, self)) + self._maybe_warn_non_full_backward_hook(args, result, grad_fn) + + return result + + # This is technically not behavior equivalent when compiling, but it's + # incredibly unlikely we will ever support throwing an exception in NN + # module, and then catching it here, and then reraising it, and then + # catching it again, and expecting the resulting frame to be compiled. + # The reraise here just gunks up our exception handling for no good + # reason. Don't try to run the always called hooks in event of + # exception. + if torch.compiler.is_compiling(): + return inner() + + try: + return inner() + except Exception: + # run always called hooks if they have not already been run + # For now only forward hooks have the always_call option but perhaps + # this functionality should be added to full backward hooks as well. + for hook_id, hook in _global_forward_hooks.items(): + if hook_id in _global_forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined] + try: + hook_result = hook(self, args, result) # type: ignore[possibly-undefined] + if hook_result is not None: + result = hook_result + except Exception as e: + warnings.warn("global module forward hook with ``always_call=True`` raised an exception " + f"that was silenced as another error was raised in forward: {str(e)}") + continue + + for hook_id, hook in self._forward_hooks.items(): + if hook_id in self._forward_hooks_always_called and hook_id not in called_always_called_hooks: # type: ignore[possibly-undefined] + try: + if hook_id in self._forward_hooks_with_kwargs: + hook_result = hook(self, args, kwargs, result) # type: ignore[possibly-undefined] + else: + hook_result = hook(self, args, result) # type: ignore[possibly-undefined] + if hook_result is not None: + result = hook_result + except Exception as e: + warnings.warn("module forward hook with ``always_call=True`` raised an exception " + f"that was silenced as another error was raised in forward: {str(e)}") + continue + # raise exception raised in try block + raise + # fmt: on + + __call__: Callable[..., Any] = _wrapped_call_impl + + def __getstate__(self): + state = self.__dict__.copy() + state.pop("_compiled_call_impl", None) + return state + + def __setstate__(self, state): + self.__dict__.update(state) + + # Support loading old checkpoints that don't have the following attrs: + if "_forward_pre_hooks" not in self.__dict__: + self._forward_pre_hooks = OrderedDict() + if "_forward_pre_hooks_with_kwargs" not in self.__dict__: + self._forward_pre_hooks_with_kwargs = OrderedDict() + if "_forward_hooks_with_kwargs" not in self.__dict__: + self._forward_hooks_with_kwargs = OrderedDict() + if "_forward_hooks_always_called" not in self.__dict__: + self._forward_hooks_always_called = OrderedDict() + if "_state_dict_hooks" not in self.__dict__: + self._state_dict_hooks = OrderedDict() + if "_state_dict_pre_hooks" not in self.__dict__: + self._state_dict_pre_hooks = OrderedDict() + if "_load_state_dict_pre_hooks" not in self.__dict__: + self._load_state_dict_pre_hooks = OrderedDict() + if "_load_state_dict_post_hooks" not in self.__dict__: + self._load_state_dict_post_hooks = OrderedDict() + if "_non_persistent_buffers_set" not in self.__dict__: + self._non_persistent_buffers_set = set() + if "_is_full_backward_hook" not in self.__dict__: + self._is_full_backward_hook = None + if "_backward_pre_hooks" not in self.__dict__: + self._backward_pre_hooks = OrderedDict() + + # It is crucial that the return type is not annotated as `Any`, otherwise type checking + # on `torch.nn.Module` and all its subclasses is largely disabled as a result. See: + # https://github.com/pytorch/pytorch/pull/115074 + def __getattr__(self, name: str) -> Union[Tensor, "Module"]: + if "_parameters" in self.__dict__: + _parameters = self.__dict__["_parameters"] + if name in _parameters: + return _parameters[name] + if "_buffers" in self.__dict__: + _buffers = self.__dict__["_buffers"] + if name in _buffers: + return _buffers[name] + if "_modules" in self.__dict__: + modules = self.__dict__["_modules"] + if name in modules: + return modules[name] + raise AttributeError( + f"'{type(self).__name__}' object has no attribute '{name}'" + ) + + def __setattr__(self, name: str, value: Union[Tensor, "Module"]) -> None: + def remove_from(*dicts_or_sets): + for d in dicts_or_sets: + if name in d: + if isinstance(d, dict): + del d[name] + else: + d.discard(name) + + params = self.__dict__.get("_parameters") + if isinstance(value, Parameter): + if params is None: + raise AttributeError( + "cannot assign parameters before Module.__init__() call" + ) + remove_from( + self.__dict__, + self._buffers, + self._modules, + self._non_persistent_buffers_set, + ) + self.register_parameter(name, value) + elif params is not None and name in params: + if value is not None: + raise TypeError( + f"cannot assign '{torch.typename(value)}' as parameter '{name}' " + "(torch.nn.Parameter or None expected)" + ) + self.register_parameter(name, value) + else: + modules = self.__dict__.get("_modules") + if isinstance(value, Module): + if modules is None: + raise AttributeError( + "cannot assign module before Module.__init__() call" + ) + remove_from( + self.__dict__, + self._parameters, + self._buffers, + self._non_persistent_buffers_set, + ) + for hook in _global_module_registration_hooks.values(): + output = hook(self, name, value) + if output is not None: + value = output + modules[name] = value + elif modules is not None and name in modules: + if value is not None: + raise TypeError( + f"cannot assign '{torch.typename(value)}' as child module '{name}' " + "(torch.nn.Module or None expected)" + ) + for hook in _global_module_registration_hooks.values(): + output = hook(self, name, value) + if output is not None: + value = output + modules[name] = value + else: + buffers = self.__dict__.get("_buffers") + if isinstance(value, Buffer) or buffers is not None and name in buffers: + if value is not None and not isinstance(value, torch.Tensor): + raise TypeError( + f"cannot assign '{torch.typename(value)}' as buffer '{name}' " + "(torch.nn.Buffer, torch.Tensor or None expected)" + ) + if isinstance(value, Buffer): + persistent = value.persistent + else: + persistent = name not in self._non_persistent_buffers_set + # === HACK === + # This whole block below should just be: + # self.register_buffer(name, value, persistent) + + # But to support subclasses of nn.Module that (wrongfully) implement a + # register_buffer() method that doesn't have the "persistent" + # argument. Only pass it in if it is accepted otherwise assume + # it is always true + if self.register_buffer is torch.nn.Module.register_buffer: + self.register_buffer(name, value, persistent) + else: + sign = inspect.signature(self.register_buffer) + if "persistent" in sign.parameters: + self.register_buffer(name, value, persistent) + else: + if not persistent: + raise RuntimeError( + "Registering a non-persistent buffer " + "on a Module subclass that implements " + "register_buffer() without the persistent " + "argument is not allowed." + ) + # Assume that the implementation without the argument has the + # behavior from before the argument was added: persistent=True + self.register_buffer(name, value) + # === HACK END === + else: + super().__setattr__(name, value) + + def __delattr__(self, name): + if name in self._parameters: + del self._parameters[name] + elif name in self._buffers: + del self._buffers[name] + self._non_persistent_buffers_set.discard(name) + elif name in self._modules: + del self._modules[name] + else: + super().__delattr__(name) + + def _register_state_dict_hook(self, hook): + r"""Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method. + + It should have the following signature:: + hook(module, state_dict, prefix, local_metadata) -> None or state_dict + + The registered hooks can modify the ``state_dict`` inplace or return a new one. + If a new ``state_dict`` is returned, it will only be respected if it is the root + module that :meth:`~nn.Module.state_dict` is called from. + """ + if getattr(hook, "_from_public_api", False): + raise RuntimeError( + "Cannot register the same function as the state dict post hook that was " + "previously registered via register_state_dict_post_hook" + ) + handle = RemovableHandle(self._state_dict_hooks) + self._state_dict_hooks[handle.id] = hook + return handle + + def register_state_dict_post_hook(self, hook): + r"""Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method. + + It should have the following signature:: + hook(module, state_dict, prefix, local_metadata) -> None + + The registered hooks can modify the ``state_dict`` inplace. + """ + # In _register_state_dict_hook there was a bug described in + # https://github.com/pytorch/pytorch/issues/117437 where the return value + # was only respected for the root module but not child submodules. + # We fix this in this public version by only allowing inplace modifications on + # the state_dict by the hook. However, since hooks registered via both these + # APIs will be added to `_state_dict_hooks` and the type of `_state_dict_hooks` + # cannot be changed due to many dependencies on it, we mark a hook + # as being registered via the public API by setting `_from_public_api` on it. + # In the implementation of `state_dict`, if the callable does not have this + # flag, the old behavior of respecting the return value will be preserved + # for the root module, otherwise, we ensure that the hook returns None. + hook._from_public_api = True + handle = RemovableHandle(self._state_dict_hooks) + self._state_dict_hooks[handle.id] = hook + return handle + + def register_state_dict_pre_hook(self, hook): + r"""Register a pre-hook for the :meth:`~torch.nn.Module.state_dict` method. + + It should have the following signature:: + hook(module, prefix, keep_vars) -> None + + The registered hooks can be used to perform pre-processing before the ``state_dict`` + call is made. + """ + handle = RemovableHandle(self._state_dict_pre_hooks) + self._state_dict_pre_hooks[handle.id] = hook + return handle + + def _save_to_state_dict(self, destination, prefix, keep_vars): + r"""Save module state to the `destination` dictionary. + + The `destination` dictionary will contain the state + of the module, but not its descendants. This is called on every + submodule in :meth:`~torch.nn.Module.state_dict`. + + In rare cases, subclasses can achieve class-specific behavior by + overriding this method with custom logic. + + Args: + destination (dict): a dict where state will be stored + prefix (str): the prefix for parameters and buffers used in this + module + """ + for name, param in self._parameters.items(): + if param is not None: + destination[prefix + name] = param if keep_vars else param.detach() + for name, buf in self._buffers.items(): + if buf is not None and name not in self._non_persistent_buffers_set: + destination[prefix + name] = buf if keep_vars else buf.detach() + extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX + if ( + getattr(self.__class__, "get_extra_state", Module.get_extra_state) + is not Module.get_extra_state + ): + destination[extra_state_key] = self.get_extra_state() + + # The user can pass an optional arbitrary mappable object to `state_dict`, in which case `state_dict` returns + # back that same object. But if they pass nothing, an `OrderedDict` is created and returned. + T_destination = TypeVar("T_destination", bound=dict[str, Any]) + + @overload + def state_dict( + self, *, destination: T_destination, prefix: str = ..., keep_vars: bool = ... + ) -> T_destination: + ... + + @overload + def state_dict(self, *, prefix: str = ..., keep_vars: bool = ...) -> dict[str, Any]: + ... + + # TODO: Change `*args` to `*` and remove the corresponding warning in docs when BC allows. + # Also remove the logic for arg parsing together. + def state_dict(self, *args, destination=None, prefix="", keep_vars=False): + r"""Return a dictionary containing references to the whole state of the module. + + Both parameters and persistent buffers (e.g. running averages) are + included. Keys are corresponding parameter and buffer names. + Parameters and buffers set to ``None`` are not included. + + .. note:: + The returned object is a shallow copy. It contains references + to the module's parameters and buffers. + + .. warning:: + Currently ``state_dict()`` also accepts positional arguments for + ``destination``, ``prefix`` and ``keep_vars`` in order. However, + this is being deprecated and keyword arguments will be enforced in + future releases. + + .. warning:: + Please avoid the use of argument ``destination`` as it is not + designed for end-users. + + Args: + destination (dict, optional): If provided, the state of module will + be updated into the dict and the same object is returned. + Otherwise, an ``OrderedDict`` will be created and returned. + Default: ``None``. + prefix (str, optional): a prefix added to parameter and buffer + names to compose the keys in state_dict. Default: ``''``. + keep_vars (bool, optional): by default the :class:`~torch.Tensor` s + returned in the state dict are detached from autograd. If it's + set to ``True``, detaching will not be performed. + Default: ``False``. + + Returns: + dict: + a dictionary containing a whole state of the module + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> module.state_dict().keys() + ['bias', 'weight'] + + """ + # TODO: Remove `args` and the parsing logic when BC allows. + if len(args) > 0: + # DeprecationWarning is ignored by default + warnings.warn( + "Positional args are being deprecated, use kwargs instead. Refer to " + "https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.state_dict" + " for details.", + FutureWarning, + stacklevel=2, + ) + if destination is None: + destination = args[0] + if len(args) > 1 and prefix == "": + prefix = args[1] + if len(args) > 2 and keep_vars is False: + keep_vars = args[2] + + if destination is None: + destination = OrderedDict() + destination._metadata = OrderedDict() + + local_metadata = dict(version=self._version) + if hasattr(destination, "_metadata"): + destination._metadata[prefix[:-1]] = local_metadata + + for hook in self._state_dict_pre_hooks.values(): + hook(self, prefix, keep_vars) + self._save_to_state_dict(destination, prefix, keep_vars) + for name, module in self._modules.items(): + if module is not None: + module.state_dict( + destination=destination, + prefix=prefix + name + ".", + keep_vars=keep_vars, + ) + for hook in self._state_dict_hooks.values(): + hook_result = hook(self, destination, prefix, local_metadata) + if not getattr(hook, "_from_public_api", False): + if hook_result is not None: + destination = hook_result + else: + if hook_result is not None: + raise RuntimeError("state_dict post-hook must return None") + return destination + + def _register_load_state_dict_pre_hook(self, hook, with_module=False): + r"""See :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` for details. + + A subtle difference is that if ``with_module`` is set to ``False``, then the + hook will not take the ``module`` as the first argument whereas + :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` always takes the + ``module`` as the first argument. + + Arguments: + hook (Callable): Callable hook that will be invoked before + loading the state dict. + with_module (bool, optional): Whether or not to pass the module + instance to the hook as the first parameter. + """ + handle = RemovableHandle(self._load_state_dict_pre_hooks) + self._load_state_dict_pre_hooks[handle.id] = _WrappedHook( + hook, self if with_module else None + ) + return handle + + def register_load_state_dict_pre_hook(self, hook): + r"""Register a pre-hook to be run before module's :meth:`~nn.Module.load_state_dict` is called. + + It should have the following signature:: + hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None # noqa: B950 + + Arguments: + hook (Callable): Callable hook that will be invoked before + loading the state dict. + """ + return self._register_load_state_dict_pre_hook(hook, with_module=True) + + def register_load_state_dict_post_hook(self, hook): + r"""Register a post-hook to be run after module's :meth:`~nn.Module.load_state_dict` is called. + + It should have the following signature:: + hook(module, incompatible_keys) -> None + + The ``module`` argument is the current module that this hook is registered + on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting + of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys`` + is a ``list`` of ``str`` containing the missing keys and + ``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys. + + The given incompatible_keys can be modified inplace if needed. + + Note that the checks performed when calling :func:`load_state_dict` with + ``strict=True`` are affected by modifications the hook makes to + ``missing_keys`` or ``unexpected_keys``, as expected. Additions to either + set of keys will result in an error being thrown when ``strict=True``, and + clearing out both missing and unexpected keys will avoid an error. + + Returns: + :class:`torch.utils.hooks.RemovableHandle`: + a handle that can be used to remove the added hook by calling + ``handle.remove()`` + """ + handle = RemovableHandle(self._load_state_dict_post_hooks) + self._load_state_dict_post_hooks[handle.id] = hook + return handle + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + r"""Copy parameters and buffers from :attr:`state_dict` into only this module, but not its descendants. + + This is called on every submodule + in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this + module in input :attr:`state_dict` is provided as :attr:`local_metadata`. + For state dicts without metadata, :attr:`local_metadata` is empty. + Subclasses can achieve class-specific backward compatible loading using + the version number at `local_metadata.get("version", None)`. + Additionally, :attr:`local_metadata` can also contain the key + `assign_to_params_buffers` that indicates whether keys should be + assigned their corresponding tensor in the state_dict. + + .. note:: + :attr:`state_dict` is not the same object as the input + :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So + it can be modified. + + Args: + state_dict (dict): a dict containing parameters and + persistent buffers. + prefix (str): the prefix for parameters and buffers used in this + module + local_metadata (dict): a dict containing the metadata for this module. + See + strict (bool): whether to strictly enforce that the keys in + :attr:`state_dict` with :attr:`prefix` match the names of + parameters and buffers in this module + missing_keys (list of str): if ``strict=True``, add missing keys to + this list + unexpected_keys (list of str): if ``strict=True``, add unexpected + keys to this list + error_msgs (list of str): error messages should be added to this + list, and will be reported together in + :meth:`~torch.nn.Module.load_state_dict` + """ + for hook in self._load_state_dict_pre_hooks.values(): + hook( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + persistent_buffers = { + k: v + for k, v in self._buffers.items() + if k not in self._non_persistent_buffers_set + } + local_name_params = itertools.chain( + self._parameters.items(), persistent_buffers.items() + ) + local_state = {k: v for k, v in local_name_params if v is not None} + assign_to_params_buffers = local_metadata.get("assign_to_params_buffers", False) + use_swap_tensors = torch.__future__.get_swap_module_params_on_conversion() + + for name, param in local_state.items(): + key = prefix + name + if key in state_dict: + input_param = state_dict[key] + if not torch.overrides.is_tensor_like(input_param): + error_msgs.append( + f'While copying the parameter named "{key}", ' + "expected torch.Tensor or Tensor-like object from checkpoint but " + f"received {type(input_param)}" + ) + continue + + # This is used to avoid copying uninitialized parameters into + # non-lazy modules, since they dont have the hook to do the checks + # in such case, it will error when accessing the .shape attribute. + is_param_lazy = torch.nn.parameter.is_lazy(param) + # Backward compatibility: loading 1-dim tensor from 0.3.* to version 0.4+ + if ( + not is_param_lazy + and len(param.shape) == 0 + and len(input_param.shape) == 1 + ): + input_param = input_param[0] + + if not is_param_lazy and input_param.shape != param.shape: + # local shape should match the one in checkpoint + error_msgs.append( + f"size mismatch for {key}: copying a param with shape {input_param.shape} from checkpoint, " + f"the shape in current model is {param.shape}." + ) + continue + + if ( + param.is_meta + and not input_param.is_meta + and not assign_to_params_buffers + ): + warnings.warn( + f"for {key}: copying from a non-meta parameter in the checkpoint to a meta " + "parameter in the current model, which is a no-op. (Did you mean to " + "pass `assign=True` to assign items in the state dictionary to their " + "corresponding key in the module instead of copying them in place?)" + ) + + try: + with torch.no_grad(): + if use_swap_tensors: + new_input_param = param.module_load( + input_param, assign=assign_to_params_buffers + ) + if id(new_input_param) == id(input_param) or id( + new_input_param + ) == id(param): + raise RuntimeError( + "module_load returned one of self or other, please .detach() " + "the result if returning one of the inputs in module_load" + ) + if isinstance(param, torch.nn.Parameter): + if not isinstance(new_input_param, torch.nn.Parameter): + new_input_param = torch.nn.Parameter( + new_input_param, + requires_grad=param.requires_grad, + ) + else: + new_input_param.requires_grad_(param.requires_grad) + torch.utils.swap_tensors(param, new_input_param) + del new_input_param + elif assign_to_params_buffers: + # Shape checks are already done above + if isinstance(param, torch.nn.Parameter): + if not isinstance(input_param, torch.nn.Parameter): + input_param = torch.nn.Parameter( + input_param, requires_grad=param.requires_grad + ) + else: + input_param.requires_grad_(param.requires_grad) + setattr(self, name, input_param) + else: + param.copy_(input_param) + except Exception as ex: + action = "swapping" if use_swap_tensors else "copying" + error_msgs.append( + f'While {action} the parameter named "{key}", ' + f"whose dimensions in the model are {param.size()} and " + f"whose dimensions in the checkpoint are {input_param.size()}, " + f"an exception occurred : {ex.args}." + ) + elif strict: + missing_keys.append(key) + + extra_state_key = prefix + _EXTRA_STATE_KEY_SUFFIX + if ( + getattr(self.__class__, "set_extra_state", Module.set_extra_state) + is not Module.set_extra_state + ): + if extra_state_key in state_dict: + self.set_extra_state(state_dict[extra_state_key]) + elif strict: + missing_keys.append(extra_state_key) + elif strict and (extra_state_key in state_dict): + unexpected_keys.append(extra_state_key) + + if strict: + for key in state_dict.keys(): + if key.startswith(prefix) and key != extra_state_key: + input_name = key[len(prefix) :].split(".", 1) + # Must be Module if it have attributes + if len(input_name) > 1: + if input_name[0] not in self._modules: + unexpected_keys.append(key) + elif input_name[0] not in local_state: + unexpected_keys.append(key) + + def load_state_dict( + self, state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False + ): + r"""Copy parameters and buffers from :attr:`state_dict` into this module and its descendants. + + If :attr:`strict` is ``True``, then + the keys of :attr:`state_dict` must exactly match the keys returned + by this module's :meth:`~torch.nn.Module.state_dict` function. + + .. warning:: + If :attr:`assign` is ``True`` the optimizer must be created after + the call to :attr:`load_state_dict` unless + :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``. + + Args: + state_dict (dict): a dict containing parameters and + persistent buffers. + strict (bool, optional): whether to strictly enforce that the keys + in :attr:`state_dict` match the keys returned by this module's + :meth:`~torch.nn.Module.state_dict` function. Default: ``True`` + assign (bool, optional): When set to ``False``, the properties of the tensors + in the current module are preserved whereas setting it to ``True`` preserves + properties of the Tensors in the state dict. The only + exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`s + for which the value from the module is preserved. + Default: ``False`` + + Returns: + ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields: + * **missing_keys** is a list of str containing any keys that are expected + by this module but missing from the provided ``state_dict``. + * **unexpected_keys** is a list of str containing the keys that are not + expected by this module but present in the provided ``state_dict``. + + Note: + If a parameter or buffer is registered as ``None`` and its corresponding key + exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a + ``RuntimeError``. + """ + if not isinstance(state_dict, Mapping): + raise TypeError( + f"Expected state_dict to be dict-like, got {type(state_dict)}." + ) + + missing_keys: list[str] = [] + unexpected_keys: list[str] = [] + error_msgs: list[str] = [] + + # copy state_dict so _load_from_state_dict can modify it + metadata = getattr(state_dict, "_metadata", None) + state_dict = OrderedDict(state_dict) + if metadata is not None: + # mypy isn't aware that "_metadata" exists in state_dict + state_dict._metadata = metadata # type: ignore[attr-defined] + + def load(module, local_state_dict, prefix=""): + local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) + if assign: + local_metadata["assign_to_params_buffers"] = assign + module._load_from_state_dict( + local_state_dict, + prefix, + local_metadata, + True, + missing_keys, + unexpected_keys, + error_msgs, + ) + for name, child in module._modules.items(): + if child is not None: + child_prefix = prefix + name + "." + child_state_dict = { + k: v + for k, v in local_state_dict.items() + if k.startswith(child_prefix) + } + load(child, child_state_dict, child_prefix) # noqa: F821 + + # Note that the hook can modify missing_keys and unexpected_keys. + incompatible_keys = _IncompatibleKeys(missing_keys, unexpected_keys) + for hook in module._load_state_dict_post_hooks.values(): + out = hook(module, incompatible_keys) + assert out is None, ( + "Hooks registered with ``register_load_state_dict_post_hook`` are not" + "expected to return new values, if incompatible_keys need to be modified," + "it should be done inplace." + ) + + load(self, state_dict) + del load + + if strict: + if len(unexpected_keys) > 0: + error_msgs.insert( + 0, + "Unexpected key(s) in state_dict: {}. ".format( + ", ".join(f'"{k}"' for k in unexpected_keys) + ), + ) + if len(missing_keys) > 0: + error_msgs.insert( + 0, + "Missing key(s) in state_dict: {}. ".format( + ", ".join(f'"{k}"' for k in missing_keys) + ), + ) + + if len(error_msgs) > 0: + raise RuntimeError( + "Error(s) in loading state_dict for {}:\n\t{}".format( + self.__class__.__name__, "\n\t".join(error_msgs) + ) + ) + return _IncompatibleKeys(missing_keys, unexpected_keys) + + def _named_members( + self, get_members_fn, prefix="", recurse=True, remove_duplicate: bool = True + ): + r"""Help yield various names + members of modules.""" + memo = set() + modules = ( + self.named_modules(prefix=prefix, remove_duplicate=remove_duplicate) + if recurse + else [(prefix, self)] + ) + for module_prefix, module in modules: + members = get_members_fn(module) + for k, v in members: + if v is None or v in memo: + continue + if remove_duplicate: + memo.add(v) + name = module_prefix + ("." if module_prefix else "") + k + yield name, v + + def parameters(self, recurse: bool = True) -> Iterator[Parameter]: + r"""Return an iterator over module parameters. + + This is typically passed to an optimizer. + + Args: + recurse (bool): if True, then yields parameters of this module + and all submodules. Otherwise, yields only parameters that + are direct members of this module. + + Yields: + Parameter: module parameter + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> for param in model.parameters(): + >>> print(type(param), param.size()) + (20L,) + (20L, 1L, 5L, 5L) + + """ + for _name, param in self.named_parameters(recurse=recurse): + yield param + + def named_parameters( + self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True + ) -> Iterator[tuple[str, Parameter]]: + r"""Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself. + + Args: + prefix (str): prefix to prepend to all parameter names. + recurse (bool): if True, then yields parameters of this module + and all submodules. Otherwise, yields only parameters that + are direct members of this module. + remove_duplicate (bool, optional): whether to remove the duplicated + parameters in the result. Defaults to True. + + Yields: + (str, Parameter): Tuple containing the name and parameter + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> for name, param in self.named_parameters(): + >>> if name in ['bias']: + >>> print(param.size()) + + """ + gen = self._named_members( + lambda module: module._parameters.items(), + prefix=prefix, + recurse=recurse, + remove_duplicate=remove_duplicate, + ) + yield from gen + + def buffers(self, recurse: bool = True) -> Iterator[Tensor]: + r"""Return an iterator over module buffers. + + Args: + recurse (bool): if True, then yields buffers of this module + and all submodules. Otherwise, yields only buffers that + are direct members of this module. + + Yields: + torch.Tensor: module buffer + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> for buf in model.buffers(): + >>> print(type(buf), buf.size()) + (20L,) + (20L, 1L, 5L, 5L) + + """ + for _, buf in self.named_buffers(recurse=recurse): + yield buf + + def named_buffers( + self, prefix: str = "", recurse: bool = True, remove_duplicate: bool = True + ) -> Iterator[tuple[str, Tensor]]: + r"""Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself. + + Args: + prefix (str): prefix to prepend to all buffer names. + recurse (bool, optional): if True, then yields buffers of this module + and all submodules. Otherwise, yields only buffers that + are direct members of this module. Defaults to True. + remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True. + + Yields: + (str, torch.Tensor): Tuple containing the name and buffer + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> for name, buf in self.named_buffers(): + >>> if name in ['running_var']: + >>> print(buf.size()) + + """ + gen = self._named_members( + lambda module: module._buffers.items(), + prefix=prefix, + recurse=recurse, + remove_duplicate=remove_duplicate, + ) + yield from gen + + def children(self) -> Iterator["Module"]: + r"""Return an iterator over immediate children modules. + + Yields: + Module: a child module + """ + for _name, module in self.named_children(): + yield module + + def named_children(self) -> Iterator[tuple[str, "Module"]]: + r"""Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself. + + Yields: + (str, Module): Tuple containing a name and child module + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> for name, module in model.named_children(): + >>> if name in ['conv4', 'conv5']: + >>> print(module) + + """ + memo = set() + for name, module in self._modules.items(): + if module is not None and module not in memo: + memo.add(module) + yield name, module + + def modules(self) -> Iterator["Module"]: + r"""Return an iterator over all modules in the network. + + Yields: + Module: a module in the network + + Note: + Duplicate modules are returned only once. In the following + example, ``l`` will be returned only once. + + Example:: + + >>> l = nn.Linear(2, 2) + >>> net = nn.Sequential(l, l) + >>> for idx, m in enumerate(net.modules()): + ... print(idx, '->', m) + + 0 -> Sequential( + (0): Linear(in_features=2, out_features=2, bias=True) + (1): Linear(in_features=2, out_features=2, bias=True) + ) + 1 -> Linear(in_features=2, out_features=2, bias=True) + + """ + for _, module in self.named_modules(): + yield module + + def named_modules( + self, + memo: Optional[set["Module"]] = None, + prefix: str = "", + remove_duplicate: bool = True, + ): + r"""Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself. + + Args: + memo: a memo to store the set of modules already added to the result + prefix: a prefix that will be added to the name of the module + remove_duplicate: whether to remove the duplicated module instances in the result + or not + + Yields: + (str, Module): Tuple of name and module + + Note: + Duplicate modules are returned only once. In the following + example, ``l`` will be returned only once. + + Example:: + + >>> l = nn.Linear(2, 2) + >>> net = nn.Sequential(l, l) + >>> for idx, m in enumerate(net.named_modules()): + ... print(idx, '->', m) + + 0 -> ('', Sequential( + (0): Linear(in_features=2, out_features=2, bias=True) + (1): Linear(in_features=2, out_features=2, bias=True) + )) + 1 -> ('0', Linear(in_features=2, out_features=2, bias=True)) + + """ + if memo is None: + memo = set() + if self not in memo: + if remove_duplicate: + memo.add(self) + yield prefix, self + for name, module in self._modules.items(): + if module is None: + continue + submodule_prefix = prefix + ("." if prefix else "") + name + yield from module.named_modules( + memo, submodule_prefix, remove_duplicate + ) + + def train(self: T, mode: bool = True) -> T: + r"""Set the module in training mode. + + This has an effect only on certain modules. See the documentation of + particular modules for details of their behaviors in training/evaluation + mode, i.e., whether they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, + etc. + + Args: + mode (bool): whether to set training mode (``True``) or evaluation + mode (``False``). Default: ``True``. + + Returns: + Module: self + """ + if not isinstance(mode, bool): + raise ValueError("training mode is expected to be boolean") + self.training = mode + for module in self.children(): + module.train(mode) + return self + + def eval(self: T) -> T: + r"""Set the module in evaluation mode. + + This has an effect only on certain modules. See the documentation of + particular modules for details of their behaviors in training/evaluation + mode, i.e. whether they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, + etc. + + This is equivalent with :meth:`self.train(False) `. + + See :ref:`locally-disable-grad-doc` for a comparison between + `.eval()` and several similar mechanisms that may be confused with it. + + Returns: + Module: self + """ + return self.train(False) + + def requires_grad_(self: T, requires_grad: bool = True) -> T: + r"""Change if autograd should record operations on parameters in this module. + + This method sets the parameters' :attr:`requires_grad` attributes + in-place. + + This method is helpful for freezing part of the module for finetuning + or training parts of a model individually (e.g., GAN training). + + See :ref:`locally-disable-grad-doc` for a comparison between + `.requires_grad_()` and several similar mechanisms that may be confused with it. + + Args: + requires_grad (bool): whether autograd should record operations on + parameters in this module. Default: ``True``. + + Returns: + Module: self + """ + for p in self.parameters(): + p.requires_grad_(requires_grad) + return self + + def zero_grad(self, set_to_none: bool = True) -> None: + r"""Reset gradients of all model parameters. + + See similar function under :class:`torch.optim.Optimizer` for more context. + + Args: + set_to_none (bool): instead of setting to zero, set the grads to None. + See :meth:`torch.optim.Optimizer.zero_grad` for details. + """ + if getattr(self, "_is_replica", False): + warnings.warn( + "Calling .zero_grad() from a module created with nn.DataParallel() has no effect. " + "The parameters are copied (in a differentiable manner) from the original module. " + "This means they are not leaf nodes in autograd and so don't accumulate gradients. " + "If you need gradients in your forward method, consider using autograd.grad instead." + ) + + for p in self.parameters(): + if p.grad is not None: + if set_to_none: + p.grad = None + else: + if p.grad.grad_fn is not None: + p.grad.detach_() + else: + p.grad.requires_grad_(False) + p.grad.zero_() + + def share_memory(self: T) -> T: + r"""See :meth:`torch.Tensor.share_memory_`.""" + return self._apply(lambda t: t.share_memory_()) + + def _get_name(self): + return self.__class__.__name__ + + def extra_repr(self) -> str: + r"""Return the extra representation of the module. + + To print customized extra information, you should re-implement + this method in your own modules. Both single-line and multi-line + strings are acceptable. + """ + return "" + + def __repr__(self): + # We treat the extra repr like the sub-module, one item per line + extra_lines = [] + extra_repr = self.extra_repr() + # empty string will be split into list [''] + if extra_repr: + extra_lines = extra_repr.split("\n") + child_lines = [] + for key, module in self._modules.items(): + mod_str = repr(module) + mod_str = _addindent(mod_str, 2) + child_lines.append("(" + key + "): " + mod_str) + lines = extra_lines + child_lines + + main_str = self._get_name() + "(" + if lines: + # simple one-liner info, which most builtin Modules will use + if len(extra_lines) == 1 and not child_lines: + main_str += extra_lines[0] + else: + main_str += "\n " + "\n ".join(lines) + "\n" + + main_str += ")" + return main_str + + def __dir__(self): + module_attrs = dir(self.__class__) + attrs = list(self.__dict__.keys()) + parameters = list(self._parameters.keys()) + modules = list(self._modules.keys()) + buffers = list(self._buffers.keys()) + keys = module_attrs + attrs + parameters + modules + buffers + + # Eliminate attrs that are not legal Python variable names + keys = [key for key in keys if not key[0].isdigit()] + + return sorted(keys) + + def _replicate_for_data_parallel(self): + replica = self.__new__(type(self)) + replica.__dict__ = self.__dict__.copy() + + # replicas do not have parameters themselves, the replicas reference the original + # module. + replica._parameters = {} + replica._buffers = replica._buffers.copy() + replica._modules = replica._modules.copy() + replica._is_replica = True # type: ignore[assignment] + + return replica + + def compile(self, *args, **kwargs): + """ + Compile this Module's forward using :func:`torch.compile`. + + This Module's `__call__` method is compiled and all arguments are passed as-is + to :func:`torch.compile`. + + See :func:`torch.compile` for details on the arguments for this function. + """ + self._compiled_call_impl = torch.compile(self._call_impl, *args, **kwargs) diff --git a/shared/package-files/93/93eaec3eb72d549d006d82a4cd31f00ba742d306a52f9167c509d1328f4fb712/torture.cpython-311.pyc b/shared/package-files/93/93eaec3eb72d549d006d82a4cd31f00ba742d306a52f9167c509d1328f4fb712/torture.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99b7a55aa9029745af8c77c5774596f5d41b7d21 Binary files /dev/null and b/shared/package-files/93/93eaec3eb72d549d006d82a4cd31f00ba742d306a52f9167c509d1328f4fb712/torture.cpython-311.pyc differ diff --git a/shared/package-files/93/93ededfb955144364363d15469aa7ac5c0ef83fccb658b226e389b65152f853e/custom_ops.cpython-311.pyc b/shared/package-files/93/93ededfb955144364363d15469aa7ac5c0ef83fccb658b226e389b65152f853e/custom_ops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72bec1fd07360243e500f0ccb408f86144387651 Binary files /dev/null and b/shared/package-files/93/93ededfb955144364363d15469aa7ac5c0ef83fccb658b226e389b65152f853e/custom_ops.cpython-311.pyc differ diff --git a/shared/package-files/93/93f5075bcba96e26c53d4efaa93f91d5090e507ba6d6892a876914d4bd01ae82/upsample_nearest3d_backward_cuda_dispatch.h b/shared/package-files/93/93f5075bcba96e26c53d4efaa93f91d5090e507ba6d6892a876914d4bd01ae82/upsample_nearest3d_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..350e37d1d2c14af7fab3d6dafe2d177e9d57e397 --- /dev/null +++ b/shared/package-files/93/93f5075bcba96e26c53d4efaa93f91d5090e507ba6d6892a876914d4bd01ae82/upsample_nearest3d_backward_cuda_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor upsample_nearest3d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor upsample_nearest3d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales_d, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input); +TORCH_API at::Tensor & upsample_nearest3d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & upsample_nearest3d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales_d, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & grad_input); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/93/93f902738784807366daccdc2155f7225c06de5df95762af40fa5112a1635fea/rnn_relu.h b/shared/package-files/93/93f902738784807366daccdc2155f7225c06de5df95762af40fa5112a1635fea/rnn_relu.h new file mode 100644 index 0000000000000000000000000000000000000000..345d21c47ac3f555ffb85aace6330a8c6fd4abb0 --- /dev/null +++ b/shared/package-files/93/93f902738784807366daccdc2155f7225c06de5df95762af40fa5112a1635fea/rnn_relu.h @@ -0,0 +1,36 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::rnn_relu.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) +inline ::std::tuple rnn_relu(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first) { + return at::_ops::rnn_relu_input::call(input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first); +} + +// aten::rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) +inline ::std::tuple rnn_relu(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional) { + return at::_ops::rnn_relu_data::call(data, batch_sizes, hx, params, has_biases, num_layers, dropout, train, bidirectional); +} + +} diff --git a/shared/package-files/93/93fa4a0fd964a876a9c5313e5156beebcf8d811899d91f26c8898e86cd5a6da4/utils.py b/shared/package-files/93/93fa4a0fd964a876a9c5313e5156beebcf8d811899d91f26c8898e86cd5a6da4/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a2790a0fdd743171270dfd9e7826bb2f8dac6842 --- /dev/null +++ b/shared/package-files/93/93fa4a0fd964a876a9c5313e5156beebcf8d811899d91f26c8898e86cd5a6da4/utils.py @@ -0,0 +1,40 @@ +import contextlib +from collections.abc import Generator +from typing import Any, Union + +import torch +from torch._C._functorch import ( + get_single_level_autograd_function_allowed, + set_single_level_autograd_function_allowed, + unwrap_if_dead, +) +from torch.utils._exposed_in import exposed_in + + +__all__ = [ + "exposed_in", + "argnums_t", + "enable_single_level_autograd_function", + "unwrap_dead_wrappers", +] + + +@contextlib.contextmanager +def enable_single_level_autograd_function() -> Generator[None, None, None]: + try: + prev_state = get_single_level_autograd_function_allowed() + set_single_level_autograd_function_allowed(True) + yield + finally: + set_single_level_autograd_function_allowed(prev_state) + + +def unwrap_dead_wrappers(args: tuple[Any, ...]) -> tuple[Any, ...]: + # NB: doesn't use tree_map_only for performance reasons + result = tuple( + unwrap_if_dead(arg) if isinstance(arg, torch.Tensor) else arg for arg in args + ) + return result + + +argnums_t = Union[int, tuple[int, ...]] diff --git a/shared/package-files/93/93fc621833d93a2a778b0dba2dc07613b5224461c1677f443abb09c50a1c8ba9/test_astype.py b/shared/package-files/93/93fc621833d93a2a778b0dba2dc07613b5224461c1677f443abb09c50a1c8ba9/test_astype.py new file mode 100644 index 0000000000000000000000000000000000000000..d545bfd2fae0f7034c8cb62a8955c8b3c0ba0d6d --- /dev/null +++ b/shared/package-files/93/93fc621833d93a2a778b0dba2dc07613b5224461c1677f443abb09c50a1c8ba9/test_astype.py @@ -0,0 +1,151 @@ +import numpy as np +import pytest + +from pandas import ( + CategoricalIndex, + DatetimeIndex, + Index, + NaT, + Period, + PeriodIndex, + period_range, +) +import pandas._testing as tm + + +class TestPeriodIndexAsType: + @pytest.mark.parametrize("dtype", [float, "timedelta64", "timedelta64[ns]"]) + def test_astype_raises(self, dtype): + # GH#13149, GH#13209 + idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.nan], freq="D") + msg = "Cannot cast PeriodIndex to dtype" + with pytest.raises(TypeError, match=msg): + idx.astype(dtype) + + def test_astype_conversion(self): + # GH#13149, GH#13209 + idx = PeriodIndex(["2016-05-16", "NaT", NaT, np.nan], freq="D", name="idx") + + result = idx.astype(object) + expected = Index( + [Period("2016-05-16", freq="D")] + [Period(NaT, freq="D")] * 3, + dtype="object", + name="idx", + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(np.int64) + expected = Index( + [16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx" + ) + tm.assert_index_equal(result, expected) + + result = idx.astype(str) + expected = Index([str(x) for x in idx], name="idx", dtype=object) + tm.assert_index_equal(result, expected) + + idx = period_range("1990", "2009", freq="Y", name="idx") + result = idx.astype("i8") + tm.assert_index_equal(result, Index(idx.asi8, name="idx")) + tm.assert_numpy_array_equal(result.values, idx.asi8) + + def test_astype_uint(self): + arr = period_range("2000", periods=2, name="idx") + + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint64") + with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): + arr.astype("uint32") + + def test_astype_object(self): + idx = PeriodIndex([], freq="M") + + exp = np.array([], dtype=object) + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), exp) + + idx = PeriodIndex(["2011-01", NaT], freq="M") + + exp = np.array([Period("2011-01", freq="M"), NaT], dtype=object) + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), exp) + + exp = np.array([Period("2011-01-01", freq="D"), NaT], dtype=object) + idx = PeriodIndex(["2011-01-01", NaT], freq="D") + tm.assert_numpy_array_equal(idx.astype(object).values, exp) + tm.assert_numpy_array_equal(idx._mpl_repr(), exp) + + # TODO: de-duplicate this version (from test_ops) with the one above + # (from test_period) + def test_astype_object2(self): + idx = period_range(start="2013-01-01", periods=4, freq="M", name="idx") + expected_list = [ + Period("2013-01-31", freq="M"), + Period("2013-02-28", freq="M"), + Period("2013-03-31", freq="M"), + Period("2013-04-30", freq="M"), + ] + expected = Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + assert isinstance(result, Index) + assert result.dtype == object + tm.assert_index_equal(result, expected) + assert result.name == expected.name + assert idx.tolist() == expected_list + + idx = PeriodIndex( + ["2013-01-01", "2013-01-02", "NaT", "2013-01-04"], freq="D", name="idx" + ) + expected_list = [ + Period("2013-01-01", freq="D"), + Period("2013-01-02", freq="D"), + Period("NaT", freq="D"), + Period("2013-01-04", freq="D"), + ] + expected = Index(expected_list, dtype=object, name="idx") + result = idx.astype(object) + assert isinstance(result, Index) + assert result.dtype == object + tm.assert_index_equal(result, expected) + for i in [0, 1, 3]: + assert result[i] == expected[i] + assert result[2] is NaT + assert result.name == expected.name + + result_list = idx.tolist() + for i in [0, 1, 3]: + assert result_list[i] == expected_list[i] + assert result_list[2] is NaT + + def test_astype_category(self): + obj = period_range("2000", periods=2, name="idx") + result = obj.astype("category") + expected = CategoricalIndex( + [Period("2000-01-01", freq="D"), Period("2000-01-02", freq="D")], name="idx" + ) + tm.assert_index_equal(result, expected) + + result = obj._data.astype("category") + expected = expected.values + tm.assert_categorical_equal(result, expected) + + def test_astype_array_fallback(self): + obj = period_range("2000", periods=2, name="idx") + result = obj.astype(bool) + expected = Index(np.array([True, True]), name="idx") + tm.assert_index_equal(result, expected) + + result = obj._data.astype(bool) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) + + def test_period_astype_to_timestamp(self, unit): + # GH#55958 + pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") + + exp = DatetimeIndex( + ["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern" + ).as_unit(unit) + res = pi.astype(f"datetime64[{unit}, US/Eastern]") + tm.assert_index_equal(res, exp) + assert res.freq == exp.freq diff --git a/shared/package-files/a5/a501f0a4913a0791ea34a001ce78d9352617dbca407aea97134c76abaad52555/request_callback_impl.h b/shared/package-files/a5/a501f0a4913a0791ea34a001ce78d9352617dbca407aea97134c76abaad52555/request_callback_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d8c3efc29ffd0111af0379a8bb2690890e7baeed --- /dev/null +++ b/shared/package-files/a5/a501f0a4913a0791ea34a001ce78d9352617dbca407aea97134c76abaad52555/request_callback_impl.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::distributed::rpc { + +class TORCH_API RequestCallbackImpl : public RequestCallbackNoPython { + public: + std::unique_ptr deserializePythonRpcCommand( + std::unique_ptr rpc, + const MessageType& messageType) const override; + + c10::intrusive_ptr processPythonCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processScriptCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processScriptRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processPythonRemoteCall( + RpcCommandBase& rpc, + const std::vector& streams) const override; + + c10::intrusive_ptr processPythonRRefFetchCall( + RpcCommandBase& rpc) const override; + + void handleRRefDelete(c10::intrusive_ptr& rref) const override; + + c10::intrusive_ptr processRpcWithErrors( + RpcCommandBase& rpc, + const MessageType& messageType, + const std::vector& streams) const override; + + bool cudaAvailable() const override; + + c10::intrusive_ptr processRRefBackward( + RpcCommandBase& rpc) const override; + + // Helpers to run user-defined functions, operators and other computations. + + c10::intrusive_ptr runJitFunction( + const c10::QualifiedName& name, + std::vector& stack, + const std::vector& streams, + bool isAsyncExecution) const; + + c10::intrusive_ptr runPythonFunction( + const py::object& function, + const std::vector& streams, + bool isAsyncExecution) const; +}; + +} // namespace torch::distributed::rpc diff --git a/shared/package-files/a5/a50f091be78645a1385fd4c313ca99543a1516ff59a5edbffae6eb3e8caa7a89/symbolic_opset10.cpython-311.pyc b/shared/package-files/a5/a50f091be78645a1385fd4c313ca99543a1516ff59a5edbffae6eb3e8caa7a89/symbolic_opset10.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2686f2bedcf68a5ba1432a60f7cbf92e91018550 Binary files /dev/null and b/shared/package-files/a5/a50f091be78645a1385fd4c313ca99543a1516ff59a5edbffae6eb3e8caa7a89/symbolic_opset10.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5198f3f372f3714a49a853bb49afe4603b9630e4d9606ec98d86f0547c625ab/log2_meta.h b/shared/package-files/a5/a5198f3f372f3714a49a853bb49afe4603b9630e4d9606ec98d86f0547c625ab/log2_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..31f2d0b252bbfb7b83d2db7dbaa11b3888e24953 --- /dev/null +++ b/shared/package-files/a5/a5198f3f372f3714a49a853bb49afe4603b9630e4d9606ec98d86f0547c625ab/log2_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_log2 : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/a5/a51ccebdadce4ff0af652e9951cac980500695f06b44064f3e3b6e00beaac396/exponential_ops.h b/shared/package-files/a5/a51ccebdadce4ff0af652e9951cac980500695f06b44064f3e3b6e00beaac396/exponential_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d9b8010303d4c6a2cd9b169cb5332f298e83fe05 --- /dev/null +++ b/shared/package-files/a5/a51ccebdadce4ff0af652e9951cac980500695f06b44064f3e3b6e00beaac396/exponential_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API exponential_ { + using schema = at::Tensor & (at::Tensor &, double, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::exponential_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self, double lambd, ::std::optional generator); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, double lambd, ::std::optional generator); +}; + +struct TORCH_API exponential_out { + using schema = at::Tensor & (const at::Tensor &, double, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::exponential"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "exponential.out(Tensor self, float lambd=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, double lambd, ::std::optional generator, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double lambd, ::std::optional generator, at::Tensor & out); +}; + +struct TORCH_API exponential { + using schema = at::Tensor (const at::Tensor &, double, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::exponential"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "exponential(Tensor self, float lambd=1, *, Generator? generator=None) -> Tensor"; + static at::Tensor call(const at::Tensor & self, double lambd, ::std::optional generator); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, double lambd, ::std::optional generator); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/a5/a522d18641eec5775bbbb6b5c84cd03dba2616b7a93af7e2296a60e0736a118c/lower_to_qnnpack.py b/shared/package-files/a5/a522d18641eec5775bbbb6b5c84cd03dba2616b7a93af7e2296a60e0736a118c/lower_to_qnnpack.py new file mode 100644 index 0000000000000000000000000000000000000000..f1fa3ecf3f5a3b2b5dc67d769853f8424bae7efb --- /dev/null +++ b/shared/package-files/a5/a522d18641eec5775bbbb6b5c84cd03dba2616b7a93af7e2296a60e0736a118c/lower_to_qnnpack.py @@ -0,0 +1,18 @@ +from torch.ao.quantization.qconfig import QConfigAny +from torch.fx import GraphModule + +from ._lower_to_native_backend import _lower_to_native_backend + + +__all__ = ["lower_to_qnnpack"] + + +def lower_to_qnnpack( + model: GraphModule, + qconfig_map: dict[str, QConfigAny], + node_name_to_scope: dict[str, tuple[str, type]], +) -> GraphModule: + """Lower a quantized reference model (with reference quantized operator patterns) + to qnnpack + """ + return _lower_to_native_backend(model, qconfig_map, node_name_to_scope) diff --git a/shared/package-files/a5/a52397b91f495edb5ebadb36ea7798c80cb28613b2f76873eef5fbe08cf9a9b8/symbolic_opset20.py b/shared/package-files/a5/a52397b91f495edb5ebadb36ea7798c80cb28613b2f76873eef5fbe08cf9a9b8/symbolic_opset20.py new file mode 100644 index 0000000000000000000000000000000000000000..d96f770ca11e26db582768332b0860c7c94558ae --- /dev/null +++ b/shared/package-files/a5/a52397b91f495edb5ebadb36ea7798c80cb28613b2f76873eef5fbe08cf9a9b8/symbolic_opset20.py @@ -0,0 +1,92 @@ +# mypy: allow-untyped-defs +"""This file exports ONNX ops for opset 20. + +Note [ONNX Operators that are added/updated in opset 20] + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +https://github.com/onnx/onnx/blob/main/docs/Changelog.md#version-20-of-the-default-onnx-operator-set +New operators: + AffineGrid + ConstantOfShape + DFT + Gelu + GridSample + ImageDecoder + IsInf + IsNaN + ReduceMax + ReduceMin + RegexFullMatch + StringConcat + StringSplit +""" + +import functools + +import torch.nn.functional as F +from torch import _C +from torch.onnx import symbolic_helper +from torch.onnx._internal import jit_utils, registration + + +# EDITING THIS FILE? READ THIS FIRST! +# see Note [Edit Symbolic Files] in symbolic_helper.py + +__all__ = ["_grid_sampler", "_affine_grid_generator", "gelu"] + + +def convert_grid_sample_mode(mode_s): + return ( + "linear" if mode_s == "bilinear" else "cubic" if mode_s == "bicubic" else mode_s + ) + + +_onnx_symbolic = functools.partial(registration.onnx_symbolic, opset=20) + + +@_onnx_symbolic("aten::grid_sampler") +@symbolic_helper.parse_args("v", "v", "i", "i", "b") +def _grid_sampler( + g: jit_utils.GraphContext, + input: _C.Value, + grid: _C.Value, + mode_enum: int, + padding_mode_enum: int, + align_corners: bool, +): + mode_s = {v: k for k, v in F.GRID_SAMPLE_INTERPOLATION_MODES.items()}[mode_enum] # type: ignore[call-arg, index] + # mode string changes at https://onnx.ai/onnx/operators/text_diff_GridSample_16_20.html + mode_s = convert_grid_sample_mode(mode_s) + padding_mode_s = {v: k for k, v in F.GRID_SAMPLE_PADDING_MODES.items()}[ # type: ignore[call-arg, index] + padding_mode_enum # type: ignore[index] + ] + return g.op( + "GridSample", + input, + grid, + align_corners_i=int(align_corners), + mode_s=mode_s, + padding_mode_s=padding_mode_s, + ) + + +@_onnx_symbolic("aten::affine_grid_generator") +@symbolic_helper.parse_args("v", "v", "b") +def _affine_grid_generator( + g: jit_utils.GraphContext, + theta: _C.Value, + size: _C.Value, + align_corners: bool, +): + return g.op( + "AffineGrid", + theta, + size, + align_corners_i=int(align_corners), + ) + + +@_onnx_symbolic("aten::gelu") +@symbolic_helper.parse_args("v", "s") +def gelu(g: jit_utils.GraphContext, self: _C.Value, approximate: str = "none"): + return g.op("Gelu", self, approximate_s=approximate) diff --git a/shared/package-files/a5/a5249a49c22f9bd46000f3b642310e0788f3de6dc739a3baa500fbf8171ef55c/remote_device.cpython-311.pyc b/shared/package-files/a5/a5249a49c22f9bd46000f3b642310e0788f3de6dc739a3baa500fbf8171ef55c/remote_device.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d6ab3dd4f0a84df3c9071385eb317f255daa7e6 Binary files /dev/null and b/shared/package-files/a5/a5249a49c22f9bd46000f3b642310e0788f3de6dc739a3baa500fbf8171ef55c/remote_device.cpython-311.pyc differ diff --git a/shared/package-files/a5/a52cb69e1487a7c4a3f4389a3f8fcf2e785b17b7755c70baf08af17bf5d96199/_sparse_bsc_tensor_unsafe_ops.h b/shared/package-files/a5/a52cb69e1487a7c4a3f4389a3f8fcf2e785b17b7755c70baf08af17bf5d96199/_sparse_bsc_tensor_unsafe_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..157c8b206f05bfd50ec9854c82a03c23877a82c9 --- /dev/null +++ b/shared/package-files/a5/a52cb69e1487a7c4a3f4389a3f8fcf2e785b17b7755c70baf08af17bf5d96199/_sparse_bsc_tensor_unsafe_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_bsc_tensor_unsafe { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, ::std::optional, ::std::optional, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_sparse_bsc_tensor_unsafe"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_sparse_bsc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor"; + static at::Tensor call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/a5/a531107f9acb7e2694fd43178279ec4b5dcd1f91fd16d1e075e88db96fcd9076/cuda_fp4.h b/shared/package-files/a5/a531107f9acb7e2694fd43178279ec4b5dcd1f91fd16d1e075e88db96fcd9076/cuda_fp4.h new file mode 100644 index 0000000000000000000000000000000000000000..7b291e7b78610171e9068b39ed5c503b35f45ad4 --- /dev/null +++ b/shared/package-files/a5/a531107f9acb7e2694fd43178279ec4b5dcd1f91fd16d1e075e88db96fcd9076/cuda_fp4.h @@ -0,0 +1,357 @@ +/* + * Copyright 2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#ifndef __CUDA_FP4_H__ +#define __CUDA_FP4_H__ + +/* Set up function decorations */ +#if defined(__CUDACC__) +#define __CUDA_FP4_DECL__ static __device__ __inline__ +#define __CUDA_HOSTDEVICE_FP4__ __host__ __device__ +#define __CUDA_HOSTDEVICE_FP4_DECL__ static __host__ __device__ __inline__ +#else /* !defined(__CUDACC__) */ +#if defined(__GNUC__) +#define __CUDA_HOSTDEVICE_FP4_DECL__ static __attribute__((unused)) +#else +#define __CUDA_HOSTDEVICE_FP4_DECL__ static +#endif /* defined(__GNUC__) */ +#define __CUDA_HOSTDEVICE_FP4__ +#endif /* defined(__CUDACC_) */ + +#if !defined(_MSC_VER) && __cplusplus >= 201103L +#define __CPP_VERSION_AT_LEAST_11_FP4 +#elif _MSC_FULL_VER >= 190024210 && _MSVC_LANG >= 201103L +#define __CPP_VERSION_AT_LEAST_11_FP4 +#endif + +/* bring in fp6 types infrastructure and dependencies */ +#include "cuda_fp6.h" + +/** + * \defgroup CUDA_MATH_INTRINSIC_FP4 FP4 Intrinsics + * This section describes fp4 intrinsic functions. + * To use these functions, include the header file \p cuda_fp4.h in your + * program. + * + * \note Most of the operations defined here benefit from native HW support + * when compiled for specific GPU targets (e.g. devices of compute capability 10.0a), + * other targets use emulation path. + * + * The following macros are available to help users selectively enable/disable + * various definitions present in the header file: + * - \p __CUDA_NO_FP4_CONVERSIONS__ - If defined, this macro will prevent any + * use of the C++ type conversions (converting constructors and conversion + * operators) defined in the header. + * - \p __CUDA_NO_FP4_CONVERSION_OPERATORS__ - If defined, this macro will + * prevent any use of the C++ conversion operators from \p fp4 to other types. + */ + +/** + * \defgroup CUDA_MATH_FP4_MISC FP4 Conversion and Data Movement + * \ingroup CUDA_MATH_INTRINSIC_FP4 + * To use these functions, include the header file \p cuda_fp4.h in your + * program. + */ + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief 8-bit \p unsigned \p integer + * type abstraction used for \p fp4 floating-point + * numbers storage. + */ +typedef __nv_fp8_storage_t __nv_fp4_storage_t; + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief 8-bit \p unsigned \p integer + * type abstraction used for storage of pairs of + * \p fp4 floating-point numbers. + */ +typedef __nv_fp8_storage_t __nv_fp4x2_storage_t; + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief 16-bit \p unsigned \p integer + * type abstraction used for storage of tetrads of + * \p fp4 floating-point numbers. + */ +typedef __nv_fp8x2_storage_t __nv_fp4x4_storage_t; + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Enumerates the possible + * interpretations of the 4-bit values when referring to them as + * \p fp4 types. + */ +typedef enum __nv_fp4_interpretation_t { + __NV_E2M1, /**< Stands for \p fp4 numbers of \p e2m1 kind. */ +} __nv_fp4_interpretation_t; + +/* Forward-declaration of C-style APIs */ + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input \p double precision \p x to \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input \p x to \p fp4 type of the kind specified by + * \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4_storage_t +__nv_cvt_double_to_fp4(const double x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input vector of two \p double precision numbers packed + * in \p double2 \p x into a vector of two values of \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input vector \p x to a vector of two \p fp4 values of the + * kind specified by \p fp4_interpretation parameter, using + * rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4x2_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4x2_storage_t +__nv_cvt_double2_to_fp4x2(const double2 x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input \p single precision \p x to \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input \p x to \p fp4 type of the kind specified by + * \p fp4_interpretation parameter, using + * rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4_storage_t +__nv_cvt_float_to_fp4(const float x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input vector of two \p single precision numbers packed + * in \p float2 \p x into a vector of two values of \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input vector \p x to a vector of two \p fp4 values of the + * kind specified by \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4x2_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4x2_storage_t +__nv_cvt_float2_to_fp4x2(const float2 x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input \p half precision \p x to \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input \p x to \p fp4 type of the kind specified by + * \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4_storage_t +__nv_cvt_halfraw_to_fp4(const __half_raw x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input vector of two \p half precision numbers packed + * in \p __half2_raw \p x into a vector of two values of \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input vector \p x to a vector of two \p fp4 values of the + * kind specified by \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4x2_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4x2_storage_t __nv_cvt_halfraw2_to_fp4x2( + const __half2_raw x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input \p nv_bfloat16 precision \p x to \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input \p x to \p fp4 type of the kind specified by + * \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4_storage_t __nv_cvt_bfloat16raw_to_fp4( + const __nv_bfloat16_raw x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input vector of two \p nv_bfloat16 precision numbers packed + * in \p __nv_bfloat162_raw \p x into a vector of two values of \p fp4 type of the + * requested kind using specified rounding mode and saturating + * the out-of-range values. + * + * \details Converts input vector \p x to a vector of two \p fp4 values of the + * kind specified by \p fp4_interpretation parameter, + * using rounding mode specified by \p rounding parameter. + * Large out-of-range values saturate to MAXNORM of the same sign. + * \p NaN input values result in positive MAXNORM. + * + * \returns + * - The \p __nv_fp4x2_storage_t value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __nv_fp4x2_storage_t +__nv_cvt_bfloat16raw2_to_fp4x2( + const __nv_bfloat162_raw x, + const __nv_fp4_interpretation_t fp4_interpretation, + const enum cudaRoundMode rounding); + +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input \p fp4 \p x of the specified kind + * to \p half precision. + * + * \details Converts input \p x of \p fp4 type of the kind specified by + * \p fp4_interpretation parameter + * to \p half precision. + * + * \returns + * - The \p __half_raw value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __half_raw +__nv_cvt_fp4_to_halfraw(const __nv_fp4_storage_t x, + const __nv_fp4_interpretation_t fp4_interpretation); +/** + * \ingroup CUDA_MATH_FP4_MISC + * \brief Converts input vector of two \p fp4 values of the specified kind + * to a vector of two \p half precision values packed in \p __half2_raw + * structure. + * + * \details Converts input vector \p x of \p fp4 type of the kind specified by + * \p fp4_interpretation parameter + * to a vector of two \p half precision values and returns as \p __half2_raw + * structure. + * + * \returns + * - The \p __half2_raw value holds the result of conversion. + */ +__CUDA_HOSTDEVICE_FP4_DECL__ __half2_raw +__nv_cvt_fp4x2_to_halfraw2(const __nv_fp4x2_storage_t x, + const __nv_fp4_interpretation_t fp4_interpretation); + +#if defined(__cplusplus) + +#define __CUDA_FP4_TYPES_EXIST__ + +/* Forward-declaration of structures defined in "cuda_fp4.hpp" */ +struct __nv_fp4_e2m1; +struct __nv_fp4x2_e2m1; +struct __nv_fp4x4_e2m1; + +#endif /* defined(__cplusplus) */ + +#include "cuda_fp4.hpp" + +#undef __CUDA_FP4_DECL__ +#undef __CUDA_HOSTDEVICE_FP4__ +#undef __CUDA_HOSTDEVICE_FP4_DECL__ + +#if defined(__CPP_VERSION_AT_LEAST_11_FP4) +#undef __CPP_VERSION_AT_LEAST_11_FP4 +#endif /* defined(__CPP_VERSION_AT_LEAST_11_FP4) */ + +#endif /* end of include guard: __CUDA_FP4_H__ */ diff --git a/shared/package-files/a5/a531f091a8b564901cb35431f7720e4a6ddc9d6a4db599668f65cc5892eff7f9/sparse_csr_tensor_native.h b/shared/package-files/a5/a531f091a8b564901cb35431f7720e4a6ddc9d6a4db599668f65cc5892eff7f9/sparse_csr_tensor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e623bb1bd1883bbb3a47ff1a30983dc0690d7ae4 --- /dev/null +++ b/shared/package-files/a5/a531f091a8b564901cb35431f7720e4a6ddc9d6a4db599668f65cc5892eff7f9/sparse_csr_tensor_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +} // namespace native +} // namespace at diff --git a/shared/package-files/a5/a534d8fbad5af8a53763a353c6912edd511a3cfc0a090e1c8d7d0a0c470552ad/transformer.h b/shared/package-files/a5/a534d8fbad5af8a53763a353c6912edd511a3cfc0a090e1c8d7d0a0c470552ad/transformer.h new file mode 100644 index 0000000000000000000000000000000000000000..2f22f087bf518bad86dd198fcc7d46073f6de435 --- /dev/null +++ b/shared/package-files/a5/a534d8fbad5af8a53763a353c6912edd511a3cfc0a090e1c8d7d0a0c470552ad/transformer.h @@ -0,0 +1,141 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include + +namespace torch::nn { + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Transformer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/// A transformer model. User is able to modify the attributes as needed. The +/// architecture is based on the paper "Attention Is All You Need". Ashish +/// Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N +/// Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. +/// In Advances in Neural Information Processing Systems, pages 6000-6010. +/// +/// See https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html to +/// learn about the exact behavior of this transformer model +/// +/// See the documentation for `torch::nn::Transformer` class to learn what +/// constructor arguments are supported for this encoder layer model +/// +/// Example: +/// ``` +/// Transformer trans(TransformerOptions(512, 8)); +/// ``` +class TORCH_API TransformerImpl : public Cloneable { + public: + explicit TransformerImpl(TransformerOptions options_); + + /// forward function for Transformer Module + /// Args: + /// src: the sequence to the encoder (required). + /// tgt: the sequence to the decoder (required). + /// src_mask: the additive mask for the src sequence (optional). + /// tgt_mask: the additive mask for the tgt sequence (optional). + /// memory_mask: the additive mask for the encoder output (optional). + /// src_key_padding_mask: the ByteTensor mask for src keys per batch + /// (optional). tgt_key_padding_mask: the ByteTensor mask for tgt keys per + /// batch (optional). memory_key_padding_mask: the ByteTensor mask for + /// memory keys per batch (optional). + /// + /// Shape: + /// src: `(S, N, E)` + /// tgt: `(T, N, E)` + /// src_mask: `(S, S)` + /// tgt_mask: `(T, T)` + /// memory_mask: `(T, S)` + /// src_key_padding_mask: `(N, S)` + /// tgt_key_padding_mask: `(N, T)` + /// memory_key_padding_mask: `(N, S)` + /// + /// Note: + /// [src/tgt/memory]_mask ensures that position i is allowed to attend the + /// unmasked positions. If a ByteTensor is provided, the non-zero + /// positions are not allowed to attend while the zero positions will be + /// unchanged. If a BoolTensor is provided, positions with `True` are not + /// allowed to attend while `False` values will be unchanged. If a + /// FloatTensor is provided, it will be added to the attention weight. + /// + /// [src/tgt/memory]_key_padding_mask provides specified elements in the + /// key to be ignored by the attention. If a ByteTensor is provided, the + /// non-zero positions will be ignored while the zero positions will be + /// unchanged. If a BoolTensor is provided, the positions with the value + /// of `True` will be ignored while the position with the value of `False` + /// will be unchanged. + /// + /// output: `(T, N, E)` + /// + /// Note: + /// Due to the multi-head attention architecture in the transformer model, + /// the output sequence length of a transformer is same as the input + /// sequence (i.e. target) length of the decode. + /// + /// where + /// S is the source sequence length, + /// T is the target sequence length, + /// N is the batch size, + /// E is the feature number. + Tensor forward( + const Tensor& src, + const Tensor& tgt, + const Tensor& src_mask = {}, + const Tensor& tgt_mask = {}, + const Tensor& memory_mask = {}, + const Tensor& src_key_padding_mask = {}, + const Tensor& tgt_key_padding_mask = {}, + const Tensor& memory_key_padding_mask = {}); + + void reset() override; + + void reset_parameters(); + + /// Generate a square mask for the sequence. + /// The masked positions are filled with `-inf` in float type. + /// Unmasked positions are filled with `0.0` in float type. + /// Note: + /// 1. This function will always return a CPU tensor. + /// 2. This function requires the platform support IEEE754, since `-inf` is + /// guaranteed to + /// be valid only when IEEE754 is supported. If the platform doesn't + /// support IEEE754, this function will fill the mask with the smallest + /// float number instead of `-inf`, a one time warning will pop up as + /// well. + static Tensor generate_square_subsequent_mask(int64_t sz); + + protected: + FORWARD_HAS_DEFAULT_ARGS( + {2, AnyValue(Tensor())}, + {3, AnyValue(Tensor())}, + {4, AnyValue(Tensor())}, + {5, AnyValue(Tensor())}, + {6, AnyValue(Tensor())}, + {7, AnyValue(Tensor())}) + + public: + /// options with which this `Transformer` was constructed + TransformerOptions options; + + /// encoder module + AnyModule encoder; + + /// decoder module + AnyModule decoder; +}; + +/// A `ModuleHolder` subclass for `TransformerImpl`. +/// See the documentation for `TransformerImpl` class to learn what +/// methods it provides, and examples of how to use `Transformer` with +/// `torch::nn::TransformerOptions`. +/// See the documentation for `ModuleHolder` to learn about PyTorch's +/// module storage semantics. +TORCH_MODULE(Transformer); + +} // namespace torch::nn diff --git a/shared/package-files/a5/a539b857e4a8f0789cab9d1353403039ae60073010dc6f8d62b3be9817bd9c58/package.py b/shared/package-files/a5/a539b857e4a8f0789cab9d1353403039ae60073010dc6f8d62b3be9817bd9c58/package.py new file mode 100644 index 0000000000000000000000000000000000000000..b139f7f1f02f612e8d23d37216dfe11cb50c1015 --- /dev/null +++ b/shared/package-files/a5/a539b857e4a8f0789cab9d1353403039ae60073010dc6f8d62b3be9817bd9c58/package.py @@ -0,0 +1,310 @@ +import io +import json +import logging +import os +import tempfile +import zipfile +from pathlib import Path +from typing import Any, IO, Optional, Union +from typing_extensions import Self + +import torch +import torch._inductor +import torch.utils._pytree as pytree +from torch._inductor import config +from torch._inductor.cpp_builder import BuildOptionsBase, CppBuilder +from torch.export._tree_utils import reorder_kwargs +from torch.types import FileLike + +from .pt2_archive_constants import ( + AOTINDUCTOR_DIR, + ARCHIVE_VERSION, + CONSTANTS_DIR, + CUSTOM_OBJ_FILENAME_PREFIX, +) + + +log = logging.getLogger(__name__) + + +class PT2ArchiveWriter: + def __init__(self, archive_path: FileLike) -> None: + self.archive_path: FileLike = archive_path + self.archive_file: Optional[zipfile.ZipFile] = None + + def __enter__(self) -> Self: + assert self.archive_file is None + self.archive_file = zipfile.ZipFile( + self.archive_path, "w", compression=zipfile.ZIP_STORED + ) + self.writestr("version", str(ARCHIVE_VERSION)) + self.writestr("archive_format", "pt2") + return self + + def __exit__(self, *args) -> None: # type: ignore[no-untyped-def] + assert self.archive_file is not None + self.archive_file.close() + self.archive_file = None + return None + + def writestr(self, name: str, data: Union[bytes, str]) -> None: + assert self.archive_file is not None + self.archive_file.writestr(name, data) + + def write_file(self, name: str, file_path: str) -> None: + """ + Copy a file into the archive. + name: The destination file inside the archive. + file_path: The source file on disk. + """ + assert Path(file_path).is_file(), f"{file_path} is not a valid file path" + assert self.archive_file is not None + self.archive_file.write(file_path, arcname=name) + + +class PT2ArchiveReader: + def __init__(self, archive_path: str) -> None: + self.archive_path: str = archive_path + self.archive_file: Optional[zipfile.ZipFile] = None + + def __enter__(self) -> Self: + self.archive_file = zipfile.ZipFile( + self.archive_path, "r", compression=zipfile.ZIP_STORED + ) + return self + + def __exit__(self, *args) -> None: # type: ignore[no-untyped-def] + if self.archive_file is not None: + self.archive_file.close() + return None + + def read(self, name: str) -> bytes: + assert self.archive_file is not None + return self.archive_file.read(name) + + def extract_to_path(self, member: str, path: str) -> str: + assert self.archive_file is not None + return self.archive_file.extract(member, path) + + def extractall(self, path: str) -> None: + assert self.archive_file is not None + self.archive_file.extractall(path) + + def get_file_names(self) -> list[str]: + assert self.archive_file is not None + return self.archive_file.namelist() + + +def compile_so(aoti_dir: str, aoti_files: list[str], so_path: str) -> str: + def get_aoti_file_with_suffix(suffix: str) -> str: + for file in aoti_files: + if file.endswith(suffix): + return file + raise RuntimeError(f"Unable to find file with suffix {suffix}") + + # Compile all the files into a .so + cpp_file = os.path.join(aoti_dir, get_aoti_file_with_suffix(".cpp")) + consts_o = os.path.join(aoti_dir, get_aoti_file_with_suffix(".o")) + + file_name = os.path.splitext(cpp_file)[0] + + # Parse compile flags and build the .o file + with open(file_name + "_compile_flags.json") as f: + compile_flags = json.load(f) + + compile_options = BuildOptionsBase( + **compile_flags, use_relative_path=config.is_fbcode() + ) + object_builder = CppBuilder( + name=file_name, + sources=cpp_file, + BuildOption=compile_options, + ) + output_o = object_builder.get_target_file_path() + object_builder.build() + + # Parse linker flags and build the .so file + with open(file_name + "_linker_flags.json") as f: + linker_flags = json.load(f) + + linker_options = BuildOptionsBase( + **linker_flags, use_relative_path=config.is_fbcode() + ) + so_builder = CppBuilder( + name=os.path.split(so_path)[-1], + sources=[output_o, consts_o], + BuildOption=linker_options, + output_dir=so_path, + ) + output_so = so_builder.get_target_file_path() + so_builder.build() + + # mmapped weights + serialized_weights_filename = file_name + "_serialized_weights.bin" + if serialized_weights_filename in aoti_files: + with open(serialized_weights_filename, "rb") as f_weights: + serialized_weights = f_weights.read() + + with open(output_so, "a+b") as f_so: + so_size = f_so.tell() + # Page align the weights + f_so.write(b" " * (16384 - so_size % 16384)) + f_so.write(serialized_weights) + + return output_so + + +def package_aoti( + archive_file: FileLike, + aoti_files: Union[list[str], dict[str, list[str]]], +) -> FileLike: + """ + Saves the AOTInductor generated files to the PT2Archive format. + + Args: + archive_file: The file name to save the package to. + aoti_files: This can either be a singular path to a directory containing + the AOTInductor files, or a dictionary mapping the model name to the + path to its AOTInductor generated files. + """ + if isinstance(aoti_files, list): + aoti_files = {"model": aoti_files} + + assert isinstance(aoti_files, dict), ( + "Please pass a list of AOTI generated files to be packaged or " + "a dictionary mapping model names to their list of AOTI generated " + "files. You can get this list of files through calling " + "`torch._inductor.aot_compile(..., options={aot_inductor.package=True})`" + ) + assert ( + isinstance(archive_file, (io.IOBase, IO)) + and archive_file.writable() + and archive_file.seekable() + ) or ( + isinstance(archive_file, (str, os.PathLike)) + and os.fspath(archive_file).endswith(".pt2") + ), ( + f"Expect archive file to be a file ending in .pt2, or is a buffer. Instead got {archive_file}" + ) + + # Save using the PT2 packaging format + # (https://docs.google.com/document/d/1jLPp8MN8Whs0-VW9PmJ93Yg02W85tpujvHrTa1pc5x8/edit#heading=h.v2y2jgnwc56a) + + with PT2ArchiveWriter(archive_file) as archive_writer: + for model_name, files in aoti_files.items(): + num_so_files = 0 + num_cpp_files = 0 + + for file in files: + if file == "": + continue + + if file.endswith(".so"): + num_so_files += 1 + if num_so_files > 1: + raise RuntimeError( + f"Multiple .so files found in {files}. " + "You might need to clear your cache " + "directory before calling aoti_compile again." + ) + if file.endswith(".cpp"): + num_cpp_files += 1 + if num_so_files > 1: + raise RuntimeError( + f"Multiple .cpp files found in {files}. " + "You might need to clear your cache " + "directory before calling aoti_compile again." + ) + + filename = os.path.basename(file) + if filename.startswith(CUSTOM_OBJ_FILENAME_PREFIX): + new_filepath = os.path.join(CONSTANTS_DIR, filename) + else: + new_filepath = os.path.join(AOTINDUCTOR_DIR, model_name, filename) + log.debug( + "Saving AOTI generated file %s to archive in %s", file, new_filepath + ) + archive_writer.write_file( + str(new_filepath), + file, + ) + + if isinstance(archive_file, (io.IOBase, IO)): + archive_file.seek(0) + return archive_file + + +class AOTICompiledModel: + """ + Callable AOT Inductor loaded model from a .pt2 + """ + + def __init__(self, loader: torch._C._aoti.AOTIModelPackageLoader) -> None: + self.loader = loader + + def __call__(self, *args, **kwargs): # type: ignore[no-untyped-def] + call_spec = self.loader.get_call_spec() # type: ignore[attr-defined] + in_spec = pytree.treespec_loads(call_spec[0]) + out_spec = pytree.treespec_loads(call_spec[1]) + flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, in_spec)))[0] + flat_inputs = [x for x in flat_inputs if isinstance(x, torch.Tensor)] + flat_outputs = self.loader.boxed_run(flat_inputs) # type: ignore[attr-defined] + return pytree.tree_unflatten(flat_outputs, out_spec) + + def get_metadata(self) -> dict[str, str]: + return self.loader.get_metadata() # type: ignore[attr-defined] + + def load_constants( + self, + constants_map: dict[str, torch.Tensor], + *, + check_full_update: bool, + ) -> None: + """ + Given a mapping of constant fqns to tensors, load the constants into the model. + You can use ``get_constant_fqns`` to get the list of constant fqns that + are needed in the compiled model. + + Args: + constants_map: A mapping of constant fqns to tensors. + check_full_update: Whether to add check to see if all the constants + are updated and have values. + """ + self.loader.load_constants(constants_map, False, check_full_update) # type: ignore[attr-defined] + + def get_constant_fqns(self) -> list[str]: + return self.loader.get_constant_fqns() # type: ignore[attr-defined] + + def __deepcopy__(self, memo: Optional[dict[Any, Any]]) -> "AOTICompiledModel": + log.warning( + "AOTICompiledModel deepcopy warning: AOTICompiledModel.loader is not deepcopied." + ) + return AOTICompiledModel(self.loader) # type: ignore[attr-defined] + + +def load_package( + path: FileLike, model_name: str = "model", run_single_threaded: bool = False +) -> AOTICompiledModel: # type: ignore[type-arg] + assert ( + isinstance(path, (io.IOBase, IO)) and path.readable() and path.seekable() + ) or (isinstance(path, (str, os.PathLike)) and os.fspath(path).endswith(".pt2")), ( + f"Unable to load package. Path must be a buffer or a file ending in .pt2. Instead got {path}" + ) + + if isinstance(path, (io.IOBase, IO)): + with tempfile.NamedTemporaryFile(suffix=".pt2") as f: + # TODO(angelayi): We shouldn't need to do this -- miniz should + # handle reading the buffer. This is just a temporary workaround + f.write(path.read()) + path.seek(0) + log.debug("Writing buffer to tmp file located at %s.", f.name) + loader = torch._C._aoti.AOTIModelPackageLoader( + f.name, model_name, run_single_threaded + ) # type: ignore[call-arg] + return AOTICompiledModel(loader) + + path = os.fspath(path) # AOTIModelPackageLoader expects (str, str) + loader = torch._C._aoti.AOTIModelPackageLoader( + path, model_name, run_single_threaded + ) # type: ignore[call-arg] + return AOTICompiledModel(loader) diff --git a/shared/package-files/a5/a54717e2500b6bae76b732f54cce94bece3b90c76a0b85906b4f2cd759c7e18d/generate.cpython-311.pyc b/shared/package-files/a5/a54717e2500b6bae76b732f54cce94bece3b90c76a0b85906b4f2cd759c7e18d/generate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31c209d397be1db0a05f20e742f0e508d1f5a0fd Binary files /dev/null and b/shared/package-files/a5/a54717e2500b6bae76b732f54cce94bece3b90c76a0b85906b4f2cd759c7e18d/generate.cpython-311.pyc differ diff --git a/shared/package-files/a5/a559a919a715fbd455535564f4f53e5d554b6d810004b98102b9532160dd861d/eigen.cpython-311.pyc b/shared/package-files/a5/a559a919a715fbd455535564f4f53e5d554b6d810004b98102b9532160dd861d/eigen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c424cb85b1af7977d8e43055e407a0eaef32b977 Binary files /dev/null and b/shared/package-files/a5/a559a919a715fbd455535564f4f53e5d554b6d810004b98102b9532160dd861d/eigen.cpython-311.pyc differ diff --git a/shared/package-files/a5/a55afed62f761b6bda141f26042695a1d1be325666579ddb38a78a2f40b22012/http.cpython-311.pyc b/shared/package-files/a5/a55afed62f761b6bda141f26042695a1d1be325666579ddb38a78a2f40b22012/http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e3dbdff27c65a921e8ffac8217ce48751744b4b Binary files /dev/null and b/shared/package-files/a5/a55afed62f761b6bda141f26042695a1d1be325666579ddb38a78a2f40b22012/http.cpython-311.pyc differ diff --git a/shared/package-files/a5/a55b9d31e51508d2b94359d5449fe68c47f8b6c2d71005c7ee0254938067d41e/_draft_export.py b/shared/package-files/a5/a55b9d31e51508d2b94359d5449fe68c47f8b6c2d71005c7ee0254938067d41e/_draft_export.py new file mode 100644 index 0000000000000000000000000000000000000000..d7b036a0a9561830fc039ebbd1fc9116f1eefa06 --- /dev/null +++ b/shared/package-files/a5/a55b9d31e51508d2b94359d5449fe68c47f8b6c2d71005c7ee0254938067d41e/_draft_export.py @@ -0,0 +1,476 @@ +import getpass +import json +import logging +import os +import re +import tempfile +from dataclasses import dataclass +from enum import IntEnum +from typing import Any, Callable, Optional, Union + +import torch +import torch._logging._internal +import torch._logging.structured +from torch._export.passes.insert_custom_op_guards import insert_custom_op_guards +from torch.export import ExportedProgram +from torch.export._trace import _export +from torch.export.dynamic_shapes import refine_dynamic_shapes_from_suggested_fixes + + +log = logging.getLogger(__name__) + + +class FailureType(IntEnum): + MISSING_FAKE_KERNEL = 1 + DATA_DEPENDENT_ERROR = 2 + CONSTRAINT_VIOLATION_ERROR = 3 + MISMATCHED_FAKE_KERNEL = 4 + + def __str__(self) -> str: + return self.name + + +def prettify_stack(stack: list[dict[str, str]], str_to_filename: dict[int, str]) -> str: + res = "" + for frame in stack: + if frame["filename"] not in str_to_filename: + continue + + res += f""" + File {str_to_filename[frame['filename']]}, lineno {frame['line']}, in {frame['name']}""" # type: ignore[index] + + res += f"\n {stack[-1]['loc']}" + return res + + +def prettify_frame_locals( + loc: str, locals: dict[str, Any], symbols: dict[str, Any] +) -> str: + local_str = "\n".join(f" {k}: {v}" for k, v in locals.items()) + res = f""" + Locals: +{local_str} +""" + if any(v is not None for v in symbols.values()): + symbol_str = "\n".join( + f" {k}: {v}" for k, v in symbols.items() if v is not None + ) + res += f""" + Symbols: +{symbol_str} +""" + return res + + +def get_loc(filename: str, lineno: int) -> Optional[str]: + try: + with open(filename) as f: + for i, line in enumerate(f): + if i == lineno - 1: + return line.strip() + except FileNotFoundError: + pass + return None + + +class FailureReport: + def __init__( + self, failure_type: FailureType, data: dict[str, Any], xfail: bool = False + ) -> None: + self.failure_type: FailureType = failure_type + self.data: dict[str, Any] = data + self.xfail: bool = xfail + + def __repr__(self) -> str: + return f"FailureReport(failure_type={self.failure_type}, xfail={self.xfail}, data={self.data})" + + def print(self, str_to_filename: dict[int, str]) -> str: + if self.failure_type == FailureType.MISSING_FAKE_KERNEL: + op = self.data["op"] + + return f"""Missing fake kernel. + torch.ops.{op} is missing a fake kernel implementation. + + Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a meta implementation. +""" # noqa: B950 + + elif self.failure_type == FailureType.CONSTRAINT_VIOLATION_ERROR: + locals_info = ( + prettify_frame_locals(**self.data["frame_locals"]) + if self.data["frame_locals"] + else "" + ) + return f"""Constraint violation error. + The specified input dynamic_shapes spec was found to be incorrect during tracing. + Specifically, this guard was added: {self.data["expr"]}, where {self.data["symbol_to_sources"]}. + This occurred at the following stacktrace: {prettify_stack(self.data["stack"], str_to_filename)}: + {locals_info} + Because of this, we have modified the dynamic shapes structure to be the + following. You can also use torch.export.Dim.AUTO instead to specify your + dynamic shapes, and we will automatically infer the dynamism for you. + ``` + dynamic_shapes = {self.data["new_dynamic_shapes"]} + ``` +""" + + elif self.failure_type == FailureType.DATA_DEPENDENT_ERROR: + locals_info = ( + prettify_frame_locals(**self.data["frame_locals"]) + if self.data["frame_locals"] + else "" + ) + return f"""Data dependent error. + When exporting, we were unable to evaluate the value of `{self.data["expr"]}`. + This was encountered {self.data["occurrences"]} times. + This occurred at the following user stacktrace: {prettify_stack(self.data["user_stack"], str_to_filename)} + {locals_info} + And the following framework stacktrace: {prettify_stack(self.data["stack"], str_to_filename)}\n + As a result, it was specialized to a constant (e.g. `{self.data["result"]}` in the 1st occurrence), and asserts were inserted into the graph. + + Please add `torch._check(...)` to the original code to assert this data-dependent assumption. + Please refer to https://docs.google.com/document/d/1kZ_BbB3JnoLbUZleDT6635dHs88ZVYId8jT-yTFgf3A/edit#heading=h.boi2xurpqa0o for more details. +""" # noqa: B950 + + elif self.failure_type == FailureType.MISMATCHED_FAKE_KERNEL: + op = self.data["op"] + reason = self.data["reason"] + return f"""Mismatched fake kernel. + torch.ops.{op} has a fake kernel implementation, but it has incorrect behavior, based on the real kernel. + The reason for the mismatch is: {reason}. + + Please refer to https://docs.google.com/document/d/1_W62p8WJOQQUzPsJYa7s701JXt0qf2OfLub2sbkHOaU/edit#heading=h.ahugy69p2jmz for more detailed instructions on how to write a fake implementation. +""" # noqa: B950 + + else: + raise ValueError(f"Unknown failure type: {self.failure_type}") + + +class DraftExportReport: + def __init__( + self, + failures: list[FailureReport], + str_to_filename: dict[int, str], + expressions_created: dict[int, dict[str, Any]], + ): + self.failures: list[FailureReport] = failures + self.str_to_filename = str_to_filename + self.expressions_created: dict[int, dict[str, Any]] = expressions_created + + def successful(self) -> bool: + return len(self.failures) == 0 or all( + failure.xfail for failure in self.failures + ) + + def __repr__(self) -> str: + return f"DraftExportReport({self.failures})" + + def __str__(self) -> str: + WARNING_COLOR = "\033[93m" + GREEN_COLOR = "\033[92m" + END_COLOR = "\033[0m" + + if self.successful(): + return f"""{GREEN_COLOR} +############################################################################################## +Congratuations: No issues are found during export, and it was able to soundly produce a graph. +You can now change back to torch.export.export() +############################################################################################## +{END_COLOR}""" + + error = f"""{WARNING_COLOR} +################################################################################################### +WARNING: {len(self.failures)} issue(s) found during export, and it was not able to soundly produce a graph. +Please follow the instructions to fix the errors. +################################################################################################### + +""" + + for i, failure in enumerate(self.failures): + error += f"{i + 1}. {failure.print(self.str_to_filename)}\n" + error += END_COLOR + return error + + def apply_suggested_fixes(self) -> None: + raise NotImplementedError("Not implemented yet") + + +@dataclass +class ExpressionCreatedNode: + result_id: int + argument_ids: list[int] + record: dict[str, object] + visited: bool = False + + +class LogRecord: + def __init__(self) -> None: + self.log_count: dict[int, int] = {} + self.logs: list[tuple[str, dict[str, Any]]] = [] + + def _hash(self, element: tuple[str, dict[str, Any]]) -> int: + key, data = element + + if key == "missing_fake_kernel": + return hash((key, data["op"])) + elif key == "mismatched_fake_kernel": + return hash((key, data["op"], data["reason"])) + elif key == "propagate_real_tensors_provenance": + return hash((key, json.dumps(data["user_stack"]))) + elif key == "create_unbacked_symbol": + return hash((key, json.dumps(data["user_stack"]))) + + return hash((key, json.dumps(data))) + + def try_add(self, element: tuple[str, dict[str, str]]) -> bool: + hash_value = self._hash(element) + if hash_value in self.log_count: + self.log_count[hash_value] += 1 + return False + + self.log_count[hash_value] = 1 + self.logs.append(element) + return True + + def get_log_count(self, element: tuple[str, dict[str, Any]]) -> int: + return self.log_count[self._hash(element)] + + +class CaptureStructuredTrace(torch._logging._internal.LazyTraceHandler): + def __init__(self) -> None: + self.specific_log_keys = [ + "str", + "exported_program", + "propagate_real_tensors_provenance", + "guard_added", + "missing_fake_kernel", + "mismatched_fake_kernel", + "expression_created", + "create_unbacked_symbol", + ] + self.log_record: LogRecord = LogRecord() + self.expression_created_logs: dict[int, ExpressionCreatedNode] = {} + self.symbol_to_expressions: dict[str, list[dict[str, Any]]] = {} + self.logger = logging.getLogger("torch.__trace") + self.prev_get_dtrace = False + + if root_dir := os.environ.get(torch._logging._internal.DTRACE_ENV_VAR): + super().__init__(root_dir) + else: + sanitized_username = re.sub(r'[\\/:*?"<>|]', "_", getpass.getuser()) + root_dir = os.path.join( + tempfile.gettempdir(), + "export_" + sanitized_username, + ) + super().__init__(root_dir) + + self.setFormatter(torch._logging._internal.TorchLogsFormatter(trace=True)) + + def __enter__(self) -> "CaptureStructuredTrace": + self.log_record = LogRecord() + self.expression_created_logs = {} + + # Remove the lazy trace handler if it exists + possible_lazy_trace_handlers = [ + handler + for handler in self.logger.handlers + if isinstance(handler, torch._logging._internal.LazyTraceHandler) + ] + for handler in possible_lazy_trace_handlers: + self.logger.removeHandler(handler) + + self.logger.addHandler(self) + self.prev_get_dtrace = torch._logging._internal.GET_DTRACE_STRUCTURED + torch._logging._internal.GET_DTRACE_STRUCTURED = True + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: # type: ignore[no-untyped-def] + self.log_record = LogRecord() + self.expression_created_logs = {} + self.logger.removeHandler(self) + torch._logging._internal.GET_DTRACE_STRUCTURED = self.prev_get_dtrace + self.prev_get_dtrace = False + + def emit(self, record: Any) -> None: + metadata = record.metadata + for key in self.specific_log_keys: + if key in metadata: + if self.log_record.try_add((key, metadata[key])): + if key == "expression_created": + # We don't want to log all expression_created logs, only + # the ones that are relevant to the + # guards/propagate_real_tensor + self.expression_created_logs[ + metadata[key]["result_id"] + ] = ExpressionCreatedNode( + metadata[key]["result_id"], + metadata[key].get("argument_ids", []), + record, + ) + continue + + elif key == "propagate_real_tensors_provenance": + + def _log_expression_created( + emit_func: Callable[[Any], None], sym_node_id: int + ) -> None: + # Log all the relevant expression_created logs + if sym_node_id is None: + return + if res := self.expression_created_logs.get( + sym_node_id, None + ): + # Don't log the expression if we have already + # printed it beforehand + if not res.visited: + res.visited = True + for arg in res.argument_ids: + _log_expression_created(emit_func, arg) + + emit_func(res.record) + + _log_expression_created( + super().emit, metadata[key].get("expr_node_id") + ) + + super().emit(record) + + +def draft_export( + mod: torch.nn.Module, + args: tuple[Any, ...], + kwargs: Optional[dict[str, Any]] = None, + *, + dynamic_shapes: Optional[Union[dict[str, Any], tuple[Any], list[Any]]] = None, + preserve_module_call_signature: tuple[str, ...] = (), + strict: bool = False, + pre_dispatch: bool = False, +) -> ExportedProgram: + kwargs = kwargs or {} + dynamic_shapes = dynamic_shapes or {} + + capture_structured_log = CaptureStructuredTrace() + + with torch._functorch.config.patch( + fake_tensor_propagate_real_tensors=True, + generate_fake_kernels_from_real_mismatches=True, + ), capture_structured_log: + try: + new_shapes = None + ep = _export( + mod, + args, + kwargs, + dynamic_shapes=dynamic_shapes, + strict=strict, + pre_dispatch=pre_dispatch, + preserve_module_call_signature=preserve_module_call_signature, + ) + except torch._dynamo.exc.UserError as exc: + new_shapes = refine_dynamic_shapes_from_suggested_fixes( + exc.msg, dynamic_shapes + ) + ep = _export( + mod, + args, + kwargs, + dynamic_shapes=new_shapes, + strict=strict, + pre_dispatch=pre_dispatch, + preserve_module_call_signature=preserve_module_call_signature, + ) + + torch._logging.dtrace_structured("exported_program", payload_fn=lambda: str(ep)) + + str_to_filename: dict[int, str] = {} + failures: list[FailureReport] = [] + custom_ops_logs: dict[ + Any, tuple[dict[str, Any], FailureType] + ] = {} # For adding in assertions before custom ops + expressions_created: dict[int, dict[str, Any]] = {} + + for log_name, log_contents in capture_structured_log.log_record.logs: + failure_type = None + + if log_name == "str": + str_to_filename[log_contents[1]] = log_contents[0] # type: ignore[index] + continue + + elif log_name == "propagate_real_tensors_provenance": + log_contents[ + "occurrences" + ] = capture_structured_log.log_record.get_log_count( + (log_name, log_contents) + ) + + failure_type = FailureType.DATA_DEPENDENT_ERROR + + elif log_name == "guard_added": + if new_shapes is None: + continue + + failure_type = FailureType.CONSTRAINT_VIOLATION_ERROR + if len(log_contents["symbol_to_sources"]) == 0: + # We only want to include guards added that are relevant to + # the symbolic shapes corresponding to the inputs which were + # specified in the dynamic_shapes arg. These have a source. + continue + + log_contents["new_dynamic_shapes"] = new_shapes + elif log_name == "missing_fake_kernel": + failure_type = FailureType.MISSING_FAKE_KERNEL + custom_ops_logs[log_contents["op"]] = (log_contents, failure_type) + + elif log_name == "mismatched_fake_kernel": + failure_type = FailureType.MISMATCHED_FAKE_KERNEL + custom_ops_logs[(log_contents["op"], log_contents["reason"])] = ( + log_contents, + failure_type, + ) + + else: + continue + + assert failure_type is not None + failures.append( + FailureReport( + failure_type, + log_contents, + ) + ) + + for k, v in capture_structured_log.expression_created_logs.items(): + if v.visited: + expressions_created[k] = v.record + + report = DraftExportReport(failures, str_to_filename, expressions_created) + + # Add asserts around custom ops + insert_custom_op_guards(ep.graph_module, list(custom_ops_logs.keys())) + + ep._report = report + if not report.successful(): + log_filename = capture_structured_log.stream.name + + log.warning( + """ +################################################################################################### +WARNING: %s issue(s) found during export, and it was not able to soundly produce a graph. +To view the report of failures in an html page, please run the command: + `tlparse %s --export` +Or, you can view the errors in python by inspecting `print(ep._report)`. +################################################################################################### + """, + len(report.failures), + log_filename, + ) + else: + log.info( + """ +############################################################################################## +Congratuations: No issues are found during export, and it was able to soundly produce a graph. +You can now change back to torch.export.export() +############################################################################################## + """ + ) + + return ep diff --git a/shared/package-files/a5/a56bc8724fc46d7d93c97cfdf9de4439bb784345a5b3cea4304ce51883cc4b1e/autodist.cpython-311.pyc b/shared/package-files/a5/a56bc8724fc46d7d93c97cfdf9de4439bb784345a5b3cea4304ce51883cc4b1e/autodist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49a04720485aa8ce61f17c0d43247289e8f73dbe Binary files /dev/null and b/shared/package-files/a5/a56bc8724fc46d7d93c97cfdf9de4439bb784345a5b3cea4304ce51883cc4b1e/autodist.cpython-311.pyc differ diff --git a/shared/package-files/a5/a56e96711e3cfd9a93ff92fbd19cf2511f3c9cd50a463d6f707939aa2619a889/topk.h b/shared/package-files/a5/a56e96711e3cfd9a93ff92fbd19cf2511f3c9cd50a463d6f707939aa2619a889/topk.h new file mode 100644 index 0000000000000000000000000000000000000000..fa4058ca61c31bcbffc4ec982b94cb1e334fa036 --- /dev/null +++ b/shared/package-files/a5/a56e96711e3cfd9a93ff92fbd19cf2511f3c9cd50a463d6f707939aa2619a889/topk.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple topk_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); +} +namespace symint { + template >> + ::std::tuple topk_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); + } +} + +// aten::topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple topk_outf(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); +} +namespace symint { + template >> + ::std::tuple topk_outf(const at::Tensor & self, int64_t k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); + } +} + +// aten::topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple topk_symint_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); +} +namespace symint { + template >> + ::std::tuple topk_out(at::Tensor & values, at::Tensor & indices, const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); + } +} + +// aten::topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) +inline ::std::tuple topk_symint_outf(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); +} +namespace symint { + template >> + ::std::tuple topk_outf(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices) { + return at::_ops::topk_values::call(self, k, dim, largest, sorted, values, indices); + } +} + +// aten::topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) +inline ::std::tuple topk(const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk::call(self, k, dim, largest, sorted); +} +namespace symint { + template >> + ::std::tuple topk(const at::Tensor & self, int64_t k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk::call(self, k, dim, largest, sorted); + } +} + +// aten::topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) +inline ::std::tuple topk_symint(const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk::call(self, k, dim, largest, sorted); +} +namespace symint { + template >> + ::std::tuple topk(const at::Tensor & self, c10::SymInt k, int64_t dim=-1, bool largest=true, bool sorted=true) { + return at::_ops::topk::call(self, k, dim, largest, sorted); + } +} + +} diff --git a/shared/package-files/a5/a57048bc672c64078d087e73324c43b79b88b8f0a68144d7884d0a7d4dfa6471/log_normal_native.h b/shared/package-files/a5/a57048bc672c64078d087e73324c43b79b88b8f0a68144d7884d0a7d4dfa6471/log_normal_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ebc939f68299dd79d6021b961cef29b21d1de22a --- /dev/null +++ b/shared/package-files/a5/a57048bc672c64078d087e73324c43b79b88b8f0a68144d7884d0a7d4dfa6471/log_normal_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor log_normal(const at::Tensor & self, double mean=1, double std=2, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & log_normal_out(const at::Tensor & self, double mean, double std, ::std::optional generator, at::Tensor & out); +TORCH_API at::Tensor & log_normal_(at::Tensor & self, double mean=1, double std=2, ::std::optional generator=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/a5/a571883746733bcce21304990e2be88a9292847d9804e05e3b8491669f7931cf/BFloat16-math.h b/shared/package-files/a5/a571883746733bcce21304990e2be88a9292847d9804e05e3b8491669f7931cf/BFloat16-math.h new file mode 100644 index 0000000000000000000000000000000000000000..8291cd744817c75ae7cf7dc47155948ca60823bb --- /dev/null +++ b/shared/package-files/a5/a571883746733bcce21304990e2be88a9292847d9804e05e3b8491669f7931cf/BFloat16-math.h @@ -0,0 +1,299 @@ +#pragma once + +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +namespace c10 { +template +struct is_reduced_floating_point + : std::integral_constant< + bool, + std::is_same_v || std::is_same_v> {}; + +template +constexpr bool is_reduced_floating_point_v = + is_reduced_floating_point::value; +} // namespace c10 + +namespace std { + +#if !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) +using c10::is_reduced_floating_point; +using c10::is_reduced_floating_point_v; +#endif // !defined(FBCODE_CAFFE2) && !defined(C10_NODEPRECATED) + +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T acos(T a) { + return std::acos(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T asin(T a) { + return std::asin(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T atan(T a) { + return std::atan(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T atanh(T a) { + return std::atanh(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T erf(T a) { + return std::erf(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T erfc(T a) { + return std::erfc(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T exp(T a) { + return std::exp(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T expm1(T a) { + return std::expm1(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline bool isfinite(T a) { + return std::isfinite(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T log(T a) { + return std::log(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T log10(T a) { + return std::log10(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T log1p(T a) { + return std::log1p(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T log2(T a) { + return std::log2(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T ceil(T a) { + return std::ceil(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T cos(T a) { + return std::cos(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T floor(T a) { + return std::floor(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T nearbyint(T a) { + return std::nearbyint(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T sin(T a) { + return std::sin(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T tan(T a) { + return std::tan(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T sinh(T a) { + return std::sinh(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T cosh(T a) { + return std::cosh(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T tanh(T a) { + return std::tanh(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T trunc(T a) { + return std::trunc(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T lgamma(T a) { + return std::lgamma(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T sqrt(T a) { + return std::sqrt(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T rsqrt(T a) { + return 1.0 / std::sqrt(float(a)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T abs(T a) { + return std::abs(float(a)); +} +#if defined(_MSC_VER) && defined(__CUDACC__) +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), float(b)); +} +#else +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T pow(T a, double b) { + return std::pow(float(a), b); +} +#endif +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T pow(T a, T b) { + return std::pow(float(a), float(b)); +} +template < + typename T, + typename std::enable_if_t, int> = 0> +inline T fmod(T a, T b) { + return std::fmod(float(a), float(b)); +} + +/* + The following function is inspired from the implementation in `musl` + Link to License: https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT + ---------------------------------------------------------------------- + Copyright © 2005-2020 Rich Felker, et al. + + 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. + ---------------------------------------------------------------------- + */ +template < + typename T, + typename std::enable_if_t, int> = 0> +C10_HOST_DEVICE inline T nextafter(T from, T to) { + // Reference: + // https://git.musl-libc.org/cgit/musl/tree/src/math/nextafter.c + using int_repr_t = uint16_t; + constexpr uint8_t bits = 16; + union { + T f; + int_repr_t i; + } ufrom = {from}, uto = {to}; + + // get a mask to get the sign bit i.e. MSB + int_repr_t sign_mask = int_repr_t{1} << (bits - 1); + + // short-circuit: if either is NaN, return NaN + if (from != from || to != to) { + return from + to; + } + + // short-circuit: if they are exactly the same. + if (ufrom.i == uto.i) { + return from; + } + + // mask the sign-bit to zero i.e. positive + // equivalent to abs(x) + int_repr_t abs_from = ufrom.i & ~sign_mask; + int_repr_t abs_to = uto.i & ~sign_mask; + if (abs_from == 0) { + // if both are zero but with different sign, + // preserve the sign of `to`. + if (abs_to == 0) { + return to; + } + // smallest subnormal with sign of `to`. + ufrom.i = (uto.i & sign_mask) | int_repr_t{1}; + return ufrom.f; + } + + // if abs(from) > abs(to) or sign(from) != sign(to) + if (abs_from > abs_to || ((ufrom.i ^ uto.i) & sign_mask)) { + ufrom.i--; + } else { + ufrom.i++; + } + + return ufrom.f; +} + +} // namespace std + +C10_CLANG_DIAGNOSTIC_POP() diff --git a/shared/package-files/a5/a5761bd5b6747e8cfc72b7cae3b1cc284d17883b4cdd70adf66ff8863306988f/vcfplugin.c.pysam.c b/shared/package-files/a5/a5761bd5b6747e8cfc72b7cae3b1cc284d17883b4cdd70adf66ff8863306988f/vcfplugin.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..f19bc9635d37b87f9e468bd7a5e0076954aa12dd --- /dev/null +++ b/shared/package-files/a5/a5761bd5b6747e8cfc72b7cae3b1cc284d17883b4cdd70adf66ff8863306988f/vcfplugin.c.pysam.c @@ -0,0 +1,847 @@ +#include "bcftools.pysam.h" + +/* vcfplugin.c -- plugin modules for operating on VCF/BCF files. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include "bcftools.h" +#include "vcmp.h" +#include "filter.h" + +#ifdef ENABLE_BCF_PLUGINS + +typedef struct _plugin_t plugin_t; + +/** + * Plugin API: + * ---------- + * const char *about(void) + * - short description used by 'bcftools plugin -lv' + * + * const char *usage(void) + * - longer description used by 'bcftools +name -h' + * + * int run(int argc, char **argv) + * - if implemented, the control is immediately handed over to the plugin, + * none of the init/process/destroy functions is called. Return 0 on + * success or non-zero value on error. + * + * int init(int argc, char **argv, bcf_hdr_t *in_hdr, bcf_hdr_t *out_hdr) + * - called once at startup, it initializes local variables. + * Return 1 to suppress normal VCF/BCF header output, -1 on critical + * errors, 0 otherwise. + * + * bcf1_t *process(bcf1_t *rec) + * - called for each VCF record, return NULL for no output + * + * void destroy(void) + * - called after all lines have been processed to clean up + */ +typedef void (*dl_version_f) (const char **, const char **); +typedef int (*dl_run_f) (int, char **); +typedef int (*dl_init_f) (int, char **, bcf_hdr_t *, bcf_hdr_t *); +typedef char* (*dl_about_f) (void); +typedef char* (*dl_usage_f) (void); +typedef bcf1_t* (*dl_process_f) (bcf1_t *); +typedef void (*dl_destroy_f) (void); + +struct _plugin_t +{ + int argc; + char *name, **argv; + dl_version_f version; + dl_run_f run; + dl_init_f init; + dl_about_f about; + dl_usage_f usage; + dl_process_f process; + dl_destroy_f destroy; + void *handle; +}; + + +struct _args_t; + +typedef struct _rm_tag_t +{ + char *key; + int hdr_id; + void (*handler)(struct _args_t *, bcf1_t *, struct _rm_tag_t *); +} +rm_tag_t; + +typedef struct +{ + char **cols; + int ncols, mcols; + char **als; + int nals, mals; + kstring_t line; + int rid, start, end; +} +annot_line_t; + +typedef struct _annot_col_t +{ + int icol, replace; + char *hdr_key; + int (*setter)(struct _args_t *, bcf1_t *, struct _annot_col_t *, void*); +} +annot_col_t; + +// Logic of the filters: include or exclude sites which match the filters? +#define FLT_INCLUDE 1 +#define FLT_EXCLUDE 2 + +typedef struct _args_t +{ + bcf_srs_t *files; + bcf_hdr_t *hdr, *hdr_out; + htsFile *out_fh; + int output_type, n_threads, clevel; + + filter_t *filter; + char *filter_str; + int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE + + plugin_t plugin; + int nplugin_paths; + char **plugin_paths; + + char **argv, *output_fname, *regions_list, *targets_list; + int argc, drop_header, verbose, record_cmd_line, plist_only; + char *index_fn; + int write_index; +} +args_t; + +char *msprintf(const char *fmt, ...); + +static void add_plugin_paths(args_t *args, const char *path) +{ + while (1) + { + size_t len = strcspn(path, HTS_PATH_SEPARATOR_STR); + + if ( len == 0 ) + { +#ifdef PLUGINPATH + add_plugin_paths(args, PLUGINPATH); +#endif + } + else + { + char *dir = (char *) malloc(len + 1); + strncpy(dir, path, len); + dir[len] = '\0'; + + struct stat st; + if ( stat(dir, &st) == 0 ) + { + args->plugin_paths = (char**) realloc(args->plugin_paths,sizeof(char*)*(args->nplugin_paths+1)); + args->plugin_paths[args->nplugin_paths] = dir; + args->nplugin_paths++; + if ( args->verbose > 1 && strcmp(".",dir) ) fprintf(bcftools_stderr, "plugin directory %s .. ok\n", dir); + } + else + { + if ( args->verbose > 1 ) fprintf(bcftools_stderr, "plugin directory %s .. %s\n", dir, strerror(errno)); + free(dir); + } + + } + + path += len; + if ( *path == HTS_PATH_SEPARATOR_CHAR ) path++; + else break; + } +} + +static void init_plugin_paths(args_t *args) +{ + if ( args->nplugin_paths!=-1 ) return; + + args->nplugin_paths = 0; + args->plugin_paths = NULL; + + char *path = getenv("BCFTOOLS_PLUGINS"); + add_plugin_paths(args, path ? path : ""); +} + +static void *dlopen_plugin(args_t *args, const char *fname) +{ + init_plugin_paths(args); + + void *handle; + char *tmp; + int is_absolute_path = 0; +#ifdef _WIN32 + // Windows accepts both forward slash (/) and backslash (\) as folder separator + // and can have any path prefixed by the drive letter and a colon (:). + if ( fname[0]=='/' || fname[0]=='\\') is_absolute_path = 1; + else if ( fname[0] && fname[1]==':' && (fname[2]=='/' || fname[2]=='\\') ) is_absolute_path = 1; +#else + if ( fname[0]=='/' ) is_absolute_path = 1; +#endif + + kstring_t err = {0,0,0}; + if ( !is_absolute_path ) + { + int i; + for (i=0; inplugin_paths; i++) + { + tmp = msprintf("%s/%s%s", args->plugin_paths[i], fname, PLUGIN_EXT); +#ifdef _WIN32 + handle = LoadLibraryA(tmp); +#else + handle = dlopen(tmp, RTLD_NOW); // valgrind complains about unfreed memory, not our problem though +#endif + if ( !handle ) +#ifdef _WIN32 + ksprintf(&err,"LoadLibraryA .. %lu\n", GetLastError()); +#else + ksprintf(&err,"%s:\n\tdlopen .. %s\n", tmp,dlerror()); +#endif + else if ( args->verbose > 1 ) + fprintf(bcftools_stderr,"%s:\n\tplugin open .. ok\n", tmp); + free(tmp); + if ( handle ) return handle; + } + } + +#ifdef _WIN32 + handle = LoadLibraryA(fname); +#else + handle = dlopen(fname, RTLD_NOW); +#endif + if ( !handle ) +#ifdef _WIN32 + ksprintf(&err,"LoadLibraryA .. %lu\n", GetLastError()); +#else + ksprintf(&err,"%s:\n\tdlopen .. %s\n", fname,dlerror()); +#endif + else if ( args->verbose > 1 ) + fprintf(bcftools_stderr,"%s:\n\tplugin open .. ok\n", fname); + + if ( !handle && (!args->plist_only || args->verbose>1) ) + fprintf(bcftools_stderr,"%s",err.s); + free(err.s); + + return handle; +} + +static void print_plugin_usage_hint(const char *name) +{ + if ( name ) + fprintf(bcftools_stderr, "\nThe bcftools plugin \"%s\" was not found or is not functional", name); + else + fprintf(bcftools_stderr, "\nNo functional bcftools plugins were found"); + if ( !getenv("BCFTOOLS_PLUGINS") ) + { + fprintf(bcftools_stderr,". The environment variable BCFTOOLS_PLUGINS is not set"); +#ifdef PLUGINPATH + fprintf(bcftools_stderr,"\nand no usable plugins were found in %s", PLUGINPATH); +#endif + fprintf(bcftools_stderr,".\n\n"); + } + else + { + fprintf(bcftools_stderr, + " in\n\tBCFTOOLS_PLUGINS=\"%s\".\n\n" + "- Is the plugin path correct?\n\n" + "- Run \"bcftools plugin -l\" or \"bcftools plugin -lvv\" for a list of available plugins.\n" + "\n", + getenv("BCFTOOLS_PLUGINS") + ); + } +} + +static int load_plugin(args_t *args, const char *fname, int exit_on_error, plugin_t *plugin) +{ + plugin->name = strdup(fname); + + plugin->handle = dlopen_plugin(args, fname); + if ( !plugin->handle ) + { + if ( exit_on_error ) + { + print_plugin_usage_hint(fname); + error("Could not load \"%s\".\n\n", fname); + } + return -1; + } + +#ifdef _WIN32 + plugin->init = (dl_init_f) GetProcAddress(plugin->handle, "init"); + if ( plugin->init && args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit .. ok\n"); + + plugin->run = (dl_run_f) GetProcAddress(plugin->handle, "run"); + if ( plugin->run && args->verbose > 1 ) fprintf(bcftools_stderr,"\trun .. ok\n"); + + if ( !plugin->init && !plugin->run ) + { + if ( exit_on_error ) error("Could not initialize %s, neither run or init found \n", plugin->name); + else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit/run .. not found\n"); + return -1; + } + + plugin->version = (dl_version_f) GetProcAddress(plugin->handle, "version"); + if ( !plugin->version ) + { + if ( exit_on_error ) error("Could not initialize %s: version string not found\n", plugin->name); + else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tversion .. not found\n"); + return -1; + } + + plugin->about = (dl_about_f) GetProcAddress(plugin->handle, "about"); + if ( !plugin->about ) + { + if ( exit_on_error ) error("Could not initialize %s: about string not found\n", plugin->name); + return -1; + } + + plugin->usage = (dl_about_f) GetProcAddress(plugin->handle, "usage"); + if ( !plugin->usage ) + plugin->usage = plugin->about; + + if ( plugin->run ) return 0; + + plugin->process = (dl_process_f) GetProcAddress(plugin->handle, "process"); + if ( !plugin->process ) + { + if ( exit_on_error ) error("Could not initialize %s: process method not found\n", plugin->name); + return -1; + } + + plugin->destroy = (dl_destroy_f) GetProcAddress(plugin->handle, "destroy"); + if ( !plugin->destroy ) + { + if ( exit_on_error ) error("Could not initialize %s: destroy method not found\n", plugin->name); + return -1; + } +#else + dlerror(); + plugin->init = (dl_init_f) dlsym(plugin->handle, "init"); + char *ret = dlerror(); + if ( ret ) + plugin->init = NULL; + else + if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit .. ok\n"); + + plugin->run = (dl_run_f) dlsym(plugin->handle, "run"); + ret = dlerror(); + if ( ret ) + plugin->run = NULL; + else + if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\trun .. ok\n"); + + if ( !plugin->init && !plugin->run ) + { + if ( exit_on_error ) error("Could not initialize %s, neither run or init found \n", plugin->name); + else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tinit/run .. not found\n"); + return -1; + } + + plugin->version = (dl_version_f) dlsym(plugin->handle, "version"); + ret = dlerror(); + if ( ret ) + { + if ( exit_on_error ) error("Could not initialize %s, version string not found\n", plugin->name); + else if ( args->verbose > 1 ) fprintf(bcftools_stderr,"\tversion .. not found\n"); + return -1; + } + + plugin->about = (dl_about_f) dlsym(plugin->handle, "about"); + ret = dlerror(); + if ( ret ) + { + if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret); + return -1; + } + + plugin->usage = (dl_about_f) dlsym(plugin->handle, "usage"); + ret = dlerror(); + if ( ret ) + plugin->usage = plugin->about; + + if ( plugin->run ) return 0; + + plugin->process = (dl_process_f) dlsym(plugin->handle, "process"); + ret = dlerror(); + if ( ret ) + { + if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret); + return -1; + } + + plugin->destroy = (dl_destroy_f) dlsym(plugin->handle, "destroy"); + ret = dlerror(); + if ( ret ) + { + if ( exit_on_error ) error("Could not initialize %s: %s\n", plugin->name, ret); + return -1; + } +#endif + + return 0; +} + +static void check_version(args_t *args) +{ + static int warned_bcftools = 0, warned_htslib = 0; + const char *bver, *hver; + args->plugin.version(&bver, &hver); + if ( strcmp(bver,bcftools_version()) && !warned_bcftools ) + { + fprintf(bcftools_stderr,"WARNING: bcftools version mismatch .. bcftools at %s, the plugin \"%s\" at %s\n", bcftools_version(),args->plugin.name,bver); + warned_bcftools = 1; + } + if ( strcmp(hver,hts_version()) && !warned_htslib ) + { + fprintf(bcftools_stderr,"WARNING: htslib version mismatch .. bcftools at %s, the plugin \"%s\" at %s\n", hts_version(),args->plugin.name,hver); + warned_htslib = 1; + } +} + +static void init_plugin(args_t *args) +{ + int ret = args->plugin.init(args->plugin.argc,args->plugin.argv,args->hdr,args->hdr_out); + if ( ret<0 ) error("The plugin exited with an error.\n"); + check_version(args); + args->drop_header += ret; +} + +static int cmp_plugin_name(const void *p1, const void *p2) +{ + plugin_t *a = (plugin_t*) p1; + plugin_t *b = (plugin_t*) p2; + return strcmp(a->name,b->name); +} + +// If args=NULL then returns the number of plugins available. Otherwise prints the +// plugins on bcftools_stdout and returns 0 on success. +static int list_plugins(args_t *args) +{ + plugin_t *plugins = NULL; + int nplugins = 0, mplugins = 0; + + int count_only = 0; + args_t _args; + if ( !args ) + { + memset(&_args,0,sizeof(_args)); + args = &_args; + args->nplugin_paths = -1; + count_only = 1; + } + init_plugin_paths(args); + + kstring_t str = {0,0,0}; + int plugin_ext_len = strlen(PLUGIN_EXT); + int i; + for (i=0; inplugin_paths; i++) + { + DIR *dp = opendir(args->plugin_paths[i]); + if ( dp==NULL ) continue; + + struct dirent *ep; + while ( (ep=readdir(dp)) ) + { + int len = strlen(ep->d_name); + if ( strcasecmp(PLUGIN_EXT,ep->d_name+len-plugin_ext_len) ) continue; + str.l = 0; + ksprintf(&str,"%s/%s", args->plugin_paths[i],ep->d_name); + hts_expand(plugin_t, nplugins+1, mplugins, plugins); + if ( load_plugin(args, str.s, 0, &plugins[nplugins]) < 0 ) continue; + nplugins++; + str.l = 0; + kputs(ep->d_name, &str); + int l = str.l - 1; + while ( l>=0 && str.s[l]!='.' ) l--; + if ( l>=0 ) str.s[l] = 0; + free(plugins[nplugins-1].name); + plugins[nplugins-1].name = strdup(str.s); // use a short name + } + closedir(dp); + } + if ( count_only ) + { + free(str.s); + return nplugins; + } + if ( nplugins ) + { + qsort(plugins, nplugins, sizeof(plugins[0]), cmp_plugin_name); + + for (i=0; iverbose ) + fprintf(bcftools_stdout, "\n-- %s --\n%s", plugins[i].name, plugins[i].about()); + else + fprintf(bcftools_stdout, "%s\n", plugins[i].name); + } + if ( args->verbose ) fprintf(bcftools_stdout, "\n"); + } + else + print_plugin_usage_hint(NULL); + free(str.s); + return nplugins ? 0 : 1; +} +int count_plugins(void) +{ + return list_plugins(NULL); +} + +static void init_data(args_t *args) +{ + args->hdr = args->files->readers[0].header; + args->hdr_out = bcf_hdr_dup(args->hdr); + + init_plugin(args); + + if ( args->filter_str ) + args->filter = filter_init(args->hdr, args->filter_str); + + if (args->record_cmd_line) bcf_hdr_append_version(args->hdr_out, args->argc, args->argv, "bcftools_plugin"); + if ( !args->drop_header ) + { + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(args->out_fh, args->n_threads); + if ( bcf_hdr_write(args->out_fh, args->hdr_out)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + if ( init_index2(args->out_fh,args->hdr_out,args->output_fname, + &args->index_fn, args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->output_fname); + } +} + +static void destroy_data(args_t *args) +{ + free(args->plugin.name); + if ( args->plugin.destroy ) args->plugin.destroy(); +#ifdef _WIN32 + FreeLibrary(args->plugin.handle); +#else + dlclose(args->plugin.handle); +#endif + if ( args->hdr_out ) bcf_hdr_destroy(args->hdr_out); + if ( args->nplugin_paths>0 ) + { + int i; + for (i=0; inplugin_paths; i++) free(args->plugin_paths[i]); + free(args->plugin_paths); + } + if ( args->filter ) + filter_destroy(args->filter); + if (args->out_fh ) + { + if ( args->write_index ) + { + if ( bcf_idx_save(args->out_fh)<0 ) + { + if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(args->out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname); + } +} + +static void usage(args_t *args) +{ + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "About: Run user defined plugin\n"); + fprintf(bcftools_stderr, "Usage: bcftools plugin [OPTIONS] [-- PLUGIN_OPTIONS]\n"); + fprintf(bcftools_stderr, " bcftools +name [OPTIONS] [-- PLUGIN_OPTIONS]\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "VCF input options:\n"); + fprintf(bcftools_stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n"); + fprintf(bcftools_stderr, " -i, --include EXPR Select sites for which the expression is true\n"); + fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(bcftools_stderr, "VCF output options:\n"); + fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(bcftools_stderr, " --threads INTT Use multithreading with worker threads [0]\n"); + fprintf(bcftools_stderr, "Plugin options:\n"); + fprintf(bcftools_stderr, " -h, --help List plugin's options\n"); + fprintf(bcftools_stderr, " -l, --list-plugins List available plugins. See BCFTOOLS_PLUGINS environment variable and man page for details\n"); + fprintf(bcftools_stderr, " -v, --verbose Print verbose information, -vv increases verbosity\n"); + fprintf(bcftools_stderr, " -V, --version Print version string and exit\n"); + fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(bcftools_stderr, "\n"); + bcftools_exit(1); +} + +static int is_verbose(int argc, char *argv[]) +{ + int c, verbose = 0, opterr_ori = opterr; + static struct option loptions[] = + { + {"verbose",no_argument,NULL,'v'}, + {NULL,0,NULL,0} + }; + opterr = 0; + while ((c = getopt_long(argc, argv, "-v",loptions,NULL)) >= 0) + { + switch (c) { + case 'v': verbose++; break; + case 1: + default: break; + } + } + opterr = opterr_ori; + optind = 0; + return verbose; +} +int main_plugin(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->output_fname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->nplugin_paths = -1; + args->clevel = -1; + int regions_is_file = 0, targets_is_file = 0, usage_only = 0, version_only = 0; + int regions_overlap = 1; + int targets_overlap = 0; + + if ( argc==1 ) usage(args); + char *plugin_name = NULL; + if ( argv[1][0]!='-' ) + { + args->verbose = is_verbose(argc, argv); + plugin_name = argv[1]; + argc--; + argv++; + load_plugin(args, plugin_name, 1, &args->plugin); + if ( args->plugin.run ) + { + check_version(args); + int ret = args->plugin.run(argc, argv); + destroy_data(args); + free(args); + return ret; + } + } + + static struct option loptions[] = + { + {"version",no_argument,NULL,'V'}, + {"verbose",no_argument,NULL,'v'}, + {"help",no_argument,NULL,'h'}, + {"list-plugins",no_argument,NULL,'l'}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"include",required_argument,NULL,'i'}, + {"exclude",required_argument,NULL,'e'}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,1}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"targets-overlap",required_argument,NULL,2}, + {"no-version",no_argument,NULL,8}, + {"write-index",optional_argument,NULL,'W'}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "h?o:O:r:R:t:T:li:e:vVW::",loptions,NULL)) >= 0) + { + switch (c) { + case 'V': version_only = 1; break; + case 'v': args->verbose++; break; + case 'o': args->output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + }; + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'e': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break; + case 'i': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; regions_is_file = 1; break; + case 't': args->targets_list = optarg; break; + case 'T': args->targets_list = optarg; targets_is_file = 1; break; + case 'l': args->plist_only = 1; break; + case 1 : + regions_overlap = parse_overlap_option(optarg); + if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 2 : + targets_overlap = parse_overlap_option(optarg); + if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 8 : args->record_cmd_line = 0; break; + case 'W': + if (!(args->write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + case '?': + case 'h': usage_only = 1; break; + default: error("Unknown argument: %s\n", optarg); + } + } + if ( args->plist_only ) return list_plugins(args); + if ( !plugin_name ) usage(args); + + if ( version_only ) + { + const char *bver, *hver; + args->plugin.version(&bver, &hver); + fprintf(bcftools_stdout, "bcftools %s using htslib %s\n", bcftools_version(), hts_version()); + fprintf(bcftools_stdout, "plugin at %s using htslib %s\n\n", bver, hver); + return 0; + } + + if ( usage_only ) + { + if ( args->plugin.usage ) + fprintf(bcftools_stderr,"%s",args->plugin.usage()); + else + fprintf(bcftools_stderr,"Usage: bcftools +%s [General Options] -- [Plugin Options]\n",plugin_name); + return 0; + } + + char *fname = NULL; + if ( optind>=argc || (argv[optind][0]=='-' && argv[optind][1]) ) + { + args->plugin.argc = argc - optind + 1; + args->plugin.argv = argv + optind - 1; + + if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin + else if ( optind>=argc ) usage(args); + else + { + optind = 1; + init_plugin(args); + } + } + else + { + fname = argv[optind]; + args->plugin.argc = argc - optind; + args->plugin.argv = argv + optind; + } + optind = 0; + + args->files = bcf_sr_init(); + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + if ( args->targets_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap); + if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 ) + error("Failed to read the targets: %s\n", args->targets_list); + args->files->collapse |= COLLAPSE_SOME; + } + if ( !bcf_sr_add_reader(args->files, fname) ) error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum)); + + init_data(args); + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) continue; + } + line = args->plugin.process(line); + if ( line ) + { + if ( line->errcode ) error("[E::main_plugin] Unchecked error (%d), exiting\n",line->errcode); + if ( bcf_write1(args->out_fh, args->hdr_out, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname); + } + } + destroy_data(args); + bcf_sr_destroy(args->files); + free(args); + return 0; +} + +#else /* ENABLE_BCF_PLUGINS */ + +int main_plugin(int argc, char *argv[]) +{ + fprintf(bcftools_stderr, "bcftools plugins are disabled. To use them, you will need to rebuild\n" + "bcftools from the source distribution with plugins enabled.\n"); + return 1; +} + +#endif /* ENABLE_BCF_PLUGINS */ diff --git a/shared/package-files/a5/a57c08c6ccb6ac2887395516b1a1cd17b224646a2067edbb535fa07b253691fa/_flash_attention_backward_cuda_dispatch.h b/shared/package-files/a5/a57c08c6ccb6ac2887395516b1a1cd17b224646a2067edbb535fa07b253691fa/_flash_attention_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0da22d3416655094c407a0264081cd8443259cf5 --- /dev/null +++ b/shared/package-files/a5/a57c08c6ccb6ac2887395516b1a1cd17b224646a2067edbb535fa07b253691fa/_flash_attention_backward_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & rng_state, const at::Tensor & unused, ::std::optional scale=::std::nullopt, ::std::optional window_size_left=::std::nullopt, ::std::optional window_size_right=::std::nullopt); +TORCH_API ::std::tuple _flash_attention_backward_symint(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & rng_state, const at::Tensor & unused, ::std::optional scale=::std::nullopt, ::std::optional window_size_left=::std::nullopt, ::std::optional window_size_right=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/a5/a586e0bfbce1b4be4c42f109cc68faa40d1b4b0ceb9c62968e1a260130f04e15/qat_utils.py b/shared/package-files/a5/a586e0bfbce1b4be4c42f109cc68faa40d1b4b0ceb9c62968e1a260130f04e15/qat_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f786f245ad21cb97a4bed9510a635bebd9414c --- /dev/null +++ b/shared/package-files/a5/a586e0bfbce1b4be4c42f109cc68faa40d1b4b0ceb9c62968e1a260130f04e15/qat_utils.py @@ -0,0 +1,991 @@ +# mypy: allow-untyped-defs +import copy +import dataclasses +import itertools +import operator +from typing import Any, Callable, Optional, TYPE_CHECKING + +import torch +import torch.nn.functional as F +from torch.ao.quantization.fx._decomposed import quantized_decomposed_lib # noqa: F401 +from torch.ao.quantization.pt2e.export_utils import _WrapperModule +from torch.ao.quantization.quantizer import ( + DerivedQuantizationSpec, + EdgeOrNode, + QuantizationSpecBase, + SharedQuantizationSpec, +) +from torch.fx import Graph, GraphModule, Node +from torch.fx.subgraph_rewriter import replace_pattern_with_filters, ReplacedPatterns + +from .utils import ( + _get_aten_graph_module_for_pattern, + _is_bn_node, + _is_conv_or_conv_transpose_node, + _is_conv_transpose_fn, + fold_bn_weights_into_conv_node, +) + + +if TYPE_CHECKING: + from torch.fx.passes.utils.matcher_with_name_node_map_utils import InternalMatch + +__all__ = [] # type: ignore[var-annotated] + + +def _get_quantized_conv_bn_example_inputs_kwargs( + is_per_channel: bool, + has_bias: bool, + bias_is_quantized: bool, + is_cuda: bool, +) -> dict[str, Any]: + """ + Optional example inputs for quantized and folded conv-bn patterns + used in convert, expressed as kwargs. + """ + kwargs = {} + # Per tensor quantization uses literals to represent scale and zero + # point, so there is no need to include them here as kwargs + if is_per_channel: + kwargs["weight_scale"] = torch.tensor([1], dtype=torch.float) + kwargs["weight_zero_point"] = torch.tensor([0], dtype=torch.int) + if has_bias and bias_is_quantized: + kwargs["bias_scale"] = torch.tensor([1], dtype=torch.float) + kwargs["bias_zero_point"] = torch.tensor([0], dtype=torch.int) + if has_bias: + kwargs["conv_bias"] = torch.randn(1) + if is_cuda: + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + kwargs[k] = v.cuda() + return kwargs + + +def _get_conv_bn_pattern(conv_fn: Callable) -> Callable: + def _conv_bn_pattern( + x: torch.Tensor, + conv_weight: torch.Tensor, + conv_bias: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + ) -> torch.Tensor: + x = conv_fn(x, conv_weight, conv_bias) + x = F.batch_norm( + x, bn_running_mean, bn_running_var, bn_weight, bn_bias, training=True + ) + return x + + return _WrapperModule(_conv_bn_pattern) + + +# TODO: merge this with the `no_conv_bias` case +def _get_qat_conv_bn_pattern(conv_fn: Callable) -> Callable: + def _qat_conv_bn_pattern( + x: torch.Tensor, + conv_weight: torch.Tensor, + conv_bias: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + ) -> torch.Tensor: + """ + Approximated method to fuse conv and bn. It requires only one forward pass. + conv_orig = conv / scale_factor where scale_factor = bn.weight / running_std. + This is based on `nniqat.ConvBn2d._forward_approximate`. + """ + # TODO: allow setting eps + bn_eps = 1e-5 + running_std = torch.sqrt(bn_running_var + bn_eps) + scale_factor = bn_weight / running_std + weight_shape = [1] * len(conv_weight.shape) + weight_in_channel_axis = 1 if _is_conv_transpose_fn(conv_fn) else 0 + weight_shape[weight_in_channel_axis] = -1 + bias_shape = [1] * len(conv_weight.shape) + bias_shape[1] = -1 + scaled_weight = conv_weight * scale_factor.reshape(weight_shape) + zero_bias = torch.zeros_like(conv_bias, dtype=x.dtype) + x = conv_fn(x, scaled_weight, zero_bias) + x = x / scale_factor.reshape(bias_shape) + x = x + conv_bias.reshape(bias_shape) + x = F.batch_norm( + x, + bn_running_mean, + bn_running_var, + bn_weight, + bn_bias, + training=True, + eps=bn_eps, + ) + return x + + return _WrapperModule(_qat_conv_bn_pattern) + + +def _get_qat_conv_bn_pattern_no_conv_bias(conv_fn: Callable) -> Callable: + def _qat_conv_bn_pattern_no_conv_bias( + x: torch.Tensor, + conv_weight: torch.Tensor, + # Not used, only for matching convenience + conv_bias: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + ) -> torch.Tensor: + """ + Same as `_get_qat_conv_bn_pattern`, but handles the case with no conv bias. + """ + # TODO: allow setting eps + bn_eps = 1e-5 + running_std = torch.sqrt(bn_running_var + bn_eps) + scale_factor = bn_weight / running_std + weight_shape = [1] * len(conv_weight.shape) + weight_in_channel_axis = 1 if _is_conv_transpose_fn(conv_fn) else 0 + weight_shape[weight_in_channel_axis] = -1 + bias_shape = [1] * len(conv_weight.shape) + bias_shape[1] = -1 + scaled_weight = conv_weight * scale_factor.reshape(weight_shape) + x = conv_fn(x, scaled_weight, None) + x = x / scale_factor.reshape(bias_shape) + x = F.batch_norm( + x, + bn_running_mean, + bn_running_var, + bn_weight, + bn_bias, + training=True, + eps=bn_eps, + ) + return x + + return _WrapperModule(_qat_conv_bn_pattern_no_conv_bias) + + +def _append_qdq(x, is_per_channel, is_bias, kwargs): + """ + Helper function to append q-dq ops after `x`, using dummy values for the qparams + and qmin/qmax. We use dummy values here because we match with `ignore_literals=True` + and will manually replace these values after subgraph rewriting. + + Return the dq node. + """ + # Dummy args to be passed into q-dq ops + per_channel_axis = 0 + scale_key = "bias_scale" if is_bias else "weight_scale" + zp_key = "bias_zero_point" if is_bias else "weight_zero_point" + scale = kwargs[scale_key] if is_per_channel else 1.0 + zp = kwargs[zp_key] if is_per_channel else 0 + qmin = -127 + qmax = 127 + dtype = torch.int8 + + qd = torch.ops.quantized_decomposed + if is_per_channel: + x = qd.quantize_per_channel(x, scale, zp, per_channel_axis, qmin, qmax, dtype) + x = qd.dequantize_per_channel(x, scale, zp, per_channel_axis, qmin, qmax, dtype) + else: + x = qd.quantize_per_tensor(x, scale, zp, qmin, qmax, dtype) + x = qd.dequantize_per_tensor(x, scale, zp, qmin, qmax, dtype) + return x + + +def _get_quantized_qat_conv_bn_pattern( + is_per_channel: bool, + has_bias: bool, + bias_is_quantized: bool, + conv_fn: Callable, + bn_is_training: bool, +) -> Callable: + """ + Return the quantized version of QAT conv + BN pattern. + This is based on `nniqat.ConvBn2d._forward_approximate`, + used in QAT convert. We first match this pattern and replace + it with the normal [conv - bn] pattern, then fold the BN + weights into conv. + """ + # TODO: allow setting eps + bn_eps = 1e-5 + + def _quantized_qat_conv_bn_pattern( + x: torch.Tensor, + conv_weight: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + running_std = torch.sqrt(bn_running_var + bn_eps) + scale_factor = bn_weight / running_std + weight_shape = [1] * len(conv_weight.shape) + weight_shape[0] = -1 + bias_shape = [1] * len(conv_weight.shape) + bias_shape[1] = -1 + scaled_weight = conv_weight * scale_factor.reshape(weight_shape) + scaled_weight = _append_qdq( + scaled_weight, + is_per_channel, + is_bias=False, + kwargs=kwargs, + ) + if has_bias: + zero_bias = torch.zeros_like(kwargs["conv_bias"], dtype=x.dtype) + if bias_is_quantized: + zero_bias = _append_qdq( + zero_bias, + is_per_channel, + is_bias=True, + kwargs=kwargs, + ) + x = conv_fn(x, scaled_weight, zero_bias) + else: + x = conv_fn(x, scaled_weight, None) + x = x / scale_factor.reshape(bias_shape) + if has_bias: + x = x + kwargs["conv_bias"].reshape(bias_shape) + x = F.batch_norm( + x, + bn_running_mean, + bn_running_var, + bn_weight, + bn_bias, + training=bn_is_training, + eps=bn_eps, + ) + return x + + return _WrapperModule(_quantized_qat_conv_bn_pattern) + + +def _get_folded_quantized_qat_conv_bn_pattern( + is_per_channel: bool, + has_bias: bool, + bias_is_quantized: bool, + conv_fn: Callable, + bn_is_training: bool, +) -> Callable: + """ + Quantized QAT conv - bn pattern with bn weights being folded into conv. + """ + # TODO: allow setting eps + bn_eps = 1e-5 + + def _folded_quantized_qat_conv_bn_pattern( + x: torch.Tensor, + conv_weight: torch.Tensor, + bn_weight: torch.Tensor, + bn_bias: torch.Tensor, + bn_running_mean: torch.Tensor, + bn_running_var: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + conv_weight = _append_qdq( + conv_weight, + is_per_channel, + is_bias=False, + kwargs=kwargs, + ) + if has_bias: + bias = kwargs["conv_bias"] + if bias_is_quantized: + bias = _append_qdq( + bias, + is_per_channel, + is_bias=True, + kwargs=kwargs, + ) + else: + bias = None + x = conv_fn(x, conv_weight, bias) + x = F.batch_norm( + x, + bn_running_mean, + bn_running_var, + bn_weight, + bn_bias, + training=bn_is_training, + eps=bn_eps, + ) + return x + + return _WrapperModule(_folded_quantized_qat_conv_bn_pattern) + + +def _has_conv_bias_filter( + match: "InternalMatch", + original_graph: Graph, + pattern_graph: Graph, +) -> bool: + """ + Match filter for the subgraph rewriter that returns True if the conv node in + the original graph has bias. + """ + for n in match.nodes_map.values(): + if _is_conv_or_conv_transpose_node(n): + return len(n.args) > 2 and n.args[2] is not None + raise ValueError("Could not find conv node in matched conv + bn pattern") + + +def _no_conv_bias_filter( + match: "InternalMatch", + original_graph: Graph, + pattern_graph: Graph, +) -> bool: + """ + Match filter for the subgraph rewriter that returns True if the conv node in + the original graph does NOT have bias. + """ + return not _has_conv_bias_filter(match, original_graph, pattern_graph) + + +def _is_quantize(n: Node) -> bool: + return n.target in [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, + ] + + +def _is_dequantize(n: Node) -> bool: + return n.target in [ + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.quantized_decomposed.dequantize_per_channel.default, + ] + + +def _get_conv_bn_pattern_nodes(r: ReplacedPatterns) -> dict[str, tuple[Node, Node]]: + """ + Helper function to extract the nodes in the conv-bn fusion pattern after + subgraph rewriting, in the form of a map: + + {name: (original_node, replacement_node)} + + The following names must exist in the map: + + "conv", "conv_weight", "conv_input", "bn", "getitem" + + The following names may exist in the map: + + "conv_weight_q", "conv_weight_dq", "conv_bias", + "conv_bias_q", "conv_bias_dq" + """ + + def _get_nodes(nodes: list[Node]) -> tuple[Node, Node, Optional[Node]]: + """ + Return a 3-tuple of (conv_node, bn_node, getitem_node). + This asserts that the match contains exactly one of each node. + """ + conv_node, bn_node, getitem_node = None, None, None + for n in nodes: + if n.op != "call_function": + continue + if _is_conv_or_conv_transpose_node(n): + assert conv_node is None + conv_node = n + if _is_bn_node(n): + assert bn_node is None + bn_node = n + if n.target == operator.getitem: + assert getitem_node is None + getitem_node = n + assert conv_node is not None + assert bn_node is not None + return (conv_node, bn_node, getitem_node) + + def _get_q_dq_nodes(n: Node) -> tuple[Node, Node, Node]: + """ + Return a 3-tuple of (orig_node, q_node, dq_node). + """ + assert _is_dequantize(n) + q_node = n.args[0] + assert isinstance(q_node, Node) + assert _is_quantize(q_node) + orig_node = q_node.args[0] + assert isinstance(orig_node, Node) + return (orig_node, q_node, n) + + original_nodes = list(_filter_nodes_map(r.nodes_map).values()) + o_conv, o_bn, o_getitem = _get_nodes(original_nodes) + r_conv, r_bn, r_getitem = _get_nodes(r.replacements) + + # Create the mapping from original node to replacement node + assert o_getitem is None + assert r_getitem is None + mapping = { + "conv": (o_conv, r_conv), + "bn": (o_bn, r_bn), + } + + # Extract conv input and weight + # Note: here we extract the original nodes indirectly through the pattern nodes + # because the args of the original nodes are no longer available after replacement + (p_conv, _, _) = _get_nodes(list(r.nodes_map.keys())) + (p_conv_input, p_conv_weight, *_) = p_conv.args + (r_conv_input, r_conv_weight, *_) = r_conv.args + assert isinstance(p_conv_input, Node) + assert isinstance(p_conv_weight, Node) + assert isinstance(r_conv_input, Node) + assert isinstance(r_conv_weight, Node) + o_conv_input = r.nodes_map[p_conv_input] + o_conv_weight = r.nodes_map[p_conv_weight] + + # If conv weight is quantized, extract the q - dq nodes + if _is_dequantize(p_conv_weight): + p_conv_weight, p_conv_weight_q, p_conv_weight_dq = _get_q_dq_nodes( + p_conv_weight + ) + r_conv_weight, r_conv_weight_q, r_conv_weight_dq = _get_q_dq_nodes( + r_conv_weight + ) + o_conv_weight = r.nodes_map[p_conv_weight] + o_conv_weight_q = r.nodes_map[p_conv_weight_q] + o_conv_weight_dq = r.nodes_map[p_conv_weight_dq] + mapping["conv_weight_q"] = (o_conv_weight_q, r_conv_weight_q) + mapping["conv_weight_dq"] = (o_conv_weight_dq, r_conv_weight_dq) + mapping["conv_input"] = (o_conv_input, r_conv_input) + mapping["conv_weight"] = (o_conv_weight, r_conv_weight) + + # Extract conv bias + if len(p_conv.args) > 2 and len(r_conv.args) > 2: + p_conv_bias = p_conv.args[2] + r_conv_bias = r_conv.args[2] + assert isinstance(p_conv_bias, Node) + assert isinstance(r_conv_bias, Node) + o_conv_bias = r.nodes_map[p_conv_bias] + + # If conv bias is quantized, extract the q - dq nodes + if _is_dequantize(p_conv_bias): + p_conv_bias, p_conv_bias_q, p_conv_bias_dq = _get_q_dq_nodes(p_conv_bias) + r_conv_bias, r_conv_bias_q, r_conv_bias_dq = _get_q_dq_nodes(r_conv_bias) + o_conv_bias = r.nodes_map[p_conv_bias] + o_conv_bias_q = r.nodes_map[p_conv_bias_q] + o_conv_bias_dq = r.nodes_map[p_conv_bias_dq] + mapping["conv_bias_q"] = (o_conv_bias_q, r_conv_bias_q) + mapping["conv_bias_dq"] = (o_conv_bias_dq, r_conv_bias_dq) + mapping["conv_bias"] = (o_conv_bias, r_conv_bias) + return mapping + + +def _filter_nodes_map(nodes_map: dict[Node, Node]) -> dict[Node, Node]: + """ + Return a filtered `nodes_map` returned from the subgraph rewriter. + The filtered `nodes_map` will contain only nodes that are actually + matched in the pattern, excluding None or placeholder nodes. + """ + new_nodes_map: dict[Node, Node] = {} + for pattern_node, graph_node in nodes_map.items(): + # bias can be None + if graph_node is None: + continue + # skip pattern placeholder nodes + if pattern_node.op == "placeholder": + continue + new_nodes_map[pattern_node] = graph_node + return new_nodes_map + + +# TODO: this is error prone, use the replace_literals_with_placeholders hack instead +def _copy_over_literal_conv_args(original_node: Node, new_node: Node): + """ + Copy over literal args in conv, such as stride and padding, from the matched node + in the original graph to its replacement in the new graph. + + This is needed due to the following limitation in the subgraph rewriter when used + with dynamo export: literal (non-tensor) args are not supported in the match and + replacement patterns. This is because dynamo export automatically inlines these + literal args, making them dead placeholder nodes. In the future, we should check + if dynamo export can optionally disable this inlining, or if subgraph rewriter + can do the copying for us. See https://github.com/pytorch/pytorch/issues/100419. + + Note: Unlike other tensor args like conv weights and biases, literal args are + preserved in the original nodes after replacement, so we can access them here. + """ + assert _is_conv_or_conv_transpose_node(original_node) + assert _is_conv_or_conv_transpose_node(new_node) + # x, weight, bias, [stride, padding, dilation, transposed, output_padding, groups] + new_args = list(new_node.args) + if len(new_args) < 3: + # bias is optional, when it is not present, it means it is None + new_args.append(None) + new_node.args = tuple(new_args[:3]) + original_node.args[3:] + + +def _update_conv_input_qspec_map_after_replacement( + original_node: Node, replacement_node: Node +): + """ + Update the `input_qspec_map` in the annotation after subgraph rewriting. + + The original annotation referred to the nodes in the original graph, + so the keys in the `input_qspec_map` will need to be updated to reflect + the corresponding nodes in the replacement graph. + """ + assert _is_conv_or_conv_transpose_node(original_node) + assert _is_conv_or_conv_transpose_node(replacement_node) + if "quantization_annotation" not in original_node.meta: + return + original_input_qspec_map = original_node.meta[ + "quantization_annotation" + ].input_qspec_map + input_qspec_map = {} + # get the list of configs, it should be ordered as input, weight, bias + # note: this is really hacky, we need a better solution, hopefully + # in subgraph_rewriter, issue tracking the problem: https://github.com/pytorch/pytorch/issues/101820 + all_configs = list(original_input_qspec_map.items()) + # input activation + input_qspec_map[replacement_node.args[0]] = all_configs[0][1] + # weight + input_qspec_map[replacement_node.args[1]] = all_configs[1][1] + # bias + if len(replacement_node.args) > 2 and len(all_configs) > 2: + input_qspec_map[replacement_node.args[2]] = all_configs[2][1] + replacement_node.meta["quantization_annotation"].input_qspec_map = input_qspec_map + + +def _update_special_qspecs_after_replacement( + node: Node, + original_to_replacement_node: dict[Node, Node], +): + """ + Update the `SharedQuantizationSpec`s and `DerivedQuantizationSpec`s + used in `node`'s quantization annotation after subgraph rewriting. + + The original annotation referred to the nodes in the original graph, + so the nodes used in these special quantization specs will need to + be updated to the corresponding nodes in the replacement graph. + """ + + def _get_new_edge_or_node(edge_or_node: EdgeOrNode): + if isinstance(edge_or_node, Node): + _node = edge_or_node + return original_to_replacement_node.get(_node, _node) + elif ( + isinstance(edge_or_node, tuple) + and len(edge_or_node) == 2 + and all(isinstance(x, Node) for x in edge_or_node) + ): + src, dest = edge_or_node + return ( + original_to_replacement_node.get(src, src), + original_to_replacement_node.get(dest, dest), + ) + else: + raise ValueError("unexpected type for edge_or_node: ", type(edge_or_node)) + + def _get_new_qspec(qspec: QuantizationSpecBase): + if isinstance(qspec, SharedQuantizationSpec): + new_edge_or_node = _get_new_edge_or_node(qspec.edge_or_node) + return SharedQuantizationSpec(new_edge_or_node) + elif isinstance(qspec, DerivedQuantizationSpec): + new_derived_from = [_get_new_edge_or_node(x) for x in qspec.derived_from] + return dataclasses.replace(qspec, derived_from=new_derived_from) + else: + return qspec + + if "quantization_annotation" not in node.meta: + return + annotation = node.meta["quantization_annotation"] + for input_node, qspec in annotation.input_qspec_map.items(): + annotation.input_qspec_map[input_node] = _get_new_qspec(qspec) + annotation.output_qspec = _get_new_qspec(annotation.output_qspec) + + +def _fuse_conv_bn_qat(m: GraphModule) -> GraphModule: + # Example inputs for conv-bn1d patterns + _conv1d_bn_example_inputs = ( + torch.randn(1, 1, 3), # x + torch.randn(1, 1, 1), # conv_weight + torch.randn(1), # conv_bias + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + # Example inputs for conv-bn2d patterns + _conv2d_bn_example_inputs = ( + torch.randn(1, 1, 3, 3), # x + torch.randn(1, 1, 1, 1), # conv_weight + torch.randn(1), # conv_bias + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + has_bn = any(_is_bn_node(n) for n in m.graph.nodes) + if not has_bn: + return m + is_cuda_options = [True, False] if torch.cuda.is_available() else [False] + for is_cuda in is_cuda_options: + m = _fuse_conv_bn_qat_helper( + m, F.conv1d, _conv1d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fuse_conv_bn_qat_helper( + m, F.conv2d, _conv2d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fuse_conv_bn_qat_helper( + m, F.conv_transpose1d, _conv1d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fuse_conv_bn_qat_helper( + m, F.conv_transpose2d, _conv2d_bn_example_inputs, is_cuda=is_cuda + ) + return m + + +def _fuse_conv_bn_qat_helper( + m: GraphModule, + conv_fn: Callable, + example_inputs: tuple[Any, ...], + is_cuda: bool, +) -> GraphModule: + """ + Given a graph of decomposed aten ops, replace the (conv + bn) pattern with + the fused QAT subgraph equivalent. The input graph should already be annotated. + The annotations in the original nodes will be preserved in the corresponding + nodes in the new subgraph. + + Note: This also handles the (conv + bn + relu) pattern. + """ + m.graph.eliminate_dead_code() + m.recompile() + + conv_bn_pattern = _get_conv_bn_pattern(conv_fn) + match_pattern = _get_aten_graph_module_for_pattern( + conv_bn_pattern, + example_inputs, + is_cuda, + ) + + # Step (1): Replace patterns with conv bias + # + # Here we do replacement separately for cases with and without conv bias, since + # the replacement patterns for these two cases are substantially different. + # TODO: use the public replace_pattern API once it also returns replacement nodes + + qat_conv_bn_pattern = _get_qat_conv_bn_pattern(conv_fn) + replacement_pattern_with_conv_bias = _get_aten_graph_module_for_pattern( + qat_conv_bn_pattern, + example_inputs, + is_cuda, + ) + replacements_with_conv_bias = replace_pattern_with_filters( + m, + match_pattern, + replacement_pattern_with_conv_bias, + match_filters=[_has_conv_bias_filter], + ignore_literals=True, + ) + m.recompile() + + # Step (2): Replace patterns without conv bias + + qat_conv_bn_pattern_no_conv_bias = _get_qat_conv_bn_pattern_no_conv_bias(conv_fn) + replacement_pattern_no_conv_bias = _get_aten_graph_module_for_pattern( + qat_conv_bn_pattern_no_conv_bias, + example_inputs, + is_cuda, + ) + replacements_no_conv_bias = replace_pattern_with_filters( + m, + match_pattern, + replacement_pattern_no_conv_bias, + match_filters=[_no_conv_bias_filter], + ignore_literals=True, + ) + m.recompile() + + # Step (3): Post processing + # + # Due to limited functionality in the subgraph rewriter, here we manually + # update the replacement graph as follows: + # + # (a) Copy over metadata from original subgraph. This ensures the stack traces + # and annotations are preserved in the new subgraph + # + # (b) Copy over literal args for conv from the original subgraph + # TODO: do this for literal args for batchnorm as well + # + # (c) Update all references of the old nodes in the original subgraph to refer + # to the corresponding nodes in the new subgraph in the annotations + # + # In the future, we should try to push as much of this functionality into the + # subgraph rewriter as possible, so we don't have to manually copy anything over. + # For more detail, see https://github.com/pytorch/pytorch/issues/100419. + + all_original_to_replacement_nodes = {} + for r in replacements_with_conv_bias + replacements_no_conv_bias: + replacement_dict = _get_conv_bn_pattern_nodes(r) + # The original conv node's "nn_module_stack" + conv_nn_module = replacement_dict["conv"][0].meta.get("nn_module_stack", None) + for k, node_tuple in replacement_dict.items(): + original_node, replacement_node = node_tuple + # Step (3a): Copy over metadata for all nodes in [conv - bn - getitem] + replacement_node.meta = original_node.meta + # If original_node is a get_attr node, it doesn't have nn_module_stack. + # In this case, we copy nn_module_stack from the original conv node. + if ( + k in ["conv_input", "conv_weight"] + and conv_nn_module + and "nn_module_stack" not in replacement_node.meta + ): + replacement_node.meta["nn_module_stack"] = copy.deepcopy(conv_nn_module) + if _is_conv_or_conv_transpose_node(original_node): + # Step (3b): Copy over conv literal args + _copy_over_literal_conv_args(original_node, replacement_node) + # Step (3c): Update old references in the conv node's input_qspec_map + _update_conv_input_qspec_map_after_replacement( + original_node, replacement_node + ) + all_original_to_replacement_nodes[original_node] = replacement_node + + # Step (3c): Update old references in the special qspecs for all nodes in the graph + for n in m.graph.nodes: + _update_special_qspecs_after_replacement(n, all_original_to_replacement_nodes) + + return m + + +def _duplicate_dequantize_node(m: GraphModule): + """ + Helper function to duplicate all dequantize nodes in the graph if the + node has more than one user. For example: + + Before: + quantize -> dequantize -> a + \\--> b + \\--> c + + After: + quantize -> dequantize_1 -> a + \\--> dequantize_2 -> b + \\--> dequantize_3 -> c + + This is useful for subgraph rewriting. E.g. if we wish to match the + pattern [dequantize - a] above, subgraph matching would fail because + the dequantize node has users outside the matched portion of the graph. + Instead, we match [dequantize_1 - a], which is safe. + """ + dq_op = torch.ops.quantized_decomposed.dequantize_per_tensor + for n in m.graph.nodes: + if n.op != "call_function" or n.target != dq_op or len(n.users) == 1: + continue + for user in list(n.users): + with m.graph.inserting_before(n): + new_node = m.graph.create_node("call_function", dq_op, n.args, n.kwargs) + user.replace_input_with(n, new_node) + m.graph.erase_node(n) + m.recompile() + + +def _remove_extra_dequantize(m: GraphModule): + """ + Removes duplicate dequant nodes in the graph, for an operator that has + multiple dequant nodes as a user, replace them with a single dequant node + that can be shared across all the uses. This should be seen as the "reverse" + of `_duplicate_dequantize_node`. + """ + dq_op = torch.ops.quantized_decomposed.dequantize_per_tensor + for n in m.graph.nodes: + dq_users = [ + user + for user in n.users + if user.op == "call_function" and user.target == dq_op + ] + if len(dq_users) > 1: + with m.graph.inserting_after(dq_users[0]): + new_node = m.graph.create_node( + "call_function", dq_op, dq_users[0].args, {} + ) + for dq_user in dq_users: + dq_user.replace_all_uses_with(new_node) + m.graph.erase_node(dq_user) + m.recompile() + + +def _copy_over_q_dq_args(original_node: Node, replacement_node: Node): + """ + Given a pair of quantize or dequantize nodes, copy over all literal args + from the original node to the replacement node. + """ + # For quantize_per_tensor, scale and zp are literals and need to be copied + # For quantize_per_channel, scale and zp are get_attr nodes and should be skipped + assert original_node.target == replacement_node.target + if original_node.target in ( + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + ): + # Args: input, [scale, zp, qmin, qmax, dtype] + start_copy_arg_index = 1 + elif original_node.target in ( + torch.ops.quantized_decomposed.quantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_channel.default, + ): + # Args: input, scale, zp, [axis, qmin, qmax, dtype] + start_copy_arg_index = 3 + else: + raise ValueError( + f"Expected quantize/dequantize nodes, got '{original_node.target}'" + ) + replacement_node.args = ( + replacement_node.args[:start_copy_arg_index] + + original_node.args[start_copy_arg_index:] + ) + + +def _fold_conv_bn_qat(m: GraphModule) -> GraphModule: + # Example inputs for quantized and folded conv-bn1d patterns used in convert + _quantized_conv1d_bn_example_inputs = ( + torch.randn(1, 1, 3), # x + torch.randn(1, 1, 1), # conv_weight + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + # Example inputs for quantized and folded conv-bn2d patterns used in convert + _quantized_conv2d_bn_example_inputs = ( + torch.randn(1, 1, 3, 3), # x + torch.randn(1, 1, 1, 1), # conv_weight + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + has_bn = any(_is_bn_node(n) for n in m.graph.nodes) + if not has_bn: + return m + is_cuda_options = [True, False] if torch.cuda.is_available() else [False] + for is_cuda in is_cuda_options: + m = _fold_conv_bn_qat_helper( + m, F.conv1d, _quantized_conv1d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fold_conv_bn_qat_helper( + m, F.conv2d, _quantized_conv2d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fold_conv_bn_qat_helper( + m, F.conv_transpose1d, _quantized_conv1d_bn_example_inputs, is_cuda=is_cuda + ) + m = _fold_conv_bn_qat_helper( + m, F.conv_transpose2d, _quantized_conv2d_bn_example_inputs, is_cuda=is_cuda + ) + + # remove in place add from batchnorm tracking traning stats + for node in m.graph.nodes: + if ( + node.target == torch.ops.aten.add_.Tensor + and node.args[0].op == "get_attr" + and node.args[1] == 1 + and torch.nn.modules.batchnorm.BatchNorm2d + in [val[1] for val in node.meta["source_fn_stack"]] + ): + m.graph.erase_node(node) + + m.graph.eliminate_dead_code() + m.recompile() + + return m + + +def _fold_conv_bn_qat_helper( + m: GraphModule, + conv_fn: Callable, + example_inputs: tuple[Any, ...], + is_cuda: bool, +) -> GraphModule: + """ + Replace the quantized (conv + bn) pattern with conv with bn weights folded into the weights of conv. + """ + + m.graph.eliminate_dead_code() + m.recompile() + _duplicate_dequantize_node(m) + + # Step (1): Replace QAT pattern with simple [conv - bn] pattern + replacements = [] + replacement_options = itertools.product( + [True, False], # is_per_channel + [True, False], # has_bias + [True, False], # bias_is_quantized + [True, False], # bn_is_training + ) + for ( + is_per_channel, + has_bias, + bias_is_quantized, + bn_is_training, + ) in replacement_options: + # For the cases without bias, `bias_is_quantized` is irrelevant, so here we arbitrarily + # filter out one of the values for this flag to avoid having duplicate patterns + if not has_bias and bias_is_quantized: + continue + kwargs = _get_quantized_conv_bn_example_inputs_kwargs( + is_per_channel, has_bias, bias_is_quantized, is_cuda + ) + match_pattern = _get_quantized_qat_conv_bn_pattern( + is_per_channel, has_bias, bias_is_quantized, conv_fn, bn_is_training + ) + match_pattern = _get_aten_graph_module_for_pattern( + match_pattern, + example_inputs, + is_cuda, + **kwargs, + ) + replacement_pattern = _get_folded_quantized_qat_conv_bn_pattern( + is_per_channel, has_bias, bias_is_quantized, conv_fn, bn_is_training + ) + replacement_pattern = _get_aten_graph_module_for_pattern( + replacement_pattern, + example_inputs, + is_cuda, + **kwargs, + ) + replacements.extend( + replace_pattern_with_filters( + m, + match_pattern, + replacement_pattern, + ignore_literals=True, + ) + ) + m.recompile() + _remove_extra_dequantize(m) + + for r in replacements: + node_map = _get_conv_bn_pattern_nodes(r) + + # Step (2): Copy over metadata from original subgraph + for original_node, replacement_node in node_map.values(): + replacement_node.meta = original_node.meta + + # Step (3): Copy over args for weight (and optionally bias) q - dq nodes + _copy_over_q_dq_args(*node_map["conv_weight_q"]) + _copy_over_q_dq_args(*node_map["conv_weight_dq"]) + if "conv_bias_q" in node_map: + assert "conv_bias_dq" in node_map + _copy_over_q_dq_args(*node_map["conv_bias_q"]) + _copy_over_q_dq_args(*node_map["conv_bias_dq"]) + + # Step (4): Fold BN weights into conv + conv_bias = None + (_, conv_node) = node_map["conv"] + (_, bn_node) = node_map["bn"] + (_, conv_weight) = node_map["conv_weight"] + if "conv_bias" in node_map: + (_, conv_bias) = node_map["conv_bias"] + fold_bn_weights_into_conv_node(conv_node, conv_weight, conv_bias, bn_node, m) + + # Copy over literal args for conv + for original_node in _filter_nodes_map(r.nodes_map).values(): + if _is_conv_or_conv_transpose_node(original_node): + _copy_over_literal_conv_args(original_node, conv_node) + + m.graph.eliminate_dead_code() + m.recompile() + return m diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nassau b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nassau new file mode 100644 index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nassau differ diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nipigon b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nipigon new file mode 100644 index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Nipigon differ diff --git a/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Toronto b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Toronto new file mode 100644 index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd Binary files /dev/null and b/shared/package-files/a5/a587a1a1607439f7bac283e1815f2bdbafb9649a453d18e06c2e44e6996d888f/Toronto differ diff --git a/shared/package-files/a5/a5891d112e3ff0c262f4c90417bf60af52854f888f52f6cc4fb3650d63fb69e7/script.ld b/shared/package-files/a5/a5891d112e3ff0c262f4c90417bf60af52854f888f52f6cc4fb3650d63fb69e7/script.ld new file mode 100644 index 0000000000000000000000000000000000000000..5a052e984fcd720526201aa93d6d13b0aba2107a --- /dev/null +++ b/shared/package-files/a5/a5891d112e3ff0c262f4c90417bf60af52854f888f52f6cc4fb3650d63fb69e7/script.ld @@ -0,0 +1,8 @@ +SECTIONS { + /* By default, in LLD 16, .lrodata is placed immediately after .rodata. + * However, .lrodata can be very large in our compiled models, which leads to + * relocation out-of-range errors for relative relocations. So we place it + * after other the sections that are referenced from .text using relative + * relocations. This is the default behavior in GNU ld. */ + .lrodata : { *(.lrodata) } + } INSERT AFTER .bss; diff --git a/shared/package-files/a5/a58d6046653cdb2d873bd7bf6833e91d8a3d2dbf003f4b7448b833d3dfd8751d/graph.py b/shared/package-files/a5/a58d6046653cdb2d873bd7bf6833e91d8a3d2dbf003f4b7448b833d3dfd8751d/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..26a4eae6d18c32954d784310b5e87834332662ae --- /dev/null +++ b/shared/package-files/a5/a58d6046653cdb2d873bd7bf6833e91d8a3d2dbf003f4b7448b833d3dfd8751d/graph.py @@ -0,0 +1,161 @@ +# mypy: allow-untyped-defs +import io +import pickle +import warnings +from collections.abc import Collection +from typing import Optional, Union + +from torch.utils._import_utils import dill_available +from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe + + +__all__ = ["traverse", "traverse_dps"] + +DataPipe = Union[IterDataPipe, MapDataPipe] +DataPipeGraph = dict[int, tuple[DataPipe, "DataPipeGraph"]] + + +def _stub_unpickler(): + return "STUB" + + +# TODO(VitalyFedyunin): Make sure it works without dill module installed +def _list_connected_datapipes( + scan_obj: DataPipe, only_datapipe: bool, cache: set[int] +) -> list[DataPipe]: + f = io.BytesIO() + p = pickle.Pickler( + f + ) # Not going to work for lambdas, but dill infinite loops on typing and can't be used as is + if dill_available(): + from dill import Pickler as dill_Pickler + + d = dill_Pickler(f) + else: + d = None + + captured_connections = [] + + def getstate_hook(ori_state): + state = None + if isinstance(ori_state, dict): + state = {} + for k, v in ori_state.items(): + if isinstance(v, (IterDataPipe, MapDataPipe, Collection)): + state[k] = v + elif isinstance(ori_state, (tuple, list)): + state = [] # type: ignore[assignment] + for v in ori_state: + if isinstance(v, (IterDataPipe, MapDataPipe, Collection)): + state.append(v) # type: ignore[attr-defined] + elif isinstance(ori_state, (IterDataPipe, MapDataPipe, Collection)): + state = ori_state # type: ignore[assignment] + return state + + def reduce_hook(obj): + if obj == scan_obj or id(obj) in cache: + raise NotImplementedError + else: + captured_connections.append(obj) + # Adding id to remove duplicate DataPipe serialized at the same level + cache.add(id(obj)) + return _stub_unpickler, () + + datapipe_classes: tuple[type[DataPipe]] = (IterDataPipe, MapDataPipe) # type: ignore[assignment] + + try: + for cls in datapipe_classes: + cls.set_reduce_ex_hook(reduce_hook) + if only_datapipe: + cls.set_getstate_hook(getstate_hook) + try: + p.dump(scan_obj) + except (pickle.PickleError, AttributeError, TypeError): + if dill_available(): + d.dump(scan_obj) + else: + raise + finally: + for cls in datapipe_classes: + cls.set_reduce_ex_hook(None) + if only_datapipe: + cls.set_getstate_hook(None) + if dill_available(): + from dill import extend as dill_extend + + dill_extend(False) # Undo change to dispatch table + return captured_connections + + +def traverse_dps(datapipe: DataPipe) -> DataPipeGraph: + r""" + Traverse the DataPipes and their attributes to extract the DataPipe graph. + + This only looks into the attribute from each DataPipe that is either a + DataPipe and a Python collection object such as ``list``, ``tuple``, + ``set`` and ``dict``. + + Args: + datapipe: the end DataPipe of the graph + Returns: + A graph represented as a nested dictionary, where keys are ids of DataPipe instances + and values are tuples of DataPipe instance and the sub-graph + """ + cache: set[int] = set() + return _traverse_helper(datapipe, only_datapipe=True, cache=cache) + + +def traverse(datapipe: DataPipe, only_datapipe: Optional[bool] = None) -> DataPipeGraph: + r""" + Traverse the DataPipes and their attributes to extract the DataPipe graph. + + [Deprecated] + When ``only_dataPipe`` is specified as ``True``, it would only look into the + attribute from each DataPipe that is either a DataPipe and a Python collection object + such as ``list``, ``tuple``, ``set`` and ``dict``. + + Note: + This function is deprecated. Please use `traverse_dps` instead. + + Args: + datapipe: the end DataPipe of the graph + only_datapipe: If ``False`` (default), all attributes of each DataPipe are traversed. + This argument is deprecating and will be removed after the next release. + Returns: + A graph represented as a nested dictionary, where keys are ids of DataPipe instances + and values are tuples of DataPipe instance and the sub-graph + """ + msg = ( + "`traverse` function and will be removed after 1.13. " + "Please use `traverse_dps` instead." + ) + if not only_datapipe: + msg += " And, the behavior will be changed to the equivalent of `only_datapipe=True`." + warnings.warn(msg, FutureWarning) + if only_datapipe is None: + only_datapipe = False + cache: set[int] = set() + return _traverse_helper(datapipe, only_datapipe, cache) + + +# Add cache here to prevent infinite recursion on DataPipe +def _traverse_helper( + datapipe: DataPipe, only_datapipe: bool, cache: set[int] +) -> DataPipeGraph: + if not isinstance(datapipe, (IterDataPipe, MapDataPipe)): + raise RuntimeError( + f"Expected `IterDataPipe` or `MapDataPipe`, but {type(datapipe)} is found" + ) + + dp_id = id(datapipe) + if dp_id in cache: + return {} + cache.add(dp_id) + # Using cache.copy() here is to prevent the same DataPipe pollutes the cache on different paths + items = _list_connected_datapipes(datapipe, only_datapipe, cache.copy()) + d: DataPipeGraph = {dp_id: (datapipe, {})} + for item in items: + # Using cache.copy() here is to prevent recursion on a single path rather than global graph + # Single DataPipe can present multiple times in different paths in graph + d[dp_id][1].update(_traverse_helper(item, only_datapipe, cache.copy())) + return d diff --git a/shared/package-files/a5/a593dadcc93415051f69ea9cc1093031b13a67f51bdae6f8b32a8c02ba4030f6/_standard_gamma_grad.h b/shared/package-files/a5/a593dadcc93415051f69ea9cc1093031b13a67f51bdae6f8b32a8c02ba4030f6/_standard_gamma_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..a6248800b2ad09ddaeca680e0581f3b94eccb355 --- /dev/null +++ b/shared/package-files/a5/a593dadcc93415051f69ea9cc1093031b13a67f51bdae6f8b32a8c02ba4030f6/_standard_gamma_grad.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_standard_gamma_grad(Tensor self, Tensor output) -> Tensor +inline at::Tensor _standard_gamma_grad(const at::Tensor & self, const at::Tensor & output) { + return at::_ops::_standard_gamma_grad::call(self, output); +} + +// aten::_standard_gamma_grad.out(Tensor self, Tensor output, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _standard_gamma_grad_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & output) { + return at::_ops::_standard_gamma_grad_out::call(self, output, out); +} +// aten::_standard_gamma_grad.out(Tensor self, Tensor output, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _standard_gamma_grad_outf(const at::Tensor & self, const at::Tensor & output, at::Tensor & out) { + return at::_ops::_standard_gamma_grad_out::call(self, output, out); +} + +} diff --git a/shared/package-files/a5/a5951477c3dc8e413893621426a27cb2f23b681b1da236307ebf1148ef37a367/adaptive_max_pool3d_backward.h b/shared/package-files/a5/a5951477c3dc8e413893621426a27cb2f23b681b1da236307ebf1148ef37a367/adaptive_max_pool3d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..066d6b4d32508565248ce126443444f37382aa04 --- /dev/null +++ b/shared/package-files/a5/a5951477c3dc8e413893621426a27cb2f23b681b1da236307ebf1148ef37a367/adaptive_max_pool3d_backward.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & adaptive_max_pool3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) { + return at::_ops::adaptive_max_pool3d_backward_grad_input::call(grad_output, self, indices, grad_input); +} +// aten::adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & adaptive_max_pool3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, at::Tensor & grad_input) { + return at::_ops::adaptive_max_pool3d_backward_grad_input::call(grad_output, self, indices, grad_input); +} + +// aten::adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor +inline at::Tensor adaptive_max_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) { + return at::_ops::adaptive_max_pool3d_backward::call(grad_output, self, indices); +} + +} diff --git a/shared/package-files/a5/a595a7ddfe8d098fa51ad562290875d4d2790a7f9c5c12a1bda70cc9c837f38e/lazy_imports.py b/shared/package-files/a5/a595a7ddfe8d098fa51ad562290875d4d2790a7f9c5c12a1bda70cc9c837f38e/lazy_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c05ca5462868fbccc270ea1e93b301037dfc8c --- /dev/null +++ b/shared/package-files/a5/a595a7ddfe8d098fa51ad562290875d4d2790a7f9c5c12a1bda70cc9c837f38e/lazy_imports.py @@ -0,0 +1,188 @@ +import importlib +import importlib.util +import inspect +import os +import sys +import types + +__all__ = ["attach", "_lazy_import"] + + +def attach(module_name, submodules=None, submod_attrs=None): + """Attach lazily loaded submodules, and functions or other attributes. + + Typically, modules import submodules and attributes as follows:: + + import mysubmodule + import anothersubmodule + + from .foo import someattr + + The idea of this function is to replace the `__init__.py` + module's `__getattr__`, `__dir__`, and `__all__` attributes such that + all imports work exactly the way they normally would, except that the + actual import is delayed until the resulting module object is first used. + + The typical way to call this function, replacing the above imports, is:: + + __getattr__, __lazy_dir__, __all__ = lazy.attach( + __name__, ["mysubmodule", "anothersubmodule"], {"foo": "someattr"} + ) + + This functionality requires Python 3.7 or higher. + + Parameters + ---------- + module_name : str + Typically use __name__. + submodules : set + List of submodules to lazily import. + submod_attrs : dict + Dictionary of submodule -> list of attributes / functions. + These attributes are imported as they are used. + + Returns + ------- + __getattr__, __dir__, __all__ + + """ + if submod_attrs is None: + submod_attrs = {} + + if submodules is None: + submodules = set() + else: + submodules = set(submodules) + + attr_to_modules = { + attr: mod for mod, attrs in submod_attrs.items() for attr in attrs + } + + __all__ = list(submodules | attr_to_modules.keys()) + + def __getattr__(name): + if name in submodules: + return importlib.import_module(f"{module_name}.{name}") + elif name in attr_to_modules: + submod = importlib.import_module(f"{module_name}.{attr_to_modules[name]}") + return getattr(submod, name) + else: + raise AttributeError(f"No {module_name} attribute {name}") + + def __dir__(): + return __all__ + + if os.environ.get("EAGER_IMPORT", ""): + for attr in set(attr_to_modules.keys()) | submodules: + __getattr__(attr) + + return __getattr__, __dir__, list(__all__) + + +class DelayedImportErrorModule(types.ModuleType): + def __init__(self, frame_data, *args, **kwargs): + self.__frame_data = frame_data + super().__init__(*args, **kwargs) + + def __getattr__(self, x): + if x in ("__class__", "__file__", "__frame_data"): + super().__getattr__(x) + else: + fd = self.__frame_data + raise ModuleNotFoundError( + f"No module named '{fd['spec']}'\n\n" + "This error is lazily reported, having originally occurred in\n" + f" File {fd['filename']}, line {fd['lineno']}, in {fd['function']}\n\n" + f"----> {''.join(fd['code_context'] or '').strip()}" + ) + + +def _lazy_import(fullname): + """Return a lazily imported proxy for a module or library. + + Warning + ------- + Importing using this function can currently cause trouble + when the user tries to import from a subpackage of a module before + the package is fully imported. In particular, this idiom may not work: + + np = lazy_import("numpy") + from numpy.lib import recfunctions + + This is due to a difference in the way Python's LazyLoader handles + subpackage imports compared to the normal import process. Hopefully + we will get Python's LazyLoader to fix this, or find a workaround. + In the meantime, this is a potential problem. + + The workaround is to import numpy before importing from the subpackage. + + Notes + ----- + We often see the following pattern:: + + def myfunc(): + import scipy as sp + sp.argmin(...) + .... + + This is to prevent a library, in this case `scipy`, from being + imported at function definition time, since that can be slow. + + This function provides a proxy module that, upon access, imports + the actual module. So the idiom equivalent to the above example is:: + + sp = lazy.load("scipy") + + def myfunc(): + sp.argmin(...) + .... + + The initial import time is fast because the actual import is delayed + until the first attribute is requested. The overall import time may + decrease as well for users that don't make use of large portions + of the library. + + Parameters + ---------- + fullname : str + The full name of the package or subpackage to import. For example:: + + sp = lazy.load("scipy") # import scipy as sp + spla = lazy.load("scipy.linalg") # import scipy.linalg as spla + + Returns + ------- + pm : importlib.util._LazyModule + Proxy module. Can be used like any regularly imported module. + Actual loading of the module occurs upon first attribute request. + + """ + try: + return sys.modules[fullname] + except: + pass + + # Not previously loaded -- look it up + spec = importlib.util.find_spec(fullname) + + if spec is None: + try: + parent = inspect.stack()[1] + frame_data = { + "spec": fullname, + "filename": parent.filename, + "lineno": parent.lineno, + "function": parent.function, + "code_context": parent.code_context, + } + return DelayedImportErrorModule(frame_data, "DelayedImportErrorModule") + finally: + del parent + + module = importlib.util.module_from_spec(spec) + sys.modules[fullname] = module + + loader = importlib.util.LazyLoader(spec.loader) + loader.exec_module(module) + + return module diff --git a/shared/package-files/a5/a5971f88be14cd1417d59adf539ae48c5d818f95362a4e0eb00017e3690ab37b/exceptions.py b/shared/package-files/a5/a5971f88be14cd1417d59adf539ae48c5d818f95362a4e0eb00017e3690ab37b/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..5ece595aad647542740e5e9efcae9642518cb147 --- /dev/null +++ b/shared/package-files/a5/a5971f88be14cd1417d59adf539ae48c5d818f95362a4e0eb00017e3690ab37b/exceptions.py @@ -0,0 +1,62 @@ +"""asyncio exceptions.""" + + +__all__ = ('BrokenBarrierError', + 'CancelledError', 'InvalidStateError', 'TimeoutError', + 'IncompleteReadError', 'LimitOverrunError', + 'SendfileNotAvailableError') + + +class CancelledError(BaseException): + """The Future or Task was cancelled.""" + + +TimeoutError = TimeoutError # make local alias for the standard exception + + +class InvalidStateError(Exception): + """The operation is not allowed in this state.""" + + +class SendfileNotAvailableError(RuntimeError): + """Sendfile syscall is not available. + + Raised if OS does not support sendfile syscall for given socket or + file type. + """ + + +class IncompleteReadError(EOFError): + """ + Incomplete read error. Attributes: + + - partial: read bytes string before the end of stream was reached + - expected: total number of expected bytes (or None if unknown) + """ + def __init__(self, partial, expected): + r_expected = 'undefined' if expected is None else repr(expected) + super().__init__(f'{len(partial)} bytes read on a total of ' + f'{r_expected} expected bytes') + self.partial = partial + self.expected = expected + + def __reduce__(self): + return type(self), (self.partial, self.expected) + + +class LimitOverrunError(Exception): + """Reached the buffer limit while looking for a separator. + + Attributes: + - consumed: total number of to be consumed bytes. + """ + def __init__(self, message, consumed): + super().__init__(message) + self.consumed = consumed + + def __reduce__(self): + return type(self), (self.args[0], self.consumed) + + +class BrokenBarrierError(RuntimeError): + """Barrier is broken by barrier.abort() call.""" diff --git a/shared/package-files/a5/a598bad5e3f6565e97788b99cc616ae4f61cb3141a6953cbfcb879de64b7e674/split_with_sizes.h b/shared/package-files/a5/a598bad5e3f6565e97788b99cc616ae4f61cb3141a6953cbfcb879de64b7e674/split_with_sizes.h new file mode 100644 index 0000000000000000000000000000000000000000..75f7e193314fe47d6207e2ed7abc67997d99c4e1 --- /dev/null +++ b/shared/package-files/a5/a598bad5e3f6565e97788b99cc616ae4f61cb3141a6953cbfcb879de64b7e674/split_with_sizes.h @@ -0,0 +1,48 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] +inline ::std::vector split_with_sizes(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { + return at::_ops::split_with_sizes::call(self, c10::fromIntArrayRefSlow(split_sizes), dim); +} +namespace symint { + template >> + ::std::vector split_with_sizes(const at::Tensor & self, at::IntArrayRef split_sizes, int64_t dim=0) { + return at::_ops::split_with_sizes::call(self, c10::fromIntArrayRefSlow(split_sizes), dim); + } +} + +// aten::split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] +inline ::std::vector split_with_sizes_symint(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { + return at::_ops::split_with_sizes::call(self, split_sizes, dim); +} +namespace symint { + template >> + ::std::vector split_with_sizes(const at::Tensor & self, c10::SymIntArrayRef split_sizes, int64_t dim=0) { + return at::_ops::split_with_sizes::call(self, split_sizes, dim); + } +} + +} diff --git a/shared/package-files/a5/a59f82ded0cfffcc2828072d3684bb230c96fbd02e0793cc1c1e41d28865a70f/__init__.py b/shared/package-files/a5/a59f82ded0cfffcc2828072d3684bb230c96fbd02e0793cc1c1e41d28865a70f/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e78fe96f84d68e9b119571eb22dedb7033811b23 --- /dev/null +++ b/shared/package-files/a5/a59f82ded0cfffcc2828072d3684bb230c96fbd02e0793cc1c1e41d28865a70f/__init__.py @@ -0,0 +1,45 @@ +"""Integration functions that integrate a SymPy expression. + + Examples + ======== + + >>> from sympy import integrate, sin + >>> from sympy.abc import x + >>> integrate(1/x,x) + log(x) + >>> integrate(sin(x),x) + -cos(x) +""" +from .integrals import integrate, Integral, line_integrate +from .transforms import (mellin_transform, inverse_mellin_transform, + MellinTransform, InverseMellinTransform, + laplace_transform, inverse_laplace_transform, + laplace_correspondence, laplace_initial_conds, + LaplaceTransform, InverseLaplaceTransform, + fourier_transform, inverse_fourier_transform, + FourierTransform, InverseFourierTransform, + sine_transform, inverse_sine_transform, + SineTransform, InverseSineTransform, + cosine_transform, inverse_cosine_transform, + CosineTransform, InverseCosineTransform, + hankel_transform, inverse_hankel_transform, + HankelTransform, InverseHankelTransform) +from .singularityfunctions import singularityintegrate + +__all__ = [ + 'integrate', 'Integral', 'line_integrate', + + 'mellin_transform', 'inverse_mellin_transform', 'MellinTransform', + 'InverseMellinTransform', 'laplace_transform', + 'inverse_laplace_transform', 'LaplaceTransform', + 'laplace_correspondence', 'laplace_initial_conds', + 'InverseLaplaceTransform', 'fourier_transform', + 'inverse_fourier_transform', 'FourierTransform', + 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', + 'SineTransform', 'InverseSineTransform', 'cosine_transform', + 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', + 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', + 'InverseHankelTransform', + + 'singularityintegrate', +] diff --git a/shared/package-files/a5/a5a0f988686fb033ec61c29755b1a6d0c9c0d924b3b440eebbbd4af16d023407/conv.py b/shared/package-files/a5/a5a0f988686fb033ec61c29755b1a6d0c9c0d924b3b440eebbbd4af16d023407/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..af9f5a8386cc23364448e6ef020718ae54d8256c --- /dev/null +++ b/shared/package-files/a5/a5a0f988686fb033ec61c29755b1a6d0c9c0d924b3b440eebbbd4af16d023407/conv.py @@ -0,0 +1,1866 @@ +# mypy: allow-untyped-defs +import math +from typing import Optional, Union +from typing_extensions import deprecated + +import torch +from torch import Tensor +from torch._torch_docs import reproducibility_notes +from torch.nn import functional as F, init +from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t +from torch.nn.parameter import Parameter, UninitializedParameter + +from .lazy import LazyModuleMixin +from .module import Module +from .utils import _pair, _reverse_repeat_tuple, _single, _triple + + +__all__ = [ + "Conv1d", + "Conv2d", + "Conv3d", + "ConvTranspose1d", + "ConvTranspose2d", + "ConvTranspose3d", + "LazyConv1d", + "LazyConv2d", + "LazyConv3d", + "LazyConvTranspose1d", + "LazyConvTranspose2d", + "LazyConvTranspose3d", +] + +convolution_notes = { + "groups_note": r"""* :attr:`groups` controls the connections between inputs and outputs. + :attr:`in_channels` and :attr:`out_channels` must both be divisible by + :attr:`groups`. For example, + + * At groups=1, all inputs are convolved to all outputs. + * At groups=2, the operation becomes equivalent to having two conv + layers side by side, each seeing half the input channels + and producing half the output channels, and both subsequently + concatenated. + * At groups= :attr:`in_channels`, each input channel is convolved with + its own set of filters (of size + :math:`\frac{\text{out\_channels}}{\text{in\_channels}}`).""", + "depthwise_separable_note": r"""When `groups == in_channels` and `out_channels == K * in_channels`, + where `K` is a positive integer, this operation is also known as a "depthwise convolution". + + In other words, for an input of size :math:`(N, C_{in}, L_{in})`, + a depthwise convolution with a depthwise multiplier `K` can be performed with the arguments + :math:`(C_\text{in}=C_\text{in}, C_\text{out}=C_\text{in} \times \text{K}, ..., \text{groups}=C_\text{in})`.""", +} # noqa: B950 + + +class _ConvNd(Module): + __constants__ = [ + "stride", + "padding", + "dilation", + "groups", + "padding_mode", + "output_padding", + "in_channels", + "out_channels", + "kernel_size", + ] + __annotations__ = {"bias": Optional[torch.Tensor]} + + def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]) -> Tensor: # type: ignore[empty-body] + ... + + in_channels: int + _reversed_padding_repeated_twice: list[int] + out_channels: int + kernel_size: tuple[int, ...] + stride: tuple[int, ...] + padding: Union[str, tuple[int, ...]] + dilation: tuple[int, ...] + transposed: bool + output_padding: tuple[int, ...] + groups: int + padding_mode: str + weight: Tensor + bias: Optional[Tensor] + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: tuple[int, ...], + stride: tuple[int, ...], + padding: Union[str, tuple[int, ...]], + dilation: tuple[int, ...], + transposed: bool, + output_padding: tuple[int, ...], + groups: int, + bias: bool, + padding_mode: str, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + if groups <= 0: + raise ValueError("groups must be a positive integer") + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups") + if out_channels % groups != 0: + raise ValueError("out_channels must be divisible by groups") + valid_padding_strings = {"same", "valid"} + if isinstance(padding, str): + if padding not in valid_padding_strings: + raise ValueError( + f"Invalid padding string {padding!r}, should be one of {valid_padding_strings}" + ) + if padding == "same" and any(s != 1 for s in stride): + raise ValueError( + "padding='same' is not supported for strided convolutions" + ) + + valid_padding_modes = {"zeros", "reflect", "replicate", "circular"} + if padding_mode not in valid_padding_modes: + raise ValueError( + f"padding_mode must be one of {valid_padding_modes}, but got padding_mode='{padding_mode}'" + ) + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = kernel_size + self.stride = stride + self.padding = padding + self.dilation = dilation + self.transposed = transposed + self.output_padding = output_padding + self.groups = groups + self.padding_mode = padding_mode + # `_reversed_padding_repeated_twice` is the padding to be passed to + # `F.pad` if needed (e.g., for non-zero padding types that are + # implemented as two ops: padding + conv). `F.pad` accepts paddings in + # reverse order than the dimension. + if isinstance(self.padding, str): + self._reversed_padding_repeated_twice = [0, 0] * len(kernel_size) + if padding == "same": + for d, k, i in zip( + dilation, kernel_size, range(len(kernel_size) - 1, -1, -1) + ): + total_padding = d * (k - 1) + left_pad = total_padding // 2 + self._reversed_padding_repeated_twice[2 * i] = left_pad + self._reversed_padding_repeated_twice[2 * i + 1] = ( + total_padding - left_pad + ) + else: + self._reversed_padding_repeated_twice = _reverse_repeat_tuple( + self.padding, 2 + ) + + if transposed: + self.weight = Parameter( + torch.empty( + (in_channels, out_channels // groups, *kernel_size), + **factory_kwargs, + ) + ) + else: + self.weight = Parameter( + torch.empty( + (out_channels, in_channels // groups, *kernel_size), + **factory_kwargs, + ) + ) + if bias: + self.bias = Parameter(torch.empty(out_channels, **factory_kwargs)) + else: + self.register_parameter("bias", None) + + self.reset_parameters() + + def reset_parameters(self) -> None: + # Setting a=sqrt(5) in kaiming_uniform is the same as initializing with + # uniform(-1/sqrt(k), 1/sqrt(k)), where k = weight.size(1) * prod(*kernel_size) + # For more details see: https://github.com/pytorch/pytorch/issues/15314#issuecomment-477448573 + init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + if self.bias is not None: + fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) + if fan_in != 0: + bound = 1 / math.sqrt(fan_in) + init.uniform_(self.bias, -bound, bound) + + def extra_repr(self): + s = ( + "{in_channels}, {out_channels}, kernel_size={kernel_size}" + ", stride={stride}" + ) + if self.padding != (0,) * len(self.padding): + s += ", padding={padding}" + if self.dilation != (1,) * len(self.dilation): + s += ", dilation={dilation}" + if self.output_padding != (0,) * len(self.output_padding): + s += ", output_padding={output_padding}" + if self.groups != 1: + s += ", groups={groups}" + if self.bias is None: + s += ", bias=False" + if self.padding_mode != "zeros": + s += ", padding_mode={padding_mode}" + return s.format(**self.__dict__) + + def __setstate__(self, state): + super().__setstate__(state) + if not hasattr(self, "padding_mode"): + self.padding_mode = "zeros" + + +class Conv1d(_ConvNd): + __doc__ = ( + r"""Applies a 1D convolution over an input signal composed of several input + planes. + + In the simplest case, the output value of the layer with input size + :math:`(N, C_{\text{in}}, L)` and output :math:`(N, C_{\text{out}}, L_{\text{out}})` can be + precisely described as: + + .. math:: + \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + + \sum_{k = 0}^{C_{in} - 1} \text{weight}(C_{\text{out}_j}, k) + \star \text{input}(N_i, k) + + where :math:`\star` is the valid `cross-correlation`_ operator, + :math:`N` is a batch size, :math:`C` denotes a number of channels, + :math:`L` is a length of signal sequence. + """ + + r""" + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation, a single + number or a one-element tuple. + + * :attr:`padding` controls the amount of padding applied to the input. It + can be either a string {{'valid', 'same'}} or a tuple of ints giving the + amount of implicit padding applied on both sides. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also + known as the \u00e0 trous algorithm. It is harder to describe, but this `link`_ + has a nice visualization of what :attr:`dilation` does. +""" + r""" + {groups_note} + + Note: + {depthwise_separable_note} + Note: + {cudnn_reproducibility_note} + + Note: + ``padding='valid'`` is the same as no padding. ``padding='same'`` pads + the input so the output has the shape as the input. However, this mode + doesn't support any stride values other than 1. + + Note: + This module supports complex data types i.e. ``complex32, complex64, complex128``. + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to both sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel + elements. Default: 1 + groups (int, optional): Number of blocked connections from input + channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the + output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, + ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})` + - Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where + + .. math:: + L_{out} = \left\lfloor\frac{L_{in} + 2 \times \text{padding} - \text{dilation} + \times (\text{kernel\_size} - 1) - 1}{\text{stride}} + 1\right\rfloor + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{out\_channels}, + \frac{\text{in\_channels}}{\text{groups}}, \text{kernel\_size})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}` + bias (Tensor): the learnable bias of the module of shape + (out_channels). If :attr:`bias` is ``True``, then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}` + + Examples:: + + >>> m = nn.Conv1d(16, 33, 3, stride=2) + >>> input = torch.randn(20, 16, 50) + >>> output = m(input) + + .. _cross-correlation: + https://en.wikipedia.org/wiki/Cross-correlation + + .. _link: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: Union[str, _size_1_t] = 0, + dilation: _size_1_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", # TODO: refine this type + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + # we create new variables below to make mypy happy since kernel_size has + # type Union[int, Tuple[int]] and kernel_size_ has type Tuple[int] + kernel_size_ = _single(kernel_size) + stride_ = _single(stride) + padding_ = padding if isinstance(padding, str) else _single(padding) + dilation_ = _single(dilation) + super().__init__( + in_channels, + out_channels, + kernel_size_, + stride_, + padding_, + dilation_, + False, + _single(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]): + if self.padding_mode != "zeros": + return F.conv1d( + F.pad( + input, self._reversed_padding_repeated_twice, mode=self.padding_mode + ), + weight, + bias, + self.stride, + _single(0), + self.dilation, + self.groups, + ) + return F.conv1d( + input, weight, bias, self.stride, self.padding, self.dilation, self.groups + ) + + def forward(self, input: Tensor) -> Tensor: + return self._conv_forward(input, self.weight, self.bias) + + +class Conv2d(_ConvNd): + __doc__ = ( + r"""Applies a 2D convolution over an input signal composed of several input + planes. + + In the simplest case, the output value of the layer with input size + :math:`(N, C_{\text{in}}, H, W)` and output :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})` + can be precisely described as: + + .. math:: + \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) + + \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k) + + + where :math:`\star` is the valid 2D `cross-correlation`_ operator, + :math:`N` is a batch size, :math:`C` denotes a number of channels, + :math:`H` is a height of input planes in pixels, and :math:`W` is + width in pixels. + """ + + r""" + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation, a single + number or a tuple. + + * :attr:`padding` controls the amount of padding applied to the input. It + can be either a string {{'valid', 'same'}} or an int / a tuple of ints giving the + amount of implicit padding applied on both sides. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also + known as the \u00e0 trous algorithm. It is harder to describe, but this `link`_ + has a nice visualization of what :attr:`dilation` does. +""" + r""" + + {groups_note} + + The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be: + + - a single ``int`` -- in which case the same value is used for the height and width dimension + - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension, + and the second `int` for the width dimension + + Note: + {depthwise_separable_note} + + Note: + {cudnn_reproducibility_note} + + Note: + ``padding='valid'`` is the same as no padding. ``padding='same'`` pads + the input so the output has the shape as the input. However, this mode + doesn't support any stride values other than 1. + + Note: + This module supports complex data types i.e. ``complex32, complex64, complex128``. + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all four sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + groups (int, optional): Number of blocked connections from input + channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the + output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, + ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where + + .. math:: + H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] + \times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor + + .. math:: + W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] + \times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},` + :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}` + bias (Tensor): the learnable bias of the module of shape + (out_channels). If :attr:`bias` is ``True``, + then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}` + + Examples: + + >>> # With square kernels and equal stride + >>> m = nn.Conv2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> # non-square kernels and unequal stride and with padding and dilation + >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)) + >>> input = torch.randn(20, 16, 50, 100) + >>> output = m(input) + + .. _cross-correlation: + https://en.wikipedia.org/wiki/Cross-correlation + + .. _link: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_2_t, + stride: _size_2_t = 1, + padding: Union[str, _size_2_t] = 0, + dilation: _size_2_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", # TODO: refine this type + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size_ = _pair(kernel_size) + stride_ = _pair(stride) + padding_ = padding if isinstance(padding, str) else _pair(padding) + dilation_ = _pair(dilation) + super().__init__( + in_channels, + out_channels, + kernel_size_, + stride_, + padding_, + dilation_, + False, + _pair(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]): + if self.padding_mode != "zeros": + return F.conv2d( + F.pad( + input, self._reversed_padding_repeated_twice, mode=self.padding_mode + ), + weight, + bias, + self.stride, + _pair(0), + self.dilation, + self.groups, + ) + return F.conv2d( + input, weight, bias, self.stride, self.padding, self.dilation, self.groups + ) + + def forward(self, input: Tensor) -> Tensor: + return self._conv_forward(input, self.weight, self.bias) + + +class Conv3d(_ConvNd): + __doc__ = ( + r"""Applies a 3D convolution over an input signal composed of several input + planes. + + In the simplest case, the output value of the layer with input size :math:`(N, C_{in}, D, H, W)` + and output :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` can be precisely described as: + + .. math:: + out(N_i, C_{out_j}) = bias(C_{out_j}) + + \sum_{k = 0}^{C_{in} - 1} weight(C_{out_j}, k) \star input(N_i, k) + + where :math:`\star` is the valid 3D `cross-correlation`_ operator + """ + + r""" + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation. + + * :attr:`padding` controls the amount of padding applied to the input. It + can be either a string {{'valid', 'same'}} or a tuple of ints giving the + amount of implicit padding applied on both sides. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm. + It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does. +""" + r""" + + {groups_note} + + The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be: + + - a single ``int`` -- in which case the same value is used for the depth, height and width dimension + - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension, + the second `int` for the height dimension and the third `int` for the width dimension + + Note: + {depthwise_separable_note} + + Note: + {cudnn_reproducibility_note} + + Note: + ``padding='valid'`` is the same as no padding. ``padding='same'`` pads + the input so the output has the shape as the input. However, this mode + doesn't support any stride values other than 1. + + Note: + This module supports complex data types i.e. ``complex32, complex64, complex128``. + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all six sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or :math:`(C_{out}, D_{out}, H_{out}, W_{out})`, + where + + .. math:: + D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] + \times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor + + .. math:: + H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] + \times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor + + .. math:: + W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] + \times (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},` + :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}` + bias (Tensor): the learnable bias of the module of shape (out_channels). If :attr:`bias` is ``True``, + then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}` + + Examples:: + + >>> # With square kernels and equal stride + >>> m = nn.Conv3d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0)) + >>> input = torch.randn(20, 16, 10, 50, 100) + >>> output = m(input) + + .. _cross-correlation: + https://en.wikipedia.org/wiki/Cross-correlation + + .. _link: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_3_t, + stride: _size_3_t = 1, + padding: Union[str, _size_3_t] = 0, + dilation: _size_3_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size_ = _triple(kernel_size) + stride_ = _triple(stride) + padding_ = padding if isinstance(padding, str) else _triple(padding) + dilation_ = _triple(dilation) + super().__init__( + in_channels, + out_channels, + kernel_size_, + stride_, + padding_, + dilation_, + False, + _triple(0), + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]): + if self.padding_mode != "zeros": + return F.conv3d( + F.pad( + input, self._reversed_padding_repeated_twice, mode=self.padding_mode + ), + weight, + bias, + self.stride, + _triple(0), + self.dilation, + self.groups, + ) + return F.conv3d( + input, weight, bias, self.stride, self.padding, self.dilation, self.groups + ) + + def forward(self, input: Tensor) -> Tensor: + return self._conv_forward(input, self.weight, self.bias) + + +class _ConvTransposeNd(_ConvNd): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + bias, + padding_mode, + device=None, + dtype=None, + ) -> None: + if padding_mode != "zeros": + raise ValueError( + f'Only "zeros" padding mode is supported for {self.__class__.__name__}' + ) + + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + # dilation being an optional parameter is for backwards + # compatibility + def _output_padding( + self, + input: Tensor, + output_size: Optional[list[int]], + stride: list[int], + padding: list[int], + kernel_size: list[int], + num_spatial_dims: int, + dilation: Optional[list[int]] = None, + ) -> list[int]: + if output_size is None: + ret = _single(self.output_padding) # converting to list if was not already + else: + has_batch_dim = input.dim() == num_spatial_dims + 2 + num_non_spatial_dims = 2 if has_batch_dim else 1 + if len(output_size) == num_non_spatial_dims + num_spatial_dims: + output_size = output_size[num_non_spatial_dims:] + if len(output_size) != num_spatial_dims: + raise ValueError( + f"ConvTranspose{num_spatial_dims}D: for {input.dim()}D input, output_size must have {num_spatial_dims} " + f"or {num_non_spatial_dims + num_spatial_dims} elements (got {len(output_size)})" + ) + + min_sizes = torch.jit.annotate(list[int], []) + max_sizes = torch.jit.annotate(list[int], []) + for d in range(num_spatial_dims): + dim_size = ( + (input.size(d + num_non_spatial_dims) - 1) * stride[d] + - 2 * padding[d] + + (dilation[d] if dilation is not None else 1) + * (kernel_size[d] - 1) + + 1 + ) + min_sizes.append(dim_size) + max_sizes.append(min_sizes[d] + stride[d] - 1) + + for i in range(len(output_size)): + size = output_size[i] + min_size = min_sizes[i] + max_size = max_sizes[i] + if size < min_size or size > max_size: + raise ValueError( + f"requested an output size of {output_size}, but valid sizes range " + f"from {min_sizes} to {max_sizes} (for an input of {input.size()[2:]})" + ) + + res = torch.jit.annotate(list[int], []) + for d in range(num_spatial_dims): + res.append(output_size[d] - min_sizes[d]) + + ret = res + return ret + + +class ConvTranspose1d(_ConvTransposeNd): + __doc__ = ( + r"""Applies a 1D transposed convolution operator over an input image + composed of several input planes. + + This module can be seen as the gradient of Conv1d with respect to its input. + It is also known as a fractionally-strided convolution or + a deconvolution (although it is not an actual deconvolution operation as it does + not compute a true inverse of convolution). For more information, see the visualizations + `here`_ and the `Deconvolutional Networks`_ paper. + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation. + + * :attr:`padding` controls the amount of implicit zero padding on both + sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note + below for details. + + * :attr:`output_padding` controls the additional size added to one side + of the output shape. See note below for details. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm. + It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does. +""" + r""" + {groups_note} + + Note: + The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding`` + amount of zero padding to both sizes of the input. This is set so that + when a :class:`~torch.nn.Conv1d` and a :class:`~torch.nn.ConvTranspose1d` + are initialized with same parameters, they are inverses of each other in + regard to the input and output shapes. However, when ``stride > 1``, + :class:`~torch.nn.Conv1d` maps multiple input shapes to the same output + shape. :attr:`output_padding` is provided to resolve this ambiguity by + effectively increasing the calculated output shape on one side. Note + that :attr:`output_padding` is only used to find output shape, but does + not actually add zero-padding to output. + + Note: + In some circumstances when using the CUDA backend with CuDNN, this operator + may select a nondeterministic algorithm to increase performance. If this is + undesirable, you can try to make the operation deterministic (potentially at + a performance cost) by setting ``torch.backends.cudnn.deterministic = + True``. + Please see the notes on :doc:`/notes/randomness` for background. + + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})` + - Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where + + .. math:: + L_{out} = (L_{in} - 1) \times \text{stride} - 2 \times \text{padding} + \text{dilation} + \times (\text{kernel\_size} - 1) + \text{output\_padding} + 1 + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},` + :math:`\text{kernel\_size})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}` + bias (Tensor): the learnable bias of the module of shape (out_channels). + If :attr:`bias` is ``True``, then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}` + + .. _`here`: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + + .. _`Deconvolutional Networks`: + https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: _size_1_t = 0, + output_padding: _size_1_t = 0, + groups: int = 1, + bias: bool = True, + dilation: _size_1_t = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _single(kernel_size) + stride = _single(stride) + padding = _single(padding) + dilation = _single(dilation) + output_padding = _single(output_padding) + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def forward(self, input: Tensor, output_size: Optional[list[int]] = None) -> Tensor: + if self.padding_mode != "zeros": + raise ValueError( + "Only `zeros` padding mode is supported for ConvTranspose1d" + ) + + assert isinstance(self.padding, tuple) + # One cannot replace List by Tuple or Sequence in "_output_padding" because + # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`. + num_spatial_dims = 1 + output_padding = self._output_padding( + input, + output_size, + self.stride, # type: ignore[arg-type] + self.padding, # type: ignore[arg-type] + self.kernel_size, # type: ignore[arg-type] + num_spatial_dims, + self.dilation, # type: ignore[arg-type] + ) + return F.conv_transpose1d( + input, + self.weight, + self.bias, + self.stride, + self.padding, + output_padding, + self.groups, + self.dilation, + ) + + +class ConvTranspose2d(_ConvTransposeNd): + __doc__ = ( + r"""Applies a 2D transposed convolution operator over an input image + composed of several input planes. + + This module can be seen as the gradient of Conv2d with respect to its input. + It is also known as a fractionally-strided convolution or + a deconvolution (although it is not an actual deconvolution operation as it does + not compute a true inverse of convolution). For more information, see the visualizations + `here`_ and the `Deconvolutional Networks`_ paper. + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation. + + * :attr:`padding` controls the amount of implicit zero padding on both + sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note + below for details. + + * :attr:`output_padding` controls the additional size added to one side + of the output shape. See note below for details. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm. + It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does. +""" + r""" + {groups_note} + + The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding` + can either be: + + - a single ``int`` -- in which case the same value is used for the height and width dimensions + - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension, + and the second `int` for the width dimension + + Note: + The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding`` + amount of zero padding to both sizes of the input. This is set so that + when a :class:`~torch.nn.Conv2d` and a :class:`~torch.nn.ConvTranspose2d` + are initialized with same parameters, they are inverses of each other in + regard to the input and output shapes. However, when ``stride > 1``, + :class:`~torch.nn.Conv2d` maps multiple input shapes to the same output + shape. :attr:`output_padding` is provided to resolve this ambiguity by + effectively increasing the calculated output shape on one side. Note + that :attr:`output_padding` is only used to find output shape, but does + not actually add zero-padding to output. + + Note: + {cudnn_reproducibility_note} + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of each dimension in the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where + + .. math:: + H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0] + \times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1 + .. math:: + W_{out} = (W_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1] + \times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1 + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},` + :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}` + bias (Tensor): the learnable bias of the module of shape (out_channels) + If :attr:`bias` is ``True``, then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}` + + Examples:: + + >>> # With square kernels and equal stride + >>> m = nn.ConvTranspose2d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2)) + >>> input = torch.randn(20, 16, 50, 100) + >>> output = m(input) + >>> # exact output size can be also specified as an argument + >>> input = torch.randn(1, 16, 12, 12) + >>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1) + >>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1) + >>> h = downsample(input) + >>> h.size() + torch.Size([1, 16, 6, 6]) + >>> output = upsample(h, output_size=input.size()) + >>> output.size() + torch.Size([1, 16, 12, 12]) + + .. _`here`: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + + .. _`Deconvolutional Networks`: + https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_2_t, + stride: _size_2_t = 1, + padding: _size_2_t = 0, + output_padding: _size_2_t = 0, + groups: int = 1, + bias: bool = True, + dilation: _size_2_t = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _pair(kernel_size) + stride = _pair(stride) + padding = _pair(padding) + dilation = _pair(dilation) + output_padding = _pair(output_padding) + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def forward(self, input: Tensor, output_size: Optional[list[int]] = None) -> Tensor: + if self.padding_mode != "zeros": + raise ValueError( + "Only `zeros` padding mode is supported for ConvTranspose2d" + ) + + assert isinstance(self.padding, tuple) + # One cannot replace List by Tuple or Sequence in "_output_padding" because + # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`. + num_spatial_dims = 2 + output_padding = self._output_padding( + input, + output_size, + self.stride, # type: ignore[arg-type] + self.padding, # type: ignore[arg-type] + self.kernel_size, # type: ignore[arg-type] + num_spatial_dims, + self.dilation, # type: ignore[arg-type] + ) + + return F.conv_transpose2d( + input, + self.weight, + self.bias, + self.stride, + self.padding, + output_padding, + self.groups, + self.dilation, + ) + + +class ConvTranspose3d(_ConvTransposeNd): + __doc__ = ( + r"""Applies a 3D transposed convolution operator over an input image composed of several input + planes. + The transposed convolution operator multiplies each input value element-wise by a learnable kernel, + and sums over the outputs from all input feature planes. + + This module can be seen as the gradient of Conv3d with respect to its input. + It is also known as a fractionally-strided convolution or + a deconvolution (although it is not an actual deconvolution operation as it does + not compute a true inverse of convolution). For more information, see the visualizations + `here`_ and the `Deconvolutional Networks`_ paper. + + This module supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + * :attr:`stride` controls the stride for the cross-correlation. + + * :attr:`padding` controls the amount of implicit zero padding on both + sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note + below for details. + + * :attr:`output_padding` controls the additional size added to one side + of the output shape. See note below for details. +""" + """ + * :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm. + It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does. +""" + r""" + {groups_note} + + The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding` + can either be: + + - a single ``int`` -- in which case the same value is used for the depth, height and width dimensions + - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension, + the second `int` for the height dimension and the third `int` for the width dimension + + Note: + The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding`` + amount of zero padding to both sizes of the input. This is set so that + when a :class:`~torch.nn.Conv3d` and a :class:`~torch.nn.ConvTranspose3d` + are initialized with same parameters, they are inverses of each other in + regard to the input and output shapes. However, when ``stride > 1``, + :class:`~torch.nn.Conv3d` maps multiple input shapes to the same output + shape. :attr:`output_padding` is provided to resolve this ambiguity by + effectively increasing the calculated output shape on one side. Note + that :attr:`output_padding` is only used to find output shape, but does + not actually add zero-padding to output. + + Note: + {cudnn_reproducibility_note} + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of each dimension in the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + """.format( + **reproducibility_notes, **convolution_notes + ) + + r""" + + Shape: + - Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})` + - Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or + :math:`(C_{out}, D_{out}, H_{out}, W_{out})`, where + + .. math:: + D_{out} = (D_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0] + \times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1 + .. math:: + H_{out} = (H_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1] + \times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1 + .. math:: + W_{out} = (W_{in} - 1) \times \text{stride}[2] - 2 \times \text{padding}[2] + \text{dilation}[2] + \times (\text{kernel\_size}[2] - 1) + \text{output\_padding}[2] + 1 + + + Attributes: + weight (Tensor): the learnable weights of the module of shape + :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},` + :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`. + The values of these weights are sampled from + :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}` + bias (Tensor): the learnable bias of the module of shape (out_channels) + If :attr:`bias` is ``True``, then the values of these weights are + sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where + :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}` + + Examples:: + + >>> # With square kernels and equal stride + >>> m = nn.ConvTranspose3d(16, 33, 3, stride=2) + >>> # non-square kernels and unequal stride and with padding + >>> m = nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2)) + >>> input = torch.randn(20, 16, 10, 50, 100) + >>> output = m(input) + + .. _`here`: + https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md + + .. _`Deconvolutional Networks`: + https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf + """ + ) + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: _size_3_t, + stride: _size_3_t = 1, + padding: _size_3_t = 0, + output_padding: _size_3_t = 0, + groups: int = 1, + bias: bool = True, + dilation: _size_3_t = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + kernel_size = _triple(kernel_size) + stride = _triple(stride) + padding = _triple(padding) + dilation = _triple(dilation) + output_padding = _triple(output_padding) + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation, + True, + output_padding, + groups, + bias, + padding_mode, + **factory_kwargs, + ) + + def forward(self, input: Tensor, output_size: Optional[list[int]] = None) -> Tensor: + if self.padding_mode != "zeros": + raise ValueError( + "Only `zeros` padding mode is supported for ConvTranspose3d" + ) + + assert isinstance(self.padding, tuple) + # One cannot replace List by Tuple or Sequence in "_output_padding" because + # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`. + num_spatial_dims = 3 + output_padding = self._output_padding( + input, + output_size, + self.stride, # type: ignore[arg-type] + self.padding, # type: ignore[arg-type] + self.kernel_size, # type: ignore[arg-type] + num_spatial_dims, + self.dilation, # type: ignore[arg-type] + ) + + return F.conv_transpose3d( + input, + self.weight, + self.bias, + self.stride, + self.padding, + output_padding, + self.groups, + self.dilation, + ) + + +# TODO: Deprecate and remove the following alias `_ConvTransposeMixin`. +# +# `_ConvTransposeMixin` was a mixin that was removed. It is meant to be used +# with `_ConvNd` to construct actual module classes that implements conv +# transpose ops: +# +# class MyConvTranspose(_ConvNd, _ConvTransposeMixin): +# ... +# +# In PyTorch, it has been replaced by `_ConvTransposeNd`, which is a proper +# subclass of `_ConvNd`. However, some user code in the wild still (incorrectly) +# use the internal class `_ConvTransposeMixin`. Hence, we provide this alias +# for BC, because it is cheap and easy for us to do so, even though that +# `_ConvTransposeNd` is really not a mixin anymore (but multiple inheritance as +# above would still work). +class _ConvTransposeMixin(_ConvTransposeNd): + @deprecated( + "`_ConvTransposeMixin` is a deprecated internal class. " + "Please consider using public APIs.", + category=FutureWarning, + ) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +# TODO: Conv2dLocal +# TODO: Conv2dMap +# TODO: ConvTranspose2dMap + + +class _LazyConvXdMixin(LazyModuleMixin): + groups: int + transposed: bool + in_channels: int + out_channels: int + kernel_size: tuple[int, ...] + weight: UninitializedParameter + bias: UninitializedParameter + + def reset_parameters(self) -> None: + # has_uninitialized_params is defined in parent class and it is using a protocol on self + if not self.has_uninitialized_params() and self.in_channels != 0: # type: ignore[misc] + # "type:ignore[..]" is required because mypy thinks that "reset_parameters" is undefined + # in super class. Turns out that it is defined in _ConvND which is inherited by any class + # that also inherits _LazyConvXdMixin + super().reset_parameters() # type: ignore[misc] + + # Signature of "initialize_parameters" is incompatible with the definition in supertype LazyModuleMixin + def initialize_parameters(self, input: Tensor, *args, **kwargs) -> None: # type: ignore[override] + # defined by parent class but using a protocol + if self.has_uninitialized_params(): # type: ignore[misc] + self.in_channels = self._get_in_channels(input) + if self.in_channels % self.groups != 0: + raise ValueError("in_channels must be divisible by groups") + assert isinstance(self.weight, UninitializedParameter) + if self.transposed: + self.weight.materialize( + ( + self.in_channels, + self.out_channels // self.groups, + *self.kernel_size, + ) + ) + else: + self.weight.materialize( + ( + self.out_channels, + self.in_channels // self.groups, + *self.kernel_size, + ) + ) + if self.bias is not None: + assert isinstance(self.bias, UninitializedParameter) + self.bias.materialize((self.out_channels,)) + self.reset_parameters() + + # Function to extract in_channels from first input. + def _get_in_channels(self, input: Tensor) -> int: + num_spatial_dims = self._get_num_spatial_dims() + num_dims_no_batch = num_spatial_dims + 1 # +1 for channels dim + num_dims_batch = num_dims_no_batch + 1 + if input.dim() not in (num_dims_no_batch, num_dims_batch): + raise RuntimeError( + f"Expected {num_dims_no_batch}D (unbatched) or {num_dims_batch}D (batched) input " + f"to {self.__class__.__name__}, but " + f"got input of size: {input.shape}" + ) + return input.shape[1] if input.dim() == num_dims_batch else input.shape[0] + + # Function to return the number of spatial dims expected for inputs to the module. + # This is expected to be implemented by subclasses. + def _get_num_spatial_dims(self) -> int: + raise NotImplementedError + + +# LazyConv1d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConv1d(_LazyConvXdMixin, Conv1d): # type: ignore[misc] + r"""A :class:`torch.nn.Conv1d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`Conv1d` is inferred from the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): Zero-padding added to both sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel + elements. Default: 1 + groups (int, optional): Number of blocked connections from input + channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the + output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, + ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + + .. seealso:: :class:`torch.nn.Conv1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = Conv1d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: _size_1_t = 0, + dilation: _size_1_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + dilation, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 1 + + +# LazyConv2d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConv2d(_LazyConvXdMixin, Conv2d): # type: ignore[misc] + r"""A :class:`torch.nn.Conv2d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`Conv2d` that is inferred from the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): Zero-padding added to both sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel + elements. Default: 1 + groups (int, optional): Number of blocked connections from input + channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the + output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, + ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + + .. seealso:: :class:`torch.nn.Conv2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = Conv2d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_2_t, + stride: _size_2_t = 1, + padding: _size_2_t = 0, + dilation: _size_2_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", # TODO: refine this type + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + dilation, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 2 + + +# LazyConv3d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConv3d(_LazyConvXdMixin, Conv3d): # type: ignore[misc] + r"""A :class:`torch.nn.Conv3d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`Conv3d` that is inferred from + the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): Zero-padding added to both sides of + the input. Default: 0 + dilation (int or tuple, optional): Spacing between kernel + elements. Default: 1 + groups (int, optional): Number of blocked connections from input + channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the + output. Default: ``True`` + padding_mode (str, optional): ``'zeros'``, ``'reflect'``, + ``'replicate'`` or ``'circular'``. Default: ``'zeros'`` + + .. seealso:: :class:`torch.nn.Conv3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = Conv3d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_3_t, + stride: _size_3_t = 1, + padding: _size_3_t = 0, + dilation: _size_3_t = 1, + groups: int = 1, + bias: bool = True, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + dilation, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 3 + + +# LazyConvTranspose1d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConvTranspose1d(_LazyConvXdMixin, ConvTranspose1d): # type: ignore[misc] + r"""A :class:`torch.nn.ConvTranspose1d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`ConvTranspose1d` that is inferred from + the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + + .. seealso:: :class:`torch.nn.ConvTranspose1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = ConvTranspose1d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_1_t, + stride: _size_1_t = 1, + padding: _size_1_t = 0, + output_padding: _size_1_t = 0, + groups: int = 1, + bias: bool = True, + dilation: _size_1_t = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + output_padding, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + dilation, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 1 + + +# LazyConvTranspose2d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConvTranspose2d(_LazyConvXdMixin, ConvTranspose2d): # type: ignore[misc] + r"""A :class:`torch.nn.ConvTranspose2d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`ConvTranspose2d` is inferred from + the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of each dimension in the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + + .. seealso:: :class:`torch.nn.ConvTranspose2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = ConvTranspose2d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_2_t, + stride: _size_2_t = 1, + padding: _size_2_t = 0, + output_padding: _size_2_t = 0, + groups: int = 1, + bias: bool = True, + dilation: int = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + output_padding, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + dilation, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 2 + + +# LazyConvTranspose3d defines weight as a Tensor but derived class defines it as UnitializeParameter +class LazyConvTranspose3d(_LazyConvXdMixin, ConvTranspose3d): # type: ignore[misc] + r"""A :class:`torch.nn.ConvTranspose3d` module with lazy initialization of the ``in_channels`` argument. + + The ``in_channels`` argument of the :class:`ConvTranspose3d` is inferred from + the ``input.size(1)``. + The attributes that will be lazily initialized are `weight` and `bias`. + + Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation + on lazy modules and their limitations. + + Args: + out_channels (int): Number of channels produced by the convolution + kernel_size (int or tuple): Size of the convolving kernel + stride (int or tuple, optional): Stride of the convolution. Default: 1 + padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding + will be added to both sides of each dimension in the input. Default: 0 + output_padding (int or tuple, optional): Additional size added to one side + of each dimension in the output shape. Default: 0 + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True`` + dilation (int or tuple, optional): Spacing between kernel elements. Default: 1 + + .. seealso:: :class:`torch.nn.ConvTranspose3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin` + """ + + # super class define this variable as None. "type: ignore[..] is required + # since we are redefining the variable. + cls_to_become = ConvTranspose3d # type: ignore[assignment] + + def __init__( + self, + out_channels: int, + kernel_size: _size_3_t, + stride: _size_3_t = 1, + padding: _size_3_t = 0, + output_padding: _size_3_t = 0, + groups: int = 1, + bias: bool = True, + dilation: _size_3_t = 1, + padding_mode: str = "zeros", + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__( + 0, + 0, + kernel_size, + stride, + padding, + output_padding, + groups, + # bias is hardcoded to False to avoid creating tensor + # that will soon be overwritten. + False, + dilation, + padding_mode, + **factory_kwargs, + ) + self.weight = UninitializedParameter(**factory_kwargs) + self.out_channels = out_channels + if bias: + self.bias = UninitializedParameter(**factory_kwargs) + + def _get_num_spatial_dims(self) -> int: + return 3 diff --git a/shared/package-files/a5/a5a4905c6aa2ae0dd8ec45cbefe27d5984bd26cfaa776368dab3dc19d69a744e/__init__.cpython-311.pyc b/shared/package-files/a5/a5a4905c6aa2ae0dd8ec45cbefe27d5984bd26cfaa776368dab3dc19d69a744e/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7160332a2ff3d6e09001e61272318a44cbd01429 Binary files /dev/null and b/shared/package-files/a5/a5a4905c6aa2ae0dd8ec45cbefe27d5984bd26cfaa776368dab3dc19d69a744e/__init__.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5a4c51c7b16ace736c391f94e7fc2bdc7b6f01520cee9bba131635368230ac5/test_shift.cpython-311.pyc b/shared/package-files/a5/a5a4c51c7b16ace736c391f94e7fc2bdc7b6f01520cee9bba131635368230ac5/test_shift.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72b89b16d9fa7e0cf2ba87374008e6ac93425c42 Binary files /dev/null and b/shared/package-files/a5/a5a4c51c7b16ace736c391f94e7fc2bdc7b6f01520cee9bba131635368230ac5/test_shift.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5a530076e2b649ec210159c69ef39e6dc9fb5ada76c4938a97bf68f60adb7e6/__init__.cpython-311.pyc b/shared/package-files/a5/a5a530076e2b649ec210159c69ef39e6dc9fb5ada76c4938a97bf68f60adb7e6/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fcbd2789e5a9eb1edcc71036126762429d80aeb Binary files /dev/null and b/shared/package-files/a5/a5a530076e2b649ec210159c69ef39e6dc9fb5ada76c4938a97bf68f60adb7e6/__init__.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5b171bd59e2d148b8c6ba5dc05f912eeeda4e96ccabf76449ed10888997b51c/planner.py b/shared/package-files/a5/a5b171bd59e2d148b8c6ba5dc05f912eeeda4e96ccabf76449ed10888997b51c/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0b26dfe4d0aee850bbdecd5871c11e39d1e8c7 --- /dev/null +++ b/shared/package-files/a5/a5b171bd59e2d148b8c6ba5dc05f912eeeda4e96ccabf76449ed10888997b51c/planner.py @@ -0,0 +1,438 @@ +import abc +import io +import operator +from dataclasses import dataclass +from enum import auto, Enum +from functools import reduce +from typing import Any, Optional, Union + +import torch +from torch.distributed.checkpoint.metadata import ( + ChunkStorageMetadata, + Metadata, + MetadataIndex, + STATE_DICT_TYPE, + StorageMeta, + TensorProperties, +) + + +__all__ = [ + "WriteItemType", + "LoadItemType", + "TensorWriteData", + "WriteItem", + "ReadItem", + "SavePlan", + "LoadPlan", + "SavePlanner", + "LoadPlanner", +] + + +class WriteItemType(Enum): + TENSOR = auto() + SHARD = auto() + BYTE_IO = auto() + + +class LoadItemType(Enum): + TENSOR = auto() + BYTE_IO = auto() + + +@dataclass(frozen=True) +class TensorWriteData: + chunk: ChunkStorageMetadata + properties: TensorProperties + size: torch.Size + + +@dataclass(frozen=True) +class WriteItem: + """Dataclass which holds information about what needs to be written to storage.""" + + index: MetadataIndex + type: WriteItemType + + # Value present if it's a tensor write + tensor_data: Optional[TensorWriteData] = None + + def tensor_storage_size(self) -> Optional[int]: + """ + Calculates the storage size of the underlying tensor, or None if this is not a tensor write. + + Returns: + Optional[int] storage size, in bytes of underlying tensor if any. + """ + if self.tensor_data is None: + return None + + numels = reduce(operator.mul, self.tensor_data.size, 1) + dtype_size = torch._utils._element_size(self.tensor_data.properties.dtype) + return numels * dtype_size + + +@dataclass(frozen=True) +class ReadItem: + # Read Item + type: LoadItemType + + # Index into the state_dict + dest_index: MetadataIndex + # Offsets into destination tensor + dest_offsets: torch.Size + + # Index into the checkpoint + storage_index: MetadataIndex + # Offset into the checkpoint data + storage_offsets: torch.Size + + # Size of the hypercube to copy + lengths: torch.Size + + +@dataclass(frozen=True) +class SavePlan: + items: list[WriteItem] + storage_data: Any = None + planner_data: Any = None + # This is used to indicate that the ranks should + # use the cached plans to write data instead. + usable: bool = True + + +@dataclass +class LoadPlan: + items: list[ReadItem] + storage_data: Any = None + planner_data: Any = None + + +class SavePlanner(abc.ABC): + """ + Abstract class defining the protocol used by save_state_dict to plan the save process. + + SavePlanners are stateful objects that can be used to customize the whole save process. + + SavePlanner acts as an access proxy to the state_dict, so any transformation done to it + will be visible to the whole process. + + A planner subclass can expect the following sequence of calls during save_state_dict: + + 1) set_up_planner - called on all ranks. + Signals the start of a checkpoint save. + + 2) create_local_plan - called on all ranks. + Process the state_dict and produces a `SavePlan` that will be sent for global planning. + + 3) create_global_plan - called on the coordinator rank only. + Takes the SavePlan from all ranks and make any global decision. + + 4) finish_plan - called on all ranks. + This gives each rank a chance to adjust to global planning decisions. + + 5) resolve_data - called multiple times on each rank + Lookups a value on the `state_dict` for the storage layer to write. + + Users are recommended to extend DefaultSavePlanner instead of this interface directly as + most changes can be expressed by changes in a single method. + + There are 3 usual patterns of extension: + + Rewriting state_dict. This is the simplest way to extend the save process as it + doesn't requite understanding the intrincacies of how SavePlan works: + + >>> # xdoctest: +SKIP("undefined vars") + >>> class RenamePlanner(DefaultSavePlanner): + >>> def set_up_planner( + >>> self, + >>> state_dict: STATE_DICT_TYPE, + >>> storage_meta: Optional[StorageMeta], + >>> is_coordinator: bool, + >>> ) -> None: + >>> # prefix all keys with `foo_`` + >>> super().set_up_planner({"foo_" + k: v for k, v in state_dict.items()}, storage_meta, is_coordinator) + + Modifying local plan and lookup in tandem. This is useful when fine control of how data is persisted + + >>> # xdoctest: +SKIP("undefined vars") + >>> class FP16Planner(DefaultSavePlanner): + >>> def create_local_plan(self): + >>> plan = super().create_local_plan() + >>> for p in plan: + >>> if p.tensor_data is not None: + >>> p.tensor_data.properties.dtype = torch.float16 + >>> return plan + >>> + >>> def resolve_data(self, write_item): + >>> item = super().resolve_data(write_item) + >>> return item if write_item.type == WriteItemType.BYTE_IO else item.to(torch.float16) + + Using the global planning step to make central decisions that can't be made individually by each rank + + >>> # xdoctest: +SKIP("undefined vars") + >>> from itertools import zip_longest + >>> from dataclasses import replace + >>> class DDPLoadBalancingPlanner(DefaultSavePlanner): + >>> # This uses the default local plan behavior of having all non-sharded writes in rank 0 + >>> # This sample doesn't handle ShardedTensors + >>> def create_global_plan(self, all_plans): + >>> iters = [iter(all_plans[0].items)] * len(all_plans) + >>> items_per_rank = [ + >>> [item for item in items if item is not None] + >>> for items in zip(*zip_longest(*iters), strict=True) + >>> ] + >>> all_plans = [ + >>> replace(plan, items=items) + >>> for plan, items in zip(all_plans, items_per_rank, strict=True) + >>> ] + >>> return super().create_global_plan(all_plans) + + Finally, some planners need to save additional metadata in the checkpoint, this is + accomplished by having each rank contribute their data items in the local plan and + the global planner aggregate them: + + >>> # xdoctest: +SKIP("undefined vars") + >>> class SaveExtraDataPlanner(DefaultSavePlanner): + >>> def create_local_plan(self) -> SavePlan: + >>> plan = super().create_local_plan() + >>> return replace(plan, planner_data="per-rank-data") + >>> + >>> def create_global_plan(self, all_plans: List[SavePlan]) -> Tuple[List[SavePlan], Metadata]: + >>> global_plan, metadata = super().create_global_plan(all_plans) + >>> merged_data = [p.planner_data for p in global_plan] + >>> metadata = replace(metadata, planner_data=merged_data) + >>> return global_plan, metadata + """ + + # Save plan for the current rank as computed by `create_local_plan` API + # Cached on the local rank. + _cached_save_plan: dict[str, SavePlan] = {} + # Final save plan for the current rank. + # This is created by merging the plan created by `create_local_plan` API + # and the result of `create_global_plan` for the given rank. + # This is the final plan computed by the `finish_plan` API that gets + # sent to the `write_data`. + # Cached on the local rank. + _cached_final_save_plan: dict[str, SavePlan] = {} + # Collection of all the local plans from all the ranks. + # This is the input to the `create_global_plan` API. + # Cached on the coordinator rank. + _cached_all_plans: dict[str, list[SavePlan]] = {} + # Global checkpoint plan as computed by `create_global_plan` API. + # Cached on the coordinator rank. + _cached_global_plan: dict[str, list[SavePlan]] = {} + + @abc.abstractmethod + def set_up_planner( + self, + state_dict: STATE_DICT_TYPE, + storage_meta: Optional[StorageMeta] = None, + is_coordinator: bool = False, + ) -> None: + """ + Initialize this planner to save ``state_dict``. + + Implementations should save those values as they won't be provided lated in the save process. + + This is called on all ranks. + """ + + @abc.abstractmethod + def create_local_plan(self) -> SavePlan: + """ + Compute the save plan for the current rank. + + This will be aggregated and passed to create_global_plan. + Planner specific data can be passed through SavePlan::planner_data. + + This is called on all ranks. + """ + + @abc.abstractmethod + def create_global_plan( + self, all_plans: list[SavePlan] + ) -> tuple[list[SavePlan], Metadata]: + """ + Compute the global checkpoint plan and return the local plan of each rank. + + This is called on the coordinator rank only. + """ + + @abc.abstractmethod + def finish_plan(self, new_plan: SavePlan) -> SavePlan: + """ + Merge the plan created by `create_local_plan` and the result of `create_global_plan`. + + This is called on all ranks. + """ + + @abc.abstractmethod + def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]: + """ + Transform and prepare ``write_item`` from ``state_dict`` for storage, ensuring idempotency and thread-safety. + + Lookup the object associated with ``write_item`` in ``state_dict`` and apply any + transformation (such as serialization) prior to the storage layer consuming it. + + Called on each rank multiple times, at least once per WriteItem in the final SavePlan. + + This method should be idempotent and thread-save. StorageWriter implementations + are free to call it as frequently as they need. + + Any transformation that allocates memory should be lazily done when his method + is called in order to reduce peak memory required by checkpointing. + + When returning tensors, they can be on any device or format, they can be views too. + It's the storage layer responsibility to figure out how to save them. + """ + + +class LoadPlanner: + """ + Abstract class defining the protocol used by load_state_dict to plan the load process. + + LoadPlanner are stateful objects that can be used to customize the whole load process. + + LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it + will be visible to the whole process. + + A planner subclass can expect the following sequence of calls during load_state_dict: + + 1) set_up_planner - called on all ranks. + Signals the start of loading a checkpoint. + + 2) create_local_plan - called on all ranks. + Process the state_dict and produces a `LoadPlan` that will be sent for global planning. + + 3) create_global_plan - called on the coordinator rank only. + Takes the LoadPlan from all ranks and make any global decision. + + 4) load_bytes - called multiple times on each rank + This is called once per non-tensor value in state_dict. + + 5) resolve_tensor and commit_tensor - called multiple times on each rank + They are called in pair for each Tensor value in state_dict. + + Users are recommended to extend DefaultLoadPlanner instead of this interface directly as + most changes can be expressed by changes in a single method. + + There are two usual patterns of extension: + + Rewriting state_dict. This is the simplest way to extend the load process as it + doesn't requite understanding the intrincacies of how LoadPlan works. We need + to keep a reference to the original state_dict as load happens in place so + we need to be able to perform it in place + + >>> # xdoctest: +SKIP("undefined vars") + >>> class RenamePlanner(DefaultLoadPlanner): + >>> def set_up_planner( + >>> self, + >>> state_dict: STATE_DICT_TYPE, + >>> metadata: Metadata, + >>> is_coordinator: bool, + >>> ) -> None: + >>> self.original_state_dict = state_dict + >>> state_dict = {"foo_" + k: v for k, v in state_dict.items()} + >>> + >>> if self.flatten_sharded_tensors: + >>> state_dict = _flatten_sharded_tensors(state_dict) + >>> + >>> if self.flatten_state_dict: + >>> state_dict, self.mappings = flatten_state_dict(state_dict) + >>> + >>> self.state_dict = state_dict + >>> self.metadata = metadata + >>> self.is_coordinator = is_coordinator + >>> + >>> def load_bytes(self, read_item, value): + >>> # Remove the "foo_" prefix + >>> self.original_state_dict[read_item.dest_index.fqn[4:]] = torch.load(value, weights_only=False) + + + Modifying resolve_tensor and commit_tensor to handle load time transformation. + + >>> # xdoctest: +SKIP("undefined vars") + >>> class MetaModelMaterialize(DefaultSavePlanner): + >>> def resolve_tensor(self, read_item): + >>> tensor = super().resolve_tensor(read_item) + >>> return torch.empty_like(tensor, device="cpu") + >>> + >>> def commit_tensor(self, read_item, tensor): + >>> self.state_dict[read_item.dest_index.fqn] = tensor + """ + + @abc.abstractmethod + def set_up_planner( + self, + state_dict: STATE_DICT_TYPE, + metadata: Optional[Metadata] = None, + is_coordinator: bool = False, + ) -> None: + """ + Initialize this instance to load data into ``state_dict``. + + . N.B. This is called on every rank. + """ + + @abc.abstractmethod + def create_local_plan(self) -> LoadPlan: + """ + Create a LoadPlan based on state_dict and metadata provided by set_up_planner. + + . N.B. This is called on every rank. + """ + + @abc.abstractmethod + def create_global_plan(self, global_plan: list[LoadPlan]) -> list[LoadPlan]: + """ + Compute the global load plan and return plans for each rank. + + . N.B. This is called on the coordinator rank only + """ + + @abc.abstractmethod + def finish_plan(self, central_plan: LoadPlan) -> LoadPlan: + """Accept the plan from coordinator and return final LoadPlan.""" + + @abc.abstractmethod + def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None: + """ + Load the item described by ``read_item``and ``value``. + + This method is expected to modify in-place the underlying state_dict. + + The contents of ``value`` are defined by the SavePlanner used to produce + the checkpoint being loaded. + """ + + def resolve_bytes(self, read_item: ReadItem) -> io.BytesIO: + """ + Return the BytesIO to be used by the StorageReader to load `read_item`. + + The BytesIO should alias with one on the underlying state_dict as StorageReader will replace its contents. + """ + raise NotImplementedError("LoadPlanner.resolve_bytes is not implemented") + + @abc.abstractmethod + def resolve_tensor(self, read_item: ReadItem) -> torch.Tensor: + """ + Return the tensor described by ``read_item`` to be used by the StorageReader to load `read_item`. + + The tensor should alias with one on the underlying state_dict as StorageReader will replace its contents. + If, for any reason, that's not possible, the planner can use the ``commit_tensor`` method to copy the data + back to the one in state_dict. + """ + + @abc.abstractmethod + def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None: + """ + Call once the StorageReader finished loading data into ``tensor``. + + The provided tensor is the same one returned by the call to ``resolve_tensor``. + This method is only needed if this LoadPlanner needs to post process ``tensor`` prior to + copying it back to the one in the state_dict. + + The contents of tensor will follow its device synchronization model. + """ diff --git a/shared/package-files/a5/a5bdd7c334325867e9de51dc8677a02613d1e8eb154f0c201e85c61cd03dc011/slogdet_ops.h b/shared/package-files/a5/a5bdd7c334325867e9de51dc8677a02613d1e8eb154f0c201e85c61cd03dc011/slogdet_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..84c432d9af81a16cdd6eab22935f63229acadfeb --- /dev/null +++ b/shared/package-files/a5/a5bdd7c334325867e9de51dc8677a02613d1e8eb154f0c201e85c61cd03dc011/slogdet_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API slogdet { + using schema = ::std::tuple (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::slogdet"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet)"; + static ::std::tuple call(const at::Tensor & self); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API slogdet_out { + using schema = ::std::tuple (const at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::slogdet"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "slogdet.out(Tensor self, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet)"; + static ::std::tuple call(const at::Tensor & self, at::Tensor & sign, at::Tensor & logabsdet); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & sign, at::Tensor & logabsdet); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/a5/a5c249a522b6b8e3aa6f1b12a8bcc09508b99ad612b58d2fc973db27ea3b7cc3/gettext.py b/shared/package-files/a5/a5c249a522b6b8e3aa6f1b12a8bcc09508b99ad612b58d2fc973db27ea3b7cc3/gettext.py new file mode 100644 index 0000000000000000000000000000000000000000..e84765bfdf064981b9cd598af319ba8a55857c10 --- /dev/null +++ b/shared/package-files/a5/a5c249a522b6b8e3aa6f1b12a8bcc09508b99ad612b58d2fc973db27ea3b7cc3/gettext.py @@ -0,0 +1,646 @@ +"""Internationalization and localization support. + +This module provides internationalization (I18N) and localization (L10N) +support for your Python programs by providing an interface to the GNU gettext +message catalog library. + +I18N refers to the operation by which a program is made aware of multiple +languages. L10N refers to the adaptation of your program, once +internationalized, to the local language and cultural habits. + +""" + +# This module represents the integration of work, contributions, feedback, and +# suggestions from the following people: +# +# Martin von Loewis, who wrote the initial implementation of the underlying +# C-based libintlmodule (later renamed _gettext), along with a skeletal +# gettext.py implementation. +# +# Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule, +# which also included a pure-Python implementation to read .mo files if +# intlmodule wasn't available. +# +# James Henstridge, who also wrote a gettext.py module, which has some +# interesting, but currently unsupported experimental features: the notion of +# a Catalog class and instances, and the ability to add to a catalog file via +# a Python API. +# +# Barry Warsaw integrated these modules, wrote the .install() API and code, +# and conformed all C and Python code to Python's coding standards. +# +# Francois Pinard and Marc-Andre Lemburg also contributed valuably to this +# module. +# +# J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs. +# +# TODO: +# - Lazy loading of .mo files. Currently the entire catalog is loaded into +# memory, but that's probably bad for large translated programs. Instead, +# the lexical sort of original strings in GNU .mo files should be exploited +# to do binary searches and lazy initializations. Or you might want to use +# the undocumented double-hash algorithm for .mo files with hash tables, but +# you'll need to study the GNU gettext code to do this. +# +# - Support Solaris .mo file formats. Unfortunately, we've been unable to +# find this format documented anywhere. + + +import operator +import os +import re +import sys + + +__all__ = ['NullTranslations', 'GNUTranslations', 'Catalog', + 'bindtextdomain', 'find', 'translation', 'install', + 'textdomain', 'dgettext', 'dngettext', 'gettext', + 'ngettext', 'pgettext', 'dpgettext', 'npgettext', + 'dnpgettext' + ] + +_default_localedir = os.path.join(sys.base_prefix, 'share', 'locale') + +# Expression parsing for plural form selection. +# +# The gettext library supports a small subset of C syntax. The only +# incompatible difference is that integer literals starting with zero are +# decimal. +# +# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms +# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y + +_token_pattern = re.compile(r""" + (?P[ \t]+) | # spaces and horizontal tabs + (?P[0-9]+\b) | # decimal integer + (?Pn\b) | # only n is allowed + (?P[()]) | + (?P[-*/%+?:]|[>, + # <=, >=, ==, !=, &&, ||, + # ? : + # unary and bitwise ops + # not allowed + (?P\w+|.) # invalid token + """, re.VERBOSE|re.DOTALL) + + +def _tokenize(plural): + for mo in re.finditer(_token_pattern, plural): + kind = mo.lastgroup + if kind == 'WHITESPACES': + continue + value = mo.group(kind) + if kind == 'INVALID': + raise ValueError('invalid token in plural form: %s' % value) + yield value + yield '' + + +def _error(value): + if value: + return ValueError('unexpected token in plural form: %s' % value) + else: + return ValueError('unexpected end of plural form') + + +_binary_ops = ( + ('||',), + ('&&',), + ('==', '!='), + ('<', '>', '<=', '>='), + ('+', '-'), + ('*', '/', '%'), +) +_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops} +_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'} + + +def _parse(tokens, priority=-1): + result = '' + nexttok = next(tokens) + while nexttok == '!': + result += 'not ' + nexttok = next(tokens) + + if nexttok == '(': + sub, nexttok = _parse(tokens) + result = '%s(%s)' % (result, sub) + if nexttok != ')': + raise ValueError('unbalanced parenthesis in plural form') + elif nexttok == 'n': + result = '%s%s' % (result, nexttok) + else: + try: + value = int(nexttok, 10) + except ValueError: + raise _error(nexttok) from None + result = '%s%d' % (result, value) + nexttok = next(tokens) + + j = 100 + while nexttok in _binary_ops: + i = _binary_ops[nexttok] + if i < priority: + break + # Break chained comparisons + if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>=' + result = '(%s)' % result + # Replace some C operators by their Python equivalents + op = _c2py_ops.get(nexttok, nexttok) + right, nexttok = _parse(tokens, i + 1) + result = '%s %s %s' % (result, op, right) + j = i + if j == priority == 4: # '<', '>', '<=', '>=' + result = '(%s)' % result + + if nexttok == '?' and priority <= 0: + if_true, nexttok = _parse(tokens, 0) + if nexttok != ':': + raise _error(nexttok) + if_false, nexttok = _parse(tokens) + result = '%s if %s else %s' % (if_true, result, if_false) + if priority == 0: + result = '(%s)' % result + + return result, nexttok + + +def _as_int(n): + try: + round(n) + except TypeError: + raise TypeError('Plural value must be an integer, got %s' % + (n.__class__.__name__,)) from None + + import warnings + frame = sys._getframe(1) + stacklevel = 2 + while frame.f_back is not None and frame.f_globals.get('__name__') == __name__: + stacklevel += 1 + frame = frame.f_back + warnings.warn('Plural value must be an integer, got %s' % + (n.__class__.__name__,), + DeprecationWarning, + stacklevel) + return n + + +def c2py(plural): + """Gets a C expression as used in PO files for plural forms and returns a + Python function that implements an equivalent expression. + """ + + if len(plural) > 1000: + raise ValueError('plural form expression is too long') + try: + result, nexttok = _parse(_tokenize(plural)) + if nexttok: + raise _error(nexttok) + + depth = 0 + for c in result: + if c == '(': + depth += 1 + if depth > 20: + # Python compiler limit is about 90. + # The most complex example has 2. + raise ValueError('plural form expression is too complex') + elif c == ')': + depth -= 1 + + ns = {'_as_int': _as_int, '__name__': __name__} + exec('''if True: + def func(n): + if not isinstance(n, int): + n = _as_int(n) + return int(%s) + ''' % result, ns) + return ns['func'] + except RecursionError: + # Recursion error can be raised in _parse() or exec(). + raise ValueError('plural form expression is too complex') + + +def _expand_lang(loc): + import locale + loc = locale.normalize(loc) + COMPONENT_CODESET = 1 << 0 + COMPONENT_TERRITORY = 1 << 1 + COMPONENT_MODIFIER = 1 << 2 + # split up the locale into its base components + mask = 0 + pos = loc.find('@') + if pos >= 0: + modifier = loc[pos:] + loc = loc[:pos] + mask |= COMPONENT_MODIFIER + else: + modifier = '' + pos = loc.find('.') + if pos >= 0: + codeset = loc[pos:] + loc = loc[:pos] + mask |= COMPONENT_CODESET + else: + codeset = '' + pos = loc.find('_') + if pos >= 0: + territory = loc[pos:] + loc = loc[:pos] + mask |= COMPONENT_TERRITORY + else: + territory = '' + language = loc + ret = [] + for i in range(mask+1): + if not (i & ~mask): # if all components for this combo exist ... + val = language + if i & COMPONENT_TERRITORY: val += territory + if i & COMPONENT_CODESET: val += codeset + if i & COMPONENT_MODIFIER: val += modifier + ret.append(val) + ret.reverse() + return ret + + +class NullTranslations: + def __init__(self, fp=None): + self._info = {} + self._charset = None + self._fallback = None + if fp is not None: + self._parse(fp) + + def _parse(self, fp): + pass + + def add_fallback(self, fallback): + if self._fallback: + self._fallback.add_fallback(fallback) + else: + self._fallback = fallback + + def gettext(self, message): + if self._fallback: + return self._fallback.gettext(message) + return message + + def ngettext(self, msgid1, msgid2, n): + if self._fallback: + return self._fallback.ngettext(msgid1, msgid2, n) + if n == 1: + return msgid1 + else: + return msgid2 + + def pgettext(self, context, message): + if self._fallback: + return self._fallback.pgettext(context, message) + return message + + def npgettext(self, context, msgid1, msgid2, n): + if self._fallback: + return self._fallback.npgettext(context, msgid1, msgid2, n) + if n == 1: + return msgid1 + else: + return msgid2 + + def info(self): + return self._info + + def charset(self): + return self._charset + + def install(self, names=None): + import builtins + builtins.__dict__['_'] = self.gettext + if names is not None: + allowed = {'gettext', 'ngettext', 'npgettext', 'pgettext'} + for name in allowed & set(names): + builtins.__dict__[name] = getattr(self, name) + + +class GNUTranslations(NullTranslations): + # Magic number of .mo files + LE_MAGIC = 0x950412de + BE_MAGIC = 0xde120495 + + # The encoding of a msgctxt and a msgid in a .mo file is + # msgctxt + "\x04" + msgid (gettext version >= 0.15) + CONTEXT = "%s\x04%s" + + # Acceptable .mo versions + VERSIONS = (0, 1) + + def _get_versions(self, version): + """Returns a tuple of major version, minor version""" + return (version >> 16, version & 0xffff) + + def _parse(self, fp): + """Override this method to support alternative .mo formats.""" + # Delay struct import for speeding up gettext import when .mo files + # are not used. + from struct import unpack + filename = getattr(fp, 'name', '') + # Parse the .mo file header, which consists of 5 little endian 32 + # bit words. + self._catalog = catalog = {} + self.plural = lambda n: int(n != 1) # germanic plural by default + buf = fp.read() + buflen = len(buf) + # Are we big endian or little endian? + magic = unpack('4I', buf[4:20]) + ii = '>II' + else: + raise OSError(0, 'Bad magic number', filename) + + major_version, minor_version = self._get_versions(version) + + if major_version not in self.VERSIONS: + raise OSError(0, 'Bad version number ' + str(major_version), filename) + + # Now put all messages from the .mo file buffer into the catalog + # dictionary. + for i in range(0, msgcount): + mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) + mend = moff + mlen + tlen, toff = unpack(ii, buf[transidx:transidx+8]) + tend = toff + tlen + if mend < buflen and tend < buflen: + msg = buf[moff:mend] + tmsg = buf[toff:tend] + else: + raise OSError(0, 'File is corrupt', filename) + # See if we're looking at GNU .mo conventions for metadata + if mlen == 0: + # Catalog description + lastk = None + for b_item in tmsg.split(b'\n'): + item = b_item.decode().strip() + if not item: + continue + # Skip over comment lines: + if item.startswith('#-#-#-#-#') and item.endswith('#-#-#-#-#'): + continue + k = v = None + if ':' in item: + k, v = item.split(':', 1) + k = k.strip().lower() + v = v.strip() + self._info[k] = v + lastk = k + elif lastk: + self._info[lastk] += '\n' + item + if k == 'content-type': + self._charset = v.split('charset=')[1] + elif k == 'plural-forms': + v = v.split(';') + plural = v[1].split('plural=')[1] + self.plural = c2py(plural) + # Note: we unconditionally convert both msgids and msgstrs to + # Unicode using the character encoding specified in the charset + # parameter of the Content-Type header. The gettext documentation + # strongly encourages msgids to be us-ascii, but some applications + # require alternative encodings (e.g. Zope's ZCML and ZPT). For + # traditional gettext applications, the msgid conversion will + # cause no problems since us-ascii should always be a subset of + # the charset encoding. We may want to fall back to 8-bit msgids + # if the Unicode conversion fails. + charset = self._charset or 'ascii' + if b'\x00' in msg: + # Plural forms + msgid1, msgid2 = msg.split(b'\x00') + tmsg = tmsg.split(b'\x00') + msgid1 = str(msgid1, charset) + for i, x in enumerate(tmsg): + catalog[(msgid1, i)] = str(x, charset) + else: + catalog[str(msg, charset)] = str(tmsg, charset) + # advance to next entry in the seek tables + masteridx += 8 + transidx += 8 + + def gettext(self, message): + missing = object() + tmsg = self._catalog.get(message, missing) + if tmsg is missing: + tmsg = self._catalog.get((message, self.plural(1)), missing) + if tmsg is not missing: + return tmsg + if self._fallback: + return self._fallback.gettext(message) + return message + + def ngettext(self, msgid1, msgid2, n): + try: + tmsg = self._catalog[(msgid1, self.plural(n))] + except KeyError: + if self._fallback: + return self._fallback.ngettext(msgid1, msgid2, n) + if n == 1: + tmsg = msgid1 + else: + tmsg = msgid2 + return tmsg + + def pgettext(self, context, message): + ctxt_msg_id = self.CONTEXT % (context, message) + missing = object() + tmsg = self._catalog.get(ctxt_msg_id, missing) + if tmsg is missing: + tmsg = self._catalog.get((ctxt_msg_id, self.plural(1)), missing) + if tmsg is not missing: + return tmsg + if self._fallback: + return self._fallback.pgettext(context, message) + return message + + def npgettext(self, context, msgid1, msgid2, n): + ctxt_msg_id = self.CONTEXT % (context, msgid1) + try: + tmsg = self._catalog[ctxt_msg_id, self.plural(n)] + except KeyError: + if self._fallback: + return self._fallback.npgettext(context, msgid1, msgid2, n) + if n == 1: + tmsg = msgid1 + else: + tmsg = msgid2 + return tmsg + + +# Locate a .mo file using the gettext strategy +def find(domain, localedir=None, languages=None, all=False): + # Get some reasonable defaults for arguments that were not supplied + if localedir is None: + localedir = _default_localedir + if languages is None: + languages = [] + for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): + val = os.environ.get(envar) + if val: + languages = val.split(':') + break + if 'C' not in languages: + languages.append('C') + # now normalize and expand the languages + nelangs = [] + for lang in languages: + for nelang in _expand_lang(lang): + if nelang not in nelangs: + nelangs.append(nelang) + # select a language + if all: + result = [] + else: + result = None + for lang in nelangs: + if lang == 'C': + break + mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) + if os.path.exists(mofile): + if all: + result.append(mofile) + else: + return mofile + return result + + +# a mapping between absolute .mo file path and Translation object +_translations = {} + + +def translation(domain, localedir=None, languages=None, + class_=None, fallback=False): + if class_ is None: + class_ = GNUTranslations + mofiles = find(domain, localedir, languages, all=True) + if not mofiles: + if fallback: + return NullTranslations() + from errno import ENOENT + raise FileNotFoundError(ENOENT, + 'No translation file found for domain', domain) + # Avoid opening, reading, and parsing the .mo file after it's been done + # once. + result = None + for mofile in mofiles: + key = (class_, os.path.abspath(mofile)) + t = _translations.get(key) + if t is None: + with open(mofile, 'rb') as fp: + t = _translations.setdefault(key, class_(fp)) + # Copy the translation object to allow setting fallbacks and + # output charset. All other instance data is shared with the + # cached object. + # Delay copy import for speeding up gettext import when .mo files + # are not used. + import copy + t = copy.copy(t) + if result is None: + result = t + else: + result.add_fallback(t) + return result + + +def install(domain, localedir=None, *, names=None): + t = translation(domain, localedir, fallback=True) + t.install(names) + + +# a mapping b/w domains and locale directories +_localedirs = {} +# current global domain, `messages' used for compatibility w/ GNU gettext +_current_domain = 'messages' + + +def textdomain(domain=None): + global _current_domain + if domain is not None: + _current_domain = domain + return _current_domain + + +def bindtextdomain(domain, localedir=None): + global _localedirs + if localedir is not None: + _localedirs[domain] = localedir + return _localedirs.get(domain, _default_localedir) + + +def dgettext(domain, message): + try: + t = translation(domain, _localedirs.get(domain, None)) + except OSError: + return message + return t.gettext(message) + + +def dngettext(domain, msgid1, msgid2, n): + try: + t = translation(domain, _localedirs.get(domain, None)) + except OSError: + if n == 1: + return msgid1 + else: + return msgid2 + return t.ngettext(msgid1, msgid2, n) + + +def dpgettext(domain, context, message): + try: + t = translation(domain, _localedirs.get(domain, None)) + except OSError: + return message + return t.pgettext(context, message) + + +def dnpgettext(domain, context, msgid1, msgid2, n): + try: + t = translation(domain, _localedirs.get(domain, None)) + except OSError: + if n == 1: + return msgid1 + else: + return msgid2 + return t.npgettext(context, msgid1, msgid2, n) + + +def gettext(message): + return dgettext(_current_domain, message) + + +def ngettext(msgid1, msgid2, n): + return dngettext(_current_domain, msgid1, msgid2, n) + + +def pgettext(context, message): + return dpgettext(_current_domain, context, message) + + +def npgettext(context, msgid1, msgid2, n): + return dnpgettext(_current_domain, context, msgid1, msgid2, n) + + +# dcgettext() has been deemed unnecessary and is not implemented. + +# James Henstridge's Catalog constructor from GNOME gettext. Documented usage +# was: +# +# import gettext +# cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR) +# _ = cat.gettext +# print _('Hello World') + +# The resulting catalog object currently don't support access through a +# dictionary API, which was supported (but apparently unused) in GNOME +# gettext. + +Catalog = translation diff --git a/shared/package-files/a5/a5c692a711dc62f5585d641b3382465d8ea077ff4cd1678fe2981c9e31b64bed/test__all__.cpython-311.pyc b/shared/package-files/a5/a5c692a711dc62f5585d641b3382465d8ea077ff4cd1678fe2981c9e31b64bed/test__all__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51ddd2f1cdcd249bcdde531a04cfcff6cc52e02e Binary files /dev/null and b/shared/package-files/a5/a5c692a711dc62f5585d641b3382465d8ea077ff4cd1678fe2981c9e31b64bed/test__all__.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5c87d5a3f0c6b1eaa118530255143e2452d78af383d83b6778699acc5832167/test_exec_command.cpython-311.pyc b/shared/package-files/a5/a5c87d5a3f0c6b1eaa118530255143e2452d78af383d83b6778699acc5832167/test_exec_command.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a6ac7c431037eeef3493c52aba7f9a7f24cef5a Binary files /dev/null and b/shared/package-files/a5/a5c87d5a3f0c6b1eaa118530255143e2452d78af383d83b6778699acc5832167/test_exec_command.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5cbfa9dc7796b08d4aa7a9a0e9af1cc583be9774abf8ccbe17717e806164f41/__init__.py b/shared/package-files/a5/a5cbfa9dc7796b08d4aa7a9a0e9af1cc583be9774abf8ccbe17717e806164f41/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7592385955a9f8660189a30d249fe795030e774a --- /dev/null +++ b/shared/package-files/a5/a5cbfa9dc7796b08d4aa7a9a0e9af1cc583be9774abf8ccbe17717e806164f41/__init__.py @@ -0,0 +1,18 @@ +from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy +from ._fully_shard import ( + FSDPModule, + fully_shard, + register_fsdp_forward_method, + UnshardHandle, +) + + +__all__ = [ + "CPUOffloadPolicy", + "FSDPModule", + "fully_shard", + "MixedPrecisionPolicy", + "OffloadPolicy", + "register_fsdp_forward_method", + "UnshardHandle", +] diff --git a/shared/package-files/a5/a5df3ee00b90cc95d623975954cda1c238dc00241e06e935143c517ae56876cb/test_parameter.cpython-311.pyc b/shared/package-files/a5/a5df3ee00b90cc95d623975954cda1c238dc00241e06e935143c517ae56876cb/test_parameter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f37a56aeebe234fff13e9805e4e720d38e9c8402 Binary files /dev/null and b/shared/package-files/a5/a5df3ee00b90cc95d623975954cda1c238dc00241e06e935143c517ae56876cb/test_parameter.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5e44dbbc4bc086f92071f1e2df227896de2f94e9da842c8800a38cf5434c02d/__init__.cpython-311.pyc b/shared/package-files/a5/a5e44dbbc4bc086f92071f1e2df227896de2f94e9da842c8800a38cf5434c02d/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47d435dc8f00641a0655514e35064f2fa84acdd4 Binary files /dev/null and b/shared/package-files/a5/a5e44dbbc4bc086f92071f1e2df227896de2f94e9da842c8800a38cf5434c02d/__init__.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5e46fe38683337d14ff4c24f3166fdede8cfdca66fdaf610402e2cabef39dd6/simplex.py b/shared/package-files/a5/a5e46fe38683337d14ff4c24f3166fdede8cfdca66fdaf610402e2cabef39dd6/simplex.py new file mode 100644 index 0000000000000000000000000000000000000000..c8e652cb626507d7829f9bc1c78fc6f49809865f --- /dev/null +++ b/shared/package-files/a5/a5e46fe38683337d14ff4c24f3166fdede8cfdca66fdaf610402e2cabef39dd6/simplex.py @@ -0,0 +1,1104 @@ +"""Tools for optimizing a linear function for a given simplex. + +For the linear objective function ``f`` with linear constraints +expressed using `Le`, `Ge` or `Eq` can be found with ``lpmin`` or +``lpmax``. The symbols are **unbounded** unless specifically +constrained. + +As an alternative, the matrices describing the objective and the +constraints, and an optional list of bounds can be passed to +``linprog`` which will solve for the minimization of ``C*x`` +under constraints ``A*x <= b`` and/or ``Aeq*x = beq``, and +individual bounds for variables given as ``(lo, hi)``. The values +returned are **nonnegative** unless bounds are provided that +indicate otherwise. + +Errors that might be raised are UnboundedLPError when there is no +finite solution for the system or InfeasibleLPError when the +constraints represent impossible conditions (i.e. a non-existent + simplex). + +Here is a simple 1-D system: minimize `x` given that ``x >= 1``. + + >>> from sympy.solvers.simplex import lpmin, linprog + >>> from sympy.abc import x + + The function and a list with the constraint is passed directly + to `lpmin`: + + >>> lpmin(x, [x >= 1]) + (1, {x: 1}) + + For `linprog` the matrix for the objective is `[1]` and the + uivariate constraint can be passed as a bound with None acting + as infinity: + + >>> linprog([1], bounds=(1, None)) + (1, [1]) + + Or the matrices, corresponding to ``x >= 1`` expressed as + ``-x <= -1`` as required by the routine, can be passed: + + >>> linprog([1], [-1], [-1]) + (1, [1]) + + If there is no limit for the objective, an error is raised. + In this case there is a valid region of interest (simplex) + but no limit to how small ``x`` can be: + + >>> lpmin(x, []) + Traceback (most recent call last): + ... + sympy.solvers.simplex.UnboundedLPError: + Objective function can assume arbitrarily large values! + + An error is raised if there is no possible solution: + + >>> lpmin(x,[x<=1,x>=2]) + Traceback (most recent call last): + ... + sympy.solvers.simplex.InfeasibleLPError: + Inconsistent/False constraint +""" + +from sympy.core import sympify +from sympy.core.exprtools import factor_terms +from sympy.core.relational import Le, Ge, Eq +from sympy.core.singleton import S +from sympy.core.symbol import Dummy +from sympy.core.sorting import ordered +from sympy.functions.elementary.complexes import sign +from sympy.matrices.dense import Matrix, zeros +from sympy.solvers.solveset import linear_eq_to_matrix +from sympy.utilities.iterables import numbered_symbols +from sympy.utilities.misc import filldedent + + +class UnboundedLPError(Exception): + """ + A linear programming problem is said to be unbounded if its objective + function can assume arbitrarily large values. + + Example + ======= + + Suppose you want to maximize + 2x + subject to + x >= 0 + + There's no upper limit that 2x can take. + """ + + pass + + +class InfeasibleLPError(Exception): + """ + A linear programming problem is considered infeasible if its + constraint set is empty. That is, if the set of all vectors + satisfying the constraints is empty, then the problem is infeasible. + + Example + ======= + + Suppose you want to maximize + x + subject to + x >= 10 + x <= 9 + + No x can satisfy those constraints. + """ + + pass + + +def _pivot(M, i, j): + """ + The pivot element `M[i, j]` is inverted and the rest of the matrix + modified and returned as a new matrix; original is left unmodified. + + Example + ======= + + >>> from sympy.matrices.dense import Matrix + >>> from sympy.solvers.simplex import _pivot + >>> from sympy import var + >>> Matrix(3, 3, var('a:i')) + Matrix([ + [a, b, c], + [d, e, f], + [g, h, i]]) + >>> _pivot(_, 1, 0) + Matrix([ + [-a/d, -a*e/d + b, -a*f/d + c], + [ 1/d, e/d, f/d], + [-g/d, h - e*g/d, i - f*g/d]]) + """ + Mi, Mj, Mij = M[i, :], M[:, j], M[i, j] + if Mij == 0: + raise ZeroDivisionError( + "Tried to pivot about zero-valued entry.") + A = M - Mj * (Mi / Mij) + A[i, :] = Mi / Mij + A[:, j] = -Mj / Mij + A[i, j] = 1 / Mij + return A + + +def _choose_pivot_row(A, B, candidate_rows, pivot_col, Y): + # Choose row with smallest ratio + # If there are ties, pick using Bland's rule + return min(candidate_rows, key=lambda i: (B[i] / A[i, pivot_col], Y[i])) + + +def _simplex(A, B, C, D=None, dual=False): + """Return ``(o, x, y)`` obtained from the two-phase simplex method + using Bland's rule: ``o`` is the minimum value of primal, + ``Cx - D``, under constraints ``Ax <= B`` (with ``x >= 0``) and + the maximum of the dual, ``y^{T}B - D``, under constraints + ``A^{T}*y >= C^{T}`` (with ``y >= 0``). To compute the dual of + the system, pass `dual=True` and ``(o, y, x)`` will be returned. + + Note: the nonnegative constraints for ``x`` and ``y`` supercede + any values of ``A`` and ``B`` that are inconsistent with that + assumption, so if a constraint of ``x >= -1`` is represented + in ``A`` and ``B``, no value will be obtained that is negative; if + a constraint of ``x <= -1`` is represented, an error will be + raised since no solution is possible. + + This routine relies on the ability of determining whether an + expression is 0 or not. This is guaranteed if the input contains + only Float or Rational entries. It will raise a TypeError if + a relationship does not evaluate to True or False. + + Examples + ======== + + >>> from sympy.solvers.simplex import _simplex + >>> from sympy import Matrix + + Consider the simple minimization of ``f = x + y + 1`` under the + constraint that ``y + 2*x >= 4``. This is the "standard form" of + a minimization. + + In the nonnegative quadrant, this inequality describes a area above + a triangle with vertices at (0, 4), (0, 0) and (2, 0). The minimum + of ``f`` occurs at (2, 0). Define A, B, C, D for the standard + minimization: + + >>> A = Matrix([[2, 1]]) + >>> B = Matrix([4]) + >>> C = Matrix([[1, 1]]) + >>> D = Matrix([-1]) + + Confirm that this is the system of interest: + + >>> from sympy.abc import x, y + >>> X = Matrix([x, y]) + >>> (C*X - D)[0] + x + y + 1 + >>> [i >= j for i, j in zip(A*X, B)] + [2*x + y >= 4] + + Since `_simplex` will do a minimization for constraints given as + ``A*x <= B``, the signs of ``A`` and ``B`` must be negated since + the currently correspond to a greater-than inequality: + + >>> _simplex(-A, -B, C, D) + (3, [2, 0], [1/2]) + + The dual of minimizing ``f`` is maximizing ``F = c*y - d`` for + ``a*y <= b`` where ``a``, ``b``, ``c``, ``d`` are derived from the + transpose of the matrix representation of the standard minimization: + + >>> tr = lambda a, b, c, d: [i.T for i in (a, c, b, d)] + >>> a, b, c, d = tr(A, B, C, D) + + This time ``a*x <= b`` is the expected inequality for the `_simplex` + method, but to maximize ``F``, the sign of ``c`` and ``d`` must be + changed (so that minimizing the negative will give the negative of + the maximum of ``F``): + + >>> _simplex(a, b, -c, -d) + (-3, [1/2], [2, 0]) + + The negative of ``F`` and the min of ``f`` are the same. The dual + point `[1/2]` is the value of ``y`` that minimized ``F = c*y - d`` + under constraints a*x <= b``: + + >>> y = Matrix(['y']) + >>> (c*y - d)[0] + 4*y + 1 + >>> [i <= j for i, j in zip(a*y,b)] + [2*y <= 1, y <= 1] + + In this 1-dimensional dual system, the more restrictive constraint is + the first which limits ``y`` between 0 and 1/2 and the maximum of + ``F`` is attained at the nonzero value, hence is ``4*(1/2) + 1 = 3``. + + In this case the values for ``x`` and ``y`` were the same when the + dual representation was solved. This is not always the case (though + the value of the function will be the same). + + >>> l = [[1, 1], [-1, 1], [0, 1], [-1, 0]], [5, 1, 2, -1], [[1, 1]], [-1] + >>> A, B, C, D = [Matrix(i) for i in l] + >>> _simplex(A, B, -C, -D) + (-6, [3, 2], [1, 0, 0, 0]) + >>> _simplex(A, B, -C, -D, dual=True) # [5, 0] != [3, 2] + (-6, [1, 0, 0, 0], [5, 0]) + + In both cases the function has the same value: + + >>> Matrix(C)*Matrix([3, 2]) == Matrix(C)*Matrix([5, 0]) + True + + See Also + ======== + _lp - poses min/max problem in form compatible with _simplex + lpmin - minimization which calls _lp + lpmax - maximimzation which calls _lp + + References + ========== + + .. [1] Thomas S. Ferguson, LINEAR PROGRAMMING: A Concise Introduction + web.tecnico.ulisboa.pt/mcasquilho/acad/or/ftp/FergusonUCLA_lp.pdf + + """ + A, B, C, D = [Matrix(i) for i in (A, B, C, D or [0])] + if dual: + _o, d, p = _simplex(-A.T, C.T, B.T, -D) + return -_o, d, p + + if A and B: + M = Matrix([[A, B], [C, D]]) + else: + if A or B: + raise ValueError("must give A and B") + # no constraints given + M = Matrix([[C, D]]) + n = M.cols - 1 + m = M.rows - 1 + + if not all(i.is_Float or i.is_Rational for i in M): + # with literal Float and Rational we are guaranteed the + # ability of determining whether an expression is 0 or not + raise TypeError(filldedent(""" + Only rationals and floats are allowed. + """ + ) + ) + + # x variables have priority over y variables during Bland's rule + # since False < True + X = [(False, j) for j in range(n)] + Y = [(True, i) for i in range(m)] + + # Phase 1: find a feasible solution or determine none exist + + ## keep track of last pivot row and column + last = None + + while True: + B = M[:-1, -1] + A = M[:-1, :-1] + if all(B[i] >= 0 for i in range(B.rows)): + # We have found a feasible solution + break + + # Find k: first row with a negative rightmost entry + for k in range(B.rows): + if B[k] < 0: + break # use current value of k below + else: + pass # error will raise below + + # Choose pivot column, c + piv_cols = [_ for _ in range(A.cols) if A[k, _] < 0] + if not piv_cols: + raise InfeasibleLPError(filldedent(""" + The constraint set is empty!""")) + _, c = min((X[i], i) for i in piv_cols) # Bland's rule + + # Choose pivot row, r + piv_rows = [_ for _ in range(A.rows) if A[_, c] > 0 and B[_] > 0] + piv_rows.append(k) + r = _choose_pivot_row(A, B, piv_rows, c, Y) + + # check for oscillation + if (r, c) == last: + # Not sure what to do here; it looks like there will be + # oscillations; see o1 test added at this commit to + # see a system with no solution and the o2 for one + # with a solution. In the case of o2, the solution + # from linprog is the same as the one from lpmin, but + # the matrices created in the lpmin case are different + # than those created without replacements in linprog and + # the matrices in the linprog case lead to oscillations. + # If the matrices could be re-written in linprog like + # lpmin does, this behavior could be avoided and then + # perhaps the oscillating case would only occur when + # there is no solution. For now, the output is checked + # before exit if oscillations were detected and an + # error is raised there if the solution was invalid. + # + # cf section 6 of Ferguson for a non-cycling modification + last = True + break + last = r, c + + M = _pivot(M, r, c) + X[c], Y[r] = Y[r], X[c] + + # Phase 2: from a feasible solution, pivot to optimal + while True: + B = M[:-1, -1] + A = M[:-1, :-1] + C = M[-1, :-1] + + # Choose a pivot column, c + piv_cols = [_ for _ in range(n) if C[_] < 0] + if not piv_cols: + break + _, c = min((X[i], i) for i in piv_cols) # Bland's rule + + # Choose a pivot row, r + piv_rows = [_ for _ in range(m) if A[_, c] > 0] + if not piv_rows: + raise UnboundedLPError(filldedent(""" + Objective function can assume + arbitrarily large values!""")) + r = _choose_pivot_row(A, B, piv_rows, c, Y) + + M = _pivot(M, r, c) + X[c], Y[r] = Y[r], X[c] + + argmax = [None] * n + argmin_dual = [None] * m + + for i, (v, n) in enumerate(X): + if v == False: + argmax[n] = 0 + else: + argmin_dual[n] = M[-1, i] + + for i, (v, n) in enumerate(Y): + if v == True: + argmin_dual[n] = 0 + else: + argmax[n] = M[i, -1] + + if last and not all(i >= 0 for i in argmax + argmin_dual): + raise InfeasibleLPError(filldedent(""" + Oscillating system led to invalid solution. + If you believe there was a valid solution, please + report this as a bug.""")) + return -M[-1, -1], argmax, argmin_dual + + +## routines that use _simplex or support those that do + + +def _abcd(M, list=False): + """return parts of M as matrices or lists + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.solvers.simplex import _abcd + + >>> m = Matrix(3, 3, range(9)); m + Matrix([ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + >>> a, b, c, d = _abcd(m) + >>> a + Matrix([ + [0, 1], + [3, 4]]) + >>> b + Matrix([ + [2], + [5]]) + >>> c + Matrix([[6, 7]]) + >>> d + Matrix([[8]]) + + The matrices can be returned as compact lists, too: + + >>> L = a, b, c, d = _abcd(m, list=True); L + ([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8]) + """ + + def aslist(i): + l = i.tolist() + if len(l[0]) == 1: # col vector + return [i[0] for i in l] + return l + + m = M[:-1, :-1], M[:-1, -1], M[-1, :-1], M[-1:, -1:] + if not list: + return m + return tuple([aslist(i) for i in m]) + + +def _m(a, b, c, d=None): + """return Matrix([[a, b], [c, d]]) from matrices + in Matrix or list form. + + Examples + ======== + + >>> from sympy import Matrix + >>> from sympy.solvers.simplex import _abcd, _m + >>> m = Matrix(3, 3, range(9)) + >>> L = _abcd(m, list=True); L + ([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8]) + >>> _abcd(m) + (Matrix([ + [0, 1], + [3, 4]]), Matrix([ + [2], + [5]]), Matrix([[6, 7]]), Matrix([[8]])) + >>> assert m == _m(*L) == _m(*_) + """ + a, b, c, d = [Matrix(i) for i in (a, b, c, d or [0])] + return Matrix([[a, b], [c, d]]) + + +def _primal_dual(M, factor=True): + """return primal and dual function and constraints + assuming that ``M = Matrix([[A, b], [c, d]])`` and the + function ``c*x - d`` is being minimized with ``Ax >= b`` + for nonnegative values of ``x``. The dual and its + constraints will be for maximizing `b.T*y - d` subject + to ``A.T*y <= c.T``. + + Examples + ======== + + >>> from sympy.solvers.simplex import _primal_dual, lpmin, lpmax + >>> from sympy import Matrix + + The following matrix represents the primal task of + minimizing x + y + 7 for y >= x + 1 and y >= -2*x + 3. + The dual task seeks to maximize x + 3*y + 7 with + 2*y - x <= 1 and and x + y <= 1: + + >>> M = Matrix([ + ... [-1, 1, 1], + ... [ 2, 1, 3], + ... [ 1, 1, -7]]) + >>> p, d = _primal_dual(M) + + The minimum of the primal and maximum of the dual are the same + (though they occur at different points): + + >>> lpmin(*p) + (28/3, {x1: 2/3, x2: 5/3}) + >>> lpmax(*d) + (28/3, {y1: 1/3, y2: 2/3}) + + If the equivalent (but canonical) inequalities are + desired, leave `factor=True`, otherwise the unmodified + inequalities for M will be returned. + + >>> m = Matrix([ + ... [-3, -2, 4, -2], + ... [ 2, 0, 0, -2], + ... [ 0, 1, -3, 0]]) + + >>> _primal_dual(m, False) # last condition is 2*x1 >= -2 + ((x2 - 3*x3, + [-3*x1 - 2*x2 + 4*x3 >= -2, 2*x1 >= -2]), + (-2*y1 - 2*y2, + [-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3])) + + >>> _primal_dual(m) # condition now x1 >= -1 + ((x2 - 3*x3, + [-3*x1 - 2*x2 + 4*x3 >= -2, x1 >= -1]), + (-2*y1 - 2*y2, + [-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3])) + + If you pass the transpose of the matrix, the primal will be + identified as the standard minimization problem and the + dual as the standard maximization: + + >>> _primal_dual(m.T) + ((-2*x1 - 2*x2, + [-3*x1 + 2*x2 >= 0, -2*x1 >= 1, 4*x1 >= -3]), + (y2 - 3*y3, + [-3*y1 - 2*y2 + 4*y3 <= -2, y1 <= -1])) + + A matrix must have some size or else None will be returned for + the functions: + + >>> _primal_dual(Matrix([[1, 2]])) + ((x1 - 2, []), (-2, [])) + + >>> _primal_dual(Matrix([])) + ((None, []), (None, [])) + + References + ========== + + .. [1] David Galvin, Relations between Primal and Dual + www3.nd.edu/~dgalvin1/30210/30210_F07/presentations/dual_opt.pdf + """ + if not M: + return (None, []), (None, []) + if not hasattr(M, "shape"): + if len(M) not in (3, 4): + raise ValueError("expecting Matrix or 3 or 4 lists") + M = _m(*M) + m, n = [i - 1 for i in M.shape] + A, b, c, d = _abcd(M) + d = d[0] + _ = lambda x: numbered_symbols(x, start=1) + x = Matrix([i for i, j in zip(_("x"), range(n))]) + yT = Matrix([i for i, j in zip(_("y"), range(m))]).T + + def ineq(L, r, op): + rv = [] + for r in (op(i, j) for i, j in zip(L, r)): + if r == True: + continue + elif r == False: + return [False] + if factor: + f = factor_terms(r) + if f.lhs.is_Mul and f.rhs % f.lhs.args[0] == 0: + assert len(f.lhs.args) == 2, f.lhs + k = f.lhs.args[0] + r = r.func(sign(k) * f.lhs.args[1], f.rhs // abs(k)) + rv.append(r) + return rv + + eq = lambda x, d: x[0] - d if x else -d + F = eq(c * x, d) + f = eq(yT * b, d) + return (F, ineq(A * x, b, Ge)), (f, ineq(yT * A, c, Le)) + + +def _rel_as_nonpos(constr, syms): + """return `(np, d, aux)` where `np` is a list of nonpositive + expressions that represent the given constraints (possibly + rewritten in terms of auxilliary variables) expressible with + nonnegative symbols, and `d` is a dictionary mapping a given + symbols to an expression with an auxilliary variable. In some + cases a symbol will be used as part of the change of variables, + e.g. x: x - z1 instead of x: z1 - z2. + + If any constraint is False/empty, return None. All variables in + ``constr`` are assumed to be unbounded unless explicitly indicated + otherwise with a univariate constraint, e.g. ``x >= 0`` will + restrict ``x`` to nonnegative values. + + The ``syms`` must be included so all symbols can be given an + unbounded assumption if they are not otherwise bound with + univariate conditions like ``x <= 3``. + + Examples + ======== + + >>> from sympy.solvers.simplex import _rel_as_nonpos + >>> from sympy.abc import x, y + >>> _rel_as_nonpos([x >= y, x >= 0, y >= 0], (x, y)) + ([-x + y], {}, []) + >>> _rel_as_nonpos([x >= 3, x <= 5], [x]) + ([_z1 - 2], {x: _z1 + 3}, [_z1]) + >>> _rel_as_nonpos([x <= 5], [x]) + ([], {x: 5 - _z1}, [_z1]) + >>> _rel_as_nonpos([x >= 1], [x]) + ([], {x: _z1 + 1}, [_z1]) + """ + r = {} # replacements to handle change of variables + np = [] # nonpositive expressions + aux = [] # auxilliary symbols added + ui = numbered_symbols("z", start=1, cls=Dummy) # auxilliary symbols + univariate = {} # {x: interval} for univariate constraints + unbound = [] # symbols designated as unbound + syms = set(syms) # the expected syms of the system + + # separate out univariates + for i in constr: + if i == True: + continue # ignore + if i == False: + return # no solution + if i.has(S.Infinity, S.NegativeInfinity): + raise ValueError("only finite bounds are permitted") + if isinstance(i, (Le, Ge)): + i = i.lts - i.gts + freei = i.free_symbols + if freei - syms: + raise ValueError( + "unexpected symbol(s) in constraint: %s" % (freei - syms) + ) + if len(freei) > 1: + np.append(i) + elif freei: + x = freei.pop() + if x in unbound: + continue # will handle later + ivl = Le(i, 0, evaluate=False).as_set() + if x not in univariate: + univariate[x] = ivl + else: + univariate[x] &= ivl + elif i: + return False + else: + raise TypeError(filldedent(""" + only equalities like Eq(x, y) or non-strict + inequalities like x >= y are allowed in lp, not %s""" % i)) + + # introduce auxilliary variables as needed for univariate + # inequalities + for x in syms: + i = univariate.get(x, True) + if not i: + return None # no solution possible + if i == True: + unbound.append(x) + continue + a, b = i.inf, i.sup + if a.is_infinite: + u = next(ui) + r[x] = b - u + aux.append(u) + elif b.is_infinite: + if a: + u = next(ui) + r[x] = a + u + aux.append(u) + else: + # standard nonnegative relationship + pass + else: + u = next(ui) + aux.append(u) + # shift so u = x - a => x = u + a + r[x] = u + a + # add constraint for u <= b - a + # since when u = b-a then x = u + a = b - a + a = b: + # the upper limit for x + np.append(u - (b - a)) + + # make change of variables for unbound variables + for x in unbound: + u = next(ui) + r[x] = u - x # reusing x + aux.append(u) + + return np, r, aux + + +def _lp_matrices(objective, constraints): + """return A, B, C, D, r, x+X, X for maximizing + objective = Cx - D with constraints Ax <= B, introducing + introducing auxilliary variables, X, as necessary to make + replacements of symbols as given in r, {xi: expression with Xj}, + so all variables in x+X will take on nonnegative values. + + Every univariate condition creates a semi-infinite + condition, e.g. a single ``x <= 3`` creates the + interval ``[-oo, 3]`` while ``x <= 3`` and ``x >= 2`` + create an interval ``[2, 3]``. Variables not in a univariate + expression will take on nonnegative values. + """ + + # sympify input and collect free symbols + F = sympify(objective) + np = [sympify(i) for i in constraints] + syms = set.union(*[i.free_symbols for i in [F] + np], set()) + + # change Eq(x, y) to x - y <= 0 and y - x <= 0 + for i in range(len(np)): + if isinstance(np[i], Eq): + np[i] = np[i].lhs - np[i].rhs <= 0 + np.append(-np[i].lhs <= 0) + + # convert constraints to nonpositive expressions + _ = _rel_as_nonpos(np, syms) + if _ is None: + raise InfeasibleLPError(filldedent(""" + Inconsistent/False constraint""")) + np, r, aux = _ + + # do change of variables + F = F.xreplace(r) + np = [i.xreplace(r) for i in np] + + # convert to matrices + xx = list(ordered(syms)) + aux + A, B = linear_eq_to_matrix(np, xx) + C, D = linear_eq_to_matrix([F], xx) + return A, B, C, D, r, xx, aux + + +def _lp(min_max, f, constr): + """Return the optimization (min or max) of ``f`` with the given + constraints. All variables are unbounded unless constrained. + + If `min_max` is 'max' then the results corresponding to the + maximization of ``f`` will be returned, else the minimization. + The constraints can be given as Le, Ge or Eq expressions. + + Examples + ======== + + >>> from sympy.solvers.simplex import _lp as lp + >>> from sympy import Eq + >>> from sympy.abc import x, y, z + >>> f = x + y - 2*z + >>> c = [7*x + 4*y - 7*z <= 3, 3*x - y + 10*z <= 6] + >>> c += [i >= 0 for i in (x, y, z)] + >>> lp(min, f, c) + (-6/5, {x: 0, y: 0, z: 3/5}) + + By passing max, the maximum value for f under the constraints + is returned (if possible): + + >>> lp(max, f, c) + (3/4, {x: 0, y: 3/4, z: 0}) + + Constraints that are equalities will require that the solution + also satisfy them: + + >>> lp(max, f, c + [Eq(y - 9*x, 1)]) + (5/7, {x: 0, y: 1, z: 1/7}) + + All symbols are reported, even if they are not in the objective + function: + + >>> lp(min, x, [y + x >= 3, x >= 0]) + (0, {x: 0, y: 3}) + """ + # get the matrix components for the system expressed + # in terms of only nonnegative variables + A, B, C, D, r, xx, aux = _lp_matrices(f, constr) + + how = str(min_max).lower() + if "max" in how: + # _simplex minimizes for Ax <= B so we + # have to change the sign of the function + # and negate the optimal value returned + _o, p, d = _simplex(A, B, -C, -D) + o = -_o + elif "min" in how: + o, p, d = _simplex(A, B, C, D) + else: + raise ValueError("expecting min or max") + + # restore original variables and remove aux from p + p = dict(zip(xx, p)) + if r: # p has original symbols and auxilliary symbols + # if r has x: x - z1 use values from p to update + r = {k: v.xreplace(p) for k, v in r.items()} + # then use the actual value of x (= x - z1) in p + p.update(r) + # don't show aux + p = {k: p[k] for k in ordered(p) if k not in aux} + + # not returning dual since there may be extra constraints + # when a variable has finite bounds + return o, p + + +def lpmin(f, constr): + """return minimum of linear equation ``f`` under + linear constraints expressed using Ge, Le or Eq. + + All variables are unbounded unless constrained. + + Examples + ======== + + >>> from sympy.solvers.simplex import lpmin + >>> from sympy import Eq + >>> from sympy.abc import x, y + >>> lpmin(x, [2*x - 3*y >= -1, Eq(x + 3*y, 2), x <= 2*y]) + (1/3, {x: 1/3, y: 5/9}) + + Negative values for variables are permitted unless explicitly + excluding, so minimizing ``x`` for ``x <= 3`` is an + unbounded problem while the following has a bounded solution: + + >>> lpmin(x, [x >= 0, x <= 3]) + (0, {x: 0}) + + Without indicating that ``x`` is nonnegative, there + is no minimum for this objective: + + >>> lpmin(x, [x <= 3]) + Traceback (most recent call last): + ... + sympy.solvers.simplex.UnboundedLPError: + Objective function can assume arbitrarily large values! + + See Also + ======== + linprog, lpmax + """ + return _lp(min, f, constr) + + +def lpmax(f, constr): + """return maximum of linear equation ``f`` under + linear constraints expressed using Ge, Le or Eq. + + All variables are unbounded unless constrained. + + Examples + ======== + + >>> from sympy.solvers.simplex import lpmax + >>> from sympy import Eq + >>> from sympy.abc import x, y + >>> lpmax(x, [2*x - 3*y >= -1, Eq(x+ 3*y,2), x <= 2*y]) + (4/5, {x: 4/5, y: 2/5}) + + Negative values for variables are permitted unless explicitly + excluding: + + >>> lpmax(x, [x <= -1]) + (-1, {x: -1}) + + If a non-negative constraint is added for x, there is no + possible solution: + + >>> lpmax(x, [x <= -1, x >= 0]) + Traceback (most recent call last): + ... + sympy.solvers.simplex.InfeasibleLPError: inconsistent/False constraint + + See Also + ======== + linprog, lpmin + """ + return _lp(max, f, constr) + + +def _handle_bounds(bounds): + # introduce auxiliary variables as needed for univariate + # inequalities + + def _make_list(length: int, index_value_pairs): + li = [0] * length + for idx, val in index_value_pairs: + li[idx] = val + return li + + unbound = [] + row = [] + row2 = [] + b_len = len(bounds) + for x, (a, b) in enumerate(bounds): + if a is None and b is None: + unbound.append(x) + elif a is None: + # r[x] = b - u + b_len += 1 + row.append(_make_list(b_len, [(x, 1), (-1, 1)])) + row.append(_make_list(b_len, [(x, -1), (-1, -1)])) + row2.extend([[b], [-b]]) + elif b is None: + if a: + # r[x] = a + u + b_len += 1 + row.append(_make_list(b_len, [(x, 1), (-1, -1)])) + row.append(_make_list(b_len, [(x, -1), (-1, 1)])) + row2.extend([[a], [-a]]) + else: + # standard nonnegative relationship + pass + else: + # r[x] = u + a + b_len += 1 + row.append(_make_list(b_len, [(x, 1), (-1, -1)])) + row.append(_make_list(b_len, [(x, -1), (-1, 1)])) + # u <= b - a + row.append(_make_list(b_len, [(-1, 1)])) + row2.extend([[a], [-a], [b - a]]) + + # make change of variables for unbound variables + for x in unbound: + # r[x] = u - v + b_len += 2 + row.append(_make_list(b_len, [(x, 1), (-1, 1), (-2, -1)])) + row.append(_make_list(b_len, [(x, -1), (-1, -1), (-2, 1)])) + row2.extend([[0], [0]]) + + return Matrix([r + [0]*(b_len - len(r)) for r in row]), Matrix(row2) + + +def linprog(c, A=None, b=None, A_eq=None, b_eq=None, bounds=None): + """Return the minimization of ``c*x`` with the given + constraints ``A*x <= b`` and ``A_eq*x = b_eq``. Unless bounds + are given, variables will have nonnegative values in the solution. + + If ``A`` is not given, then the dimension of the system will + be determined by the length of ``C``. + + By default, all variables will be nonnegative. If ``bounds`` + is given as a single tuple, ``(lo, hi)``, then all variables + will be constrained to be between ``lo`` and ``hi``. Use + None for a ``lo`` or ``hi`` if it is unconstrained in the + negative or positive direction, respectively, e.g. + ``(None, 0)`` indicates nonpositive values. To set + individual ranges, pass a list with length equal to the + number of columns in ``A``, each element being a tuple; if + only a few variables take on non-default values they can be + passed as a dictionary with keys giving the corresponding + column to which the variable is assigned, e.g. ``bounds={2: + (1, 4)}`` would limit the 3rd variable to have a value in + range ``[1, 4]``. + + Examples + ======== + + >>> from sympy.solvers.simplex import linprog + >>> from sympy import symbols, Eq, linear_eq_to_matrix as M, Matrix + >>> x = x1, x2, x3, x4 = symbols('x1:5') + >>> X = Matrix(x) + >>> c, d = M(5*x2 + x3 + 4*x4 - x1, x) + >>> a, b = M([5*x2 + 2*x3 + 5*x4 - (x1 + 5)], x) + >>> aeq, beq = M([Eq(3*x2 + x4, 2), Eq(-x1 + x3 + 2*x4, 1)], x) + >>> constr = [i <= j for i,j in zip(a*X, b)] + >>> constr += [Eq(i, j) for i,j in zip(aeq*X, beq)] + >>> linprog(c, a, b, aeq, beq) + (9/2, [0, 1/2, 0, 1/2]) + >>> assert all(i.subs(dict(zip(x, _[1]))) for i in constr) + + See Also + ======== + lpmin, lpmax + """ + + ## the objective + C = Matrix(c) + if C.rows != 1 and C.cols == 1: + C = C.T + if C.rows != 1: + raise ValueError("C must be a single row.") + + ## the inequalities + if not A: + if b: + raise ValueError("A and b must both be given") + # the governing equations will be simple constraints + # on variables + A, b = zeros(0, C.cols), zeros(C.cols, 1) + else: + A, b = [Matrix(i) for i in (A, b)] + + if A.cols != C.cols: + raise ValueError("number of columns in A and C must match") + + ## the equalities + if A_eq is None: + if not b_eq is None: + raise ValueError("A_eq and b_eq must both be given") + else: + A_eq, b_eq = [Matrix(i) for i in (A_eq, b_eq)] + # if x == y then x <= y and x >= y (-x <= -y) + A = A.col_join(A_eq) + A = A.col_join(-A_eq) + b = b.col_join(b_eq) + b = b.col_join(-b_eq) + + if not (bounds is None or bounds == {} or bounds == (0, None)): + ## the bounds are interpreted + if type(bounds) is tuple and len(bounds) == 2: + bounds = [bounds] * A.cols + elif len(bounds) == A.cols and all( + type(i) is tuple and len(i) == 2 for i in bounds): + pass # individual bounds + elif type(bounds) is dict and all( + type(i) is tuple and len(i) == 2 + for i in bounds.values()): + # sparse bounds + db = bounds + bounds = [(0, None)] * A.cols + while db: + i, j = db.popitem() + bounds[i] = j # IndexError if out-of-bounds indices + else: + raise ValueError("unexpected bounds %s" % bounds) + A_, b_ = _handle_bounds(bounds) + aux = A_.cols - A.cols + if A: + A = Matrix([[A, zeros(A.rows, aux)], [A_]]) + b = b.col_join(b_) + else: + A = A_ + b = b_ + C = C.row_join(zeros(1, aux)) + else: + aux = -A.cols # set so -aux will give all cols below + + o, p, d = _simplex(A, b, C) + return o, p[:-aux] # don't include aux values + +def show_linprog(c, A=None, b=None, A_eq=None, b_eq=None, bounds=None): + from sympy import symbols + ## the objective + C = Matrix(c) + if C.rows != 1 and C.cols == 1: + C = C.T + if C.rows != 1: + raise ValueError("C must be a single row.") + + ## the inequalities + if not A: + if b: + raise ValueError("A and b must both be given") + # the governing equations will be simple constraints + # on variables + A, b = zeros(0, C.cols), zeros(C.cols, 1) + else: + A, b = [Matrix(i) for i in (A, b)] + + if A.cols != C.cols: + raise ValueError("number of columns in A and C must match") + + ## the equalities + if A_eq is None: + if not b_eq is None: + raise ValueError("A_eq and b_eq must both be given") + else: + A_eq, b_eq = [Matrix(i) for i in (A_eq, b_eq)] + + if not (bounds is None or bounds == {} or bounds == (0, None)): + ## the bounds are interpreted + if type(bounds) is tuple and len(bounds) == 2: + bounds = [bounds] * A.cols + elif len(bounds) == A.cols and all( + type(i) is tuple and len(i) == 2 for i in bounds): + pass # individual bounds + elif type(bounds) is dict and all( + type(i) is tuple and len(i) == 2 + for i in bounds.values()): + # sparse bounds + db = bounds + bounds = [(0, None)] * A.cols + while db: + i, j = db.popitem() + bounds[i] = j # IndexError if out-of-bounds indices + else: + raise ValueError("unexpected bounds %s" % bounds) + + x = Matrix(symbols('x1:%s' % (A.cols+1))) + f,c = (C*x)[0], [i<=j for i,j in zip(A*x, b)] + [Eq(i,j) for i,j in zip(A_eq*x,b_eq)] + for i, (lo, hi) in enumerate(bounds): + if lo is not None: + c.append(x[i]>=lo) + if hi is not None: + c.append(x[i]<=hi) + return f,c diff --git a/shared/package-files/a5/a5e7cefd894e2ebf9122cc076acf03010e23f358e1a8b4f95c612e4368bc0ed2/test_bz2.py b/shared/package-files/a5/a5e7cefd894e2ebf9122cc076acf03010e23f358e1a8b4f95c612e4368bc0ed2/test_bz2.py new file mode 100644 index 0000000000000000000000000000000000000000..ce83f1e2d20c87cf7914a31e4536e55c01e9aed5 --- /dev/null +++ b/shared/package-files/a5/a5e7cefd894e2ebf9122cc076acf03010e23f358e1a8b4f95c612e4368bc0ed2/test_bz2.py @@ -0,0 +1,66 @@ +import itertools + +import numpy as np + +from numcodecs.bz2 import BZ2 +from numcodecs.tests.common import ( + check_backwards_compatibility, + check_config, + check_encode_decode, + check_err_decode_object_buffer, + check_err_encode_object_buffer, + check_repr, +) + +codecs = [ + BZ2(), + BZ2(level=1), + BZ2(level=5), + BZ2(level=9), +] + + +# mix of dtypes: integer, float, bool, string +# mix of shapes: 1D, 2D, 3D +# mix of orders: C, F +arrays = [ + np.arange(1000, dtype='i4'), + np.linspace(1000, 1001, 1000, dtype='f8'), + np.random.normal(loc=1000, scale=1, size=(100, 10)), + np.random.randint(0, 2, size=1000, dtype=bool).reshape(100, 10, order='F'), + np.random.choice([b'a', b'bb', b'ccc'], size=1000).reshape(10, 10, 10), + np.random.randint(0, 2**60, size=1000, dtype='u8').view('M8[ns]'), + np.random.randint(0, 2**60, size=1000, dtype='u8').view('m8[ns]'), + np.random.randint(0, 2**25, size=1000, dtype='u8').view('M8[m]'), + np.random.randint(0, 2**25, size=1000, dtype='u8').view('m8[m]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('M8[ns]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('m8[ns]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('M8[m]'), + np.random.randint(-(2**63), -(2**63) + 20, size=1000, dtype='i8').view('m8[m]'), +] + + +def test_encode_decode(): + for arr, codec in itertools.product(arrays, codecs): + check_encode_decode(arr, codec) + + +def test_config(): + codec = BZ2(level=3) + check_config(codec) + + +def test_repr(): + check_repr("BZ2(level=3)") + + +def test_backwards_compatibility(): + check_backwards_compatibility(BZ2.codec_id, arrays, codecs) + + +def test_err_decode_object_buffer(): + check_err_decode_object_buffer(BZ2()) + + +def test_err_encode_object_buffer(): + check_err_encode_object_buffer(BZ2()) diff --git a/shared/package-files/a5/a5ef3bcd474c649230ecb435be758d415ea2c42fcd38979851ed08db4741cf5f/metrics.py b/shared/package-files/a5/a5ef3bcd474c649230ecb435be758d415ea2c42fcd38979851ed08db4741cf5f/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4892a2b5e3697a1e7303f7cfb849ad4f416eee40 --- /dev/null +++ b/shared/package-files/a5/a5ef3bcd474c649230ecb435be758d415ea2c42fcd38979851ed08db4741cf5f/metrics.py @@ -0,0 +1,454 @@ +from __future__ import annotations + +import csv +import dataclasses +import inspect +import os +import re +from dataclasses import dataclass +from functools import lru_cache +from typing import Callable, cast, Optional, TYPE_CHECKING, Union + +from torch._inductor import config +from torch._inductor.utils import get_benchmark_name +from torch.utils._ordered_set import OrderedSet + + +# Prevent circular import +if TYPE_CHECKING: + from torch._inductor.scheduler import BaseSchedulerNode + +# counter for tracking how many kernels have been generated +generated_kernel_count = 0 +generated_cpp_vec_kernel_count = 0 +num_bytes_accessed = 0 +nodes_num_elem: list[ + tuple[ + BaseSchedulerNode, + int, + ] +] = [] +node_runtimes: list[tuple[BaseSchedulerNode, float]] = [] + +# counters for tracking fusions +ir_nodes_pre_fusion = 0 + +# counters for tracking to_dtype inserted +cpp_to_dtype_count = 0 + + +@dataclasses.dataclass +class CppOuterLoopFusedCount: + inner_kernel_number: int + local_buffer_number: int = 0 + + +# The length counts the number of outer loop fusions. +cpp_outer_loop_fused_inner_counts: list[CppOuterLoopFusedCount] = [] + +num_comprehensive_padding = 0 +num_matches_for_scatter_upon_const_tensor = 0 + +num_loop_reordering = 0 + +# counter for parallel reduction. +parallel_reduction_count = 0 + + +# reset all counters +def reset() -> None: + global generated_kernel_count + global generated_cpp_vec_kernel_count + global num_bytes_accessed, nodes_num_elem + global ir_nodes_pre_fusion + global cpp_to_dtype_count + global cpp_outer_loop_fused_inner_counts + global num_comprehensive_padding + global num_matches_for_scatter_upon_const_tensor + global num_loop_reordering + global parallel_reduction_count + + generated_kernel_count = 0 + generated_cpp_vec_kernel_count = 0 + num_bytes_accessed = 0 + nodes_num_elem.clear() + node_runtimes.clear() + ir_nodes_pre_fusion = 0 + cpp_to_dtype_count = 0 + cpp_outer_loop_fused_inner_counts.clear() + num_comprehensive_padding = 0 + num_matches_for_scatter_upon_const_tensor = 0 + num_loop_reordering = 0 + parallel_reduction_count = 0 + + +@dataclass +class CachedMetricsDeltas: + """ + The subset of metrics we want update across cache hits, e.g., the + FxGraphCache. + """ + + generated_kernel_count: int + generated_cpp_vec_kernel_count: int + ir_nodes_pre_fusion: int + cpp_to_dtype_count: int + num_bytes_accessed: int + num_matches_for_scatter_upon_const_tensor: int + + +def get_metric_fields() -> list[str]: + return [field.name for field in dataclasses.fields(CachedMetricsDeltas)] + + +class CachedMetricsHelper: + """ + A helper class to help calculate and apply counter deltas for those + metrics we want to save with cache entries (e.g., FxGraphCache) and + apply on a cache hit. + """ + + def __init__(self) -> None: + self.cached_metrics = {} + for metric in get_metric_fields(): + self.cached_metrics[metric] = globals()[metric] + + def get_deltas(self) -> CachedMetricsDeltas: + delta_metrics = {} + for metric in get_metric_fields(): + delta_metrics[metric] = globals()[metric] - self.cached_metrics[metric] + + return CachedMetricsDeltas(**delta_metrics) + + @staticmethod + def apply_deltas(delta: CachedMetricsDeltas) -> None: + for metric in get_metric_fields(): + globals()[metric] += getattr(delta, metric) + + +REGISTERED_METRIC_TABLES: dict[str, MetricTable] = {} + + +@dataclass +class MetricTable: + table_name: str + column_names: list[str] + + num_rows_added: int = 0 + + def add_row( + self, row_fn: Callable[[], dict[str, Optional[Union[str, float]]]] + ) -> None: + if self.table_name not in enabled_metric_tables(): + return + + row_dict = row_fn() + assert len(self.column_names) == len(row_dict), ( + f"{len(self.column_names)} v.s. {len(row_dict)}" + ) + assert OrderedSet(self.column_names) == OrderedSet(row_dict.keys()), ( + f"{OrderedSet(self.column_names)} v.s. {OrderedSet(row_dict.keys())}" + ) + + bn = get_benchmark_name() + # assert bn is not None + row = [bn] + [row_dict[column_name] for column_name in self.column_names] + assert all(isinstance(i, str) for i in row) + self._write_row(cast(list[str], row)) + + def output_filename(self) -> str: + return f"metric_table_{self.table_name}.csv" + + def write_header(self) -> None: + filename = self.output_filename() + with open(filename, "w") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(["model_name"] + self.column_names) + + def _write_row(self, row: list[str]) -> None: + filename = self.output_filename() + if self.num_rows_added == 0 and not os.path.exists(filename): + self.write_header() + + self.num_rows_added += 1 + + for idx, orig_val in enumerate(row): + if isinstance(orig_val, float): + new_val = f"{orig_val:.6f}" + elif orig_val is None: + new_val = "" + else: + new_val = orig_val + row[idx] = new_val + + with open(filename, "a") as fd: + writer = csv.writer(fd, lineterminator="\n") + writer.writerow(row) + + @staticmethod + def register_table(name: str, column_names: list[str]) -> None: + table = MetricTable(name, column_names) + REGISTERED_METRIC_TABLES[name] = table + + +MetricTable.register_table( + "slow_fusion", + [ + "kernel1_path", + "kernel1_latency", + "kernel2_path", + "kernel2_latency", + "fused_kernel_path", + "fused_kernel_latency", + "slow_down_ratio", + ], +) + +# track the fusion statistics for each graph +MetricTable.register_table( + "graph_stats", + [ + "graph_id", + "num_nodes_before_fusion", + "num_nodes_after_fusion", + ], +) + +# track the perf difference between persistent reduction and non-persistent +# reductions +MetricTable.register_table( + "persistent_red_perf", + [ + "kernel0_path", + "kernel1_path", + "kernel2_path", + "kernel3_path", + "kernel0_latency", + "kernel1_latency", + "kernel2_latency", + "kernel3_latency", + "size_hints", + "reduction_hint", + ], +) + +# Log the fusion failures due to indexing mismatch +MetricTable.register_table( + "fusion_failure_due_to_indexing_mismatch", + [ + "pre_grad_graph_id", + "post_grad_graph_id", + "node1_name", + "node2_name", + "node1_debug_str", + "node2_debug_str", + "common_buffer_names", + "failure_reason", + ], +) + +# Log metadata for pointwise/reduction kernels. E.g., model name, kernel path, numel, rnumel, reduction hint +MetricTable.register_table( + "kernel_metadata", + [ + "kernel_name", + "kernel_path", + "kernel_category", # pointwise/reduction/foreach etc. + "size_hints", + "reduction_hint", + "line_of_code", + "num_load", + "num_store", + "num_for_loop", + "num_atomic_add", + "num_args", + # xyz numel can be different to size_hints since size_hints are rounded + # up to the nearest power of 2. + # Inductor kernel will burn in the xyz numel in kernel code for static + # shape kernels. + # Logging them will be helpful to find unaligned shape for reduction + "xnumel", + "ynumel", + "rnumel", + "kernel_args_num_gb", + ], +) + + +def _parse_kernel_fn_code(kernel_module_code: str) -> str: + """ + The kernel_module_code is the python module that contains kernel function code. + kernel function is the proper triton kernel function annotated with + @triton.jit + """ + from .codecache import PyCodeCache + from .wrapper_benchmark import get_triton_kernel + + mod = PyCodeCache.load(kernel_module_code) + kernel = get_triton_kernel(mod) + # kernel is a CachingAutotune; kernel.fn is the JITFunction; + # kernel.fn.fn is the function being decorate by triton.jit + return inspect.getsource(kernel.fn.fn) + + +def _parse_kernel_line_of_code(proper_kernel_fn_code: str) -> int: + """ + Return the line of code for the kernel excluding the decorators. + """ + return len(proper_kernel_fn_code.splitlines()) + + +def _parse_size_hints(kernel_module_code: str, kernel_category: str) -> Optional[str]: + if kernel_category == "foreach": + # foreach kernel does not have size_hints + return None + m = re.search(r"size_hints=(\[[0-9, ]*\]),", kernel_module_code) + assert m, "size_hints missing!" + return m.group(1) + + +def _parse_reduction_hint( + kernel_category: str, kernel_module_code: str +) -> Optional[str]: + if kernel_category not in ("reduction", "persistent_reduction"): + return None + m = re.search(r"reduction_hint=ReductionHint\.(\w*),", kernel_module_code) + assert m, "reduction_hint not found in kernel source code!" + return m.group(1) + + +def _count_pattern(proper_kernel_fn_code: str, pattern: str) -> int: + return proper_kernel_fn_code.count(pattern) + + +def _count_args(proper_kernel_fn_code: str) -> int: + def_line = proper_kernel_fn_code.splitlines()[0] + assert def_line.startswith("def ") + start_idx = def_line.index("(") + end_idx = def_line.index("):") + decl_csv = def_line[start_idx + 1 : end_idx] + comps = decl_csv.split(",") + return len(comps) + + +def _parse_proper_kernel_fn_code(kernel_fn_code: str) -> str: + """ + Skip decorators. + """ + start_pos = kernel_fn_code.index("def ") + return kernel_fn_code[start_pos:] + + +def _parse_numel(proper_kernel_fn_code: str, numel_arg_name: str) -> Optional[int]: + m = re.search(f"{numel_arg_name} = ([\\d]+)", proper_kernel_fn_code) + if m: + return int(m.group(1)) + else: + return None + + +def _parse_kernel_args_num_gb( + kernel_fn_code: str, kernel_category: str +) -> Optional[float]: + """ + inductor meta looks like: + inductor_meta={... 'mutated_arg_names': [], 'no_x_dim': False, 'kernel_num_gb': 2.0}, + """ + m = re.search(r".kernel_num_gb.:\s*([0-9.]+)", kernel_fn_code) + if m: + return float(m.group(1)) + else: + """ + There are a few cases that kernel_num_gdb field can be missing: + 1. the field will be missing if config.benchmark_kernel and + config.profile_bandwidth are false + 2. even if config.benchmark_kernel or config.profile_bandwidth is true. + foreach kernel does not have kernel_num_gb field in the metadata + """ + return None + + +def log_kernel_metadata( + kernel_name: str, kernel_path: str, kernel_module_code: str +) -> None: + """ + An utility to log kernel metadata. We may parse metadata from kernel source code here. + + It's fine to parse the generated kernel code here since the logging is + disabled by default. It would hurt compilation time. + """ + from .wrapper_benchmark import get_kernel_category_by_source_code + + kernel_category = get_kernel_category_by_source_code(kernel_module_code) + reduction_hint = _parse_reduction_hint(kernel_category, kernel_module_code) + size_hints = _parse_size_hints(kernel_module_code, kernel_category) + kernel_fn_code = _parse_kernel_fn_code(kernel_module_code) + + proper_kernel_fn_code = _parse_proper_kernel_fn_code(kernel_fn_code) + + # the line of code excluding the decortors + kernel_line_of_code = _parse_kernel_line_of_code(proper_kernel_fn_code) + + get_metric_table("kernel_metadata").add_row( + lambda: { + "kernel_name": kernel_name, + "kernel_path": kernel_path, + "kernel_category": kernel_category, + "size_hints": size_hints, + "reduction_hint": reduction_hint, + "line_of_code": kernel_line_of_code, + "num_load": _count_pattern(proper_kernel_fn_code, "tl.load"), + "num_store": _count_pattern(proper_kernel_fn_code, "tl.store"), + "num_for_loop": _count_pattern(proper_kernel_fn_code, "for "), + "num_atomic_add": _count_pattern(proper_kernel_fn_code, "tl.atomic_add"), + "num_args": _count_args(proper_kernel_fn_code), + "xnumel": _parse_numel(proper_kernel_fn_code, "xnumel"), + "ynumel": _parse_numel(proper_kernel_fn_code, "ynumel"), + "rnumel": _parse_numel(proper_kernel_fn_code, "rnumel"), + "kernel_args_num_gb": _parse_kernel_args_num_gb( + kernel_fn_code, kernel_category + ), + } + ) + + +def purge_old_log_files() -> None: + """ + Purge the old log file at the beginning when the benchmark script runs. + Should do it in the parent process rather than the child processes running + each individual model. + """ + for name, table in REGISTERED_METRIC_TABLES.items(): + if name in enabled_metric_tables(): + filename = table.output_filename() + if os.path.exists(filename): + os.unlink(filename) + + table.write_header() + + +def enabled_metric_tables() -> OrderedSet[str]: + return enabled_metric_tables_impl(config.enabled_metric_tables) + + +@lru_cache +def enabled_metric_tables_impl(config_str: str) -> OrderedSet[str]: + enabled = OrderedSet[str]() + for name in config_str.split(","): + name = name.strip() + if not name: + continue + assert name in REGISTERED_METRIC_TABLES, ( + f"Metric table name {name} is not registered" + ) + enabled.add(name) + return enabled + + +def is_metric_table_enabled(name: str) -> bool: + return name in enabled_metric_tables() + + +def get_metric_table(name: str) -> MetricTable: + assert name in REGISTERED_METRIC_TABLES, f"Metric table {name} is not defined" + return REGISTERED_METRIC_TABLES[name] diff --git a/shared/package-files/a5/a5f0ef58d36798821918ed671166617ca54ae6a4b2c31751cc88e954686ad265/nan_to_num.h b/shared/package-files/a5/a5f0ef58d36798821918ed671166617ca54ae6a4b2c31751cc88e954686ad265/nan_to_num.h new file mode 100644 index 0000000000000000000000000000000000000000..751edcd77bc8faed0c3dcbae3de30603229693a7 --- /dev/null +++ b/shared/package-files/a5/a5f0ef58d36798821918ed671166617ca54ae6a4b2c31751cc88e954686ad265/nan_to_num.h @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor +inline at::Tensor nan_to_num(const at::Tensor & self, ::std::optional nan=::std::nullopt, ::std::optional posinf=::std::nullopt, ::std::optional neginf=::std::nullopt) { + return at::_ops::nan_to_num::call(self, nan, posinf, neginf); +} + +// aten::nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!) +inline at::Tensor & nan_to_num_(at::Tensor & self, ::std::optional nan=::std::nullopt, ::std::optional posinf=::std::nullopt, ::std::optional neginf=::std::nullopt) { + return at::_ops::nan_to_num_::call(self, nan, posinf, neginf); +} + +// aten::nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & nan_to_num_out(at::Tensor & out, const at::Tensor & self, ::std::optional nan=::std::nullopt, ::std::optional posinf=::std::nullopt, ::std::optional neginf=::std::nullopt) { + return at::_ops::nan_to_num_out::call(self, nan, posinf, neginf, out); +} +// aten::nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & nan_to_num_outf(const at::Tensor & self, ::std::optional nan, ::std::optional posinf, ::std::optional neginf, at::Tensor & out) { + return at::_ops::nan_to_num_out::call(self, nan, posinf, neginf, out); +} + +} diff --git a/shared/package-files/a5/a5f745aa336f6fe3c44ecc1adbf531666eb7d8efb2d8b7b1fa0ffaf082698ae9/astype.py b/shared/package-files/a5/a5f745aa336f6fe3c44ecc1adbf531666eb7d8efb2d8b7b1fa0ffaf082698ae9/astype.py new file mode 100644 index 0000000000000000000000000000000000000000..4947d53c917fef805b8a72da471209520026c958 --- /dev/null +++ b/shared/package-files/a5/a5f745aa336f6fe3c44ecc1adbf531666eb7d8efb2d8b7b1fa0ffaf082698ae9/astype.py @@ -0,0 +1,72 @@ +import numpy as np + +from .abc import Codec +from .compat import ensure_ndarray, ndarray_copy + + +class AsType(Codec): + """Filter to convert data between different types. + + Parameters + ---------- + encode_dtype : dtype + Data type to use for encoded data. + decode_dtype : dtype, optional + Data type to use for decoded data. + + Notes + ----- + If `encode_dtype` is of lower precision than `decode_dtype`, please be + aware that data loss can occur by writing data to disk using this filter. + No checks are made to ensure the casting will work in that direction and + data corruption will occur. + + Examples + -------- + >>> import numcodecs + >>> import numpy as np + >>> x = np.arange(100, 120, 2, dtype=np.int8) + >>> x + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int8) + >>> f = numcodecs.AsType(encode_dtype=x.dtype, decode_dtype=np.int16) + >>> y = f.decode(x) + >>> y + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int16) + >>> z = f.encode(y) + >>> z + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int8) + + """ + + codec_id = 'astype' + + def __init__(self, encode_dtype, decode_dtype): + self.encode_dtype = np.dtype(encode_dtype) + self.decode_dtype = np.dtype(decode_dtype) + + def encode(self, buf): + # normalise input + arr = ensure_ndarray(buf).view(self.decode_dtype) + + # convert and copy + return arr.astype(self.encode_dtype) + + def decode(self, buf, out=None): + # normalise input + enc = ensure_ndarray(buf).view(self.encode_dtype) + + # convert and copy + dec = enc.astype(self.decode_dtype) + + # handle output + return ndarray_copy(dec, out) + + def get_config(self): + return { + 'id': self.codec_id, + 'encode_dtype': self.encode_dtype.str, + 'decode_dtype': self.decode_dtype.str, + } + + def __repr__(self): + return f'{type(self).__name__}(encode_dtype={self.encode_dtype.str!r}, decode_dtype={self.decode_dtype.str!r})' diff --git a/shared/package-files/a5/a5f90df0d0db217e07e69a7b11c933cd55ecb59dbf3d8d6952586cb0d815a43d/group_norm_native.h b/shared/package-files/a5/a5f90df0d0db217e07e69a7b11c933cd55ecb59dbf3d8d6952586cb0d815a43d/group_norm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..8448aa99ccc1289739137342a490cb4d1ec89247 --- /dev/null +++ b/shared/package-files/a5/a5f90df0d0db217e07e69a7b11c933cd55ecb59dbf3d8d6952586cb0d815a43d/group_norm_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor group_norm(const at::Tensor & input, int64_t num_groups, const ::std::optional & weight={}, const ::std::optional & bias={}, double eps=1e-05, bool cudnn_enabled=true); +} // namespace native +} // namespace at diff --git a/shared/package-files/a5/a5faf3217b3ec24c434e7fa42854e6caec5dccfa05776f0ff521a7390d8135f6/base.cpython-311.pyc b/shared/package-files/a5/a5faf3217b3ec24c434e7fa42854e6caec5dccfa05776f0ff521a7390d8135f6/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb5e80dfe2507b993d39902b3cdf9ed5d93d2e27 Binary files /dev/null and b/shared/package-files/a5/a5faf3217b3ec24c434e7fa42854e6caec5dccfa05776f0ff521a7390d8135f6/base.cpython-311.pyc differ diff --git a/shared/package-files/a5/a5fd059a8028e76b492fb8001b073a4d78347a6c25765d2012fde39a7b1f4a9e/properties.cpython-311-x86_64-linux-gnu.so b/shared/package-files/a5/a5fd059a8028e76b492fb8001b073a4d78347a6c25765d2012fde39a7b1f4a9e/properties.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3a5f34144210a94cf8b6cecbb07dbd50749d1b0a Binary files /dev/null and b/shared/package-files/a5/a5fd059a8028e76b492fb8001b073a4d78347a6c25765d2012fde39a7b1f4a9e/properties.cpython-311-x86_64-linux-gnu.so differ diff --git a/shared/package-files/a5/a5fdf76920f0ed656a093b88eab59b577225539980b94c78ebebc7464a87b02c/profiler.py b/shared/package-files/a5/a5fdf76920f0ed656a093b88eab59b577225539980b94c78ebebc7464a87b02c/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0674f4a4a1d9d3f20a759301606c8236b09828 --- /dev/null +++ b/shared/package-files/a5/a5fdf76920f0ed656a093b88eab59b577225539980b94c78ebebc7464a87b02c/profiler.py @@ -0,0 +1,86 @@ +# mypy: allow-untyped-defs +import contextlib +import tempfile + +import torch + +from . import check_error, cudart + + +__all__ = ["init", "start", "stop", "profile"] + +DEFAULT_FLAGS = [ + "gpustarttimestamp", + "gpuendtimestamp", + "gridsize3d", + "threadblocksize", + "streamid", + "enableonstart 0", + "conckerneltrace", +] + + +def init(output_file, flags=None, output_mode="key_value"): + rt = cudart() + if not hasattr(rt, "cudaOutputMode"): + raise AssertionError("HIP does not support profiler initialization!") + if ( + hasattr(torch.version, "cuda") + and torch.version.cuda is not None + and int(torch.version.cuda.split(".")[0]) >= 12 + ): + # Check https://github.com/pytorch/pytorch/pull/91118 + # cudaProfilerInitialize is no longer needed after CUDA 12 + raise AssertionError("CUDA12+ does not need profiler initialization!") + flags = DEFAULT_FLAGS if flags is None else flags + if output_mode == "key_value": + output_mode_enum = rt.cudaOutputMode.KeyValuePair + elif output_mode == "csv": + output_mode_enum = rt.cudaOutputMode.CSV + else: + raise RuntimeError( + "supported CUDA profiler output modes are: key_value and csv" + ) + with tempfile.NamedTemporaryFile(delete=True) as f: + f.write(b"\n".join(f.encode("ascii") for f in flags)) + f.flush() + check_error(rt.cudaProfilerInitialize(f.name, output_file, output_mode_enum)) + + +def start(): + r"""Starts cuda profiler data collection. + + .. warning:: + Raises CudaError in case of it is unable to start the profiler. + """ + check_error(cudart().cudaProfilerStart()) + + +def stop(): + r"""Stops cuda profiler data collection. + + .. warning:: + Raises CudaError in case of it is unable to stop the profiler. + """ + check_error(cudart().cudaProfilerStop()) + + +@contextlib.contextmanager +def profile(): + """ + Enable profiling. + + Context Manager to enabling profile collection by the active profiling tool from CUDA backend. + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> import torch + >>> model = torch.nn.Linear(20, 30).cuda() + >>> inputs = torch.randn(128, 20).cuda() + >>> with torch.cuda.profiler.profile() as prof: + ... model(inputs) + """ + try: + start() + yield + finally: + stop() diff --git a/shared/package-files/b6/b60376b4df0d5f19305f773c5d5c083997cad98503ea13e8e3abcac877a47bfc/logical_and_native.h b/shared/package-files/b6/b60376b4df0d5f19305f773c5d5c083997cad98503ea13e8e3abcac877a47bfc/logical_and_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a899a2f167d74ffb533cef846c0ec4e4ef1ba688 --- /dev/null +++ b/shared/package-files/b6/b60376b4df0d5f19305f773c5d5c083997cad98503ea13e8e3abcac877a47bfc/logical_and_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor logical_and(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_and_(at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_and_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/b6/b60451435781a82f3d77c85eec9f235e57db3bcf95b97ce914e1f9bf9598e5ad/test_common.cpython-311.pyc b/shared/package-files/b6/b60451435781a82f3d77c85eec9f235e57db3bcf95b97ce914e1f9bf9598e5ad/test_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b1df47a5cc2d91699ae2735866a6a6481462d6 Binary files /dev/null and b/shared/package-files/b6/b60451435781a82f3d77c85eec9f235e57db3bcf95b97ce914e1f9bf9598e5ad/test_common.cpython-311.pyc differ diff --git a/shared/package-files/b6/b607102a6e2ff7de241744008144a5480e2925098694be2a46003d8f60da0f52/browser.py b/shared/package-files/b6/b607102a6e2ff7de241744008144a5480e2925098694be2a46003d8f60da0f52/browser.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9060e57072ea041f1f3b31ccd5ba1e3ab377de --- /dev/null +++ b/shared/package-files/b6/b607102a6e2ff7de241744008144a5480e2925098694be2a46003d8f60da0f52/browser.py @@ -0,0 +1,260 @@ +"""Module browser. + +XXX TO DO: + +- reparse when source changed (maybe just a button would be OK?) + (or recheck on window popup) +- add popup menu with more options (e.g. doc strings, base classes, imports) +- add base classes to class browser tree +""" + +import os +import pyclbr +import sys + +from idlelib.config import idleConf +from idlelib import pyshell +from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas +from idlelib.util import py_extensions +from idlelib.window import ListedToplevel + + +file_open = None # Method...Item and Class...Item use this. +# Normally pyshell.flist.open, but there is no pyshell.flist for htest. + +# The browser depends on pyclbr and importlib which do not support .pyi files. +browseable_extension_blocklist = ('.pyi',) + + +def is_browseable_extension(path): + _, ext = os.path.splitext(path) + ext = os.path.normcase(ext) + return ext in py_extensions and ext not in browseable_extension_blocklist + + +def transform_children(child_dict, modname=None): + """Transform a child dictionary to an ordered sequence of objects. + + The dictionary maps names to pyclbr information objects. + Filter out imported objects. + Augment class names with bases. + The insertion order of the dictionary is assumed to have been in line + number order, so sorting is not necessary. + + The current tree only calls this once per child_dict as it saves + TreeItems once created. A future tree and tests might violate this, + so a check prevents multiple in-place augmentations. + """ + obs = [] # Use list since values should already be sorted. + for key, obj in child_dict.items(): + if modname is None or obj.module == modname: + if hasattr(obj, 'super') and obj.super and obj.name == key: + # If obj.name != key, it has already been suffixed. + supers = [] + for sup in obj.super: + if isinstance(sup, str): + sname = sup + else: + sname = sup.name + if sup.module != obj.module: + sname = f'{sup.module}.{sname}' + supers.append(sname) + obj.name += '({})'.format(', '.join(supers)) + obs.append(obj) + return obs + + +class ModuleBrowser: + """Browse module classes and functions in IDLE. + """ + # This class is also the base class for pathbrowser.PathBrowser. + # Init and close are inherited, other methods are overridden. + # PathBrowser.__init__ does not call __init__ below. + + def __init__(self, master, path, *, _htest=False, _utest=False): + """Create a window for browsing a module's structure. + + Args: + master: parent for widgets. + path: full path of file to browse. + _htest - bool; change box location when running htest. + -utest - bool; suppress contents when running unittest. + + Global variables: + file_open: Function used for opening a file. + + Instance variables: + name: Module name. + file: Full path and module with supported extension. + Used in creating ModuleBrowserTreeItem as the rootnode for + the tree and subsequently in the children. + """ + self.master = master + self.path = path + self._htest = _htest + self._utest = _utest + self.init() + + def close(self, event=None): + "Dismiss the window and the tree nodes." + self.top.destroy() + self.node.destroy() + + def init(self): + "Create browser tkinter widgets, including the tree." + global file_open + root = self.master + flist = (pyshell.flist if not (self._htest or self._utest) + else pyshell.PyShellFileList(root)) + file_open = flist.open + pyclbr._modules.clear() + + # create top + self.top = top = ListedToplevel(root) + top.protocol("WM_DELETE_WINDOW", self.close) + top.bind("", self.close) + if self._htest: # place dialog below parent if running htest + top.geometry("+%d+%d" % + (root.winfo_rootx(), root.winfo_rooty() + 200)) + self.settitle() + top.focus_set() + + # create scrolled canvas + theme = idleConf.CurrentTheme() + background = idleConf.GetHighlight(theme, 'normal')['background'] + sc = ScrolledCanvas(top, bg=background, highlightthickness=0, + takefocus=1) + sc.frame.pack(expand=1, fill="both") + item = self.rootnode() + self.node = node = TreeNode(sc.canvas, None, item) + if not self._utest: + node.update() + node.expand() + + def settitle(self): + "Set the window title." + self.top.wm_title("Module Browser - " + os.path.basename(self.path)) + self.top.wm_iconname("Module Browser") + + def rootnode(self): + "Return a ModuleBrowserTreeItem as the root of the tree." + return ModuleBrowserTreeItem(self.path) + + +class ModuleBrowserTreeItem(TreeItem): + """Browser tree for Python module. + + Uses TreeItem as the basis for the structure of the tree. + Used by both browsers. + """ + + def __init__(self, file): + """Create a TreeItem for the file. + + Args: + file: Full path and module name. + """ + self.file = file + + def GetText(self): + "Return the module name as the text string to display." + return os.path.basename(self.file) + + def GetIconName(self): + "Return the name of the icon to display." + return "python" + + def GetSubList(self): + "Return ChildBrowserTreeItems for children." + return [ChildBrowserTreeItem(obj) for obj in self.listchildren()] + + def OnDoubleClick(self): + "Open a module in an editor window when double clicked." + if not is_browseable_extension(self.file): + return + if not os.path.exists(self.file): + return + file_open(self.file) + + def IsExpandable(self): + "Return True if Python file." + return is_browseable_extension(self.file) + + def listchildren(self): + "Return sequenced classes and functions in the module." + if not is_browseable_extension(self.file): + return [] + dir, base = os.path.split(self.file) + name, _ = os.path.splitext(base) + try: + tree = pyclbr.readmodule_ex(name, [dir] + sys.path) + except ImportError: + return [] + return transform_children(tree, name) + + +class ChildBrowserTreeItem(TreeItem): + """Browser tree for child nodes within the module. + + Uses TreeItem as the basis for the structure of the tree. + """ + + def __init__(self, obj): + "Create a TreeItem for a pyclbr class/function object." + self.obj = obj + self.name = obj.name + self.isfunction = isinstance(obj, pyclbr.Function) + + def GetText(self): + "Return the name of the function/class to display." + name = self.name + if self.isfunction: + return "def " + name + "(...)" + else: + return "class " + name + + def GetIconName(self): + "Return the name of the icon to display." + if self.isfunction: + return "python" + else: + return "folder" + + def IsExpandable(self): + "Return True if self.obj has nested objects." + return self.obj.children != {} + + def GetSubList(self): + "Return ChildBrowserTreeItems for children." + return [ChildBrowserTreeItem(obj) + for obj in transform_children(self.obj.children)] + + def OnDoubleClick(self): + "Open module with file_open and position to lineno." + try: + edit = file_open(self.obj.file) + edit.gotoline(self.obj.lineno) + except (OSError, AttributeError): + pass + + +def _module_browser(parent): # htest # + if len(sys.argv) > 1: # If pass file on command line. + file = sys.argv[1] + else: + file = __file__ + # Add nested objects for htest. + class Nested_in_func(TreeNode): + def nested_in_class(): pass + def closure(): + class Nested_in_closure: pass + ModuleBrowser(parent, file, _htest=True) + + +if __name__ == "__main__": + if len(sys.argv) == 1: # If pass file on command line, unittest fails. + from unittest import main + main('idlelib.idle_test.test_browser', verbosity=2, exit=False) + + from idlelib.idle_test.htest import run + run(_module_browser) diff --git a/shared/package-files/b6/b60e6974a2f68a2029b9cadb3f29d8af4a45d471e5ee6bc0b2faaa19c6681d47/sparse_csr_tensor_compositeimplicitautograd_dispatch.h b/shared/package-files/b6/b60e6974a2f68a2029b9cadb3f29d8af4a45d471e5ee6bc0b2faaa19c6681d47/sparse_csr_tensor_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f3972d9fae14032193f67bbc6f3ed8491d13d309 --- /dev/null +++ b/shared/package-files/b6/b60e6974a2f68a2029b9cadb3f29d8af4a45d471e5ee6bc0b2faaa19c6681d47/sparse_csr_tensor_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options); +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, at::TensorOptions options); +TORCH_API at::Tensor sparse_csr_tensor(const at::Tensor & crow_indices, const at::Tensor & col_indices, const at::Tensor & values, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/b6/b614f00be26aa9c2e9dc4cd60aab4049544008a5b29827dbc85355eb4d5c5ccf/istft_ops.h b/shared/package-files/b6/b614f00be26aa9c2e9dc4cd60aab4049544008a5b29827dbc85355eb4d5c5ccf/istft_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..4dcdf957608ad9f6d6ee966fae85cac6aeae2bea --- /dev/null +++ b/shared/package-files/b6/b614f00be26aa9c2e9dc4cd60aab4049544008a5b29827dbc85355eb4d5c5ccf/istft_ops.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API istft { + using schema = at::Tensor (const at::Tensor &, int64_t, ::std::optional, ::std::optional, const ::std::optional &, bool, bool, ::std::optional, ::std::optional, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::istft"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t n_fft, ::std::optional hop_length, ::std::optional win_length, const ::std::optional & window, bool center, bool normalized, ::std::optional onesided, ::std::optional length, bool return_complex); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t n_fft, ::std::optional hop_length, ::std::optional win_length, const ::std::optional & window, bool center, bool normalized, ::std::optional onesided, ::std::optional length, bool return_complex); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/b6/b61716453fc0dc0d14b647beeb683af6bedfb4975aceeb2beb4d9c6d4e8f997d/addcmul.h b/shared/package-files/b6/b61716453fc0dc0d14b647beeb683af6bedfb4975aceeb2beb4d9c6d4e8f997d/addcmul.h new file mode 100644 index 0000000000000000000000000000000000000000..bef875072d5ca0775c8e27045d48c8d6f3cff5e9 --- /dev/null +++ b/shared/package-files/b6/b61716453fc0dc0d14b647beeb683af6bedfb4975aceeb2beb4d9c6d4e8f997d/addcmul.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & addcmul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) { + return at::_ops::addcmul_out::call(self, tensor1, tensor2, value, out); +} +// aten::addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & addcmul_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out) { + return at::_ops::addcmul_out::call(self, tensor1, tensor2, value, out); +} + +// aten::addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor +inline at::Tensor addcmul(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1) { + return at::_ops::addcmul::call(self, tensor1, tensor2, value); +} + +} diff --git a/shared/package-files/b6/b617f58c674f0469c79ea2d30b03d4341393b0f235d3a767e9a06d705f188afe/test_to_csv.cpython-311.pyc b/shared/package-files/b6/b617f58c674f0469c79ea2d30b03d4341393b0f235d3a767e9a06d705f188afe/test_to_csv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9152da3f44d01ba31343c1870060ff8df2cd8c1a Binary files /dev/null and b/shared/package-files/b6/b617f58c674f0469c79ea2d30b03d4341393b0f235d3a767e9a06d705f188afe/test_to_csv.cpython-311.pyc differ diff --git a/shared/package-files/b6/b619ed0dfbf752aee8f3db1cee35cb1103572c9e11ce51378907b605d9ddec66/config.cpython-311.pyc b/shared/package-files/b6/b619ed0dfbf752aee8f3db1cee35cb1103572c9e11ce51378907b605d9ddec66/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08d98255f64a5bec1132d1840ad73279503ea950 Binary files /dev/null and b/shared/package-files/b6/b619ed0dfbf752aee8f3db1cee35cb1103572c9e11ce51378907b605d9ddec66/config.cpython-311.pyc differ diff --git a/shared/package-files/b6/b62d1a42061e60265023b7cda213cc910b8b9c74b04a644adcfc7835a4e5fa2e/__init__.cpython-311.pyc b/shared/package-files/b6/b62d1a42061e60265023b7cda213cc910b8b9c74b04a644adcfc7835a4e5fa2e/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5edf9cacafeba28664b8225976ba01b874410079 Binary files /dev/null and b/shared/package-files/b6/b62d1a42061e60265023b7cda213cc910b8b9c74b04a644adcfc7835a4e5fa2e/__init__.cpython-311.pyc differ diff --git a/shared/package-files/b6/b62fe0252cfccc1d6c7fea08c9f5c0c38c640c6910699b3fdf84520bee8795d6/compatibility.py b/shared/package-files/b6/b62fe0252cfccc1d6c7fea08c9f5c0c38c640c6910699b3fdf84520bee8795d6/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..eb239d282a738d1e5611a2249d313ff1d3b7671c --- /dev/null +++ b/shared/package-files/b6/b62fe0252cfccc1d6c7fea08c9f5c0c38c640c6910699b3fdf84520bee8795d6/compatibility.py @@ -0,0 +1,1152 @@ +"""Compatibility interface between dense and sparse polys. """ + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from sympy.core.expr import Expr + from sympy.polys.domains.domain import Domain + from sympy.polys.orderings import MonomialOrder + from sympy.polys.rings import PolyElement + +from sympy.polys.densearith import dup_add_term +from sympy.polys.densearith import dmp_add_term +from sympy.polys.densearith import dup_sub_term +from sympy.polys.densearith import dmp_sub_term +from sympy.polys.densearith import dup_mul_term +from sympy.polys.densearith import dmp_mul_term +from sympy.polys.densearith import dup_add_ground +from sympy.polys.densearith import dmp_add_ground +from sympy.polys.densearith import dup_sub_ground +from sympy.polys.densearith import dmp_sub_ground +from sympy.polys.densearith import dup_mul_ground +from sympy.polys.densearith import dmp_mul_ground +from sympy.polys.densearith import dup_quo_ground +from sympy.polys.densearith import dmp_quo_ground +from sympy.polys.densearith import dup_exquo_ground +from sympy.polys.densearith import dmp_exquo_ground +from sympy.polys.densearith import dup_lshift +from sympy.polys.densearith import dup_rshift +from sympy.polys.densearith import dup_abs +from sympy.polys.densearith import dmp_abs +from sympy.polys.densearith import dup_neg +from sympy.polys.densearith import dmp_neg +from sympy.polys.densearith import dup_add +from sympy.polys.densearith import dmp_add +from sympy.polys.densearith import dup_sub +from sympy.polys.densearith import dmp_sub +from sympy.polys.densearith import dup_add_mul +from sympy.polys.densearith import dmp_add_mul +from sympy.polys.densearith import dup_sub_mul +from sympy.polys.densearith import dmp_sub_mul +from sympy.polys.densearith import dup_mul +from sympy.polys.densearith import dmp_mul +from sympy.polys.densearith import dup_sqr +from sympy.polys.densearith import dmp_sqr +from sympy.polys.densearith import dup_pow +from sympy.polys.densearith import dmp_pow +from sympy.polys.densearith import dup_pdiv +from sympy.polys.densearith import dup_prem +from sympy.polys.densearith import dup_pquo +from sympy.polys.densearith import dup_pexquo +from sympy.polys.densearith import dmp_pdiv +from sympy.polys.densearith import dmp_prem +from sympy.polys.densearith import dmp_pquo +from sympy.polys.densearith import dmp_pexquo +from sympy.polys.densearith import dup_rr_div +from sympy.polys.densearith import dmp_rr_div +from sympy.polys.densearith import dup_ff_div +from sympy.polys.densearith import dmp_ff_div +from sympy.polys.densearith import dup_div +from sympy.polys.densearith import dup_rem +from sympy.polys.densearith import dup_quo +from sympy.polys.densearith import dup_exquo +from sympy.polys.densearith import dmp_div +from sympy.polys.densearith import dmp_rem +from sympy.polys.densearith import dmp_quo +from sympy.polys.densearith import dmp_exquo +from sympy.polys.densearith import dup_max_norm +from sympy.polys.densearith import dmp_max_norm +from sympy.polys.densearith import dup_l1_norm +from sympy.polys.densearith import dmp_l1_norm +from sympy.polys.densearith import dup_l2_norm_squared +from sympy.polys.densearith import dmp_l2_norm_squared +from sympy.polys.densearith import dup_expand +from sympy.polys.densearith import dmp_expand +from sympy.polys.densebasic import dup_LC +from sympy.polys.densebasic import dmp_LC +from sympy.polys.densebasic import dup_TC +from sympy.polys.densebasic import dmp_TC +from sympy.polys.densebasic import dmp_ground_LC +from sympy.polys.densebasic import dmp_ground_TC +from sympy.polys.densebasic import dup_degree +from sympy.polys.densebasic import dmp_degree +from sympy.polys.densebasic import dmp_degree_in +from sympy.polys.densebasic import dmp_to_dict +from sympy.polys.densetools import dup_integrate +from sympy.polys.densetools import dmp_integrate +from sympy.polys.densetools import dmp_integrate_in +from sympy.polys.densetools import dup_diff +from sympy.polys.densetools import dmp_diff +from sympy.polys.densetools import dmp_diff_in +from sympy.polys.densetools import dup_eval +from sympy.polys.densetools import dmp_eval +from sympy.polys.densetools import dmp_eval_in +from sympy.polys.densetools import dmp_eval_tail +from sympy.polys.densetools import dmp_diff_eval_in +from sympy.polys.densetools import dup_trunc +from sympy.polys.densetools import dmp_trunc +from sympy.polys.densetools import dmp_ground_trunc +from sympy.polys.densetools import dup_monic +from sympy.polys.densetools import dmp_ground_monic +from sympy.polys.densetools import dup_content +from sympy.polys.densetools import dmp_ground_content +from sympy.polys.densetools import dup_primitive +from sympy.polys.densetools import dmp_ground_primitive +from sympy.polys.densetools import dup_extract +from sympy.polys.densetools import dmp_ground_extract +from sympy.polys.densetools import dup_real_imag +from sympy.polys.densetools import dup_mirror +from sympy.polys.densetools import dup_scale +from sympy.polys.densetools import dup_shift +from sympy.polys.densetools import dmp_shift +from sympy.polys.densetools import dup_transform +from sympy.polys.densetools import dup_compose +from sympy.polys.densetools import dmp_compose +from sympy.polys.densetools import dup_decompose +from sympy.polys.densetools import dmp_lift +from sympy.polys.densetools import dup_sign_variations +from sympy.polys.densetools import dup_clear_denoms +from sympy.polys.densetools import dmp_clear_denoms +from sympy.polys.densetools import dup_revert +from sympy.polys.euclidtools import dup_half_gcdex +from sympy.polys.euclidtools import dmp_half_gcdex +from sympy.polys.euclidtools import dup_gcdex +from sympy.polys.euclidtools import dmp_gcdex +from sympy.polys.euclidtools import dup_invert +from sympy.polys.euclidtools import dmp_invert +from sympy.polys.euclidtools import dup_euclidean_prs +from sympy.polys.euclidtools import dmp_euclidean_prs +from sympy.polys.euclidtools import dup_primitive_prs +from sympy.polys.euclidtools import dmp_primitive_prs +from sympy.polys.euclidtools import dup_inner_subresultants +from sympy.polys.euclidtools import dup_subresultants +from sympy.polys.euclidtools import dup_prs_resultant +from sympy.polys.euclidtools import dup_resultant +from sympy.polys.euclidtools import dmp_inner_subresultants +from sympy.polys.euclidtools import dmp_subresultants +from sympy.polys.euclidtools import dmp_prs_resultant +from sympy.polys.euclidtools import dmp_zz_modular_resultant +from sympy.polys.euclidtools import dmp_zz_collins_resultant +from sympy.polys.euclidtools import dmp_qq_collins_resultant +from sympy.polys.euclidtools import dmp_resultant +from sympy.polys.euclidtools import dup_discriminant +from sympy.polys.euclidtools import dmp_discriminant +from sympy.polys.euclidtools import dup_rr_prs_gcd +from sympy.polys.euclidtools import dup_ff_prs_gcd +from sympy.polys.euclidtools import dmp_rr_prs_gcd +from sympy.polys.euclidtools import dmp_ff_prs_gcd +from sympy.polys.euclidtools import dup_zz_heu_gcd +from sympy.polys.euclidtools import dmp_zz_heu_gcd +from sympy.polys.euclidtools import dup_qq_heu_gcd +from sympy.polys.euclidtools import dmp_qq_heu_gcd +from sympy.polys.euclidtools import dup_inner_gcd +from sympy.polys.euclidtools import dmp_inner_gcd +from sympy.polys.euclidtools import dup_gcd +from sympy.polys.euclidtools import dmp_gcd +from sympy.polys.euclidtools import dup_rr_lcm +from sympy.polys.euclidtools import dup_ff_lcm +from sympy.polys.euclidtools import dup_lcm +from sympy.polys.euclidtools import dmp_rr_lcm +from sympy.polys.euclidtools import dmp_ff_lcm +from sympy.polys.euclidtools import dmp_lcm +from sympy.polys.euclidtools import dmp_content +from sympy.polys.euclidtools import dmp_primitive +from sympy.polys.euclidtools import dup_cancel +from sympy.polys.euclidtools import dmp_cancel +from sympy.polys.factortools import dup_trial_division +from sympy.polys.factortools import dmp_trial_division +from sympy.polys.factortools import dup_zz_mignotte_bound +from sympy.polys.factortools import dmp_zz_mignotte_bound +from sympy.polys.factortools import dup_zz_hensel_step +from sympy.polys.factortools import dup_zz_hensel_lift +from sympy.polys.factortools import dup_zz_zassenhaus +from sympy.polys.factortools import dup_zz_irreducible_p +from sympy.polys.factortools import dup_cyclotomic_p +from sympy.polys.factortools import dup_zz_cyclotomic_poly +from sympy.polys.factortools import dup_zz_cyclotomic_factor +from sympy.polys.factortools import dup_zz_factor_sqf +from sympy.polys.factortools import dup_zz_factor +from sympy.polys.factortools import dmp_zz_wang_non_divisors +from sympy.polys.factortools import dmp_zz_wang_lead_coeffs +from sympy.polys.factortools import dup_zz_diophantine +from sympy.polys.factortools import dmp_zz_diophantine +from sympy.polys.factortools import dmp_zz_wang_hensel_lifting +from sympy.polys.factortools import dmp_zz_wang +from sympy.polys.factortools import dmp_zz_factor +from sympy.polys.factortools import dup_qq_i_factor +from sympy.polys.factortools import dup_zz_i_factor +from sympy.polys.factortools import dmp_qq_i_factor +from sympy.polys.factortools import dmp_zz_i_factor +from sympy.polys.factortools import dup_ext_factor +from sympy.polys.factortools import dmp_ext_factor +from sympy.polys.factortools import dup_gf_factor +from sympy.polys.factortools import dmp_gf_factor +from sympy.polys.factortools import dup_factor_list +from sympy.polys.factortools import dup_factor_list_include +from sympy.polys.factortools import dmp_factor_list +from sympy.polys.factortools import dmp_factor_list_include +from sympy.polys.factortools import dup_irreducible_p +from sympy.polys.factortools import dmp_irreducible_p +from sympy.polys.rootisolation import dup_sturm +from sympy.polys.rootisolation import dup_root_upper_bound +from sympy.polys.rootisolation import dup_root_lower_bound +from sympy.polys.rootisolation import dup_step_refine_real_root +from sympy.polys.rootisolation import dup_inner_refine_real_root +from sympy.polys.rootisolation import dup_outer_refine_real_root +from sympy.polys.rootisolation import dup_refine_real_root +from sympy.polys.rootisolation import dup_inner_isolate_real_roots +from sympy.polys.rootisolation import dup_inner_isolate_positive_roots +from sympy.polys.rootisolation import dup_inner_isolate_negative_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_sqf +from sympy.polys.rootisolation import dup_isolate_real_roots +from sympy.polys.rootisolation import dup_isolate_real_roots_list +from sympy.polys.rootisolation import dup_count_real_roots +from sympy.polys.rootisolation import dup_count_complex_roots +from sympy.polys.rootisolation import dup_isolate_complex_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots_sqf +from sympy.polys.rootisolation import dup_isolate_all_roots + +from sympy.polys.sqfreetools import ( + dup_sqf_p, dmp_sqf_p, dmp_norm, dup_sqf_norm, dmp_sqf_norm, + dup_gf_sqf_part, dmp_gf_sqf_part, dup_sqf_part, dmp_sqf_part, + dup_gf_sqf_list, dmp_gf_sqf_list, dup_sqf_list, dup_sqf_list_include, + dmp_sqf_list, dmp_sqf_list_include, dup_gff_list, dmp_gff_list) + +from sympy.polys.galoistools import ( + gf_degree, gf_LC, gf_TC, gf_strip, gf_from_dict, + gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, + gf_mul_ground, gf_quo_ground, gf_add, gf_sub, gf_mul, gf_sqr, gf_add_mul, gf_sub_mul, + gf_expand, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_pow, gf_pow_mod, + gf_gcd, gf_lcm, gf_cofactors, gf_gcdex, gf_monic, gf_diff, gf_eval, gf_multi_eval, + gf_compose, gf_compose_mod, gf_trace_map, gf_random, gf_irreducible, gf_irred_p_ben_or, + gf_irred_p_rabin, gf_irreducible_p, gf_sqf_p, gf_sqf_part, gf_Qmatrix, + gf_berlekamp, gf_ddf_zassenhaus, gf_edf_zassenhaus, gf_ddf_shoup, gf_edf_shoup, + gf_zassenhaus, gf_shoup, gf_factor_sqf, gf_factor) + +from sympy.utilities import public + +@public +class IPolys: + + gens: tuple[PolyElement, ...] + symbols: tuple[Expr, ...] + ngens: int + domain: Domain + order: MonomialOrder + + def drop(self, gen): + pass + + def clone(self, symbols=None, domain=None, order=None): + pass + + def to_ground(self): + pass + + def ground_new(self, element): + pass + + def domain_new(self, element): + pass + + def from_dict(self, d): + pass + + def wrap(self, element): + from sympy.polys.rings import PolyElement + if isinstance(element, PolyElement): + if element.ring == self: + return element + else: + raise NotImplementedError("domain conversions") + else: + return self.ground_new(element) + + def to_dense(self, element): + return self.wrap(element).to_dense() + + def from_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) + + def dup_add_term(self, f, c, i): + return self.from_dense(dup_add_term(self.to_dense(f), c, i, self.domain)) + def dmp_add_term(self, f, c, i): + return self.from_dense(dmp_add_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_sub_term(self, f, c, i): + return self.from_dense(dup_sub_term(self.to_dense(f), c, i, self.domain)) + def dmp_sub_term(self, f, c, i): + return self.from_dense(dmp_sub_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + def dup_mul_term(self, f, c, i): + return self.from_dense(dup_mul_term(self.to_dense(f), c, i, self.domain)) + def dmp_mul_term(self, f, c, i): + return self.from_dense(dmp_mul_term(self.to_dense(f), self.wrap(c).drop(0).to_dense(), i, self.ngens-1, self.domain)) + + def dup_add_ground(self, f, c): + return self.from_dense(dup_add_ground(self.to_dense(f), c, self.domain)) + def dmp_add_ground(self, f, c): + return self.from_dense(dmp_add_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_sub_ground(self, f, c): + return self.from_dense(dup_sub_ground(self.to_dense(f), c, self.domain)) + def dmp_sub_ground(self, f, c): + return self.from_dense(dmp_sub_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_mul_ground(self, f, c): + return self.from_dense(dup_mul_ground(self.to_dense(f), c, self.domain)) + def dmp_mul_ground(self, f, c): + return self.from_dense(dmp_mul_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_quo_ground(self, f, c): + return self.from_dense(dup_quo_ground(self.to_dense(f), c, self.domain)) + def dmp_quo_ground(self, f, c): + return self.from_dense(dmp_quo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + def dup_exquo_ground(self, f, c): + return self.from_dense(dup_exquo_ground(self.to_dense(f), c, self.domain)) + def dmp_exquo_ground(self, f, c): + return self.from_dense(dmp_exquo_ground(self.to_dense(f), c, self.ngens-1, self.domain)) + + def dup_lshift(self, f, n): + return self.from_dense(dup_lshift(self.to_dense(f), n, self.domain)) + def dup_rshift(self, f, n): + return self.from_dense(dup_rshift(self.to_dense(f), n, self.domain)) + + def dup_abs(self, f): + return self.from_dense(dup_abs(self.to_dense(f), self.domain)) + def dmp_abs(self, f): + return self.from_dense(dmp_abs(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_neg(self, f): + return self.from_dense(dup_neg(self.to_dense(f), self.domain)) + def dmp_neg(self, f): + return self.from_dense(dmp_neg(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_add(self, f, g): + return self.from_dense(dup_add(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_add(self, f, g): + return self.from_dense(dmp_add(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sub(self, f, g): + return self.from_dense(dup_sub(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_sub(self, f, g): + return self.from_dense(dmp_sub(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_add_mul(self, f, g, h): + return self.from_dense(dup_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_add_mul(self, f, g, h): + return self.from_dense(dmp_add_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + def dup_sub_mul(self, f, g, h): + return self.from_dense(dup_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.domain)) + def dmp_sub_mul(self, f, g, h): + return self.from_dense(dmp_sub_mul(self.to_dense(f), self.to_dense(g), self.to_dense(h), self.ngens-1, self.domain)) + + def dup_mul(self, f, g): + return self.from_dense(dup_mul(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_mul(self, f, g): + return self.from_dense(dmp_mul(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_sqr(self, f): + return self.from_dense(dup_sqr(self.to_dense(f), self.domain)) + def dmp_sqr(self, f): + return self.from_dense(dmp_sqr(self.to_dense(f), self.ngens-1, self.domain)) + def dup_pow(self, f, n): + return self.from_dense(dup_pow(self.to_dense(f), n, self.domain)) + def dmp_pow(self, f, n): + return self.from_dense(dmp_pow(self.to_dense(f), n, self.ngens-1, self.domain)) + + def dup_pdiv(self, f, g): + q, r = dup_pdiv(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_prem(self, f, g): + return self.from_dense(dup_prem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pquo(self, f, g): + return self.from_dense(dup_pquo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_pexquo(self, f, g): + return self.from_dense(dup_pexquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_pdiv(self, f, g): + q, r = dmp_pdiv(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_prem(self, f, g): + return self.from_dense(dmp_prem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pquo(self, f, g): + return self.from_dense(dmp_pquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_pexquo(self, f, g): + return self.from_dense(dmp_pexquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_rr_div(self, f, g): + q, r = dup_rr_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rr_div(self, f, g): + q, r = dmp_rr_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_ff_div(self, f, g): + q, r = dup_ff_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_ff_div(self, f, g): + q, r = dmp_ff_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + + def dup_div(self, f, g): + q, r = dup_div(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dup_rem(self, f, g): + return self.from_dense(dup_rem(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_quo(self, f, g): + return self.from_dense(dup_quo(self.to_dense(f), self.to_dense(g), self.domain)) + def dup_exquo(self, f, g): + return self.from_dense(dup_exquo(self.to_dense(f), self.to_dense(g), self.domain)) + + def dmp_div(self, f, g): + q, r = dmp_div(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(q), self.from_dense(r)) + def dmp_rem(self, f, g): + return self.from_dense(dmp_rem(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_quo(self, f, g): + return self.from_dense(dmp_quo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + def dmp_exquo(self, f, g): + return self.from_dense(dmp_exquo(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_max_norm(self, f): + return dup_max_norm(self.to_dense(f), self.domain) + def dmp_max_norm(self, f): + return dmp_max_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l1_norm(self, f): + return dup_l1_norm(self.to_dense(f), self.domain) + def dmp_l1_norm(self, f): + return dmp_l1_norm(self.to_dense(f), self.ngens-1, self.domain) + + def dup_l2_norm_squared(self, f): + return dup_l2_norm_squared(self.to_dense(f), self.domain) + def dmp_l2_norm_squared(self, f): + return dmp_l2_norm_squared(self.to_dense(f), self.ngens-1, self.domain) + + def dup_expand(self, polys): + return self.from_dense(dup_expand(list(map(self.to_dense, polys)), self.domain)) + def dmp_expand(self, polys): + return self.from_dense(dmp_expand(list(map(self.to_dense, polys)), self.ngens-1, self.domain)) + + def dup_LC(self, f): + return dup_LC(self.to_dense(f), self.domain) + def dmp_LC(self, f): + LC = dmp_LC(self.to_dense(f), self.domain) + if isinstance(LC, list): + return self[1:].from_dense(LC) + else: + return LC + def dup_TC(self, f): + return dup_TC(self.to_dense(f), self.domain) + def dmp_TC(self, f): + TC = dmp_TC(self.to_dense(f), self.domain) + if isinstance(TC, list): + return self[1:].from_dense(TC) + else: + return TC + + def dmp_ground_LC(self, f): + return dmp_ground_LC(self.to_dense(f), self.ngens-1, self.domain) + def dmp_ground_TC(self, f): + return dmp_ground_TC(self.to_dense(f), self.ngens-1, self.domain) + + def dup_degree(self, f): + return dup_degree(self.to_dense(f)) + def dmp_degree(self, f): + return dmp_degree(self.to_dense(f), self.ngens-1) + def dmp_degree_in(self, f, j): + return dmp_degree_in(self.to_dense(f), j, self.ngens-1) + def dup_integrate(self, f, m): + return self.from_dense(dup_integrate(self.to_dense(f), m, self.domain)) + def dmp_integrate(self, f, m): + return self.from_dense(dmp_integrate(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dup_diff(self, f, m): + return self.from_dense(dup_diff(self.to_dense(f), m, self.domain)) + def dmp_diff(self, f, m): + return self.from_dense(dmp_diff(self.to_dense(f), m, self.ngens-1, self.domain)) + + def dmp_diff_in(self, f, m, j): + return self.from_dense(dmp_diff_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + def dmp_integrate_in(self, f, m, j): + return self.from_dense(dmp_integrate_in(self.to_dense(f), m, j, self.ngens-1, self.domain)) + + def dup_eval(self, f, a): + return dup_eval(self.to_dense(f), a, self.domain) + def dmp_eval(self, f, a): + result = dmp_eval(self.to_dense(f), a, self.ngens-1, self.domain) + return self[1:].from_dense(result) + + def dmp_eval_in(self, f, a, j): + result = dmp_eval_in(self.to_dense(f), a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + def dmp_diff_eval_in(self, f, m, a, j): + result = dmp_diff_eval_in(self.to_dense(f), m, a, j, self.ngens-1, self.domain) + return self.drop(j).from_dense(result) + + def dmp_eval_tail(self, f, A): + result = dmp_eval_tail(self.to_dense(f), A, self.ngens-1, self.domain) + if isinstance(result, list): + return self[:-len(A)].from_dense(result) + else: + return result + + def dup_trunc(self, f, p): + return self.from_dense(dup_trunc(self.to_dense(f), p, self.domain)) + def dmp_trunc(self, f, g): + return self.from_dense(dmp_trunc(self.to_dense(f), self[1:].to_dense(g), self.ngens-1, self.domain)) + def dmp_ground_trunc(self, f, p): + return self.from_dense(dmp_ground_trunc(self.to_dense(f), p, self.ngens-1, self.domain)) + + def dup_monic(self, f): + return self.from_dense(dup_monic(self.to_dense(f), self.domain)) + def dmp_ground_monic(self, f): + return self.from_dense(dmp_ground_monic(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_extract(self, f, g): + c, F, G = dup_extract(self.to_dense(f), self.to_dense(g), self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + def dmp_ground_extract(self, f, g): + c, F, G = dmp_ground_extract(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (c, self.from_dense(F), self.from_dense(G)) + + def dup_real_imag(self, f): + p, q = dup_real_imag(self.wrap(f).drop(1).to_dense(), self.domain) + return (self.from_dense(p), self.from_dense(q)) + + def dup_mirror(self, f): + return self.from_dense(dup_mirror(self.to_dense(f), self.domain)) + def dup_scale(self, f, a): + return self.from_dense(dup_scale(self.to_dense(f), a, self.domain)) + def dup_shift(self, f, a): + return self.from_dense(dup_shift(self.to_dense(f), a, self.domain)) + def dmp_shift(self, f, a): + return self.from_dense(dmp_shift(self.to_dense(f), a, self.ngens-1, self.domain)) + def dup_transform(self, f, p, q): + return self.from_dense(dup_transform(self.to_dense(f), self.to_dense(p), self.to_dense(q), self.domain)) + + def dup_compose(self, f, g): + return self.from_dense(dup_compose(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_compose(self, f, g): + return self.from_dense(dmp_compose(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_decompose(self, f): + components = dup_decompose(self.to_dense(f), self.domain) + return list(map(self.from_dense, components)) + + def dmp_lift(self, f): + result = dmp_lift(self.to_dense(f), self.ngens-1, self.domain) + return self.to_ground().from_dense(result) + + def dup_sign_variations(self, f): + return dup_sign_variations(self.to_dense(f), self.domain) + + def dup_clear_denoms(self, f, convert=False): + c, F = dup_clear_denoms(self.to_dense(f), self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + def dmp_clear_denoms(self, f, convert=False): + c, F = dmp_clear_denoms(self.to_dense(f), self.ngens-1, self.domain, convert=convert) + if convert: + ring = self.clone(domain=self.domain.get_ring()) + else: + ring = self + return (c, ring.from_dense(F)) + + def dup_revert(self, f, n): + return self.from_dense(dup_revert(self.to_dense(f), n, self.domain)) + + def dup_half_gcdex(self, f, g): + s, h = dup_half_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dmp_half_gcdex(self, f, g): + s, h = dmp_half_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(h)) + def dup_gcdex(self, f, g): + s, t, h = dup_gcdex(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + def dmp_gcdex(self, f, g): + s, t, h = dmp_gcdex(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(s), self.from_dense(t), self.from_dense(h)) + + def dup_invert(self, f, g): + return self.from_dense(dup_invert(self.to_dense(f), self.to_dense(g), self.domain)) + def dmp_invert(self, f, g): + return self.from_dense(dmp_invert(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain)) + + def dup_euclidean_prs(self, f, g): + prs = dup_euclidean_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_euclidean_prs(self, f, g): + prs = dmp_euclidean_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + def dup_primitive_prs(self, f, g): + prs = dup_primitive_prs(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_primitive_prs(self, f, g): + prs = dmp_primitive_prs(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_inner_subresultants(self, f, g): + prs, sres = dup_inner_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return (list(map(self.from_dense, prs)), sres) + def dmp_inner_subresultants(self, f, g): + prs, sres = dmp_inner_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (list(map(self.from_dense, prs)), sres) + + def dup_subresultants(self, f, g): + prs = dup_subresultants(self.to_dense(f), self.to_dense(g), self.domain) + return list(map(self.from_dense, prs)) + def dmp_subresultants(self, f, g): + prs = dmp_subresultants(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return list(map(self.from_dense, prs)) + + def dup_prs_resultant(self, f, g): + res, prs = dup_prs_resultant(self.to_dense(f), self.to_dense(g), self.domain) + return (res, list(map(self.from_dense, prs))) + def dmp_prs_resultant(self, f, g): + res, prs = dmp_prs_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self[1:].from_dense(res), list(map(self.from_dense, prs))) + + def dmp_zz_modular_resultant(self, f, g, p): + res = dmp_zz_modular_resultant(self.to_dense(f), self.to_dense(g), self.domain_new(p), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_zz_collins_resultant(self, f, g): + res = dmp_zz_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + def dmp_qq_collins_resultant(self, f, g): + res = dmp_qq_collins_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self[1:].from_dense(res) + + def dup_resultant(self, f, g): #, includePRS=False): + return dup_resultant(self.to_dense(f), self.to_dense(g), self.domain) #, includePRS=includePRS) + def dmp_resultant(self, f, g): #, includePRS=False): + res = dmp_resultant(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) #, includePRS=includePRS) + if isinstance(res, list): + return self[1:].from_dense(res) + else: + return res + + def dup_discriminant(self, f): + return dup_discriminant(self.to_dense(f), self.domain) + def dmp_discriminant(self, f): + disc = dmp_discriminant(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(disc, list): + return self[1:].from_dense(disc) + else: + return disc + + def dup_rr_prs_gcd(self, f, g): + H, F, G = dup_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_ff_prs_gcd(self, f, g): + H, F, G = dup_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_rr_prs_gcd(self, f, g): + H, F, G = dmp_rr_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_ff_prs_gcd(self, f, g): + H, F, G = dmp_ff_prs_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_zz_heu_gcd(self, f, g): + H, F, G = dup_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_zz_heu_gcd(self, f, g): + H, F, G = dmp_zz_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_qq_heu_gcd(self, f, g): + H, F, G = dup_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_qq_heu_gcd(self, f, g): + H, F, G = dmp_qq_heu_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_inner_gcd(self, f, g): + H, F, G = dup_inner_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dmp_inner_gcd(self, f, g): + H, F, G = dmp_inner_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return (self.from_dense(H), self.from_dense(F), self.from_dense(G)) + def dup_gcd(self, f, g): + H = dup_gcd(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_gcd(self, f, g): + H = dmp_gcd(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dup_rr_lcm(self, f, g): + H = dup_rr_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_ff_lcm(self, f, g): + H = dup_ff_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dup_lcm(self, f, g): + H = dup_lcm(self.to_dense(f), self.to_dense(g), self.domain) + return self.from_dense(H) + def dmp_rr_lcm(self, f, g): + H = dmp_rr_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_ff_lcm(self, f, g): + H = dmp_ff_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + def dmp_lcm(self, f, g): + H = dmp_lcm(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain) + return self.from_dense(H) + + def dup_content(self, f): + cont = dup_content(self.to_dense(f), self.domain) + return cont + def dup_primitive(self, f): + cont, prim = dup_primitive(self.to_dense(f), self.domain) + return cont, self.from_dense(prim) + + def dmp_content(self, f): + cont = dmp_content(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return self[1:].from_dense(cont) + else: + return cont + def dmp_primitive(self, f): + cont, prim = dmp_primitive(self.to_dense(f), self.ngens-1, self.domain) + if isinstance(cont, list): + return (self[1:].from_dense(cont), self.from_dense(prim)) + else: + return (cont, self.from_dense(prim)) + + def dmp_ground_content(self, f): + cont = dmp_ground_content(self.to_dense(f), self.ngens-1, self.domain) + return cont + def dmp_ground_primitive(self, f): + cont, prim = dmp_ground_primitive(self.to_dense(f), self.ngens-1, self.domain) + return (cont, self.from_dense(prim)) + + def dup_cancel(self, f, g, include=True): + result = dup_cancel(self.to_dense(f), self.to_dense(g), self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + def dmp_cancel(self, f, g, include=True): + result = dmp_cancel(self.to_dense(f), self.to_dense(g), self.ngens-1, self.domain, include=include) + if not include: + cf, cg, F, G = result + return (cf, cg, self.from_dense(F), self.from_dense(G)) + else: + F, G = result + return (self.from_dense(F), self.from_dense(G)) + + def dup_trial_division(self, f, factors): + factors = dup_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_trial_division(self, f, factors): + factors = dmp_trial_division(self.to_dense(f), list(map(self.to_dense, factors)), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_mignotte_bound(self, f): + return dup_zz_mignotte_bound(self.to_dense(f), self.domain) + def dmp_zz_mignotte_bound(self, f): + return dmp_zz_mignotte_bound(self.to_dense(f), self.ngens-1, self.domain) + + def dup_zz_hensel_step(self, m, f, g, h, s, t): + D = self.to_dense + G, H, S, T = dup_zz_hensel_step(m, D(f), D(g), D(h), D(s), D(t), self.domain) + return (self.from_dense(G), self.from_dense(H), self.from_dense(S), self.from_dense(T)) + def dup_zz_hensel_lift(self, p, f, f_list, l): + D = self.to_dense + polys = dup_zz_hensel_lift(p, D(f), list(map(D, f_list)), l, self.domain) + return list(map(self.from_dense, polys)) + + def dup_zz_zassenhaus(self, f): + factors = dup_zz_zassenhaus(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_zz_irreducible_p(self, f): + return dup_zz_irreducible_p(self.to_dense(f), self.domain) + def dup_cyclotomic_p(self, f, irreducible=False): + return dup_cyclotomic_p(self.to_dense(f), self.domain, irreducible=irreducible) + def dup_zz_cyclotomic_poly(self, n): + F = dup_zz_cyclotomic_poly(n, self.domain) + return self.from_dense(F) + def dup_zz_cyclotomic_factor(self, f): + result = dup_zz_cyclotomic_factor(self.to_dense(f), self.domain) + if result is None: + return result + else: + return list(map(self.from_dense, result)) + + # E: List[ZZ], cs: ZZ, ct: ZZ + def dmp_zz_wang_non_divisors(self, E, cs, ct): + return dmp_zz_wang_non_divisors(E, cs, ct, self.domain) + + # f: Poly, T: List[(Poly, int)], ct: ZZ, A: List[ZZ] + #def dmp_zz_wang_test_points(f, T, ct, A): + # dmp_zz_wang_test_points(self.to_dense(f), T, ct, A, self.ngens-1, self.domain) + + # f: Poly, T: List[(Poly, int)], cs: ZZ, E: List[ZZ], H: List[Poly], A: List[ZZ] + def dmp_zz_wang_lead_coeffs(self, f, T, cs, E, H, A): + mv = self[1:] + T = [ (mv.to_dense(t), k) for t, k in T ] + uv = self[:1] + H = list(map(uv.to_dense, H)) + f, HH, CC = dmp_zz_wang_lead_coeffs(self.to_dense(f), T, cs, E, H, A, self.ngens-1, self.domain) + return self.from_dense(f), list(map(uv.from_dense, HH)), list(map(mv.from_dense, CC)) + + # f: List[Poly], m: int, p: ZZ + def dup_zz_diophantine(self, F, m, p): + result = dup_zz_diophantine(list(map(self.to_dense, F)), m, p, self.domain) + return list(map(self.from_dense, result)) + + # f: List[Poly], c: List[Poly], A: List[ZZ], d: int, p: ZZ + def dmp_zz_diophantine(self, F, c, A, d, p): + result = dmp_zz_diophantine(list(map(self.to_dense, F)), self.to_dense(c), A, d, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + # f: Poly, H: List[Poly], LC: List[Poly], A: List[ZZ], p: ZZ + def dmp_zz_wang_hensel_lifting(self, f, H, LC, A, p): + uv = self[:1] + mv = self[1:] + H = list(map(uv.to_dense, H)) + LC = list(map(mv.to_dense, LC)) + result = dmp_zz_wang_hensel_lifting(self.to_dense(f), H, LC, A, p, self.ngens-1, self.domain) + return list(map(self.from_dense, result)) + + def dmp_zz_wang(self, f, mod=None, seed=None): + factors = dmp_zz_wang(self.to_dense(f), self.ngens-1, self.domain, mod=mod, seed=seed) + return [ self.from_dense(g) for g in factors ] + + def dup_zz_factor_sqf(self, f): + coeff, factors = dup_zz_factor_sqf(self.to_dense(f), self.domain) + return (coeff, [ self.from_dense(g) for g in factors ]) + + def dup_zz_factor(self, f): + coeff, factors = dup_zz_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_factor(self, f): + coeff, factors = dmp_zz_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_qq_i_factor(self, f): + coeff, factors = dup_qq_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_qq_i_factor(self, f): + coeff, factors = dmp_qq_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_zz_i_factor(self, f): + coeff, factors = dup_zz_i_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_zz_i_factor(self, f): + coeff, factors = dmp_zz_i_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_ext_factor(self, f): + coeff, factors = dup_ext_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_ext_factor(self, f): + coeff, factors = dmp_ext_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_gf_factor(self, f): + coeff, factors = dup_gf_factor(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_factor(self, f): + coeff, factors = dmp_gf_factor(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_factor_list(self, f): + coeff, factors = dup_factor_list(self.to_dense(f), self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_factor_list_include(self, f): + factors = dup_factor_list_include(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dmp_factor_list(self, f): + coeff, factors = dmp_factor_list(self.to_dense(f), self.ngens-1, self.domain) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_factor_list_include(self, f): + factors = dmp_factor_list_include(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_irreducible_p(self, f): + return dup_irreducible_p(self.to_dense(f), self.domain) + def dmp_irreducible_p(self, f): + return dmp_irreducible_p(self.to_dense(f), self.ngens-1, self.domain) + + def dup_sturm(self, f): + seq = dup_sturm(self.to_dense(f), self.domain) + return list(map(self.from_dense, seq)) + + def dup_sqf_p(self, f): + return dup_sqf_p(self.to_dense(f), self.domain) + def dmp_sqf_p(self, f): + return dmp_sqf_p(self.to_dense(f), self.ngens-1, self.domain) + + def dmp_norm(self, f): + n = dmp_norm(self.to_dense(f), self.ngens-1, self.domain) + return self.to_ground().from_dense(n) + + def dup_sqf_norm(self, f): + s, F, R = dup_sqf_norm(self.to_dense(f), self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + def dmp_sqf_norm(self, f): + s, F, R = dmp_sqf_norm(self.to_dense(f), self.ngens-1, self.domain) + return (s, self.from_dense(F), self.to_ground().from_dense(R)) + + def dup_gf_sqf_part(self, f): + return self.from_dense(dup_gf_sqf_part(self.to_dense(f), self.domain)) + def dmp_gf_sqf_part(self, f): + return self.from_dense(dmp_gf_sqf_part(self.to_dense(f), self.domain)) + def dup_sqf_part(self, f): + return self.from_dense(dup_sqf_part(self.to_dense(f), self.domain)) + def dmp_sqf_part(self, f): + return self.from_dense(dmp_sqf_part(self.to_dense(f), self.ngens-1, self.domain)) + + def dup_gf_sqf_list(self, f, all=False): + coeff, factors = dup_gf_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_gf_sqf_list(self, f, all=False): + coeff, factors = dmp_gf_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + + def dup_sqf_list(self, f, all=False): + coeff, factors = dup_sqf_list(self.to_dense(f), self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dup_sqf_list_include(self, f, all=False): + factors = dup_sqf_list_include(self.to_dense(f), self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_sqf_list(self, f, all=False): + coeff, factors = dmp_sqf_list(self.to_dense(f), self.ngens-1, self.domain, all=all) + return (coeff, [ (self.from_dense(g), k) for g, k in factors ]) + def dmp_sqf_list_include(self, f, all=False): + factors = dmp_sqf_list_include(self.to_dense(f), self.ngens-1, self.domain, all=all) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_gff_list(self, f): + factors = dup_gff_list(self.to_dense(f), self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + def dmp_gff_list(self, f): + factors = dmp_gff_list(self.to_dense(f), self.ngens-1, self.domain) + return [ (self.from_dense(g), k) for g, k in factors ] + + def dup_root_upper_bound(self, f): + return dup_root_upper_bound(self.to_dense(f), self.domain) + def dup_root_lower_bound(self, f): + return dup_root_lower_bound(self.to_dense(f), self.domain) + + def dup_step_refine_real_root(self, f, M, fast=False): + return dup_step_refine_real_root(self.to_dense(f), M, self.domain, fast=fast) + def dup_inner_refine_real_root(self, f, M, eps=None, steps=None, disjoint=None, fast=False, mobius=False): + return dup_inner_refine_real_root(self.to_dense(f), M, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast, mobius=mobius) + def dup_outer_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_outer_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_refine_real_root(self, f, s, t, eps=None, steps=None, disjoint=None, fast=False): + return dup_refine_real_root(self.to_dense(f), s, t, self.domain, eps=eps, steps=steps, disjoint=disjoint, fast=fast) + def dup_inner_isolate_real_roots(self, f, eps=None, fast=False): + return dup_inner_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, fast=fast) + def dup_inner_isolate_positive_roots(self, f, eps=None, inf=None, sup=None, fast=False, mobius=False): + return dup_inner_isolate_positive_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, mobius=mobius) + def dup_inner_isolate_negative_roots(self, f, inf=None, sup=None, eps=None, fast=False, mobius=False): + return dup_inner_isolate_negative_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, eps=eps, fast=fast, mobius=mobius) + def dup_isolate_real_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_real_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_real_roots(self, f, eps=None, inf=None, sup=None, basis=False, fast=False): + return dup_isolate_real_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, basis=basis, fast=fast) + def dup_isolate_real_roots_list(self, polys, eps=None, inf=None, sup=None, strict=False, basis=False, fast=False): + return dup_isolate_real_roots_list(list(map(self.to_dense, polys)), self.domain, eps=eps, inf=inf, sup=sup, strict=strict, basis=basis, fast=fast) + def dup_count_real_roots(self, f, inf=None, sup=None): + return dup_count_real_roots(self.to_dense(f), self.domain, inf=inf, sup=sup) + def dup_count_complex_roots(self, f, inf=None, sup=None, exclude=None): + return dup_count_complex_roots(self.to_dense(f), self.domain, inf=inf, sup=sup, exclude=exclude) + def dup_isolate_complex_roots_sqf(self, f, eps=None, inf=None, sup=None, blackbox=False): + return dup_isolate_complex_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, blackbox=blackbox) + def dup_isolate_all_roots_sqf(self, f, eps=None, inf=None, sup=None, fast=False, blackbox=False): + return dup_isolate_all_roots_sqf(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast, blackbox=blackbox) + def dup_isolate_all_roots(self, f, eps=None, inf=None, sup=None, fast=False): + return dup_isolate_all_roots(self.to_dense(f), self.domain, eps=eps, inf=inf, sup=sup, fast=fast) + + def fateman_poly_F_1(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_1 + return tuple(map(self.from_dense, dmp_fateman_poly_F_1(self.ngens-1, self.domain))) + def fateman_poly_F_2(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_2 + return tuple(map(self.from_dense, dmp_fateman_poly_F_2(self.ngens-1, self.domain))) + def fateman_poly_F_3(self): + from sympy.polys.specialpolys import dmp_fateman_poly_F_3 + return tuple(map(self.from_dense, dmp_fateman_poly_F_3(self.ngens-1, self.domain))) + + def to_gf_dense(self, element): + return gf_strip([ self.domain.dom.convert(c, self.domain) for c in self.wrap(element).to_dense() ]) + + def from_gf_dense(self, element): + return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain.dom)) + + def gf_degree(self, f): + return gf_degree(self.to_gf_dense(f)) + + def gf_LC(self, f): + return gf_LC(self.to_gf_dense(f), self.domain.dom) + def gf_TC(self, f): + return gf_TC(self.to_gf_dense(f), self.domain.dom) + + def gf_strip(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f))) + def gf_trunc(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod)) + def gf_normal(self, f): + return self.from_gf_dense(gf_strip(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_from_dict(self, f): + return self.from_gf_dense(gf_from_dict(f, self.domain.mod, self.domain.dom)) + def gf_to_dict(self, f, symmetric=True): + return gf_to_dict(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_from_int_poly(self, f): + return self.from_gf_dense(gf_from_int_poly(f, self.domain.mod)) + def gf_to_int_poly(self, f, symmetric=True): + return gf_to_int_poly(self.to_gf_dense(f), self.domain.mod, symmetric=symmetric) + + def gf_neg(self, f): + return self.from_gf_dense(gf_neg(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_ground(self, f, a): + return self.from_gf_dense(gf_add_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_sub_ground(self, f, a): + return self.from_gf_dense(gf_sub_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_mul_ground(self, f, a): + return self.from_gf_dense(gf_mul_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + def gf_quo_ground(self, f, a): + return self.from_gf_dense(gf_quo_ground(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom)) + + def gf_add(self, f, g): + return self.from_gf_dense(gf_add(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sub(self, f, g): + return self.from_gf_dense(gf_sub(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_mul(self, f, g): + return self.from_gf_dense(gf_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_sqr(self, f): + return self.from_gf_dense(gf_sqr(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_add_mul(self, f, g, h): + return self.from_gf_dense(gf_add_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + def gf_sub_mul(self, f, g, h): + return self.from_gf_dense(gf_sub_mul(self.to_gf_dense(f), self.to_gf_dense(g), self.to_gf_dense(h), self.domain.mod, self.domain.dom)) + + def gf_expand(self, F): + return self.from_gf_dense(gf_expand(list(map(self.to_gf_dense, F)), self.domain.mod, self.domain.dom)) + + def gf_div(self, f, g): + q, r = gf_div(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(q), self.from_gf_dense(r) + def gf_rem(self, f, g): + return self.from_gf_dense(gf_rem(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_quo(self, f, g): + return self.from_gf_dense(gf_quo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_exquo(self, f, g): + return self.from_gf_dense(gf_exquo(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_lshift(self, f, n): + return self.from_gf_dense(gf_lshift(self.to_gf_dense(f), n, self.domain.dom)) + def gf_rshift(self, f, n): + return self.from_gf_dense(gf_rshift(self.to_gf_dense(f), n, self.domain.dom)) + + def gf_pow(self, f, n): + return self.from_gf_dense(gf_pow(self.to_gf_dense(f), n, self.domain.mod, self.domain.dom)) + def gf_pow_mod(self, f, n, g): + return self.from_gf_dense(gf_pow_mod(self.to_gf_dense(f), n, self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_cofactors(self, f, g): + h, cff, cfg = gf_cofactors(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom) + return self.from_gf_dense(h), self.from_gf_dense(cff), self.from_gf_dense(cfg) + def gf_gcd(self, f, g): + return self.from_gf_dense(gf_gcd(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_lcm(self, f, g): + return self.from_gf_dense(gf_lcm(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_gcdex(self, f, g): + return self.from_gf_dense(gf_gcdex(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + + def gf_monic(self, f): + return self.from_gf_dense(gf_monic(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_diff(self, f): + return self.from_gf_dense(gf_diff(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_eval(self, f, a): + return gf_eval(self.to_gf_dense(f), a, self.domain.mod, self.domain.dom) + def gf_multi_eval(self, f, A): + return gf_multi_eval(self.to_gf_dense(f), A, self.domain.mod, self.domain.dom) + + def gf_compose(self, f, g): + return self.from_gf_dense(gf_compose(self.to_gf_dense(f), self.to_gf_dense(g), self.domain.mod, self.domain.dom)) + def gf_compose_mod(self, g, h, f): + return self.from_gf_dense(gf_compose_mod(self.to_gf_dense(g), self.to_gf_dense(h), self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + + def gf_trace_map(self, a, b, c, n, f): + a = self.to_gf_dense(a) + b = self.to_gf_dense(b) + c = self.to_gf_dense(c) + f = self.to_gf_dense(f) + U, V = gf_trace_map(a, b, c, n, f, self.domain.mod, self.domain.dom) + return self.from_gf_dense(U), self.from_gf_dense(V) + + def gf_random(self, n): + return self.from_gf_dense(gf_random(n, self.domain.mod, self.domain.dom)) + def gf_irreducible(self, n): + return self.from_gf_dense(gf_irreducible(n, self.domain.mod, self.domain.dom)) + + def gf_irred_p_ben_or(self, f): + return gf_irred_p_ben_or(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irred_p_rabin(self, f): + return gf_irred_p_rabin(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_irreducible_p(self, f): + return gf_irreducible_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_sqf_p(self, f): + return gf_sqf_p(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + + def gf_sqf_part(self, f): + return self.from_gf_dense(gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom)) + def gf_sqf_list(self, f, all=False): + coeff, factors = gf_sqf_part(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] + + def gf_Qmatrix(self, f): + return gf_Qmatrix(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + def gf_berlekamp(self, f): + factors = gf_berlekamp(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_zassenhaus(self, f): + factors = gf_ddf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_zassenhaus(self, f, n): + factors = gf_edf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_ddf_shoup(self, f): + factors = gf_ddf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ (self.from_gf_dense(g), k) for g, k in factors ] + def gf_edf_shoup(self, f, n): + factors = gf_edf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_zassenhaus(self, f): + factors = gf_zassenhaus(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + def gf_shoup(self, f): + factors = gf_shoup(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return [ self.from_gf_dense(g) for g in factors ] + + def gf_factor_sqf(self, f, method=None): + coeff, factors = gf_factor_sqf(self.to_gf_dense(f), self.domain.mod, self.domain.dom, method=method) + return coeff, [ self.from_gf_dense(g) for g in factors ] + def gf_factor(self, f): + coeff, factors = gf_factor(self.to_gf_dense(f), self.domain.mod, self.domain.dom) + return coeff, [ (self.from_gf_dense(g), k) for g, k in factors ] diff --git a/shared/package-files/b6/b65694cb0a50764ebe0c25137bdd78e266947e77a84755a753fd8bb8c4a217ce/msvc9compiler.cpython-311.pyc b/shared/package-files/b6/b65694cb0a50764ebe0c25137bdd78e266947e77a84755a753fd8bb8c4a217ce/msvc9compiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..605455b7eb4be4f6c218c690134ace068cbee526 Binary files /dev/null and b/shared/package-files/b6/b65694cb0a50764ebe0c25137bdd78e266947e77a84755a753fd8bb8c4a217ce/msvc9compiler.cpython-311.pyc differ diff --git a/shared/package-files/b6/b65fa37c96bd0b99bdbb681b4e62f58163817a4da517ae8b19f88bbaf0f7543f/package_exporter.cpython-311.pyc b/shared/package-files/b6/b65fa37c96bd0b99bdbb681b4e62f58163817a4da517ae8b19f88bbaf0f7543f/package_exporter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94260fea24b9efc77eb7c6e3afd3758f8b21091c Binary files /dev/null and b/shared/package-files/b6/b65fa37c96bd0b99bdbb681b4e62f58163817a4da517ae8b19f88bbaf0f7543f/package_exporter.cpython-311.pyc differ diff --git a/shared/package-files/b6/b67462782c847f69fd9ef30c1db2ebcb7e7d0c404e23ced5ac2557ed48060214/special_polygamma_ops.h b/shared/package-files/b6/b67462782c847f69fd9ef30c1db2ebcb7e7d0c404e23ced5ac2557ed48060214/special_polygamma_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..76ec139b125876d8410c9b5e105ba6a42059def7 --- /dev/null +++ b/shared/package-files/b6/b67462782c847f69fd9ef30c1db2ebcb7e7d0c404e23ced5ac2557ed48060214/special_polygamma_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_polygamma { + using schema = at::Tensor (int64_t, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_polygamma"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "special_polygamma(int n, Tensor self) -> Tensor"; + static at::Tensor call(int64_t n, const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, int64_t n, const at::Tensor & self); +}; + +struct TORCH_API special_polygamma_out { + using schema = at::Tensor & (int64_t, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::special_polygamma"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "special_polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(int64_t n, const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, int64_t n, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/b6/b676481789a7b528197c9a65506127b7cbdbb92b78c6642fbe1bb7592d44ef00/setup.cpython-311.pyc b/shared/package-files/b6/b676481789a7b528197c9a65506127b7cbdbb92b78c6642fbe1bb7592d44ef00/setup.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fec6ead899ad48fa2b106229ab90ec823d31be3 Binary files /dev/null and b/shared/package-files/b6/b676481789a7b528197c9a65506127b7cbdbb92b78c6642fbe1bb7592d44ef00/setup.cpython-311.pyc differ diff --git a/shared/package-files/b6/b680e0a168699ce262c32b6ac91fd7e40989926a9eb58bc1aba29b311f53ebe5/managers.py b/shared/package-files/b6/b680e0a168699ce262c32b6ac91fd7e40989926a9eb58bc1aba29b311f53ebe5/managers.py new file mode 100644 index 0000000000000000000000000000000000000000..2e0e04717373fbe80490990d929c35130a7c733a --- /dev/null +++ b/shared/package-files/b6/b680e0a168699ce262c32b6ac91fd7e40989926a9eb58bc1aba29b311f53ebe5/managers.py @@ -0,0 +1,2375 @@ +from __future__ import annotations + +from collections.abc import ( + Hashable, + Sequence, +) +import itertools +from typing import ( + TYPE_CHECKING, + Callable, + Literal, + cast, +) +import warnings + +import numpy as np + +from pandas._config import ( + using_copy_on_write, + warn_copy_on_write, +) + +from pandas._libs import ( + internals as libinternals, + lib, +) +from pandas._libs.internals import ( + BlockPlacement, + BlockValuesRefs, +) +from pandas._libs.tslibs import Timestamp +from pandas.errors import PerformanceWarning +from pandas.util._decorators import cache_readonly +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.cast import infer_dtype_from_scalar +from pandas.core.dtypes.common import ( + ensure_platform_int, + is_1d_only_ea_dtype, + is_list_like, +) +from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, + ExtensionDtype, +) +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCSeries, +) +from pandas.core.dtypes.missing import ( + array_equals, + isna, +) + +import pandas.core.algorithms as algos +from pandas.core.arrays import ( + ArrowExtensionArray, + ArrowStringArray, + DatetimeArray, +) +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) +from pandas.core.indexers import maybe_convert_indices +from pandas.core.indexes.api import ( + Index, + ensure_index, +) +from pandas.core.internals.base import ( + DataManager, + SingleDataManager, + ensure_np_dtype, + interleaved_dtype, +) +from pandas.core.internals.blocks import ( + COW_WARNING_GENERAL_MSG, + COW_WARNING_SETITEM_MSG, + Block, + NumpyBlock, + ensure_block_shape, + extend_blocks, + get_block_type, + maybe_coerce_values, + new_block, + new_block_2d, +) +from pandas.core.internals.ops import ( + blockwise_all, + operate_blockwise, +) + +if TYPE_CHECKING: + from pandas._typing import ( + ArrayLike, + AxisInt, + DtypeObj, + QuantileInterpolation, + Self, + Shape, + npt, + ) + + from pandas.api.extensions import ExtensionArray + + +class BaseBlockManager(DataManager): + """ + Core internal data structure to implement DataFrame, Series, etc. + + Manage a bunch of labeled 2D mixed-type ndarrays. Essentially it's a + lightweight blocked set of labeled data to be manipulated by the DataFrame + public API class + + Attributes + ---------- + shape + ndim + axes + values + items + + Methods + ------- + set_axis(axis, new_labels) + copy(deep=True) + + get_dtypes + + apply(func, axes, block_filter_fn) + + get_bool_data + get_numeric_data + + get_slice(slice_like, axis) + get(label) + iget(loc) + + take(indexer, axis) + reindex_axis(new_labels, axis) + reindex_indexer(new_labels, indexer, axis) + + delete(label) + insert(loc, label, value) + set(label, value) + + Parameters + ---------- + blocks: Sequence of Block + axes: Sequence of Index + verify_integrity: bool, default True + + Notes + ----- + This is *not* a public API class + """ + + __slots__ = () + + _blknos: npt.NDArray[np.intp] + _blklocs: npt.NDArray[np.intp] + blocks: tuple[Block, ...] + axes: list[Index] + + @property + def ndim(self) -> int: + raise NotImplementedError + + _known_consolidated: bool + _is_consolidated: bool + + def __init__(self, blocks, axes, verify_integrity: bool = True) -> None: + raise NotImplementedError + + @classmethod + def from_blocks(cls, blocks: list[Block], axes: list[Index]) -> Self: + raise NotImplementedError + + @property + def blknos(self) -> npt.NDArray[np.intp]: + """ + Suppose we want to find the array corresponding to our i'th column. + + blknos[i] identifies the block from self.blocks that contains this column. + + blklocs[i] identifies the column of interest within + self.blocks[self.blknos[i]] + """ + if self._blknos is None: + # Note: these can be altered by other BlockManager methods. + self._rebuild_blknos_and_blklocs() + + return self._blknos + + @property + def blklocs(self) -> npt.NDArray[np.intp]: + """ + See blknos.__doc__ + """ + if self._blklocs is None: + # Note: these can be altered by other BlockManager methods. + self._rebuild_blknos_and_blklocs() + + return self._blklocs + + def make_empty(self, axes=None) -> Self: + """return an empty BlockManager with the items axis of len 0""" + if axes is None: + axes = [Index([])] + self.axes[1:] + + # preserve dtype if possible + if self.ndim == 1: + assert isinstance(self, SingleBlockManager) # for mypy + blk = self.blocks[0] + arr = blk.values[:0] + bp = BlockPlacement(slice(0, 0)) + nb = blk.make_block_same_class(arr, placement=bp) + blocks = [nb] + else: + blocks = [] + return type(self).from_blocks(blocks, axes) + + def __nonzero__(self) -> bool: + return True + + # Python3 compat + __bool__ = __nonzero__ + + def _normalize_axis(self, axis: AxisInt) -> int: + # switch axis to follow BlockManager logic + if self.ndim == 2: + axis = 1 if axis == 0 else 0 + return axis + + def set_axis(self, axis: AxisInt, new_labels: Index) -> None: + # Caller is responsible for ensuring we have an Index object. + self._validate_set_axis(axis, new_labels) + self.axes[axis] = new_labels + + @property + def is_single_block(self) -> bool: + # Assumes we are 2D; overridden by SingleBlockManager + return len(self.blocks) == 1 + + @property + def items(self) -> Index: + return self.axes[0] + + def _has_no_reference(self, i: int) -> bool: + """ + Check for column `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the column has no references. + """ + blkno = self.blknos[i] + return self._has_no_reference_block(blkno) + + def _has_no_reference_block(self, blkno: int) -> bool: + """ + Check for block `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the block has no references. + """ + return not self.blocks[blkno].refs.has_reference() + + def add_references(self, mgr: BaseBlockManager) -> None: + """ + Adds the references from one manager to another. We assume that both + managers have the same block structure. + """ + if len(self.blocks) != len(mgr.blocks): + # If block structure changes, then we made a copy + return + for i, blk in enumerate(self.blocks): + blk.refs = mgr.blocks[i].refs + blk.refs.add_reference(blk) + + def references_same_values(self, mgr: BaseBlockManager, blkno: int) -> bool: + """ + Checks if two blocks from two different block managers reference the + same underlying values. + """ + blk = self.blocks[blkno] + return any(blk is ref() for ref in mgr.blocks[blkno].refs.referenced_blocks) + + def get_dtypes(self) -> npt.NDArray[np.object_]: + dtypes = np.array([blk.dtype for blk in self.blocks], dtype=object) + return dtypes.take(self.blknos) + + @property + def arrays(self) -> list[ArrayLike]: + """ + Quick access to the backing arrays of the Blocks. + + Only for compatibility with ArrayManager for testing convenience. + Not to be used in actual code, and return value is not the same as the + ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs). + + Warning! The returned arrays don't handle Copy-on-Write, so this should + be used with caution (only in read-mode). + """ + return [blk.values for blk in self.blocks] + + def __repr__(self) -> str: + output = type(self).__name__ + for i, ax in enumerate(self.axes): + if i == 0: + output += f"\nItems: {ax}" + else: + output += f"\nAxis {i}: {ax}" + + for block in self.blocks: + output += f"\n{block}" + return output + + def apply( + self, + f, + align_keys: list[str] | None = None, + **kwargs, + ) -> Self: + """ + Iterate over the blocks, collect and create a new BlockManager. + + Parameters + ---------- + f : str or callable + Name of the Block method to apply. + align_keys: List[str] or None, default None + **kwargs + Keywords to pass to `f` + + Returns + ------- + BlockManager + """ + assert "filter" not in kwargs + + align_keys = align_keys or [] + result_blocks: list[Block] = [] + # fillna: Series/DataFrame is responsible for making sure value is aligned + + aligned_args = {k: kwargs[k] for k in align_keys} + + for b in self.blocks: + if aligned_args: + for k, obj in aligned_args.items(): + if isinstance(obj, (ABCSeries, ABCDataFrame)): + # The caller is responsible for ensuring that + # obj.axes[-1].equals(self.items) + if obj.ndim == 1: + kwargs[k] = obj.iloc[b.mgr_locs.indexer]._values + else: + kwargs[k] = obj.iloc[:, b.mgr_locs.indexer]._values + else: + # otherwise we have an ndarray + kwargs[k] = obj[b.mgr_locs.indexer] + + if callable(f): + applied = b.apply(f, **kwargs) + else: + applied = getattr(b, f)(**kwargs) + result_blocks = extend_blocks(applied, result_blocks) + + out = type(self).from_blocks(result_blocks, self.axes) + return out + + # Alias so we can share code with ArrayManager + apply_with_block = apply + + def setitem(self, indexer, value, warn: bool = True) -> Self: + """ + Set values with indexer. + + For SingleBlockManager, this backs s[indexer] = value + """ + if isinstance(indexer, np.ndarray) and indexer.ndim > self.ndim: + raise ValueError(f"Cannot set values with ndim > {self.ndim}") + + if warn and warn_copy_on_write() and not self._has_no_reference(0): + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + elif using_copy_on_write() and not self._has_no_reference(0): + # this method is only called if there is a single block -> hardcoded 0 + # Split blocks to only copy the columns we want to modify + if self.ndim == 2 and isinstance(indexer, tuple): + blk_loc = self.blklocs[indexer[1]] + if is_list_like(blk_loc) and blk_loc.ndim == 2: + blk_loc = np.squeeze(blk_loc, axis=0) + elif not is_list_like(blk_loc): + # Keep dimension and copy data later + blk_loc = [blk_loc] # type: ignore[assignment] + if len(blk_loc) == 0: + return self.copy(deep=False) + + values = self.blocks[0].values + if values.ndim == 2: + values = values[blk_loc] + # "T" has no attribute "_iset_split_block" + self._iset_split_block( # type: ignore[attr-defined] + 0, blk_loc, values + ) + # first block equals values + self.blocks[0].setitem((indexer[0], np.arange(len(blk_loc))), value) + return self + # No need to split if we either set all columns or on a single block + # manager + self = self.copy() + + return self.apply("setitem", indexer=indexer, value=value) + + def diff(self, n: int) -> Self: + # only reached with self.ndim == 2 + return self.apply("diff", n=n) + + def astype(self, dtype, copy: bool | None = False, errors: str = "raise") -> Self: + if copy is None: + if using_copy_on_write(): + copy = False + else: + copy = True + elif using_copy_on_write(): + copy = False + + return self.apply( + "astype", + dtype=dtype, + copy=copy, + errors=errors, + using_cow=using_copy_on_write(), + ) + + def convert(self, copy: bool | None) -> Self: + if copy is None: + if using_copy_on_write(): + copy = False + else: + copy = True + elif using_copy_on_write(): + copy = False + + return self.apply("convert", copy=copy, using_cow=using_copy_on_write()) + + def convert_dtypes(self, **kwargs): + if using_copy_on_write(): + copy = False + else: + copy = True + + return self.apply( + "convert_dtypes", copy=copy, using_cow=using_copy_on_write(), **kwargs + ) + + def get_values_for_csv( + self, *, float_format, date_format, decimal, na_rep: str = "nan", quoting=None + ) -> Self: + """ + Convert values to native types (strings / python objects) that are used + in formatting (repr / csv). + """ + return self.apply( + "get_values_for_csv", + na_rep=na_rep, + quoting=quoting, + float_format=float_format, + date_format=date_format, + decimal=decimal, + ) + + @property + def any_extension_types(self) -> bool: + """Whether any of the blocks in this manager are extension blocks""" + return any(block.is_extension for block in self.blocks) + + @property + def is_view(self) -> bool: + """return a boolean if we are a single block and are a view""" + if len(self.blocks) == 1: + return self.blocks[0].is_view + + # It is technically possible to figure out which blocks are views + # e.g. [ b.values.base is not None for b in self.blocks ] + # but then we have the case of possibly some blocks being a view + # and some blocks not. setting in theory is possible on the non-view + # blocks w/o causing a SettingWithCopy raise/warn. But this is a bit + # complicated + + return False + + def _get_data_subset(self, predicate: Callable) -> Self: + blocks = [blk for blk in self.blocks if predicate(blk.values)] + return self._combine(blocks) + + def get_bool_data(self) -> Self: + """ + Select blocks that are bool-dtype and columns from object-dtype blocks + that are all-bool. + """ + + new_blocks = [] + + for blk in self.blocks: + if blk.dtype == bool: + new_blocks.append(blk) + + elif blk.is_object: + nbs = blk._split() + new_blocks.extend(nb for nb in nbs if nb.is_bool) + + return self._combine(new_blocks) + + def get_numeric_data(self) -> Self: + numeric_blocks = [blk for blk in self.blocks if blk.is_numeric] + if len(numeric_blocks) == len(self.blocks): + # Avoid somewhat expensive _combine + return self + return self._combine(numeric_blocks) + + def _combine(self, blocks: list[Block], index: Index | None = None) -> Self: + """return a new manager with the blocks""" + if len(blocks) == 0: + if self.ndim == 2: + # retain our own Index dtype + if index is not None: + axes = [self.items[:0], index] + else: + axes = [self.items[:0]] + self.axes[1:] + return self.make_empty(axes) + return self.make_empty() + + # FIXME: optimization potential + indexer = np.sort(np.concatenate([b.mgr_locs.as_array for b in blocks])) + inv_indexer = lib.get_reverse_indexer(indexer, self.shape[0]) + + new_blocks: list[Block] = [] + for b in blocks: + nb = b.copy(deep=False) + nb.mgr_locs = BlockPlacement(inv_indexer[nb.mgr_locs.indexer]) + new_blocks.append(nb) + + axes = list(self.axes) + if index is not None: + axes[-1] = index + axes[0] = self.items.take(indexer) + + return type(self).from_blocks(new_blocks, axes) + + @property + def nblocks(self) -> int: + return len(self.blocks) + + def copy(self, deep: bool | None | Literal["all"] = True) -> Self: + """ + Make deep or shallow copy of BlockManager + + Parameters + ---------- + deep : bool, string or None, default True + If False or None, return a shallow copy (do not copy data) + If 'all', copy data and a deep copy of the index + + Returns + ------- + BlockManager + """ + if deep is None: + if using_copy_on_write(): + # use shallow copy + deep = False + else: + # preserve deep copy for BlockManager with copy=None + deep = True + + # this preserves the notion of view copying of axes + if deep: + # hit in e.g. tests.io.json.test_pandas + + def copy_func(ax): + return ax.copy(deep=True) if deep == "all" else ax.view() + + new_axes = [copy_func(ax) for ax in self.axes] + else: + if using_copy_on_write(): + new_axes = [ax.view() for ax in self.axes] + else: + new_axes = list(self.axes) + + res = self.apply("copy", deep=deep) + res.axes = new_axes + + if self.ndim > 1: + # Avoid needing to re-compute these + blknos = self._blknos + if blknos is not None: + res._blknos = blknos.copy() + res._blklocs = self._blklocs.copy() + + if deep: + res._consolidate_inplace() + return res + + def consolidate(self) -> Self: + """ + Join together blocks having same dtype + + Returns + ------- + y : BlockManager + """ + if self.is_consolidated(): + return self + + bm = type(self)(self.blocks, self.axes, verify_integrity=False) + bm._is_consolidated = False + bm._consolidate_inplace() + return bm + + def reindex_indexer( + self, + new_axis: Index, + indexer: npt.NDArray[np.intp] | None, + axis: AxisInt, + fill_value=None, + allow_dups: bool = False, + copy: bool | None = True, + only_slice: bool = False, + *, + use_na_proxy: bool = False, + ) -> Self: + """ + Parameters + ---------- + new_axis : Index + indexer : ndarray[intp] or None + axis : int + fill_value : object, default None + allow_dups : bool, default False + copy : bool or None, default True + If None, regard as False to get shallow copy. + only_slice : bool, default False + Whether to take views, not copies, along columns. + use_na_proxy : bool, default False + Whether to use a np.void ndarray for newly introduced columns. + + pandas-indexer with -1's only. + """ + if copy is None: + if using_copy_on_write(): + # use shallow copy + copy = False + else: + # preserve deep copy for BlockManager with copy=None + copy = True + + if indexer is None: + if new_axis is self.axes[axis] and not copy: + return self + + result = self.copy(deep=copy) + result.axes = list(self.axes) + result.axes[axis] = new_axis + return result + + # Should be intp, but in some cases we get int64 on 32bit builds + assert isinstance(indexer, np.ndarray) + + # some axes don't allow reindexing with dups + if not allow_dups: + self.axes[axis]._validate_can_reindex(indexer) + + if axis >= self.ndim: + raise IndexError("Requested axis not found in manager") + + if axis == 0: + new_blocks = self._slice_take_blocks_ax0( + indexer, + fill_value=fill_value, + only_slice=only_slice, + use_na_proxy=use_na_proxy, + ) + else: + new_blocks = [ + blk.take_nd( + indexer, + axis=1, + fill_value=( + fill_value if fill_value is not None else blk.fill_value + ), + ) + for blk in self.blocks + ] + + new_axes = list(self.axes) + new_axes[axis] = new_axis + + new_mgr = type(self).from_blocks(new_blocks, new_axes) + if axis == 1: + # We can avoid the need to rebuild these + new_mgr._blknos = self.blknos.copy() + new_mgr._blklocs = self.blklocs.copy() + return new_mgr + + def _slice_take_blocks_ax0( + self, + slice_or_indexer: slice | np.ndarray, + fill_value=lib.no_default, + only_slice: bool = False, + *, + use_na_proxy: bool = False, + ref_inplace_op: bool = False, + ) -> list[Block]: + """ + Slice/take blocks along axis=0. + + Overloaded for SingleBlock + + Parameters + ---------- + slice_or_indexer : slice or np.ndarray[int64] + fill_value : scalar, default lib.no_default + only_slice : bool, default False + If True, we always return views on existing arrays, never copies. + This is used when called from ops.blockwise.operate_blockwise. + use_na_proxy : bool, default False + Whether to use a np.void ndarray for newly introduced columns. + ref_inplace_op: bool, default False + Don't track refs if True because we operate inplace + + Returns + ------- + new_blocks : list of Block + """ + allow_fill = fill_value is not lib.no_default + + sl_type, slobj, sllen = _preprocess_slice_or_indexer( + slice_or_indexer, self.shape[0], allow_fill=allow_fill + ) + + if self.is_single_block: + blk = self.blocks[0] + + if sl_type == "slice": + # GH#32959 EABlock would fail since we can't make 0-width + # TODO(EA2D): special casing unnecessary with 2D EAs + if sllen == 0: + return [] + bp = BlockPlacement(slice(0, sllen)) + return [blk.getitem_block_columns(slobj, new_mgr_locs=bp)] + elif not allow_fill or self.ndim == 1: + if allow_fill and fill_value is None: + fill_value = blk.fill_value + + if not allow_fill and only_slice: + # GH#33597 slice instead of take, so we get + # views instead of copies + blocks = [ + blk.getitem_block_columns( + slice(ml, ml + 1), + new_mgr_locs=BlockPlacement(i), + ref_inplace_op=ref_inplace_op, + ) + for i, ml in enumerate(slobj) + ] + return blocks + else: + bp = BlockPlacement(slice(0, sllen)) + return [ + blk.take_nd( + slobj, + axis=0, + new_mgr_locs=bp, + fill_value=fill_value, + ) + ] + + if sl_type == "slice": + blknos = self.blknos[slobj] + blklocs = self.blklocs[slobj] + else: + blknos = algos.take_nd( + self.blknos, slobj, fill_value=-1, allow_fill=allow_fill + ) + blklocs = algos.take_nd( + self.blklocs, slobj, fill_value=-1, allow_fill=allow_fill + ) + + # When filling blknos, make sure blknos is updated before appending to + # blocks list, that way new blkno is exactly len(blocks). + blocks = [] + group = not only_slice + for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=group): + if blkno == -1: + # If we've got here, fill_value was not lib.no_default + + blocks.append( + self._make_na_block( + placement=mgr_locs, + fill_value=fill_value, + use_na_proxy=use_na_proxy, + ) + ) + else: + blk = self.blocks[blkno] + + # Otherwise, slicing along items axis is necessary. + if not blk._can_consolidate and not blk._validate_ndim: + # i.e. we dont go through here for DatetimeTZBlock + # A non-consolidatable block, it's easy, because there's + # only one item and each mgr loc is a copy of that single + # item. + deep = not (only_slice or using_copy_on_write()) + for mgr_loc in mgr_locs: + newblk = blk.copy(deep=deep) + newblk.mgr_locs = BlockPlacement(slice(mgr_loc, mgr_loc + 1)) + blocks.append(newblk) + + else: + # GH#32779 to avoid the performance penalty of copying, + # we may try to only slice + taker = blklocs[mgr_locs.indexer] + max_len = max(len(mgr_locs), taker.max() + 1) + if only_slice or using_copy_on_write(): + taker = lib.maybe_indices_to_slice(taker, max_len) + + if isinstance(taker, slice): + nb = blk.getitem_block_columns(taker, new_mgr_locs=mgr_locs) + blocks.append(nb) + elif only_slice: + # GH#33597 slice instead of take, so we get + # views instead of copies + for i, ml in zip(taker, mgr_locs): + slc = slice(i, i + 1) + bp = BlockPlacement(ml) + nb = blk.getitem_block_columns(slc, new_mgr_locs=bp) + # We have np.shares_memory(nb.values, blk.values) + blocks.append(nb) + else: + nb = blk.take_nd(taker, axis=0, new_mgr_locs=mgr_locs) + blocks.append(nb) + + return blocks + + def _make_na_block( + self, placement: BlockPlacement, fill_value=None, use_na_proxy: bool = False + ) -> Block: + # Note: we only get here with self.ndim == 2 + + if use_na_proxy: + assert fill_value is None + shape = (len(placement), self.shape[1]) + vals = np.empty(shape, dtype=np.void) + nb = NumpyBlock(vals, placement, ndim=2) + return nb + + if fill_value is None: + fill_value = np.nan + + shape = (len(placement), self.shape[1]) + + dtype, fill_value = infer_dtype_from_scalar(fill_value) + block_values = make_na_array(dtype, shape, fill_value) + return new_block_2d(block_values, placement=placement) + + def take( + self, + indexer: npt.NDArray[np.intp], + axis: AxisInt = 1, + verify: bool = True, + ) -> Self: + """ + Take items along any axis. + + indexer : np.ndarray[np.intp] + axis : int, default 1 + verify : bool, default True + Check that all entries are between 0 and len(self) - 1, inclusive. + Pass verify=False if this check has been done by the caller. + + Returns + ------- + BlockManager + """ + # Caller is responsible for ensuring indexer annotation is accurate + + n = self.shape[axis] + indexer = maybe_convert_indices(indexer, n, verify=verify) + + new_labels = self.axes[axis].take(indexer) + return self.reindex_indexer( + new_axis=new_labels, + indexer=indexer, + axis=axis, + allow_dups=True, + copy=None, + ) + + +class BlockManager(libinternals.BlockManager, BaseBlockManager): + """ + BaseBlockManager that holds 2D blocks. + """ + + ndim = 2 + + # ---------------------------------------------------------------- + # Constructors + + def __init__( + self, + blocks: Sequence[Block], + axes: Sequence[Index], + verify_integrity: bool = True, + ) -> None: + if verify_integrity: + # Assertion disabled for performance + # assert all(isinstance(x, Index) for x in axes) + + for block in blocks: + if self.ndim != block.ndim: + raise AssertionError( + f"Number of Block dimensions ({block.ndim}) must equal " + f"number of axes ({self.ndim})" + ) + # As of 2.0, the caller is responsible for ensuring that + # DatetimeTZBlock with block.ndim == 2 has block.values.ndim ==2; + # previously there was a special check for fastparquet compat. + + self._verify_integrity() + + def _verify_integrity(self) -> None: + mgr_shape = self.shape + tot_items = sum(len(x.mgr_locs) for x in self.blocks) + for block in self.blocks: + if block.shape[1:] != mgr_shape[1:]: + raise_construction_error(tot_items, block.shape[1:], self.axes) + if len(self.items) != tot_items: + raise AssertionError( + "Number of manager items must equal union of " + f"block items\n# manager items: {len(self.items)}, # " + f"tot_items: {tot_items}" + ) + + @classmethod + def from_blocks(cls, blocks: list[Block], axes: list[Index]) -> Self: + """ + Constructor for BlockManager and SingleBlockManager with same signature. + """ + return cls(blocks, axes, verify_integrity=False) + + # ---------------------------------------------------------------- + # Indexing + + def fast_xs(self, loc: int) -> SingleBlockManager: + """ + Return the array corresponding to `frame.iloc[loc]`. + + Parameters + ---------- + loc : int + + Returns + ------- + np.ndarray or ExtensionArray + """ + if len(self.blocks) == 1: + # TODO: this could be wrong if blk.mgr_locs is not slice(None)-like; + # is this ruled out in the general case? + result = self.blocks[0].iget((slice(None), loc)) + # in the case of a single block, the new block is a view + bp = BlockPlacement(slice(0, len(result))) + block = new_block( + result, + placement=bp, + ndim=1, + refs=self.blocks[0].refs, + ) + return SingleBlockManager(block, self.axes[0]) + + dtype = interleaved_dtype([blk.dtype for blk in self.blocks]) + + n = len(self) + + if isinstance(dtype, ExtensionDtype): + # TODO: use object dtype as workaround for non-performant + # EA.__setitem__ methods. (primarily ArrowExtensionArray.__setitem__ + # when iteratively setting individual values) + # https://github.com/pandas-dev/pandas/pull/54508#issuecomment-1675827918 + result = np.empty(n, dtype=object) + else: + result = np.empty(n, dtype=dtype) + result = ensure_wrapped_if_datetimelike(result) + + for blk in self.blocks: + # Such assignment may incorrectly coerce NaT to None + # result[blk.mgr_locs] = blk._slice((slice(None), loc)) + for i, rl in enumerate(blk.mgr_locs): + result[rl] = blk.iget((i, loc)) + + if isinstance(dtype, ExtensionDtype): + cls = dtype.construct_array_type() + result = cls._from_sequence(result, dtype=dtype) + + bp = BlockPlacement(slice(0, len(result))) + block = new_block(result, placement=bp, ndim=1) + return SingleBlockManager(block, self.axes[0]) + + def iget(self, i: int, track_ref: bool = True) -> SingleBlockManager: + """ + Return the data as a SingleBlockManager. + """ + block = self.blocks[self.blknos[i]] + values = block.iget(self.blklocs[i]) + + # shortcut for select a single-dim from a 2-dim BM + bp = BlockPlacement(slice(0, len(values))) + nb = type(block)( + values, placement=bp, ndim=1, refs=block.refs if track_ref else None + ) + return SingleBlockManager(nb, self.axes[1]) + + def iget_values(self, i: int) -> ArrayLike: + """ + Return the data for column i as the values (ndarray or ExtensionArray). + + Warning! The returned array is a view but doesn't handle Copy-on-Write, + so this should be used with caution. + """ + # TODO(CoW) making the arrays read-only might make this safer to use? + block = self.blocks[self.blknos[i]] + values = block.iget(self.blklocs[i]) + return values + + @property + def column_arrays(self) -> list[np.ndarray]: + """ + Used in the JSON C code to access column arrays. + This optimizes compared to using `iget_values` by converting each + + Warning! This doesn't handle Copy-on-Write, so should be used with + caution (current use case of consuming this in the JSON code is fine). + """ + # This is an optimized equivalent to + # result = [self.iget_values(i) for i in range(len(self.items))] + result: list[np.ndarray | None] = [None] * len(self.items) + + for blk in self.blocks: + mgr_locs = blk._mgr_locs + values = blk.array_values._values_for_json() + if values.ndim == 1: + # TODO(EA2D): special casing not needed with 2D EAs + result[mgr_locs[0]] = values + + else: + for i, loc in enumerate(mgr_locs): + result[loc] = values[i] + + # error: Incompatible return value type (got "List[None]", + # expected "List[ndarray[Any, Any]]") + return result # type: ignore[return-value] + + def iset( + self, + loc: int | slice | np.ndarray, + value: ArrayLike, + inplace: bool = False, + refs: BlockValuesRefs | None = None, + ) -> None: + """ + Set new item in-place. Does not consolidate. Adds new Block if not + contained in the current set of items + """ + + # FIXME: refactor, clearly separate broadcasting & zip-like assignment + # can prob also fix the various if tests for sparse/categorical + if self._blklocs is None and self.ndim > 1: + self._rebuild_blknos_and_blklocs() + + # Note: we exclude DTA/TDA here + value_is_extension_type = is_1d_only_ea_dtype(value.dtype) + if not value_is_extension_type: + if value.ndim == 2: + value = value.T + else: + value = ensure_block_shape(value, ndim=2) + + if value.shape[1:] != self.shape[1:]: + raise AssertionError( + "Shape of new values must be compatible with manager shape" + ) + + if lib.is_integer(loc): + # We have 6 tests where loc is _not_ an int. + # In this case, get_blkno_placements will yield only one tuple, + # containing (self._blknos[loc], BlockPlacement(slice(0, 1, 1))) + + # Check if we can use _iset_single fastpath + loc = cast(int, loc) + blkno = self.blknos[loc] + blk = self.blocks[blkno] + if len(blk._mgr_locs) == 1: # TODO: fastest way to check this? + return self._iset_single( + loc, + value, + inplace=inplace, + blkno=blkno, + blk=blk, + refs=refs, + ) + + # error: Incompatible types in assignment (expression has type + # "List[Union[int, slice, ndarray]]", variable has type "Union[int, + # slice, ndarray]") + loc = [loc] # type: ignore[assignment] + + # categorical/sparse/datetimetz + if value_is_extension_type: + + def value_getitem(placement): + return value + + else: + + def value_getitem(placement): + return value[placement.indexer] + + # Accessing public blknos ensures the public versions are initialized + blknos = self.blknos[loc] + blklocs = self.blklocs[loc].copy() + + unfit_mgr_locs = [] + unfit_val_locs = [] + removed_blknos = [] + for blkno_l, val_locs in libinternals.get_blkno_placements(blknos, group=True): + blk = self.blocks[blkno_l] + blk_locs = blklocs[val_locs.indexer] + if inplace and blk.should_store(value): + # Updating inplace -> check if we need to do Copy-on-Write + if using_copy_on_write() and not self._has_no_reference_block(blkno_l): + self._iset_split_block( + blkno_l, blk_locs, value_getitem(val_locs), refs=refs + ) + else: + blk.set_inplace(blk_locs, value_getitem(val_locs)) + continue + else: + unfit_mgr_locs.append(blk.mgr_locs.as_array[blk_locs]) + unfit_val_locs.append(val_locs) + + # If all block items are unfit, schedule the block for removal. + if len(val_locs) == len(blk.mgr_locs): + removed_blknos.append(blkno_l) + continue + else: + # Defer setting the new values to enable consolidation + self._iset_split_block(blkno_l, blk_locs, refs=refs) + + if len(removed_blknos): + # Remove blocks & update blknos accordingly + is_deleted = np.zeros(self.nblocks, dtype=np.bool_) + is_deleted[removed_blknos] = True + + new_blknos = np.empty(self.nblocks, dtype=np.intp) + new_blknos.fill(-1) + new_blknos[~is_deleted] = np.arange(self.nblocks - len(removed_blknos)) + self._blknos = new_blknos[self._blknos] + self.blocks = tuple( + blk for i, blk in enumerate(self.blocks) if i not in set(removed_blknos) + ) + + if unfit_val_locs: + unfit_idxr = np.concatenate(unfit_mgr_locs) + unfit_count = len(unfit_idxr) + + new_blocks: list[Block] = [] + if value_is_extension_type: + # This code (ab-)uses the fact that EA blocks contain only + # one item. + # TODO(EA2D): special casing unnecessary with 2D EAs + new_blocks.extend( + new_block_2d( + values=value, + placement=BlockPlacement(slice(mgr_loc, mgr_loc + 1)), + refs=refs, + ) + for mgr_loc in unfit_idxr + ) + + self._blknos[unfit_idxr] = np.arange(unfit_count) + len(self.blocks) + self._blklocs[unfit_idxr] = 0 + + else: + # unfit_val_locs contains BlockPlacement objects + unfit_val_items = unfit_val_locs[0].append(unfit_val_locs[1:]) + + new_blocks.append( + new_block_2d( + values=value_getitem(unfit_val_items), + placement=BlockPlacement(unfit_idxr), + refs=refs, + ) + ) + + self._blknos[unfit_idxr] = len(self.blocks) + self._blklocs[unfit_idxr] = np.arange(unfit_count) + + self.blocks += tuple(new_blocks) + + # Newly created block's dtype may already be present. + self._known_consolidated = False + + def _iset_split_block( + self, + blkno_l: int, + blk_locs: np.ndarray | list[int], + value: ArrayLike | None = None, + refs: BlockValuesRefs | None = None, + ) -> None: + """Removes columns from a block by splitting the block. + + Avoids copying the whole block through slicing and updates the manager + after determinint the new block structure. Optionally adds a new block, + otherwise has to be done by the caller. + + Parameters + ---------- + blkno_l: The block number to operate on, relevant for updating the manager + blk_locs: The locations of our block that should be deleted. + value: The value to set as a replacement. + refs: The reference tracking object of the value to set. + """ + blk = self.blocks[blkno_l] + + if self._blklocs is None: + self._rebuild_blknos_and_blklocs() + + nbs_tup = tuple(blk.delete(blk_locs)) + if value is not None: + locs = blk.mgr_locs.as_array[blk_locs] + first_nb = new_block_2d(value, BlockPlacement(locs), refs=refs) + else: + first_nb = nbs_tup[0] + nbs_tup = tuple(nbs_tup[1:]) + + nr_blocks = len(self.blocks) + blocks_tup = ( + self.blocks[:blkno_l] + (first_nb,) + self.blocks[blkno_l + 1 :] + nbs_tup + ) + self.blocks = blocks_tup + + if not nbs_tup and value is not None: + # No need to update anything if split did not happen + return + + self._blklocs[first_nb.mgr_locs.indexer] = np.arange(len(first_nb)) + + for i, nb in enumerate(nbs_tup): + self._blklocs[nb.mgr_locs.indexer] = np.arange(len(nb)) + self._blknos[nb.mgr_locs.indexer] = i + nr_blocks + + def _iset_single( + self, + loc: int, + value: ArrayLike, + inplace: bool, + blkno: int, + blk: Block, + refs: BlockValuesRefs | None = None, + ) -> None: + """ + Fastpath for iset when we are only setting a single position and + the Block currently in that position is itself single-column. + + In this case we can swap out the entire Block and blklocs and blknos + are unaffected. + """ + # Caller is responsible for verifying value.shape + + if inplace and blk.should_store(value): + copy = False + if using_copy_on_write() and not self._has_no_reference_block(blkno): + # perform Copy-on-Write and clear the reference + copy = True + iloc = self.blklocs[loc] + blk.set_inplace(slice(iloc, iloc + 1), value, copy=copy) + return + + nb = new_block_2d(value, placement=blk._mgr_locs, refs=refs) + old_blocks = self.blocks + new_blocks = old_blocks[:blkno] + (nb,) + old_blocks[blkno + 1 :] + self.blocks = new_blocks + return + + def column_setitem( + self, loc: int, idx: int | slice | np.ndarray, value, inplace_only: bool = False + ) -> None: + """ + Set values ("setitem") into a single column (not setting the full column). + + This is a method on the BlockManager level, to avoid creating an + intermediate Series at the DataFrame level (`s = df[loc]; s[idx] = value`) + """ + needs_to_warn = False + if warn_copy_on_write() and not self._has_no_reference(loc): + if not isinstance( + self.blocks[self.blknos[loc]].values, + (ArrowExtensionArray, ArrowStringArray), + ): + # We might raise if we are in an expansion case, so defer + # warning till we actually updated + needs_to_warn = True + + elif using_copy_on_write() and not self._has_no_reference(loc): + blkno = self.blknos[loc] + # Split blocks to only copy the column we want to modify + blk_loc = self.blklocs[loc] + # Copy our values + values = self.blocks[blkno].values + if values.ndim == 1: + values = values.copy() + else: + # Use [blk_loc] as indexer to keep ndim=2, this already results in a + # copy + values = values[[blk_loc]] + self._iset_split_block(blkno, [blk_loc], values) + + # this manager is only created temporarily to mutate the values in place + # so don't track references, otherwise the `setitem` would perform CoW again + col_mgr = self.iget(loc, track_ref=False) + if inplace_only: + col_mgr.setitem_inplace(idx, value) + else: + new_mgr = col_mgr.setitem((idx,), value) + self.iset(loc, new_mgr._block.values, inplace=True) + + if needs_to_warn: + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + def insert(self, loc: int, item: Hashable, value: ArrayLike, refs=None) -> None: + """ + Insert item at selected position. + + Parameters + ---------- + loc : int + item : hashable + value : np.ndarray or ExtensionArray + refs : The reference tracking object of the value to set. + """ + with warnings.catch_warnings(): + # TODO: re-issue this with setitem-specific message? + warnings.filterwarnings( + "ignore", + "The behavior of Index.insert with object-dtype is deprecated", + category=FutureWarning, + ) + new_axis = self.items.insert(loc, item) + + if value.ndim == 2: + value = value.T + if len(value) > 1: + raise ValueError( + f"Expected a 1D array, got an array with shape {value.T.shape}" + ) + else: + value = ensure_block_shape(value, ndim=self.ndim) + + bp = BlockPlacement(slice(loc, loc + 1)) + block = new_block_2d(values=value, placement=bp, refs=refs) + + if not len(self.blocks): + # Fastpath + self._blklocs = np.array([0], dtype=np.intp) + self._blknos = np.array([0], dtype=np.intp) + else: + self._insert_update_mgr_locs(loc) + self._insert_update_blklocs_and_blknos(loc) + + self.axes[0] = new_axis + self.blocks += (block,) + + self._known_consolidated = False + + if sum(not block.is_extension for block in self.blocks) > 100: + warnings.warn( + "DataFrame is highly fragmented. This is usually the result " + "of calling `frame.insert` many times, which has poor performance. " + "Consider joining all columns at once using pd.concat(axis=1) " + "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", + PerformanceWarning, + stacklevel=find_stack_level(), + ) + + def _insert_update_mgr_locs(self, loc) -> None: + """ + When inserting a new Block at location 'loc', we increment + all of the mgr_locs of blocks above that by one. + """ + for blkno, count in _fast_count_smallints(self.blknos[loc:]): + # .620 this way, .326 of which is in increment_above + blk = self.blocks[blkno] + blk._mgr_locs = blk._mgr_locs.increment_above(loc) + + def _insert_update_blklocs_and_blknos(self, loc) -> None: + """ + When inserting a new Block at location 'loc', we update our + _blklocs and _blknos. + """ + + # Accessing public blklocs ensures the public versions are initialized + if loc == self.blklocs.shape[0]: + # np.append is a lot faster, let's use it if we can. + self._blklocs = np.append(self._blklocs, 0) + self._blknos = np.append(self._blknos, len(self.blocks)) + elif loc == 0: + # np.append is a lot faster, let's use it if we can. + self._blklocs = np.append(self._blklocs[::-1], 0)[::-1] + self._blknos = np.append(self._blknos[::-1], len(self.blocks))[::-1] + else: + new_blklocs, new_blknos = libinternals.update_blklocs_and_blknos( + self.blklocs, self.blknos, loc, len(self.blocks) + ) + self._blklocs = new_blklocs + self._blknos = new_blknos + + def idelete(self, indexer) -> BlockManager: + """ + Delete selected locations, returning a new BlockManager. + """ + is_deleted = np.zeros(self.shape[0], dtype=np.bool_) + is_deleted[indexer] = True + taker = (~is_deleted).nonzero()[0] + + nbs = self._slice_take_blocks_ax0(taker, only_slice=True, ref_inplace_op=True) + new_columns = self.items[~is_deleted] + axes = [new_columns, self.axes[1]] + return type(self)(tuple(nbs), axes, verify_integrity=False) + + # ---------------------------------------------------------------- + # Block-wise Operation + + def grouped_reduce(self, func: Callable) -> Self: + """ + Apply grouped reduction function blockwise, returning a new BlockManager. + + Parameters + ---------- + func : grouped reduction function + + Returns + ------- + BlockManager + """ + result_blocks: list[Block] = [] + + for blk in self.blocks: + if blk.is_object: + # split on object-dtype blocks bc some columns may raise + # while others do not. + for sb in blk._split(): + applied = sb.apply(func) + result_blocks = extend_blocks(applied, result_blocks) + else: + applied = blk.apply(func) + result_blocks = extend_blocks(applied, result_blocks) + + if len(result_blocks) == 0: + nrows = 0 + else: + nrows = result_blocks[0].values.shape[-1] + index = Index(range(nrows)) + + return type(self).from_blocks(result_blocks, [self.axes[0], index]) + + def reduce(self, func: Callable) -> Self: + """ + Apply reduction function blockwise, returning a single-row BlockManager. + + Parameters + ---------- + func : reduction function + + Returns + ------- + BlockManager + """ + # If 2D, we assume that we're operating column-wise + assert self.ndim == 2 + + res_blocks: list[Block] = [] + for blk in self.blocks: + nbs = blk.reduce(func) + res_blocks.extend(nbs) + + index = Index([None]) # placeholder + new_mgr = type(self).from_blocks(res_blocks, [self.items, index]) + return new_mgr + + def operate_blockwise(self, other: BlockManager, array_op) -> BlockManager: + """ + Apply array_op blockwise with another (aligned) BlockManager. + """ + return operate_blockwise(self, other, array_op) + + def _equal_values(self: BlockManager, other: BlockManager) -> bool: + """ + Used in .equals defined in base class. Only check the column values + assuming shape and indexes have already been checked. + """ + return blockwise_all(self, other, array_equals) + + def quantile( + self, + *, + qs: Index, # with dtype float 64 + interpolation: QuantileInterpolation = "linear", + ) -> Self: + """ + Iterate over blocks applying quantile reduction. + This routine is intended for reduction type operations and + will do inference on the generated blocks. + + Parameters + ---------- + interpolation : type of interpolation, default 'linear' + qs : list of the quantiles to be computed + + Returns + ------- + BlockManager + """ + # Series dispatches to DataFrame for quantile, which allows us to + # simplify some of the code here and in the blocks + assert self.ndim >= 2 + assert is_list_like(qs) # caller is responsible for this + + new_axes = list(self.axes) + new_axes[1] = Index(qs, dtype=np.float64) + + blocks = [ + blk.quantile(qs=qs, interpolation=interpolation) for blk in self.blocks + ] + + return type(self)(blocks, new_axes) + + # ---------------------------------------------------------------- + + def unstack(self, unstacker, fill_value) -> BlockManager: + """ + Return a BlockManager with all blocks unstacked. + + Parameters + ---------- + unstacker : reshape._Unstacker + fill_value : Any + fill_value for newly introduced missing values. + + Returns + ------- + unstacked : BlockManager + """ + new_columns = unstacker.get_new_columns(self.items) + new_index = unstacker.new_index + + allow_fill = not unstacker.mask_all + if allow_fill: + # calculating the full mask once and passing it to Block._unstack is + # faster than letting calculating it in each repeated call + new_mask2D = (~unstacker.mask).reshape(*unstacker.full_shape) + needs_masking = new_mask2D.any(axis=0) + else: + needs_masking = np.zeros(unstacker.full_shape[1], dtype=bool) + + new_blocks: list[Block] = [] + columns_mask: list[np.ndarray] = [] + + if len(self.items) == 0: + factor = 1 + else: + fac = len(new_columns) / len(self.items) + assert fac == int(fac) + factor = int(fac) + + for blk in self.blocks: + mgr_locs = blk.mgr_locs + new_placement = mgr_locs.tile_for_unstack(factor) + + blocks, mask = blk._unstack( + unstacker, + fill_value, + new_placement=new_placement, + needs_masking=needs_masking, + ) + + new_blocks.extend(blocks) + columns_mask.extend(mask) + + # Block._unstack should ensure this holds, + assert mask.sum() == sum(len(nb._mgr_locs) for nb in blocks) + # In turn this ensures that in the BlockManager call below + # we have len(new_columns) == sum(x.shape[0] for x in new_blocks) + # which suffices to allow us to pass verify_inegrity=False + + new_columns = new_columns[columns_mask] + + bm = BlockManager(new_blocks, [new_columns, new_index], verify_integrity=False) + return bm + + def to_dict(self) -> dict[str, Self]: + """ + Return a dict of str(dtype) -> BlockManager + + Returns + ------- + values : a dict of dtype -> BlockManager + """ + + bd: dict[str, list[Block]] = {} + for b in self.blocks: + bd.setdefault(str(b.dtype), []).append(b) + + # TODO(EA2D): the combine will be unnecessary with 2D EAs + return {dtype: self._combine(blocks) for dtype, blocks in bd.items()} + + def as_array( + self, + dtype: np.dtype | None = None, + copy: bool = False, + na_value: object = lib.no_default, + ) -> np.ndarray: + """ + Convert the blockmanager data into an numpy array. + + Parameters + ---------- + dtype : np.dtype or None, default None + Data type of the return array. + copy : bool, default False + If True then guarantee that a copy is returned. A value of + False does not guarantee that the underlying data is not + copied. + na_value : object, default lib.no_default + Value to be used as the missing value sentinel. + + Returns + ------- + arr : ndarray + """ + passed_nan = lib.is_float(na_value) and isna(na_value) + + if len(self.blocks) == 0: + arr = np.empty(self.shape, dtype=float) + return arr.transpose() + + if self.is_single_block: + blk = self.blocks[0] + + if na_value is not lib.no_default: + # We want to copy when na_value is provided to avoid + # mutating the original object + if lib.is_np_dtype(blk.dtype, "f") and passed_nan: + # We are already numpy-float and na_value=np.nan + pass + else: + copy = True + + if blk.is_extension: + # Avoid implicit conversion of extension blocks to object + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, + na_value=na_value, + copy=copy, + ).reshape(blk.shape) + elif not copy: + arr = np.asarray(blk.values, dtype=dtype) + else: + arr = np.array(blk.values, dtype=dtype, copy=copy) + + if using_copy_on_write() and not copy: + arr = arr.view() + arr.flags.writeable = False + else: + arr = self._interleave(dtype=dtype, na_value=na_value) + # The underlying data was copied within _interleave, so no need + # to further copy if copy=True or setting na_value + + if na_value is lib.no_default: + pass + elif arr.dtype.kind == "f" and passed_nan: + pass + else: + arr[isna(arr)] = na_value + + return arr.transpose() + + def _interleave( + self, + dtype: np.dtype | None = None, + na_value: object = lib.no_default, + ) -> np.ndarray: + """ + Return ndarray from blocks with specified item order + Items must be contained in the blocks + """ + if not dtype: + # Incompatible types in assignment (expression has type + # "Optional[Union[dtype[Any], ExtensionDtype]]", variable has + # type "Optional[dtype[Any]]") + dtype = interleaved_dtype( # type: ignore[assignment] + [blk.dtype for blk in self.blocks] + ) + + # error: Argument 1 to "ensure_np_dtype" has incompatible type + # "Optional[dtype[Any]]"; expected "Union[dtype[Any], ExtensionDtype]" + dtype = ensure_np_dtype(dtype) # type: ignore[arg-type] + result = np.empty(self.shape, dtype=dtype) + + itemmask = np.zeros(self.shape[0]) + + if dtype == np.dtype("object") and na_value is lib.no_default: + # much more performant than using to_numpy below + for blk in self.blocks: + rl = blk.mgr_locs + arr = blk.get_values(dtype) + result[rl.indexer] = arr + itemmask[rl.indexer] = 1 + return result + + for blk in self.blocks: + rl = blk.mgr_locs + if blk.is_extension: + # Avoid implicit conversion of extension blocks to object + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, + na_value=na_value, + ) + else: + arr = blk.get_values(dtype) + result[rl.indexer] = arr + itemmask[rl.indexer] = 1 + + if not itemmask.all(): + raise AssertionError("Some items were not contained in blocks") + + return result + + # ---------------------------------------------------------------- + # Consolidation + + def is_consolidated(self) -> bool: + """ + Return True if more than one block with the same dtype + """ + if not self._known_consolidated: + self._consolidate_check() + return self._is_consolidated + + def _consolidate_check(self) -> None: + if len(self.blocks) == 1: + # fastpath + self._is_consolidated = True + self._known_consolidated = True + return + dtypes = [blk.dtype for blk in self.blocks if blk._can_consolidate] + self._is_consolidated = len(dtypes) == len(set(dtypes)) + self._known_consolidated = True + + def _consolidate_inplace(self) -> None: + # In general, _consolidate_inplace should only be called via + # DataFrame._consolidate_inplace, otherwise we will fail to invalidate + # the DataFrame's _item_cache. The exception is for newly-created + # BlockManager objects not yet attached to a DataFrame. + if not self.is_consolidated(): + self.blocks = _consolidate(self.blocks) + self._is_consolidated = True + self._known_consolidated = True + self._rebuild_blknos_and_blklocs() + + # ---------------------------------------------------------------- + # Concatenation + + @classmethod + def concat_horizontal(cls, mgrs: list[Self], axes: list[Index]) -> Self: + """ + Concatenate uniformly-indexed BlockManagers horizontally. + """ + offset = 0 + blocks: list[Block] = [] + for mgr in mgrs: + for blk in mgr.blocks: + # We need to do getitem_block here otherwise we would be altering + # blk.mgr_locs in place, which would render it invalid. This is only + # relevant in the copy=False case. + nb = blk.slice_block_columns(slice(None)) + nb._mgr_locs = nb._mgr_locs.add(offset) + blocks.append(nb) + + offset += len(mgr.items) + + new_mgr = cls(tuple(blocks), axes) + return new_mgr + + @classmethod + def concat_vertical(cls, mgrs: list[Self], axes: list[Index]) -> Self: + """ + Concatenate uniformly-indexed BlockManagers vertically. + """ + raise NotImplementedError("This logic lives (for now) in internals.concat") + + +class SingleBlockManager(BaseBlockManager, SingleDataManager): + """manage a single block with""" + + @property + def ndim(self) -> Literal[1]: + return 1 + + _is_consolidated = True + _known_consolidated = True + __slots__ = () + is_single_block = True + + def __init__( + self, + block: Block, + axis: Index, + verify_integrity: bool = False, + ) -> None: + # Assertions disabled for performance + # assert isinstance(block, Block), type(block) + # assert isinstance(axis, Index), type(axis) + + self.axes = [axis] + self.blocks = (block,) + + @classmethod + def from_blocks( + cls, + blocks: list[Block], + axes: list[Index], + ) -> Self: + """ + Constructor for BlockManager and SingleBlockManager with same signature. + """ + assert len(blocks) == 1 + assert len(axes) == 1 + return cls(blocks[0], axes[0], verify_integrity=False) + + @classmethod + def from_array( + cls, array: ArrayLike, index: Index, refs: BlockValuesRefs | None = None + ) -> SingleBlockManager: + """ + Constructor for if we have an array that is not yet a Block. + """ + array = maybe_coerce_values(array) + bp = BlockPlacement(slice(0, len(index))) + block = new_block(array, placement=bp, ndim=1, refs=refs) + return cls(block, index) + + def to_2d_mgr(self, columns: Index) -> BlockManager: + """ + Manager analogue of Series.to_frame + """ + blk = self.blocks[0] + arr = ensure_block_shape(blk.values, ndim=2) + bp = BlockPlacement(0) + new_blk = type(blk)(arr, placement=bp, ndim=2, refs=blk.refs) + axes = [columns, self.axes[0]] + return BlockManager([new_blk], axes=axes, verify_integrity=False) + + def _has_no_reference(self, i: int = 0) -> bool: + """ + Check for column `i` if it has references. + (whether it references another array or is itself being referenced) + Returns True if the column has no references. + """ + return not self.blocks[0].refs.has_reference() + + def __getstate__(self): + block_values = [b.values for b in self.blocks] + block_items = [self.items[b.mgr_locs.indexer] for b in self.blocks] + axes_array = list(self.axes) + + extra_state = { + "0.14.1": { + "axes": axes_array, + "blocks": [ + {"values": b.values, "mgr_locs": b.mgr_locs.indexer} + for b in self.blocks + ], + } + } + + # First three elements of the state are to maintain forward + # compatibility with 0.13.1. + return axes_array, block_values, block_items, extra_state + + def __setstate__(self, state) -> None: + def unpickle_block(values, mgr_locs, ndim: int) -> Block: + # TODO(EA2D): ndim would be unnecessary with 2D EAs + # older pickles may store e.g. DatetimeIndex instead of DatetimeArray + values = extract_array(values, extract_numpy=True) + if not isinstance(mgr_locs, BlockPlacement): + mgr_locs = BlockPlacement(mgr_locs) + + values = maybe_coerce_values(values) + return new_block(values, placement=mgr_locs, ndim=ndim) + + if isinstance(state, tuple) and len(state) >= 4 and "0.14.1" in state[3]: + state = state[3]["0.14.1"] + self.axes = [ensure_index(ax) for ax in state["axes"]] + ndim = len(self.axes) + self.blocks = tuple( + unpickle_block(b["values"], b["mgr_locs"], ndim=ndim) + for b in state["blocks"] + ) + else: + raise NotImplementedError("pre-0.14.1 pickles are no longer supported") + + self._post_setstate() + + def _post_setstate(self) -> None: + pass + + @cache_readonly + def _block(self) -> Block: + return self.blocks[0] + + @property + def _blknos(self): + """compat with BlockManager""" + return None + + @property + def _blklocs(self): + """compat with BlockManager""" + return None + + def get_rows_with_mask(self, indexer: npt.NDArray[np.bool_]) -> Self: + # similar to get_slice, but not restricted to slice indexer + blk = self._block + if using_copy_on_write() and len(indexer) > 0 and indexer.all(): + return type(self)(blk.copy(deep=False), self.index) + array = blk.values[indexer] + + if isinstance(indexer, np.ndarray) and indexer.dtype.kind == "b": + # boolean indexing always gives a copy with numpy + refs = None + else: + # TODO(CoW) in theory only need to track reference if new_array is a view + refs = blk.refs + + bp = BlockPlacement(slice(0, len(array))) + block = type(blk)(array, placement=bp, ndim=1, refs=refs) + + new_idx = self.index[indexer] + return type(self)(block, new_idx) + + def get_slice(self, slobj: slice, axis: AxisInt = 0) -> SingleBlockManager: + # Assertion disabled for performance + # assert isinstance(slobj, slice), type(slobj) + if axis >= self.ndim: + raise IndexError("Requested axis not found in manager") + + blk = self._block + array = blk.values[slobj] + bp = BlockPlacement(slice(0, len(array))) + # TODO this method is only used in groupby SeriesSplitter at the moment, + # so passing refs is not yet covered by the tests + block = type(blk)(array, placement=bp, ndim=1, refs=blk.refs) + new_index = self.index._getitem_slice(slobj) + return type(self)(block, new_index) + + @property + def index(self) -> Index: + return self.axes[0] + + @property + def dtype(self) -> DtypeObj: + return self._block.dtype + + def get_dtypes(self) -> npt.NDArray[np.object_]: + return np.array([self._block.dtype], dtype=object) + + def external_values(self): + """The array that Series.values returns""" + return self._block.external_values() + + def internal_values(self): + """The array that Series._values returns""" + return self._block.values + + def array_values(self) -> ExtensionArray: + """The array that Series.array returns""" + return self._block.array_values + + def get_numeric_data(self) -> Self: + if self._block.is_numeric: + return self.copy(deep=False) + return self.make_empty() + + @property + def _can_hold_na(self) -> bool: + return self._block._can_hold_na + + def setitem_inplace(self, indexer, value, warn: bool = True) -> None: + """ + Set values with indexer. + + For Single[Block/Array]Manager, this backs s[indexer] = value + + This is an inplace version of `setitem()`, mutating the manager/values + in place, not returning a new Manager (and Block), and thus never changing + the dtype. + """ + using_cow = using_copy_on_write() + warn_cow = warn_copy_on_write() + if (using_cow or warn_cow) and not self._has_no_reference(0): + if using_cow: + self.blocks = (self._block.copy(),) + self._cache.clear() + elif warn_cow and warn: + warnings.warn( + COW_WARNING_SETITEM_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + + super().setitem_inplace(indexer, value) + + def idelete(self, indexer) -> SingleBlockManager: + """ + Delete single location from SingleBlockManager. + + Ensures that self.blocks doesn't become empty. + """ + nb = self._block.delete(indexer)[0] + self.blocks = (nb,) + self.axes[0] = self.axes[0].delete(indexer) + self._cache.clear() + return self + + def fast_xs(self, loc): + """ + fast path for getting a cross-section + return a view of the data + """ + raise NotImplementedError("Use series._values[loc] instead") + + def set_values(self, values: ArrayLike) -> None: + """ + Set the values of the single block in place. + + Use at your own risk! This does not check if the passed values are + valid for the current Block/SingleBlockManager (length, dtype, etc), + and this does not properly keep track of references. + """ + # NOTE(CoW) Currently this is only used for FrameColumnApply.series_generator + # which handles CoW by setting the refs manually if necessary + self.blocks[0].values = values + self.blocks[0]._mgr_locs = BlockPlacement(slice(len(values))) + + def _equal_values(self, other: Self) -> bool: + """ + Used in .equals defined in base class. Only check the column values + assuming shape and indexes have already been checked. + """ + # For SingleBlockManager (i.e.Series) + if other.ndim != 1: + return False + left = self.blocks[0].values + right = other.blocks[0].values + return array_equals(left, right) + + +# -------------------------------------------------------------------- +# Constructor Helpers + + +def create_block_manager_from_blocks( + blocks: list[Block], + axes: list[Index], + consolidate: bool = True, + verify_integrity: bool = True, +) -> BlockManager: + # If verify_integrity=False, then caller is responsible for checking + # all(x.shape[-1] == len(axes[1]) for x in blocks) + # sum(x.shape[0] for x in blocks) == len(axes[0]) + # set(x for blk in blocks for x in blk.mgr_locs) == set(range(len(axes[0]))) + # all(blk.ndim == 2 for blk in blocks) + # This allows us to safely pass verify_integrity=False + + try: + mgr = BlockManager(blocks, axes, verify_integrity=verify_integrity) + + except ValueError as err: + arrays = [blk.values for blk in blocks] + tot_items = sum(arr.shape[0] for arr in arrays) + raise_construction_error(tot_items, arrays[0].shape[1:], axes, err) + + if consolidate: + mgr._consolidate_inplace() + return mgr + + +def create_block_manager_from_column_arrays( + arrays: list[ArrayLike], + axes: list[Index], + consolidate: bool, + refs: list, +) -> BlockManager: + # Assertions disabled for performance (caller is responsible for verifying) + # assert isinstance(axes, list) + # assert all(isinstance(x, Index) for x in axes) + # assert all(isinstance(x, (np.ndarray, ExtensionArray)) for x in arrays) + # assert all(type(x) is not NumpyExtensionArray for x in arrays) + # assert all(x.ndim == 1 for x in arrays) + # assert all(len(x) == len(axes[1]) for x in arrays) + # assert len(arrays) == len(axes[0]) + # These last three are sufficient to allow us to safely pass + # verify_integrity=False below. + + try: + blocks = _form_blocks(arrays, consolidate, refs) + mgr = BlockManager(blocks, axes, verify_integrity=False) + except ValueError as e: + raise_construction_error(len(arrays), arrays[0].shape, axes, e) + if consolidate: + mgr._consolidate_inplace() + return mgr + + +def raise_construction_error( + tot_items: int, + block_shape: Shape, + axes: list[Index], + e: ValueError | None = None, +): + """raise a helpful message about our construction""" + passed = tuple(map(int, [tot_items] + list(block_shape))) + # Correcting the user facing error message during dataframe construction + if len(passed) <= 2: + passed = passed[::-1] + + implied = tuple(len(ax) for ax in axes) + # Correcting the user facing error message during dataframe construction + if len(implied) <= 2: + implied = implied[::-1] + + # We return the exception object instead of raising it so that we + # can raise it in the caller; mypy plays better with that + if passed == implied and e is not None: + raise e + if block_shape[0] == 0: + raise ValueError("Empty data passed with indices specified.") + raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}") + + +# ----------------------------------------------------------------------- + + +def _grouping_func(tup: tuple[int, ArrayLike]) -> tuple[int, DtypeObj]: + dtype = tup[1].dtype + + if is_1d_only_ea_dtype(dtype): + # We know these won't be consolidated, so don't need to group these. + # This avoids expensive comparisons of CategoricalDtype objects + sep = id(dtype) + else: + sep = 0 + + return sep, dtype + + +def _form_blocks(arrays: list[ArrayLike], consolidate: bool, refs: list) -> list[Block]: + tuples = list(enumerate(arrays)) + + if not consolidate: + return _tuples_to_blocks_no_consolidate(tuples, refs) + + # when consolidating, we can ignore refs (either stacking always copies, + # or the EA is already copied in the calling dict_to_mgr) + + # group by dtype + grouper = itertools.groupby(tuples, _grouping_func) + + nbs: list[Block] = [] + for (_, dtype), tup_block in grouper: + block_type = get_block_type(dtype) + + if isinstance(dtype, np.dtype): + is_dtlike = dtype.kind in "mM" + + if issubclass(dtype.type, (str, bytes)): + dtype = np.dtype(object) + + values, placement = _stack_arrays(list(tup_block), dtype) + if is_dtlike: + values = ensure_wrapped_if_datetimelike(values) + blk = block_type(values, placement=BlockPlacement(placement), ndim=2) + nbs.append(blk) + + elif is_1d_only_ea_dtype(dtype): + dtype_blocks = [ + block_type(x[1], placement=BlockPlacement(x[0]), ndim=2) + for x in tup_block + ] + nbs.extend(dtype_blocks) + + else: + dtype_blocks = [ + block_type( + ensure_block_shape(x[1], 2), placement=BlockPlacement(x[0]), ndim=2 + ) + for x in tup_block + ] + nbs.extend(dtype_blocks) + return nbs + + +def _tuples_to_blocks_no_consolidate(tuples, refs) -> list[Block]: + # tuples produced within _form_blocks are of the form (placement, array) + return [ + new_block_2d( + ensure_block_shape(arr, ndim=2), placement=BlockPlacement(i), refs=ref + ) + for ((i, arr), ref) in zip(tuples, refs) + ] + + +def _stack_arrays(tuples, dtype: np.dtype): + placement, arrays = zip(*tuples) + + first = arrays[0] + shape = (len(arrays),) + first.shape + + stacked = np.empty(shape, dtype=dtype) + for i, arr in enumerate(arrays): + stacked[i] = arr + + return stacked, placement + + +def _consolidate(blocks: tuple[Block, ...]) -> tuple[Block, ...]: + """ + Merge blocks having same dtype, exclude non-consolidating blocks + """ + # sort by _can_consolidate, dtype + gkey = lambda x: x._consolidate_key + grouper = itertools.groupby(sorted(blocks, key=gkey), gkey) + + new_blocks: list[Block] = [] + for (_can_consolidate, dtype), group_blocks in grouper: + merged_blocks, _ = _merge_blocks( + list(group_blocks), dtype=dtype, can_consolidate=_can_consolidate + ) + new_blocks = extend_blocks(merged_blocks, new_blocks) + return tuple(new_blocks) + + +def _merge_blocks( + blocks: list[Block], dtype: DtypeObj, can_consolidate: bool +) -> tuple[list[Block], bool]: + if len(blocks) == 1: + return blocks, False + + if can_consolidate: + # TODO: optimization potential in case all mgrs contain slices and + # combination of those slices is a slice, too. + new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) + + new_values: ArrayLike + + if isinstance(blocks[0].dtype, np.dtype): + # error: List comprehension has incompatible type List[Union[ndarray, + # ExtensionArray]]; expected List[Union[complex, generic, + # Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], SupportsArray]] + new_values = np.vstack([b.values for b in blocks]) # type: ignore[misc] + else: + bvals = [blk.values for blk in blocks] + bvals2 = cast(Sequence[NDArrayBackedExtensionArray], bvals) + new_values = bvals2[0]._concat_same_type(bvals2, axis=0) + + argsort = np.argsort(new_mgr_locs) + new_values = new_values[argsort] + new_mgr_locs = new_mgr_locs[argsort] + + bp = BlockPlacement(new_mgr_locs) + return [new_block_2d(new_values, placement=bp)], True + + # can't consolidate --> no merge + return blocks, False + + +def _fast_count_smallints(arr: npt.NDArray[np.intp]): + """Faster version of set(arr) for sequences of small numbers.""" + counts = np.bincount(arr) + nz = counts.nonzero()[0] + # Note: list(zip(...) outperforms list(np.c_[nz, counts[nz]]) here, + # in one benchmark by a factor of 11 + return zip(nz, counts[nz]) + + +def _preprocess_slice_or_indexer( + slice_or_indexer: slice | np.ndarray, length: int, allow_fill: bool +): + if isinstance(slice_or_indexer, slice): + return ( + "slice", + slice_or_indexer, + libinternals.slice_len(slice_or_indexer, length), + ) + else: + if ( + not isinstance(slice_or_indexer, np.ndarray) + or slice_or_indexer.dtype.kind != "i" + ): + dtype = getattr(slice_or_indexer, "dtype", None) + raise TypeError(type(slice_or_indexer), dtype) + + indexer = ensure_platform_int(slice_or_indexer) + if not allow_fill: + indexer = maybe_convert_indices(indexer, length) + return "fancy", indexer, len(indexer) + + +def make_na_array(dtype: DtypeObj, shape: Shape, fill_value) -> ArrayLike: + if isinstance(dtype, DatetimeTZDtype): + # NB: exclude e.g. pyarrow[dt64tz] dtypes + ts = Timestamp(fill_value).as_unit(dtype.unit) + i8values = np.full(shape, ts._value) + dt64values = i8values.view(f"M8[{dtype.unit}]") + return DatetimeArray._simple_new(dt64values, dtype=dtype) + + elif is_1d_only_ea_dtype(dtype): + dtype = cast(ExtensionDtype, dtype) + cls = dtype.construct_array_type() + + missing_arr = cls._from_sequence([], dtype=dtype) + ncols, nrows = shape + assert ncols == 1, ncols + empty_arr = -1 * np.ones((nrows,), dtype=np.intp) + return missing_arr.take(empty_arr, allow_fill=True, fill_value=fill_value) + elif isinstance(dtype, ExtensionDtype): + # TODO: no tests get here, a handful would if we disabled + # the dt64tz special-case above (which is faster) + cls = dtype.construct_array_type() + missing_arr = cls._empty(shape=shape, dtype=dtype) + missing_arr[:] = fill_value + return missing_arr + else: + # NB: we should never get here with dtype integer or bool; + # if we did, the missing_arr.fill would cast to gibberish + missing_arr = np.empty(shape, dtype=dtype) + missing_arr.fill(fill_value) + + if dtype.kind in "mM": + missing_arr = ensure_wrapped_if_datetimelike(missing_arr) + return missing_arr diff --git a/shared/package-files/b6/b6883c86efbe8a8210cce2e58cf0cf3551d2588d451f4685ea0316da9aee37dc/argmax_native.h b/shared/package-files/b6/b6883c86efbe8a8210cce2e58cf0cf3551d2588d451f4685ea0316da9aee37dc/argmax_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2df60bdd2e88070b4515dd237087d18b6a269091 --- /dev/null +++ b/shared/package-files/b6/b6883c86efbe8a8210cce2e58cf0cf3551d2588d451f4685ea0316da9aee37dc/argmax_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_argmax_out : public at::meta::structured_argmax { +void impl(const at::Tensor & self, ::std::optional dim, bool keepdim, const at::Tensor & out); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/b6/b6a056d44b9203bd4de645c3531661dff2506128daecdebe4edced830b0566e1/composable_quantizer.py b/shared/package-files/b6/b6a056d44b9203bd4de645c3531661dff2506128daecdebe4edced830b0566e1/composable_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..6b95edbc2193a40bdae9e872467c7bb12dfc5af1 --- /dev/null +++ b/shared/package-files/b6/b6a056d44b9203bd4de645c3531661dff2506128daecdebe4edced830b0566e1/composable_quantizer.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .quantizer import QuantizationAnnotation, Quantizer + + +if TYPE_CHECKING: + import torch + from torch.fx import Node + +__all__ = [ + "ComposableQuantizer", +] + + +class ComposableQuantizer(Quantizer): + """ + ComposableQuantizer allows users to combine more than one quantizer into a single quantizer. + This allows users to quantize a model with multiple quantizers. E.g., embedding quantization + maybe supported by one quantizer while linear layers and other ops might be supported by another + quantizer. + + ComposableQuantizer is initialized with a list of `Quantizer` instances. + The order of the composition matters since that is the order in which the quantizers will be + applies. + Example: + ``` + embedding_quantizer = EmbeddingQuantizer() + linear_quantizer = MyLinearQuantizer() + xnnpack_quantizer = XNNPackQuantizer() # to handle ops not quantized by previous two quantizers + composed_quantizer = ComposableQuantizer([embedding_quantizer, linear_quantizer, xnnpack_quantizer]) + prepared_m = prepare_pt2e(model, composed_quantizer) + ``` + """ + + def __init__(self, quantizers: list[Quantizer]): + super().__init__() + self.quantizers = quantizers + self._graph_annotations: dict[Node, QuantizationAnnotation] = {} + + def _record_and_validate_annotations( + self, gm: torch.fx.GraphModule, quantizer: Quantizer + ) -> None: + for n in gm.graph.nodes: + if "quantization_annotation" in n.meta: + # check if the annotation has been changed by + # comparing QuantizationAnnotation object id + if n in self._graph_annotations and ( + id(self._graph_annotations[n]) + != id(n.meta["quantization_annotation"]) + ): + raise RuntimeError( + f"Quantizer {quantizer.__class__.__name__} has changed annotations on node {n}" + ) + else: + self._graph_annotations[n] = n.meta["quantization_annotation"] + else: + if n in self._graph_annotations: + raise RuntimeError( + f"Quantizer {quantizer.__class__.__name__} has removed annotations on node {n}" + ) + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + for quantizer in self.quantizers: + quantizer.annotate(model) + self._record_and_validate_annotations(model, quantizer) + return model + + def transform_for_annotation( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + for quantizer in self.quantizers: + model = quantizer.transform_for_annotation(model) + return model + + def validate(self, model: torch.fx.GraphModule) -> None: + pass diff --git a/shared/package-files/b6/b6a1f2937bdeab4ca082fe4eb9920e62e19409a9a5c29bad12aa8cfb3bd04a9c/disjoint_paths.cpython-311.pyc b/shared/package-files/b6/b6a1f2937bdeab4ca082fe4eb9920e62e19409a9a5c29bad12aa8cfb3bd04a9c/disjoint_paths.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fc2ebdcb62a44be2d473d0fd650ba63c447c393 Binary files /dev/null and b/shared/package-files/b6/b6a1f2937bdeab4ca082fe4eb9920e62e19409a9a5c29bad12aa8cfb3bd04a9c/disjoint_paths.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6a69f7580827b3ff90e73e54a457735b6a134248beecf83d544459ed9148c2c/medium.cpython-311.pyc b/shared/package-files/b6/b6a69f7580827b3ff90e73e54a457735b6a134248beecf83d544459ed9148c2c/medium.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bdf3cd51032522adc42e023464c0fca7fe7cc08 Binary files /dev/null and b/shared/package-files/b6/b6a69f7580827b3ff90e73e54a457735b6a134248beecf83d544459ed9148c2c/medium.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6b0989d31dad8b843db19ea549ea2bf50446a11e91b814330d6e3c3f306d3bc/test_keys.py b/shared/package-files/b6/b6b0989d31dad8b843db19ea549ea2bf50446a11e91b814330d6e3c3f306d3bc/test_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..55bd3f0d5a03a1636ae07ea9e1e3776743fd6464 --- /dev/null +++ b/shared/package-files/b6/b6b0989d31dad8b843db19ea549ea2bf50446a11e91b814330d6e3c3f306d3bc/test_keys.py @@ -0,0 +1,87 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + HDFStore, + Index, + Series, + date_range, +) +from pandas.tests.io.pytables.common import ( + ensure_clean_store, + tables, +) + +pytestmark = pytest.mark.single_cpu + + +def test_keys(setup_path): + with ensure_clean_store(setup_path) as store: + store["a"] = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + store["b"] = Series( + range(10), dtype="float64", index=[f"i_{i}" for i in range(10)] + ) + store["c"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + + assert len(store) == 3 + expected = {"/a", "/b", "/c"} + assert set(store.keys()) == expected + assert set(store) == expected + + +def test_non_pandas_keys(tmp_path, setup_path): + class Table1(tables.IsDescription): + value1 = tables.Float32Col() + + class Table2(tables.IsDescription): + value2 = tables.Float32Col() + + class Table3(tables.IsDescription): + value3 = tables.Float32Col() + + path = tmp_path / setup_path + with tables.open_file(path, mode="w") as h5file: + group = h5file.create_group("/", "group") + h5file.create_table(group, "table1", Table1, "Table 1") + h5file.create_table(group, "table2", Table2, "Table 2") + h5file.create_table(group, "table3", Table3, "Table 3") + with HDFStore(path) as store: + assert len(store.keys(include="native")) == 3 + expected = {"/group/table1", "/group/table2", "/group/table3"} + assert set(store.keys(include="native")) == expected + assert set(store.keys(include="pandas")) == set() + for name in expected: + df = store.get(name) + assert len(df.columns) == 1 + + +def test_keys_illegal_include_keyword_value(setup_path): + with ensure_clean_store(setup_path) as store: + with pytest.raises( + ValueError, + match="`include` should be either 'pandas' or 'native' but is 'illegal'", + ): + store.keys(include="illegal") + + +def test_keys_ignore_hdf_softlink(setup_path): + # GH 20523 + # Puts a softlink into HDF file and rereads + + with ensure_clean_store(setup_path) as store: + df = DataFrame({"A": range(5), "B": range(5)}) + store.put("df", df) + + assert store.keys() == ["/df"] + + store._handle.create_soft_link(store._handle.root, "symlink", "df") + + # Should ignore the softlink + assert store.keys() == ["/df"] diff --git a/shared/package-files/b6/b6bd2bcaecb8a8ded507b91f47d2101379174ec7cee30a00c704eb8be4b3e8f5/polyhedron.cpython-311.pyc b/shared/package-files/b6/b6bd2bcaecb8a8ded507b91f47d2101379174ec7cee30a00c704eb8be4b3e8f5/polyhedron.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d190f75c54ef3551fe776d59f69c4a0639fb7e7 Binary files /dev/null and b/shared/package-files/b6/b6bd2bcaecb8a8ded507b91f47d2101379174ec7cee30a00c704eb8be4b3e8f5/polyhedron.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6c0a17cb2ef15960d075cad569998008da9f89ff8bc5cb24e09442f420945fb/array.cpython-311.pyc b/shared/package-files/b6/b6c0a17cb2ef15960d075cad569998008da9f89ff8bc5cb24e09442f420945fb/array.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea146c3bff553e90acaf8bc48a0af7dbfd3de486 Binary files /dev/null and b/shared/package-files/b6/b6c0a17cb2ef15960d075cad569998008da9f89ff8bc5cb24e09442f420945fb/array.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6c1b42b63c8a4ba8112ed923958ad3e43d2bcfd289917fb5933471cce72ed1e/custom_ops.py b/shared/package-files/b6/b6c1b42b63c8a4ba8112ed923958ad3e43d2bcfd289917fb5933471cce72ed1e/custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..54392ebaf884fc40f076634f7d0cc0562d0b3c4a --- /dev/null +++ b/shared/package-files/b6/b6c1b42b63c8a4ba8112ed923958ad3e43d2bcfd289917fb5933471cce72ed1e/custom_ops.py @@ -0,0 +1,23 @@ +import torch + + +lib = torch.library.Library("export", "FRAGMENT") # noqa: TOR901 + +lib.define( + "access_subclass_inner_tensor(Tensor src_subclass_tensor, str attr) -> Tensor" +) + + +@torch.library.impl(lib, "access_subclass_inner_tensor", "Autograd") +def _access_subclass_inner_tensor( + src_subclass_tensor: torch.Tensor, attr: str +) -> torch.Tensor: + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + assert is_traceable_wrapper_subclass(src_subclass_tensor) + val = getattr(src_subclass_tensor, attr, None) + if val is None or not isinstance(val, torch.Tensor): + raise RuntimeError( + f"Attribute {attr} is not a tensor or doesn't exist in {src_subclass_tensor}" + ) + return val diff --git a/shared/package-files/b6/b6c2564b307fc3fcd84438961072782d92de32cd628bc574a41b08ba781ed837/assume.cpython-311.pyc b/shared/package-files/b6/b6c2564b307fc3fcd84438961072782d92de32cd628bc574a41b08ba781ed837/assume.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d0928f321f7a52de76fade55938ebec7ef517c2 Binary files /dev/null and b/shared/package-files/b6/b6c2564b307fc3fcd84438961072782d92de32cd628bc574a41b08ba781ed837/assume.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6c4764509dec77906d5793630e2ada9d702e31dcd4c9431d52dac72d9d07f58/_test_optional_intlist.h b/shared/package-files/b6/b6c4764509dec77906d5793630e2ada9d702e31dcd4c9431d52dac72d9d07f58/_test_optional_intlist.h new file mode 100644 index 0000000000000000000000000000000000000000..995bb5f2ba76cdb3745b1d91ec62fc768f7add77 --- /dev/null +++ b/shared/package-files/b6/b6c4764509dec77906d5793630e2ada9d702e31dcd4c9431d52dac72d9d07f58/_test_optional_intlist.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_test_optional_intlist(Tensor values, int[]? addends) -> Tensor +inline at::Tensor _test_optional_intlist(const at::Tensor & values, at::OptionalIntArrayRef addends) { + return at::_ops::_test_optional_intlist::call(values, addends); +} + +// aten::_test_optional_intlist.out(Tensor values, int[]? addends, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_optional_intlist_out(at::Tensor & out, const at::Tensor & values, at::OptionalIntArrayRef addends) { + return at::_ops::_test_optional_intlist_out::call(values, addends, out); +} +// aten::_test_optional_intlist.out(Tensor values, int[]? addends, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_optional_intlist_outf(const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out) { + return at::_ops::_test_optional_intlist_out::call(values, addends, out); +} + +} diff --git a/shared/package-files/b6/b6cb0234e19840fae77e43d2c7b23f33184fc4ad656200724763d367dd12f85c/delta_functions.cpython-311.pyc b/shared/package-files/b6/b6cb0234e19840fae77e43d2c7b23f33184fc4ad656200724763d367dd12f85c/delta_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7862897e7477ecf9f512a20ea1901e14815d642 Binary files /dev/null and b/shared/package-files/b6/b6cb0234e19840fae77e43d2c7b23f33184fc4ad656200724763d367dd12f85c/delta_functions.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6e8c07cde097ebea7fcce73df6ff84ad3b01e321de3e3d6a3a2e4c60da80d87/max_pool2d_with_indices_native.h b/shared/package-files/b6/b6e8c07cde097ebea7fcce73df6ff84ad3b01e321de3e3d6a3a2e4c60da80d87/max_pool2d_with_indices_native.h new file mode 100644 index 0000000000000000000000000000000000000000..5382df32fbd0cd3382d68979d2d164b5241f50e2 --- /dev/null +++ b/shared/package-files/b6/b6e8c07cde097ebea7fcce73df6ff84ad3b01e321de3e3d6a3a2e4c60da80d87/max_pool2d_with_indices_native.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_max_pool2d_with_indices_out_cpu : public at::meta::structured_max_pool2d_with_indices { +void impl(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & out, const at::Tensor & indices); +}; +struct TORCH_API structured_max_pool2d_with_indices_out_cuda : public at::meta::structured_max_pool2d_with_indices { +void impl(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, const at::Tensor & out, const at::Tensor & indices); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/b6/b6ed845677a7c549b87d9fe10d757832aac695ea01b49eacc150a659ac20cc72/_foreach_sub_ops.h b/shared/package-files/b6/b6ed845677a7c549b87d9fe10d757832aac695ea01b49eacc150a659ac20cc72/_foreach_sub_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..fc0946dd2016d67a8bdf6e4c31a15c8eea5d8c25 --- /dev/null +++ b/shared/package-files/b6/b6ed845677a7c549b87d9fe10d757832aac695ea01b49eacc150a659ac20cc72/_foreach_sub_ops.h @@ -0,0 +1,117 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_sub_Scalar { + using schema = ::std::vector (at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "Scalar"; + static constexpr const char* schema_str = "_foreach_sub.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]"; + static ::std::vector call(at::TensorList self, const at::Scalar & scalar); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar); +}; + +struct TORCH_API _foreach_sub__Scalar { + using schema = void (at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub_"; + static constexpr const char* overload_name = "Scalar"; + static constexpr const char* schema_str = "_foreach_sub_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()"; + static void call(at::TensorList self, const at::Scalar & scalar); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar); +}; + +struct TORCH_API _foreach_sub_List { + using schema = ::std::vector (at::TensorList, at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "List"; + static constexpr const char* schema_str = "_foreach_sub.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]"; + static ::std::vector call(at::TensorList self, at::TensorList other, const at::Scalar & alpha); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, const at::Scalar & alpha); +}; + +struct TORCH_API _foreach_sub__List { + using schema = void (at::TensorList, at::TensorList, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub_"; + static constexpr const char* overload_name = "List"; + static constexpr const char* schema_str = "_foreach_sub_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()"; + static void call(at::TensorList self, at::TensorList other, const at::Scalar & alpha); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, const at::Scalar & alpha); +}; + +struct TORCH_API _foreach_sub_ScalarList { + using schema = ::std::vector (at::TensorList, at::ArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "ScalarList"; + static constexpr const char* schema_str = "_foreach_sub.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]"; + static ::std::vector call(at::TensorList self, at::ArrayRef scalars); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars); +}; + +struct TORCH_API _foreach_sub__ScalarList { + using schema = void (at::TensorList, at::ArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub_"; + static constexpr const char* overload_name = "ScalarList"; + static constexpr const char* schema_str = "_foreach_sub_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()"; + static void call(at::TensorList self, at::ArrayRef scalars); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars); +}; + +struct TORCH_API _foreach_sub_Scalar_out { + using schema = void (at::TensorList, const at::Scalar &, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "Scalar_out"; + static constexpr const char* schema_str = "_foreach_sub.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, const at::Scalar & scalar, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar, at::TensorList out); +}; + +struct TORCH_API _foreach_sub_List_out { + using schema = void (at::TensorList, at::TensorList, const at::Scalar &, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "List_out"; + static constexpr const char* schema_str = "_foreach_sub.List_out(Tensor[] self, Tensor[] other, *, Scalar alpha=1, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, at::TensorList other, const at::Scalar & alpha, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, const at::Scalar & alpha, at::TensorList out); +}; + +struct TORCH_API _foreach_sub_ScalarList_out { + using schema = void (at::TensorList, at::ArrayRef, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_sub"; + static constexpr const char* overload_name = "ScalarList_out"; + static constexpr const char* schema_str = "_foreach_sub.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, at::ArrayRef scalars, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef scalars, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/b6/b6f37a9142597626529a4349dcae66b8d69bd60705cf645d173b91865fb515b4/DeviceAccelerator.h b/shared/package-files/b6/b6f37a9142597626529a4349dcae66b8d69bd60705cf645d173b91865fb515b4/DeviceAccelerator.h new file mode 100644 index 0000000000000000000000000000000000000000..60e74a90d604b4a512f5e3f189155958f741f055 --- /dev/null +++ b/shared/package-files/b6/b6f37a9142597626529a4349dcae66b8d69bd60705cf645d173b91865fb515b4/DeviceAccelerator.h @@ -0,0 +1,75 @@ +#pragma once + +#include +#include + +#include +#include + +namespace at::accelerator { + +// Note [Accelerator Concept] +// This file defines the top level Accelerator concept for PyTorch. +// A device is an accelerator per the definition here if: +// - It is mutually exclusive with all other accelerators +// - It performs asynchronous compute via a Stream/Event system +// - It provides a set of common APIs as defined by AcceleratorHooksInterface +// +// As of today, accelerator devices are (in no particular order): +// CUDA, MTIA, XPU, HIP, MPS, PrivateUse1 + +// Ensures that only one accelerator is available (at +// compile time if possible) and return it. +// When checked is true, the returned optional always has a value. +TORCH_API std::optional getAccelerator(bool checked = false); + +// Check if the given device type is an accelerator. +TORCH_API bool isAccelerator(c10::DeviceType device_type); + +// Check if the given device type is an accelerator, not an excluded one. +TORCH_API inline bool isAcceleratorExcluded( + c10::DeviceType device_type, + c10::DeviceType excluded) { + return device_type != excluded && isAccelerator(device_type); +} + +// Check if the given device type is an accelerator, not the excluded ones. +template < + typename... T, + typename = std::enable_if_t<(std::is_same_v && ...)>> +TORCH_API inline bool isAcceleratorExcluded( + c10::DeviceType device_type, + c10::DeviceType first_excluded, + T... rest_excluded) { + return device_type != first_excluded && + isAcceleratorExcluded(device_type, rest_excluded...); +} + +// Return the number of the device available. Note that this is *REQUIRED* to +// not raise any exception. +TORCH_API c10::DeviceIndex deviceCount(); + +// Set the current device index to the given device index. +TORCH_API void setDeviceIndex(c10::DeviceIndex device_index); + +// Get the current device index. +TORCH_API c10::DeviceIndex getDeviceIndex(); + +// Set the current stream to a given stream. Note that this API doesn't change +// the current device index. +TORCH_API void setCurrentStream(c10::Stream stream); + +// Get the current stream of the given device index. +TORCH_API c10::Stream getCurrentStream(c10::DeviceIndex device_index); + +// Wait (by blocking the calling thread) until all the work previously enqueued +// on the given device index has been completed. +TORCH_API void synchronizeDevice(c10::DeviceIndex device_index); + +} // namespace at::accelerator + +namespace at { +// Keep BC only +using at::accelerator::getAccelerator; +using at::accelerator::isAccelerator; +} // namespace at diff --git a/shared/package-files/b6/b6f497059cc056d9c070608f9be881abb95beaa2e8cc31312a43670756509516/algebraicconnectivity.cpython-311.pyc b/shared/package-files/b6/b6f497059cc056d9c070608f9be881abb95beaa2e8cc31312a43670756509516/algebraicconnectivity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d89771ea0da236af2a20b937df0353f6c853a82c Binary files /dev/null and b/shared/package-files/b6/b6f497059cc056d9c070608f9be881abb95beaa2e8cc31312a43670756509516/algebraicconnectivity.cpython-311.pyc differ diff --git a/shared/package-files/b6/b6f5e6b15ae57e173e06bddb69ee472a2b9096628f58bf6d4556e2ecc861669c/base.py b/shared/package-files/b6/b6f5e6b15ae57e173e06bddb69ee472a2b9096628f58bf6d4556e2ecc861669c/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e98f1157572bb91d72708e296702d9d4cd34eee8 --- /dev/null +++ b/shared/package-files/b6/b6f5e6b15ae57e173e06bddb69ee472a2b9096628f58bf6d4556e2ecc861669c/base.py @@ -0,0 +1,1391 @@ +""" +Base and utility classes for pandas objects. +""" + +from __future__ import annotations + +import textwrap +from typing import ( + TYPE_CHECKING, + Any, + Generic, + Literal, + cast, + final, + overload, +) +import warnings + +import numpy as np + +from pandas._config import using_copy_on_write + +from pandas._libs import lib +from pandas._typing import ( + AxisInt, + DtypeObj, + IndexLabel, + NDFrameT, + Self, + Shape, + npt, +) +from pandas.compat import PYPY +from pandas.compat.numpy import function as nv +from pandas.errors import AbstractMethodError +from pandas.util._decorators import ( + cache_readonly, + doc, +) +from pandas.util._exceptions import find_stack_level + +from pandas.core.dtypes.cast import can_hold_element +from pandas.core.dtypes.common import ( + is_object_dtype, + is_scalar, +) +from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCIndex, + ABCSeries, +) +from pandas.core.dtypes.missing import ( + isna, + remove_na_arraylike, +) + +from pandas.core import ( + algorithms, + nanops, + ops, +) +from pandas.core.accessor import DirNamesMixin +from pandas.core.arraylike import OpsMixin +from pandas.core.arrays import ExtensionArray +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) + +if TYPE_CHECKING: + from collections.abc import ( + Hashable, + Iterator, + ) + + from pandas._typing import ( + DropKeep, + NumpySorter, + NumpyValueArrayLike, + ScalarLike_co, + ) + + from pandas import ( + DataFrame, + Index, + Series, + ) + + +_shared_docs: dict[str, str] = {} +_indexops_doc_kwargs = { + "klass": "IndexOpsMixin", + "inplace": "", + "unique": "IndexOpsMixin", + "duplicated": "IndexOpsMixin", +} + + +class PandasObject(DirNamesMixin): + """ + Baseclass for various pandas objects. + """ + + # results from calls to methods decorated with cache_readonly get added to _cache + _cache: dict[str, Any] + + @property + def _constructor(self): + """ + Class constructor (for this class it's just `__class__`). + """ + return type(self) + + def __repr__(self) -> str: + """ + Return a string representation for a particular object. + """ + # Should be overwritten by base classes + return object.__repr__(self) + + def _reset_cache(self, key: str | None = None) -> None: + """ + Reset cached properties. If ``key`` is passed, only clears that key. + """ + if not hasattr(self, "_cache"): + return + if key is None: + self._cache.clear() + else: + self._cache.pop(key, None) + + def __sizeof__(self) -> int: + """ + Generates the total memory usage for an object that returns + either a value or Series of values + """ + memory_usage = getattr(self, "memory_usage", None) + if memory_usage: + mem = memory_usage(deep=True) # pylint: disable=not-callable + return int(mem if is_scalar(mem) else mem.sum()) + + # no memory_usage attribute, so fall back to object's 'sizeof' + return super().__sizeof__() + + +class NoNewAttributesMixin: + """ + Mixin which prevents adding new attributes. + + Prevents additional attributes via xxx.attribute = "something" after a + call to `self.__freeze()`. Mainly used to prevent the user from using + wrong attributes on an accessor (`Series.cat/.str/.dt`). + + If you really want to add a new attribute at a later time, you need to use + `object.__setattr__(self, key, value)`. + """ + + def _freeze(self) -> None: + """ + Prevents setting additional attributes. + """ + object.__setattr__(self, "__frozen", True) + + # prevent adding any attribute via s.xxx.new_attribute = ... + def __setattr__(self, key: str, value) -> None: + # _cache is used by a decorator + # We need to check both 1.) cls.__dict__ and 2.) getattr(self, key) + # because + # 1.) getattr is false for attributes that raise errors + # 2.) cls.__dict__ doesn't traverse into base classes + if getattr(self, "__frozen", False) and not ( + key == "_cache" + or key in type(self).__dict__ + or getattr(self, key, None) is not None + ): + raise AttributeError(f"You cannot add any new attribute '{key}'") + object.__setattr__(self, key, value) + + +class SelectionMixin(Generic[NDFrameT]): + """ + mixin implementing the selection & aggregation interface on a group-like + object sub-classes need to define: obj, exclusions + """ + + obj: NDFrameT + _selection: IndexLabel | None = None + exclusions: frozenset[Hashable] + _internal_names = ["_cache", "__setstate__"] + _internal_names_set = set(_internal_names) + + @final + @property + def _selection_list(self): + if not isinstance( + self._selection, (list, tuple, ABCSeries, ABCIndex, np.ndarray) + ): + return [self._selection] + return self._selection + + @cache_readonly + def _selected_obj(self): + if self._selection is None or isinstance(self.obj, ABCSeries): + return self.obj + else: + return self.obj[self._selection] + + @final + @cache_readonly + def ndim(self) -> int: + return self._selected_obj.ndim + + @final + @cache_readonly + def _obj_with_exclusions(self): + if isinstance(self.obj, ABCSeries): + return self.obj + + if self._selection is not None: + return self.obj._getitem_nocopy(self._selection_list) + + if len(self.exclusions) > 0: + # equivalent to `self.obj.drop(self.exclusions, axis=1) + # but this avoids consolidating and making a copy + # TODO: following GH#45287 can we now use .drop directly without + # making a copy? + return self.obj._drop_axis(self.exclusions, axis=1, only_slice=True) + else: + return self.obj + + def __getitem__(self, key): + if self._selection is not None: + raise IndexError(f"Column(s) {self._selection} already selected") + + if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)): + if len(self.obj.columns.intersection(key)) != len(set(key)): + bad_keys = list(set(key).difference(self.obj.columns)) + raise KeyError(f"Columns not found: {str(bad_keys)[1:-1]}") + return self._gotitem(list(key), ndim=2) + + else: + if key not in self.obj: + raise KeyError(f"Column not found: {key}") + ndim = self.obj[key].ndim + return self._gotitem(key, ndim=ndim) + + def _gotitem(self, key, ndim: int, subset=None): + """ + sub-classes to define + return a sliced object + + Parameters + ---------- + key : str / list of selections + ndim : {1, 2} + requested ndim of result + subset : object, default None + subset to act on + """ + raise AbstractMethodError(self) + + @final + def _infer_selection(self, key, subset: Series | DataFrame): + """ + Infer the `selection` to pass to our constructor in _gotitem. + """ + # Shared by Rolling and Resample + selection = None + if subset.ndim == 2 and ( + (lib.is_scalar(key) and key in subset) or lib.is_list_like(key) + ): + selection = key + elif subset.ndim == 1 and lib.is_scalar(key) and key == subset.name: + selection = key + return selection + + def aggregate(self, func, *args, **kwargs): + raise AbstractMethodError(self) + + agg = aggregate + + +class IndexOpsMixin(OpsMixin): + """ + Common ops mixin to support a unified interface / docs for Series / Index + """ + + # ndarray compatibility + __array_priority__ = 1000 + _hidden_attrs: frozenset[str] = frozenset( + ["tolist"] # tolist is not deprecated, just suppressed in the __dir__ + ) + + @property + def dtype(self) -> DtypeObj: + # must be defined here as a property for mypy + raise AbstractMethodError(self) + + @property + def _values(self) -> ExtensionArray | np.ndarray: + # must be defined here as a property for mypy + raise AbstractMethodError(self) + + @final + def transpose(self, *args, **kwargs) -> Self: + """ + Return the transpose, which is by definition self. + + Returns + ------- + %(klass)s + """ + nv.validate_transpose(args, kwargs) + return self + + T = property( + transpose, + doc=""" + Return the transpose, which is by definition self. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.T + 0 Ant + 1 Bear + 2 Cow + dtype: object + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx.T + Index([1, 2, 3], dtype='int64') + """, + ) + + @property + def shape(self) -> Shape: + """ + Return a tuple of the shape of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.shape + (3,) + """ + return self._values.shape + + def __len__(self) -> int: + # We need this defined here for mypy + raise AbstractMethodError(self) + + @property + def ndim(self) -> Literal[1]: + """ + Number of dimensions of the underlying data, by definition 1. + + Examples + -------- + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.ndim + 1 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.ndim + 1 + """ + return 1 + + @final + def item(self): + """ + Return the first element of the underlying data as a Python scalar. + + Returns + ------- + scalar + The first element of Series or Index. + + Raises + ------ + ValueError + If the data is not length = 1. + + Examples + -------- + >>> s = pd.Series([1]) + >>> s.item() + 1 + + For an index: + + >>> s = pd.Series([1], index=['a']) + >>> s.index.item() + 'a' + """ + if len(self) == 1: + return next(iter(self)) + raise ValueError("can only convert an array of size 1 to a Python scalar") + + @property + def nbytes(self) -> int: + """ + Return the number of bytes in the underlying data. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.nbytes + 24 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.nbytes + 24 + """ + return self._values.nbytes + + @property + def size(self) -> int: + """ + Return the number of elements in the underlying data. + + Examples + -------- + For Series: + + >>> s = pd.Series(['Ant', 'Bear', 'Cow']) + >>> s + 0 Ant + 1 Bear + 2 Cow + dtype: object + >>> s.size + 3 + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + >>> idx.size + 3 + """ + return len(self._values) + + @property + def array(self) -> ExtensionArray: + """ + The ExtensionArray of the data backing this Series or Index. + + Returns + ------- + ExtensionArray + An ExtensionArray of the values stored within. For extension + types, this is the actual array. For NumPy native types, this + is a thin (no copy) wrapper around :class:`numpy.ndarray`. + + ``.array`` differs from ``.values``, which may require converting + the data to a different form. + + See Also + -------- + Index.to_numpy : Similar method that always returns a NumPy array. + Series.to_numpy : Similar method that always returns a NumPy array. + + Notes + ----- + This table lays out the different array types for each extension + dtype within pandas. + + ================== ============================= + dtype array type + ================== ============================= + category Categorical + period PeriodArray + interval IntervalArray + IntegerNA IntegerArray + string StringArray + boolean BooleanArray + datetime64[ns, tz] DatetimeArray + ================== ============================= + + For any 3rd-party extension types, the array type will be an + ExtensionArray. + + For all remaining dtypes ``.array`` will be a + :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray + stored within. If you absolutely need a NumPy array (possibly with + copying / coercing data), then use :meth:`Series.to_numpy` instead. + + Examples + -------- + For regular NumPy types like int, and float, a NumpyExtensionArray + is returned. + + >>> pd.Series([1, 2, 3]).array + + [1, 2, 3] + Length: 3, dtype: int64 + + For extension types, like Categorical, the actual ExtensionArray + is returned + + >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) + >>> ser.array + ['a', 'b', 'a'] + Categories (2, object): ['a', 'b'] + """ + raise AbstractMethodError(self) + + @final + def to_numpy( + self, + dtype: npt.DTypeLike | None = None, + copy: bool = False, + na_value: object = lib.no_default, + **kwargs, + ) -> np.ndarray: + """ + A NumPy ndarray representing the values in this Series or Index. + + Parameters + ---------- + dtype : str or numpy.dtype, optional + The dtype to pass to :meth:`numpy.asarray`. + copy : bool, default False + Whether to ensure that the returned value is not a view on + another array. Note that ``copy=False`` does not *ensure* that + ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that + a copy is made, even if not strictly necessary. + na_value : Any, optional + The value to use for missing values. The default value depends + on `dtype` and the type of the array. + **kwargs + Additional keywords passed through to the ``to_numpy`` method + of the underlying array (for extension arrays). + + Returns + ------- + numpy.ndarray + + See Also + -------- + Series.array : Get the actual data stored within. + Index.array : Get the actual data stored within. + DataFrame.to_numpy : Similar method for DataFrame. + + Notes + ----- + The returned array will be the same up to equality (values equal + in `self` will be equal in the returned array; likewise for values + that are not equal). When `self` contains an ExtensionArray, the + dtype may be different. For example, for a category-dtype Series, + ``to_numpy()`` will return a NumPy array and the categorical dtype + will be lost. + + For NumPy dtypes, this will be a reference to the actual data stored + in this Series or Index (assuming ``copy=False``). Modifying the result + in place will modify the data stored in the Series or Index (not that + we recommend doing that). + + For extension types, ``to_numpy()`` *may* require copying data and + coercing the result to a NumPy type (possibly object), which may be + expensive. When you need a no-copy reference to the underlying data, + :attr:`Series.array` should be used instead. + + This table lays out the different dtypes and default return types of + ``to_numpy()`` for various dtypes within pandas. + + ================== ================================ + dtype array type + ================== ================================ + category[T] ndarray[T] (same dtype as input) + period ndarray[object] (Periods) + interval ndarray[object] (Intervals) + IntegerNA ndarray[object] + datetime64[ns] datetime64[ns] + datetime64[ns, tz] ndarray[object] (Timestamps) + ================== ================================ + + Examples + -------- + >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) + >>> ser.to_numpy() + array(['a', 'b', 'a'], dtype=object) + + Specify the `dtype` to control how datetime-aware data is represented. + Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp` + objects, each with the correct ``tz``. + + >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) + >>> ser.to_numpy(dtype=object) + array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'), + Timestamp('2000-01-02 00:00:00+0100', tz='CET')], + dtype=object) + + Or ``dtype='datetime64[ns]'`` to return an ndarray of native + datetime64 values. The values are converted to UTC and the timezone + info is dropped. + + >>> ser.to_numpy(dtype="datetime64[ns]") + ... # doctest: +ELLIPSIS + array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'], + dtype='datetime64[ns]') + """ + if isinstance(self.dtype, ExtensionDtype): + return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs) + elif kwargs: + bad_keys = next(iter(kwargs.keys())) + raise TypeError( + f"to_numpy() got an unexpected keyword argument '{bad_keys}'" + ) + + fillna = ( + na_value is not lib.no_default + # no need to fillna with np.nan if we already have a float dtype + and not (na_value is np.nan and np.issubdtype(self.dtype, np.floating)) + ) + + values = self._values + if fillna: + if not can_hold_element(values, na_value): + # if we can't hold the na_value asarray either makes a copy or we + # error before modifying values. The asarray later on thus won't make + # another copy + values = np.asarray(values, dtype=dtype) + else: + values = values.copy() + + values[np.asanyarray(isna(self))] = na_value + + result = np.asarray(values, dtype=dtype) + + if (copy and not fillna) or (not copy and using_copy_on_write()): + if np.shares_memory(self._values[:2], result[:2]): + # Take slices to improve performance of check + if using_copy_on_write() and not copy: + result = result.view() + result.flags.writeable = False + else: + result = result.copy() + + return result + + @final + @property + def empty(self) -> bool: + return not self.size + + @doc(op="max", oppose="min", value="largest") + def argmax( + self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs + ) -> int: + """ + Return int position of the {value} value in the Series. + + If the {op}imum is achieved in multiple locations, + the first row position is returned. + + Parameters + ---------- + axis : {{None}} + Unused. Parameter needed for compatibility with DataFrame. + skipna : bool, default True + Exclude NA/null values when showing the result. + *args, **kwargs + Additional arguments and keywords for compatibility with NumPy. + + Returns + ------- + int + Row position of the {op}imum value. + + See Also + -------- + Series.arg{op} : Return position of the {op}imum value. + Series.arg{oppose} : Return position of the {oppose}imum value. + numpy.ndarray.arg{op} : Equivalent method for numpy arrays. + Series.idxmax : Return index label of the maximum values. + Series.idxmin : Return index label of the minimum values. + + Examples + -------- + Consider dataset containing cereal calories + + >>> s = pd.Series({{'Corn Flakes': 100.0, 'Almond Delight': 110.0, + ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}}) + >>> s + Corn Flakes 100.0 + Almond Delight 110.0 + Cinnamon Toast Crunch 120.0 + Cocoa Puff 110.0 + dtype: float64 + + >>> s.argmax() + 2 + >>> s.argmin() + 0 + + The maximum cereal calories is the third element and + the minimum cereal calories is the first element, + since series is zero-indexed. + """ + delegate = self._values + nv.validate_minmax_axis(axis) + skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs) + + if isinstance(delegate, ExtensionArray): + if not skipna and delegate.isna().any(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + else: + return delegate.argmax() + else: + result = nanops.nanargmax(delegate, skipna=skipna) + if result == -1: + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return result # type: ignore[return-value] + + @doc(argmax, op="min", oppose="max", value="smallest") + def argmin( + self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs + ) -> int: + delegate = self._values + nv.validate_minmax_axis(axis) + skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs) + + if isinstance(delegate, ExtensionArray): + if not skipna and delegate.isna().any(): + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + return -1 + else: + return delegate.argmin() + else: + result = nanops.nanargmin(delegate, skipna=skipna) + if result == -1: + warnings.warn( + f"The behavior of {type(self).__name__}.argmax/argmin " + "with skipna=False and NAs, or with all-NAs is deprecated. " + "In a future version this will raise ValueError.", + FutureWarning, + stacklevel=find_stack_level(), + ) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return result # type: ignore[return-value] + + def tolist(self): + """ + Return a list of the values. + + These are each a scalar type, which is a Python scalar + (for str, int, float) or a pandas scalar + (for Timestamp/Timedelta/Interval/Period) + + Returns + ------- + list + + See Also + -------- + numpy.ndarray.tolist : Return the array as an a.ndim-levels deep + nested list of Python scalars. + + Examples + -------- + For Series + + >>> s = pd.Series([1, 2, 3]) + >>> s.to_list() + [1, 2, 3] + + For Index: + + >>> idx = pd.Index([1, 2, 3]) + >>> idx + Index([1, 2, 3], dtype='int64') + + >>> idx.to_list() + [1, 2, 3] + """ + return self._values.tolist() + + to_list = tolist + + def __iter__(self) -> Iterator: + """ + Return an iterator of the values. + + These are each a scalar type, which is a Python scalar + (for str, int, float) or a pandas scalar + (for Timestamp/Timedelta/Interval/Period) + + Returns + ------- + iterator + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> for x in s: + ... print(x) + 1 + 2 + 3 + """ + # We are explicitly making element iterators. + if not isinstance(self._values, np.ndarray): + # Check type instead of dtype to catch DTA/TDA + return iter(self._values) + else: + return map(self._values.item, range(self._values.size)) + + @cache_readonly + def hasnans(self) -> bool: + """ + Return True if there are any NaNs. + + Enables various performance speedups. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 3, None]) + >>> s + 0 1.0 + 1 2.0 + 2 3.0 + 3 NaN + dtype: float64 + >>> s.hasnans + True + """ + # error: Item "bool" of "Union[bool, ndarray[Any, dtype[bool_]], NDFrame]" + # has no attribute "any" + return bool(isna(self).any()) # type: ignore[union-attr] + + @final + def _map_values(self, mapper, na_action=None, convert: bool = True): + """ + An internal function that maps values using the input + correspondence (which can be a dict, Series, or function). + + Parameters + ---------- + mapper : function, dict, or Series + The input correspondence object + na_action : {None, 'ignore'} + If 'ignore', propagate NA values, without passing them to the + mapping function + convert : bool, default True + Try to find better dtype for elementwise function results. If + False, leave as dtype=object. Note that the dtype is always + preserved for some extension array dtypes, such as Categorical. + + Returns + ------- + Union[Index, MultiIndex], inferred + The output of the mapping function applied to the index. + If the function returns a tuple with more than one element + a MultiIndex will be returned. + """ + arr = self._values + + if isinstance(arr, ExtensionArray): + return arr.map(mapper, na_action=na_action) + + return algorithms.map_array(arr, mapper, na_action=na_action, convert=convert) + + @final + def value_counts( + self, + normalize: bool = False, + sort: bool = True, + ascending: bool = False, + bins=None, + dropna: bool = True, + ) -> Series: + """ + Return a Series containing counts of unique values. + + The resulting object will be in descending order so that the + first element is the most frequently-occurring element. + Excludes NA values by default. + + Parameters + ---------- + normalize : bool, default False + If True then the object returned will contain the relative + frequencies of the unique values. + sort : bool, default True + Sort by frequencies when True. Preserve the order of the data when False. + ascending : bool, default False + Sort in ascending order. + bins : int, optional + Rather than count values, group them into half-open bins, + a convenience for ``pd.cut``, only works with numeric data. + dropna : bool, default True + Don't include counts of NaN. + + Returns + ------- + Series + + See Also + -------- + Series.count: Number of non-NA elements in a Series. + DataFrame.count: Number of non-NA elements in a DataFrame. + DataFrame.value_counts: Equivalent method on DataFrames. + + Examples + -------- + >>> index = pd.Index([3, 1, 2, 3, 4, np.nan]) + >>> index.value_counts() + 3.0 2 + 1.0 1 + 2.0 1 + 4.0 1 + Name: count, dtype: int64 + + With `normalize` set to `True`, returns the relative frequency by + dividing all values by the sum of values. + + >>> s = pd.Series([3, 1, 2, 3, 4, np.nan]) + >>> s.value_counts(normalize=True) + 3.0 0.4 + 1.0 0.2 + 2.0 0.2 + 4.0 0.2 + Name: proportion, dtype: float64 + + **bins** + + Bins can be useful for going from a continuous variable to a + categorical variable; instead of counting unique + apparitions of values, divide the index in the specified + number of half-open bins. + + >>> s.value_counts(bins=3) + (0.996, 2.0] 2 + (2.0, 3.0] 2 + (3.0, 4.0] 1 + Name: count, dtype: int64 + + **dropna** + + With `dropna` set to `False` we can also see NaN index values. + + >>> s.value_counts(dropna=False) + 3.0 2 + 1.0 1 + 2.0 1 + 4.0 1 + NaN 1 + Name: count, dtype: int64 + """ + return algorithms.value_counts_internal( + self, + sort=sort, + ascending=ascending, + normalize=normalize, + bins=bins, + dropna=dropna, + ) + + def unique(self): + values = self._values + if not isinstance(values, np.ndarray): + # i.e. ExtensionArray + result = values.unique() + else: + result = algorithms.unique1d(values) + return result + + @final + def nunique(self, dropna: bool = True) -> int: + """ + Return number of unique elements in the object. + + Excludes NA values by default. + + Parameters + ---------- + dropna : bool, default True + Don't include NaN in the count. + + Returns + ------- + int + + See Also + -------- + DataFrame.nunique: Method nunique for DataFrame. + Series.count: Count non-NA/null observations in the Series. + + Examples + -------- + >>> s = pd.Series([1, 3, 5, 7, 7]) + >>> s + 0 1 + 1 3 + 2 5 + 3 7 + 4 7 + dtype: int64 + + >>> s.nunique() + 4 + """ + uniqs = self.unique() + if dropna: + uniqs = remove_na_arraylike(uniqs) + return len(uniqs) + + @property + def is_unique(self) -> bool: + """ + Return boolean if values in the object are unique. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.is_unique + True + + >>> s = pd.Series([1, 2, 3, 1]) + >>> s.is_unique + False + """ + return self.nunique(dropna=False) == len(self) + + @property + def is_monotonic_increasing(self) -> bool: + """ + Return boolean if values in the object are monotonically increasing. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([1, 2, 2]) + >>> s.is_monotonic_increasing + True + + >>> s = pd.Series([3, 2, 1]) + >>> s.is_monotonic_increasing + False + """ + from pandas import Index + + return Index(self).is_monotonic_increasing + + @property + def is_monotonic_decreasing(self) -> bool: + """ + Return boolean if values in the object are monotonically decreasing. + + Returns + ------- + bool + + Examples + -------- + >>> s = pd.Series([3, 2, 2, 1]) + >>> s.is_monotonic_decreasing + True + + >>> s = pd.Series([1, 2, 3]) + >>> s.is_monotonic_decreasing + False + """ + from pandas import Index + + return Index(self).is_monotonic_decreasing + + @final + def _memory_usage(self, deep: bool = False) -> int: + """ + Memory usage of the values. + + Parameters + ---------- + deep : bool, default False + Introspect the data deeply, interrogate + `object` dtypes for system-level memory consumption. + + Returns + ------- + bytes used + + See Also + -------- + numpy.ndarray.nbytes : Total bytes consumed by the elements of the + array. + + Notes + ----- + Memory usage does not include memory consumed by elements that + are not components of the array if deep=False or if used on PyPy + + Examples + -------- + >>> idx = pd.Index([1, 2, 3]) + >>> idx.memory_usage() + 24 + """ + if hasattr(self.array, "memory_usage"): + return self.array.memory_usage( # pyright: ignore[reportGeneralTypeIssues] + deep=deep, + ) + + v = self.array.nbytes + if deep and is_object_dtype(self.dtype) and not PYPY: + values = cast(np.ndarray, self._values) + v += lib.memory_usage_of_objects(values) + return v + + @doc( + algorithms.factorize, + values="", + order="", + size_hint="", + sort=textwrap.dedent( + """\ + sort : bool, default False + Sort `uniques` and shuffle `codes` to maintain the + relationship. + """ + ), + ) + def factorize( + self, + sort: bool = False, + use_na_sentinel: bool = True, + ) -> tuple[npt.NDArray[np.intp], Index]: + codes, uniques = algorithms.factorize( + self._values, sort=sort, use_na_sentinel=use_na_sentinel + ) + if uniques.dtype == np.float16: + uniques = uniques.astype(np.float32) + + if isinstance(self, ABCIndex): + # preserve e.g. MultiIndex + uniques = self._constructor(uniques) + else: + from pandas import Index + + uniques = Index(uniques) + return codes, uniques + + _shared_docs[ + "searchsorted" + ] = """ + Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted {klass} `self` such that, if the + corresponding elements in `value` were inserted before the indices, + the order of `self` would be preserved. + + .. note:: + + The {klass} *must* be monotonically sorted, otherwise + wrong locations will likely be returned. Pandas does *not* + check this for you. + + Parameters + ---------- + value : array-like or scalar + Values to insert into `self`. + side : {{'left', 'right'}}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `self`). + sorter : 1-D array-like, optional + Optional array of integer indices that sort `self` into ascending + order. They are typically the result of ``np.argsort``. + + Returns + ------- + int or array of int + A scalar or array of insertion points with the + same shape as `value`. + + See Also + -------- + sort_values : Sort by the values along either axis. + numpy.searchsorted : Similar method from NumPy. + + Notes + ----- + Binary search is used to find the required insertion points. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + >>> ser + 0 1 + 1 2 + 2 3 + dtype: int64 + + >>> ser.searchsorted(4) + 3 + + >>> ser.searchsorted([0, 4]) + array([0, 3]) + + >>> ser.searchsorted([1, 3], side='left') + array([0, 2]) + + >>> ser.searchsorted([1, 3], side='right') + array([1, 3]) + + >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'])) + >>> ser + 0 2000-03-11 + 1 2000-03-12 + 2 2000-03-13 + dtype: datetime64[ns] + + >>> ser.searchsorted('3/14/2000') + 3 + + >>> ser = pd.Categorical( + ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True + ... ) + >>> ser + ['apple', 'bread', 'bread', 'cheese', 'milk'] + Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk'] + + >>> ser.searchsorted('bread') + 1 + + >>> ser.searchsorted(['bread'], side='right') + array([3]) + + If the values are not monotonically sorted, wrong locations + may be returned: + + >>> ser = pd.Series([2, 1, 3]) + >>> ser + 0 2 + 1 1 + 2 3 + dtype: int64 + + >>> ser.searchsorted(1) # doctest: +SKIP + 0 # wrong result, correct would be 1 + """ + + # This overload is needed so that the call to searchsorted in + # pandas.core.resample.TimeGrouper._get_period_bins picks the correct result + + # error: Overloaded function signatures 1 and 2 overlap with incompatible + # return types + @overload + def searchsorted( # type: ignore[overload-overlap] + self, + value: ScalarLike_co, + side: Literal["left", "right"] = ..., + sorter: NumpySorter = ..., + ) -> np.intp: + ... + + @overload + def searchsorted( + self, + value: npt.ArrayLike | ExtensionArray, + side: Literal["left", "right"] = ..., + sorter: NumpySorter = ..., + ) -> npt.NDArray[np.intp]: + ... + + @doc(_shared_docs["searchsorted"], klass="Index") + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + if isinstance(value, ABCDataFrame): + msg = ( + "Value must be 1-D array-like or scalar, " + f"{type(value).__name__} is not supported" + ) + raise ValueError(msg) + + values = self._values + if not isinstance(values, np.ndarray): + # Going through EA.searchsorted directly improves performance GH#38083 + return values.searchsorted(value, side=side, sorter=sorter) + + return algorithms.searchsorted( + values, + value, + side=side, + sorter=sorter, + ) + + def drop_duplicates(self, *, keep: DropKeep = "first"): + duplicated = self._duplicated(keep=keep) + # error: Value of type "IndexOpsMixin" is not indexable + return self[~duplicated] # type: ignore[index] + + @final + def _duplicated(self, keep: DropKeep = "first") -> npt.NDArray[np.bool_]: + arr = self._values + if isinstance(arr, ExtensionArray): + return arr.duplicated(keep=keep) + return algorithms.duplicated(arr, keep=keep) + + def _arith_method(self, other, op): + res_name = ops.get_op_result_name(self, other) + + lvalues = self._values + rvalues = extract_array(other, extract_numpy=True, extract_range=True) + rvalues = ops.maybe_prepare_scalar_for_op(rvalues, lvalues.shape) + rvalues = ensure_wrapped_if_datetimelike(rvalues) + if isinstance(rvalues, range): + rvalues = np.arange(rvalues.start, rvalues.stop, rvalues.step) + + with np.errstate(all="ignore"): + result = ops.arithmetic_op(lvalues, rvalues, op) + + return self._construct_result(result, name=res_name) + + def _construct_result(self, result, name): + """ + Construct an appropriately-wrapped result from the ArrayLike result + of an arithmetic-like operation. + """ + raise AbstractMethodError(self) diff --git a/shared/package-files/b6/b6f63dcb74dd39147e9c5066d11fdcf3b8f9a802e4235629e70c85ed01436167/__init__.cpython-311.pyc b/shared/package-files/b6/b6f63dcb74dd39147e9c5066d11fdcf3b8f9a802e4235629e70c85ed01436167/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..271c755134eb73ebc8ff0358d18d4071a523fb4c Binary files /dev/null and b/shared/package-files/b6/b6f63dcb74dd39147e9c5066d11fdcf3b8f9a802e4235629e70c85ed01436167/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc00072eb4512aff43ccbe82e73f4573ccf41e36015a8097434105b7398f3707/gmpyfinitefield.cpython-311.pyc b/shared/package-files/bc/bc00072eb4512aff43ccbe82e73f4573ccf41e36015a8097434105b7398f3707/gmpyfinitefield.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c425a99ca81511a24f433e05a588574be18c83e7 Binary files /dev/null and b/shared/package-files/bc/bc00072eb4512aff43ccbe82e73f4573ccf41e36015a8097434105b7398f3707/gmpyfinitefield.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc0c70aae73c02b4d013d50d6ec3b6d45a926ba275eec085f80e2f8533d72d8d/test_mathematica.py b/shared/package-files/bc/bc0c70aae73c02b4d013d50d6ec3b6d45a926ba275eec085f80e2f8533d72d8d/test_mathematica.py new file mode 100644 index 0000000000000000000000000000000000000000..df193b6d61f9c82778d8e0a40b893cbe6cb8f06a --- /dev/null +++ b/shared/package-files/bc/bc0c70aae73c02b4d013d50d6ec3b6d45a926ba275eec085f80e2f8533d72d8d/test_mathematica.py @@ -0,0 +1,280 @@ +from sympy import sin, Function, symbols, Dummy, Lambda, cos +from sympy.parsing.mathematica import parse_mathematica, MathematicaParser +from sympy.core.sympify import sympify +from sympy.abc import n, w, x, y, z +from sympy.testing.pytest import raises + + +def test_mathematica(): + d = { + '- 6x': '-6*x', + 'Sin[x]^2': 'sin(x)**2', + '2(x-1)': '2*(x-1)', + '3y+8': '3*y+8', + 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x', + 'x+y': 'x+y', + '355/113': '355/113', + '2.718281828': '2.718281828', + 'Cos(1/2 * π)': 'Cos(π/2)', + 'Sin[12]': 'sin(12)', + 'Exp[Log[4]]': 'exp(log(4))', + '(x+1)(x+3)': '(x+1)*(x+3)', + 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))', + 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))', + '2*Sin[x+y]': '2*sin(x+y)', + 'Sin[x]+Cos[y]': 'sin(x)+cos(y)', + 'Sin[Cos[x]]': 'sin(cos(x))', + '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259 + '+Sqrt[2]': 'sqrt(2)', + '-Sqrt[2]': '-sqrt(2)', + '-1/Sqrt[2]': '-1/sqrt(2)', + '-(1/Sqrt[3])': '-(1/sqrt(3))', + '1/(2*Sqrt[5])': '1/(2*sqrt(5))', + 'Mod[5,3]': 'Mod(5,3)', + '-Mod[5,3]': '-Mod(5,3)', + '(x+1)y': '(x+1)*y', + 'x(y+1)': 'x*(y+1)', + 'Sin[x]Cos[y]': 'sin(x)*cos(y)', + 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2', + 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)', + 'x y': 'x*y', + 'x y': 'x*y', + '2 x': '2*x', + 'x 8': 'x*8', + '2 8': '2*8', + '4.x': '4.*x', + '4. 3': '4.*3', + '4. 3.': '4.*3.', + '1 2 3': '1*2*3', + ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))', + 'Log[2,4]': 'log(4,2)', + 'Log[Log[2,4],4]': 'log(4,log(4,2))', + 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))', + 'ArcSin[Cos[0]]': 'asin(cos(0))', + 'Log2[16]': 'log(16,2)', + 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)', + 'Min[1,-2,3]': 'Min(1,-2,3)', + 'Exp[I Pi/2]': 'exp(I*pi/2)', + 'ArcTan[x,y]': 'atan2(y,x)', + 'Pochhammer[x,y]': 'rf(x,y)', + 'ExpIntegralEi[x]': 'Ei(x)', + 'SinIntegral[x]': 'Si(x)', + 'CosIntegral[x]': 'Ci(x)', + 'AiryAi[x]': 'airyai(x)', + 'AiryAiPrime[5]': 'airyaiprime(5)', + 'AiryBi[x]': 'airybi(x)', + 'AiryBiPrime[7]': 'airybiprime(7)', + 'LogIntegral[4]': ' li(4)', + 'PrimePi[7]': 'primepi(7)', + 'Prime[5]': 'prime(5)', + 'PrimeQ[5]': 'isprime(5)', + 'Rational[2,19]': 'Rational(2,19)', # test case for issue 25716 + } + + for e in d: + assert parse_mathematica(e) == sympify(d[e]) + + # The parsed form of this expression should not evaluate the Lambda object: + assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2 + + d1, d2, d3 = symbols("d1:4", cls=Dummy) + assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3))) + assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2))) + assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3) + assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2) + + +def test_parser_mathematica_tokenizer(): + parser = MathematicaParser() + + chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr)) + + # Basic patterns + assert chain("x") == "x" + assert chain("42") == "42" + assert chain(".2") == ".2" + assert chain("+x") == "x" + assert chain("-1") == "-1" + assert chain("- 3") == "-3" + assert chain("α") == "α" + assert chain("+Sin[x]") == ["Sin", "x"] + assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]] + assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]] + assert chain("(x)") == "x" + assert chain("(+x)") == "x" + assert chain("-a") == ["Times", "-1", "a"] + assert chain("(-x)") == ["Times", "-1", "x"] + assert chain("(x + y)") == ["Plus", "x", "y"] + assert chain("3 + 4") == ["Plus", "3", "4"] + assert chain("a - 3") == ["Plus", "a", "-3"] + assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]] + assert chain("7 * 8") == ["Times", "7", "8"] + assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]] + assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]] + assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]] + + # Missing asterisk (*) patterns: + assert chain("x y") == ["Times", "x", "y"] + assert chain("3 4") == ["Times", "3", "4"] + assert chain("a[b] c") == ["Times", ["a", "b"], "c"] + assert chain("(x) (y)") == ["Times", "x", "y"] + assert chain("3 (a)") == ["Times", "3", "a"] + assert chain("(a) b") == ["Times", "a", "b"] + assert chain("4.2") == "4.2" + assert chain("4 2") == ["Times", "4", "2"] + assert chain("4 2") == ["Times", "4", "2"] + assert chain("3 . 4") == ["Dot", "3", "4"] + assert chain("4. 2") == ["Times", "4.", "2"] + assert chain("x.y") == ["Dot", "x", "y"] + assert chain("4.y") == ["Times", "4.", "y"] + assert chain("4 .y") == ["Dot", "4", "y"] + assert chain("x.4") == ["Times", "x", ".4"] + assert chain("x0.3") == ["Times", "x0", ".3"] + assert chain("x. 4") == ["Dot", "x", "4"] + + # Comments + assert chain("a (* +b *) + c") == ["Plus", "a", "c"] + assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"] + assert chain("""a + (* + + b + *) c + (* d + *) e + """) == ["Plus", "a", "c", "e"] + + # Operators couples + and -, * and / are mutually associative: + # (i.e. expression gets flattened when mixing these operators) + assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]] + assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"] + assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]] + assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"] + assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]] + assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"] + assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]] + assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]] + assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]] + assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]] + assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"] + + # Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { } + assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"] + assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"] + assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]] + assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]] + assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"] + assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]] + assert chain("{{a}}") == ["List", ["List", "a"]] + assert chain("a[b, c]") == ["a", "b", "c"] + assert chain("a[[b, c]]") == ["Part", "a", "b", "c"] + assert chain("a[b[c]]") == ["a", ["b", "c"]] + assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]] + assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]] + assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]] + assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]] + assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]] + assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]] + assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] + assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] + assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] + + # Flat operator: + assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"] + assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"] + + # Right priority operator: + assert chain("a^b") == ["Power", "a", "b"] + assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]] + assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]] + + # Left priority operator: + assert chain("a/.b") == ["ReplaceAll", "a", "b"] + assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"] + + assert chain("a//b") == ["a", "b"] + assert chain("a//b//c") == [["a", "b"], "c"] + assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"] + + # Compound expressions + assert chain("a;b") == ["CompoundExpression", "a", "b"] + assert chain("a;") == ["CompoundExpression", "a", "Null"] + assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"] + assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]] + assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"] + assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"] + + # New lines + assert chain("a\nb\n") == ["CompoundExpression", "a", "b"] + assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]] + assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"] + assert chain("a + \nb\n") == ["Plus", "a", "b"] + assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]] + assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]] + + # Patterns + assert chain("y_") == ["Pattern", "y", ["Blank"]] + assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]] + assert chain("y__") == ["Pattern", "y", ["BlankSequence"]] + assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]] + assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]] + assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"] + + # Slots for lambda functions + assert chain("#") == ["Slot", "1"] + assert chain("#3") == ["Slot", "3"] + assert chain("#n") == ["Slot", "n"] + assert chain("##") == ["SlotSequence", "1"] + assert chain("##a") == ["SlotSequence", "a"] + + # Lambda functions + assert chain("x&") == ["Function", "x"] + assert chain("#&") == ["Function", ["Slot", "1"]] + assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]] + assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]] + assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]] + assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"] + assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"] + assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]] + + # Strings inside Mathematica expressions: + assert chain('"abc"') == ["_Str", "abc"] + assert chain('"a\\"b"') == ["_Str", 'a"b'] + # This expression does not make sense mathematically, it's just testing the parser: + assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]] + assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"] + assert chain('"a" (* b *) ') == ["_Str", "a"] + assert chain('"a [ b] "') == ["_Str", "a [ b] "] + raises(SyntaxError, lambda: chain('"')) + raises(SyntaxError, lambda: chain('"\\"')) + raises(SyntaxError, lambda: chain('"abc')) + raises(SyntaxError, lambda: chain('"abc\\"def')) + + # Invalid expressions: + raises(SyntaxError, lambda: chain("(,")) + raises(SyntaxError, lambda: chain("()")) + raises(SyntaxError, lambda: chain("a (* b")) + + +def test_parser_mathematica_exp_alt(): + parser = MathematicaParser() + + convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr)) + convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr)) + + Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function) + + full_form1 = "Sin[Times[x, y]]" + full_form2 = "Plus[Times[x, y], z]" + full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]" + full_form4 = "Rational[Rational[x, y], z]" + + assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]] + assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"] + assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]] + assert parser._from_fullform_to_fullformlist(full_form4) == ["Rational", ["Rational", "x", "y"], "z"] + + assert convert_chain2(full_form1) == Sin(Times(x, y)) + assert convert_chain2(full_form2) == Plus(Times(x, y), z) + assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n))) + + assert convert_chain3(full_form1) == sin(x*y) + assert convert_chain3(full_form2) == x*y + z + assert convert_chain3(full_form3) == sin(x*(y + z)*w**n) diff --git a/shared/package-files/bc/bc0d5e9cff2e2aaf1ec6624f738cfe065802312e062586389ee4e46411731a00/_dtypes.py b/shared/package-files/bc/bc0d5e9cff2e2aaf1ec6624f738cfe065802312e062586389ee4e46411731a00/_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..27799adaf56376433ccc27e2181e4751dccde685 --- /dev/null +++ b/shared/package-files/bc/bc0d5e9cff2e2aaf1ec6624f738cfe065802312e062586389ee4e46411731a00/_dtypes.py @@ -0,0 +1,453 @@ +# mypy: ignore-errors + +""" Define analogs of numpy dtypes supported by pytorch. +Define the scalar types and supported dtypes and numpy <--> torch dtype mappings. +""" +import builtins + +import torch + +from . import _dtypes_impl + + +# ### Scalar types ### + + +class generic: + name = "generic" + + def __new__(cls, value): + # NumPy scalars are modelled as 0-D arrays + # so a call to np.float32(4) produces a 0-D array. + + from ._ndarray import asarray, ndarray + + if isinstance(value, str) and value in ["inf", "nan"]: + value = {"inf": torch.inf, "nan": torch.nan}[value] + + if isinstance(value, ndarray): + return value.astype(cls) + else: + return asarray(value, dtype=cls) + + +################## +# abstract types # +################## + + +class number(generic): + name = "number" + + +class integer(number): + name = "integer" + + +class inexact(number): + name = "inexact" + + +class signedinteger(integer): + name = "signedinteger" + + +class unsignedinteger(integer): + name = "unsignedinteger" + + +class floating(inexact): + name = "floating" + + +class complexfloating(inexact): + name = "complexfloating" + + +_abstract_dtypes = [ + "generic", + "number", + "integer", + "signedinteger", + "unsignedinteger", + "inexact", + "floating", + "complexfloating", +] + +# ##### concrete types + +# signed integers + + +class int8(signedinteger): + name = "int8" + typecode = "b" + torch_dtype = torch.int8 + + +class int16(signedinteger): + name = "int16" + typecode = "h" + torch_dtype = torch.int16 + + +class int32(signedinteger): + name = "int32" + typecode = "i" + torch_dtype = torch.int32 + + +class int64(signedinteger): + name = "int64" + typecode = "l" + torch_dtype = torch.int64 + + +# unsigned integers + + +class uint8(unsignedinteger): + name = "uint8" + typecode = "B" + torch_dtype = torch.uint8 + + +class uint16(unsignedinteger): + name = "uint16" + typecode = "H" + torch_dtype = torch.uint16 + + +class uint32(signedinteger): + name = "uint32" + typecode = "I" + torch_dtype = torch.uint32 + + +class uint64(signedinteger): + name = "uint64" + typecode = "L" + torch_dtype = torch.uint64 + + +# floating point + + +class float16(floating): + name = "float16" + typecode = "e" + torch_dtype = torch.float16 + + +class float32(floating): + name = "float32" + typecode = "f" + torch_dtype = torch.float32 + + +class float64(floating): + name = "float64" + typecode = "d" + torch_dtype = torch.float64 + + +class complex64(complexfloating): + name = "complex64" + typecode = "F" + torch_dtype = torch.complex64 + + +class complex128(complexfloating): + name = "complex128" + typecode = "D" + torch_dtype = torch.complex128 + + +class bool_(generic): + name = "bool_" + typecode = "?" + torch_dtype = torch.bool + + +# name aliases +_name_aliases = { + "intp": int64, + "int_": int64, + "intc": int32, + "byte": int8, + "short": int16, + "longlong": int64, # XXX: is this correct? + "ulonglong": uint64, + "ubyte": uint8, + "half": float16, + "single": float32, + "double": float64, + "float_": float64, + "csingle": complex64, + "singlecomplex": complex64, + "cdouble": complex128, + "cfloat": complex128, + "complex_": complex128, +} +# We register float_ = float32 and so on +for name, obj in _name_aliases.items(): + vars()[name] = obj + + +# Replicate this NumPy-defined way of grouping scalar types, +# cf tests/core/test_scalar_methods.py +sctypes = { + "int": [int8, int16, int32, int64], + "uint": [uint8, uint16, uint32, uint64], + "float": [float16, float32, float64], + "complex": [complex64, complex128], + "others": [bool_], +} + + +# Support mappings/functions + +_names = {st.name: st for cat in sctypes for st in sctypes[cat]} +_typecodes = {st.typecode: st for cat in sctypes for st in sctypes[cat]} +_torch_dtypes = {st.torch_dtype: st for cat in sctypes for st in sctypes[cat]} + + +_aliases = { + "u1": uint8, + "i1": int8, + "i2": int16, + "i4": int32, + "i8": int64, + "b": int8, # XXX: srsly? + "f2": float16, + "f4": float32, + "f8": float64, + "c8": complex64, + "c16": complex128, + # numpy-specific trailing underscore + "bool_": bool_, +} + + +_python_types = { + int: int64, + float: float64, + complex: complex128, + builtins.bool: bool_, + # also allow stringified names of python types + int.__name__: int64, + float.__name__: float64, + complex.__name__: complex128, + builtins.bool.__name__: bool_, +} + + +def sctype_from_string(s): + """Normalize a string value: a type 'name' or a typecode or a width alias.""" + if s in _names: + return _names[s] + if s in _name_aliases.keys(): + return _name_aliases[s] + if s in _typecodes: + return _typecodes[s] + if s in _aliases: + return _aliases[s] + if s in _python_types: + return _python_types[s] + raise TypeError(f"data type {s!r} not understood") + + +def sctype_from_torch_dtype(torch_dtype): + return _torch_dtypes[torch_dtype] + + +# ### DTypes. ### + + +def dtype(arg): + if arg is None: + arg = _dtypes_impl.default_dtypes().float_dtype + return DType(arg) + + +class DType: + def __init__(self, arg): + # a pytorch object? + if isinstance(arg, torch.dtype): + sctype = _torch_dtypes[arg] + elif isinstance(arg, torch.Tensor): + sctype = _torch_dtypes[arg.dtype] + # a scalar type? + elif issubclass_(arg, generic): + sctype = arg + # a dtype already? + elif isinstance(arg, DType): + sctype = arg._scalar_type + # a has a right attribute? + elif hasattr(arg, "dtype"): + sctype = arg.dtype._scalar_type + else: + sctype = sctype_from_string(arg) + self._scalar_type = sctype + + @property + def name(self): + return self._scalar_type.name + + @property + def type(self): + return self._scalar_type + + @property + def kind(self): + # https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html + return _torch_dtypes[self.torch_dtype].name[0] + + @property + def typecode(self): + return self._scalar_type.typecode + + def __eq__(self, other): + if isinstance(other, DType): + return self._scalar_type == other._scalar_type + try: + other_instance = DType(other) + except TypeError: + return False + return self._scalar_type == other_instance._scalar_type + + @property + def torch_dtype(self): + return self._scalar_type.torch_dtype + + def __hash__(self): + return hash(self._scalar_type.name) + + def __repr__(self): + return f'dtype("{self.name}")' + + __str__ = __repr__ + + @property + def itemsize(self): + elem = self.type(1) + return elem.tensor.element_size() + + def __getstate__(self): + return self._scalar_type + + def __setstate__(self, value): + self._scalar_type = value + + +typecodes = { + "All": "efdFDBbhil?", + "AllFloat": "efdFD", + "AllInteger": "Bbhil", + "Integer": "bhil", + "UnsignedInteger": "B", + "Float": "efd", + "Complex": "FD", +} + + +# ### Defaults and dtype discovery + + +def set_default_dtype(fp_dtype="numpy", int_dtype="numpy"): + """Set the (global) defaults for fp, complex, and int dtypes. + + The complex dtype is inferred from the float (fp) dtype. It has + a width at least twice the width of the float dtype, + i.e., it's complex128 for float64 and complex64 for float32. + + Parameters + ---------- + fp_dtype + Allowed values are "numpy", "pytorch" or dtype_like things which + can be converted into a DType instance. + Default is "numpy" (i.e. float64). + int_dtype + Allowed values are "numpy", "pytorch" or dtype_like things which + can be converted into a DType instance. + Default is "numpy" (i.e. int64). + + Returns + ------- + The old default dtype state: a namedtuple with attributes ``float_dtype``, + ``complex_dtypes`` and ``int_dtype``. These attributes store *pytorch* + dtypes. + + Notes + ------------ + This functions has a side effect: it sets the global state with the provided dtypes. + + The complex dtype has bit width of at least twice the width of the float + dtype, i.e. it's complex128 for float64 and complex64 for float32. + + """ + if fp_dtype not in ["numpy", "pytorch"]: + fp_dtype = dtype(fp_dtype).torch_dtype + if int_dtype not in ["numpy", "pytorch"]: + int_dtype = dtype(int_dtype).torch_dtype + + if fp_dtype == "numpy": + float_dtype = torch.float64 + elif fp_dtype == "pytorch": + float_dtype = torch.float32 + else: + float_dtype = fp_dtype + + complex_dtype = { + torch.float64: torch.complex128, + torch.float32: torch.complex64, + torch.float16: torch.complex64, + }[float_dtype] + + if int_dtype in ["numpy", "pytorch"]: + int_dtype = torch.int64 + else: + int_dtype = int_dtype + + new_defaults = _dtypes_impl.DefaultDTypes( + float_dtype=float_dtype, complex_dtype=complex_dtype, int_dtype=int_dtype + ) + + # set the new global state and return the old state + old_defaults = _dtypes_impl.default_dtypes + _dtypes_impl._default_dtypes = new_defaults + return old_defaults + + +def issubclass_(arg, klass): + try: + return issubclass(arg, klass) + except TypeError: + return False + + +def issubdtype(arg1, arg2): + # cf https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numerictypes.py#L356-L420 + + # We also accept strings even if NumPy doesn't as dtypes are serialized as their + # string representation in dynamo's graph + def str_to_abstract(t): + if isinstance(t, str) and t in _abstract_dtypes: + return globals()[t] + return t + + arg1 = str_to_abstract(arg1) + arg2 = str_to_abstract(arg2) + + if not issubclass_(arg1, generic): + arg1 = dtype(arg1).type + if not issubclass_(arg2, generic): + arg2 = dtype(arg2).type + return issubclass(arg1, arg2) + + +__all__ = ["dtype", "DType", "typecodes", "issubdtype", "set_default_dtype", "sctypes"] +__all__ += list(_names.keys()) # noqa: PLE0605 +__all__ += list(_name_aliases.keys()) # noqa: PLE0605 +__all__ += _abstract_dtypes # noqa: PLE0605 diff --git a/shared/package-files/bc/bc1f0c98818bae9fd15f1a4d3e238bb1482690a8868281ae8f5d25b80e909188/ascii.cpython-311.pyc b/shared/package-files/bc/bc1f0c98818bae9fd15f1a4d3e238bb1482690a8868281ae8f5d25b80e909188/ascii.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275cf4187c1841491bc4aa48ca01ce4a841fc76e Binary files /dev/null and b/shared/package-files/bc/bc1f0c98818bae9fd15f1a4d3e238bb1482690a8868281ae8f5d25b80e909188/ascii.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc22bdabd54741cc5c958705fc4e566b985ff83e123b9a2cf9b7238b10a7db55/_linalg_det_meta.h b/shared/package-files/bc/bc22bdabd54741cc5c958705fc4e566b985ff83e123b9a2cf9b7238b10a7db55/_linalg_det_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..e4e27432fae033147ad24486861053566fb5ff18 --- /dev/null +++ b/shared/package-files/bc/bc22bdabd54741cc5c958705fc4e566b985ff83e123b9a2cf9b7238b10a7db55/_linalg_det_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured__linalg_det : public at::impl::MetaBase { + + + void meta(const at::Tensor & A); +}; + +} // namespace native +} // namespace at diff --git a/shared/package-files/bc/bc2432cd3fb578d2cb0c9cb8341c02a795f9382a0f399f6272cc7c6227da3ec7/cxx.py b/shared/package-files/bc/bc2432cd3fb578d2cb0c9cb8341c02a795f9382a0f399f6272cc7c6227da3ec7/cxx.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed4f468b866e1b44aba6ae94a85c740dd324689 --- /dev/null +++ b/shared/package-files/bc/bc2432cd3fb578d2cb0c9cb8341c02a795f9382a0f399f6272cc7c6227da3ec7/cxx.py @@ -0,0 +1,181 @@ +""" +C++ code printer +""" + +from itertools import chain +from sympy.codegen.ast import Type, none +from .codeprinter import requires +from .c import C89CodePrinter, C99CodePrinter + +# These are defined in the other file so we can avoid importing sympy.codegen +# from the top-level 'import sympy'. Export them here as well. +from sympy.printing.codeprinter import cxxcode # noqa:F401 + +# from https://en.cppreference.com/w/cpp/keyword +reserved = { + 'C++98': [ + 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break', + 'case', 'catch,', 'char', 'class', 'compl', 'const', 'const_cast', + 'continue', 'default', 'delete', 'do', 'double', 'dynamic_cast', + 'else', 'enum', 'explicit', 'export', 'extern', 'false', 'float', + 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long', 'mutable', + 'namespace', 'new', 'not', 'not_eq', 'operator', 'or', 'or_eq', + 'private', 'protected', 'public', 'register', 'reinterpret_cast', + 'return', 'short', 'signed', 'sizeof', 'static', 'static_cast', + 'struct', 'switch', 'template', 'this', 'throw', 'true', 'try', + 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', + 'virtual', 'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq' + ] +} + +reserved['C++11'] = reserved['C++98'][:] + [ + 'alignas', 'alignof', 'char16_t', 'char32_t', 'constexpr', 'decltype', + 'noexcept', 'nullptr', 'static_assert', 'thread_local' +] +reserved['C++17'] = reserved['C++11'][:] +reserved['C++17'].remove('register') +# TM TS: atomic_cancel, atomic_commit, atomic_noexcept, synchronized +# concepts TS: concept, requires +# module TS: import, module + + +_math_functions = { + 'C++98': { + 'Mod': 'fmod', + 'ceiling': 'ceil', + }, + 'C++11': { + 'gamma': 'tgamma', + }, + 'C++17': { + 'beta': 'beta', + 'Ei': 'expint', + 'zeta': 'riemann_zeta', + } +} + +# from https://en.cppreference.com/w/cpp/header/cmath +for k in ('Abs', 'exp', 'log', 'log10', 'sqrt', 'sin', 'cos', 'tan', # 'Pow' + 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'floor'): + _math_functions['C++98'][k] = k.lower() + + +for k in ('asinh', 'acosh', 'atanh', 'erf', 'erfc'): + _math_functions['C++11'][k] = k.lower() + + +def _attach_print_method(cls, sympy_name, func_name): + meth_name = '_print_%s' % sympy_name + if hasattr(cls, meth_name): + raise ValueError("Edit method (or subclass) instead of overwriting.") + def _print_method(self, expr): + return '{}{}({})'.format(self._ns, func_name, ', '.join(map(self._print, expr.args))) + _print_method.__doc__ = "Prints code for %s" % k + setattr(cls, meth_name, _print_method) + + +def _attach_print_methods(cls, cont): + for sympy_name, cxx_name in cont[cls.standard].items(): + _attach_print_method(cls, sympy_name, cxx_name) + + +class _CXXCodePrinterBase: + printmethod = "_cxxcode" + language = 'C++' + _ns = 'std::' # namespace + + def __init__(self, settings=None): + super().__init__(settings or {}) + + @requires(headers={'algorithm'}) + def _print_Max(self, expr): + from sympy.functions.elementary.miscellaneous import Max + if len(expr.args) == 1: + return self._print(expr.args[0]) + return "%smax(%s, %s)" % (self._ns, self._print(expr.args[0]), + self._print(Max(*expr.args[1:]))) + + @requires(headers={'algorithm'}) + def _print_Min(self, expr): + from sympy.functions.elementary.miscellaneous import Min + if len(expr.args) == 1: + return self._print(expr.args[0]) + return "%smin(%s, %s)" % (self._ns, self._print(expr.args[0]), + self._print(Min(*expr.args[1:]))) + + def _print_using(self, expr): + if expr.alias == none: + return 'using %s' % expr.type + else: + raise ValueError("C++98 does not support type aliases") + + def _print_Raise(self, rs): + arg, = rs.args + return 'throw %s' % self._print(arg) + + @requires(headers={'stdexcept'}) + def _print_RuntimeError_(self, re): + message, = re.args + return "%sruntime_error(%s)" % (self._ns, self._print(message)) + + +class CXX98CodePrinter(_CXXCodePrinterBase, C89CodePrinter): + standard = 'C++98' + reserved_words = set(reserved['C++98']) + + +# _attach_print_methods(CXX98CodePrinter, _math_functions) + + +class CXX11CodePrinter(_CXXCodePrinterBase, C99CodePrinter): + standard = 'C++11' + reserved_words = set(reserved['C++11']) + type_mappings = dict(chain( + CXX98CodePrinter.type_mappings.items(), + { + Type('int8'): ('int8_t', {'cstdint'}), + Type('int16'): ('int16_t', {'cstdint'}), + Type('int32'): ('int32_t', {'cstdint'}), + Type('int64'): ('int64_t', {'cstdint'}), + Type('uint8'): ('uint8_t', {'cstdint'}), + Type('uint16'): ('uint16_t', {'cstdint'}), + Type('uint32'): ('uint32_t', {'cstdint'}), + Type('uint64'): ('uint64_t', {'cstdint'}), + Type('complex64'): ('std::complex', {'complex'}), + Type('complex128'): ('std::complex', {'complex'}), + Type('bool'): ('bool', None), + }.items() + )) + + def _print_using(self, expr): + if expr.alias == none: + return super()._print_using(expr) + else: + return 'using %(alias)s = %(type)s' % expr.kwargs(apply=self._print) + +# _attach_print_methods(CXX11CodePrinter, _math_functions) + + +class CXX17CodePrinter(_CXXCodePrinterBase, C99CodePrinter): + standard = 'C++17' + reserved_words = set(reserved['C++17']) + + _kf = dict(C99CodePrinter._kf, **_math_functions['C++17']) + + def _print_beta(self, expr): + return self._print_math_func(expr) + + def _print_Ei(self, expr): + return self._print_math_func(expr) + + def _print_zeta(self, expr): + return self._print_math_func(expr) + + +# _attach_print_methods(CXX17CodePrinter, _math_functions) + +cxx_code_printers = { + 'c++98': CXX98CodePrinter, + 'c++11': CXX11CodePrinter, + 'c++17': CXX17CodePrinter +} diff --git a/shared/package-files/bc/bc2453b4b8ca4b1847c1609b73507ebab27133cb56382771989bc1d943a91683/test_laplacian_centrality.cpython-311.pyc b/shared/package-files/bc/bc2453b4b8ca4b1847c1609b73507ebab27133cb56382771989bc1d943a91683/test_laplacian_centrality.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96dd0b5114685b71536d7805349f876ffd3ccf3b Binary files /dev/null and b/shared/package-files/bc/bc2453b4b8ca4b1847c1609b73507ebab27133cb56382771989bc1d943a91683/test_laplacian_centrality.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc248bc68d29ca7ac7ac20a8ed2e3ddb9960461a129bf32be5884887fd5b61cc/test_dyadic.py b/shared/package-files/bc/bc248bc68d29ca7ac7ac20a8ed2e3ddb9960461a129bf32be5884887fd5b61cc/test_dyadic.py new file mode 100644 index 0000000000000000000000000000000000000000..ab365b4687162ccbd3b21dd9709b84dbcdec8aa0 --- /dev/null +++ b/shared/package-files/bc/bc248bc68d29ca7ac7ac20a8ed2e3ddb9960461a129bf32be5884887fd5b61cc/test_dyadic.py @@ -0,0 +1,123 @@ +from sympy.core.numbers import (Float, pi) +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.physics.vector import ReferenceFrame, dynamicsymbols, outer +from sympy.physics.vector.dyadic import _check_dyadic +from sympy.testing.pytest import raises + +A = ReferenceFrame('A') + + +def test_dyadic(): + d1 = A.x | A.x + d2 = A.y | A.y + d3 = A.x | A.y + assert d1 * 0 == 0 + assert d1 != 0 + assert d1 * 2 == 2 * A.x | A.x + assert d1 / 2. == 0.5 * d1 + assert d1 & (0 * d1) == 0 + assert d1 & d2 == 0 + assert d1 & A.x == A.x + assert d1 ^ A.x == 0 + assert d1 ^ A.y == A.x | A.z + assert d1 ^ A.z == - A.x | A.y + assert d2 ^ A.x == - A.y | A.z + assert A.x ^ d1 == 0 + assert A.y ^ d1 == - A.z | A.x + assert A.z ^ d1 == A.y | A.x + assert A.x & d1 == A.x + assert A.y & d1 == 0 + assert A.y & d2 == A.y + assert d1 & d3 == A.x | A.y + assert d3 & d1 == 0 + assert d1.dt(A) == 0 + q = dynamicsymbols('q') + qd = dynamicsymbols('q', 1) + B = A.orientnew('B', 'Axis', [q, A.z]) + assert d1.express(B) == d1.express(B, B) + assert d1.express(B) == ((cos(q)**2) * (B.x | B.x) + (-sin(q) * cos(q)) * + (B.x | B.y) + (-sin(q) * cos(q)) * (B.y | B.x) + (sin(q)**2) * + (B.y | B.y)) + assert d1.express(B, A) == (cos(q)) * (B.x | A.x) + (-sin(q)) * (B.y | A.x) + assert d1.express(A, B) == (cos(q)) * (A.x | B.x) + (-sin(q)) * (A.x | B.y) + assert d1.dt(B) == (-qd) * (A.y | A.x) + (-qd) * (A.x | A.y) + + assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]]) + assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0], + [0, 0, 0], + [0, 0, 0]]) + assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) + a, b, c, d, e, f = symbols('a, b, c, d, e, f') + v1 = a * A.x + b * A.y + c * A.z + v2 = d * A.x + e * A.y + f * A.z + d4 = v1.outer(v2) + assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f], + [b * d, b * e, b * f], + [c * d, c * e, c * f]]) + d5 = v1.outer(v1) + C = A.orientnew('C', 'Axis', [q, A.x]) + for expected, actual in zip(C.dcm(A) * d5.to_matrix(A) * C.dcm(A).T, + d5.to_matrix(C)): + assert (expected - actual).simplify() == 0 + + raises(TypeError, lambda: d1.applyfunc(0)) + + +def test_dyadic_simplify(): + x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A') + N = ReferenceFrame('N') + + dy = N.x | N.x + test1 = (1 / x + 1 / y) * dy + assert (N.x & test1 & N.x) != (x + y) / (x * y) + test1 = test1.simplify() + assert (N.x & test1 & N.x) == (x + y) / (x * y) + + test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy + test2 = test2.simplify() + assert (N.x & test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3)) + + test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy + test3 = test3.simplify() + assert (N.x & test3 & N.x) == 0 + + test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy + test4 = test4.simplify() + assert (N.x & test4 & N.x) == -2 * y + + +def test_dyadic_subs(): + N = ReferenceFrame('N') + s = symbols('s') + a = s*(N.x | N.x) + assert a.subs({s: 2}) == 2*(N.x | N.x) + + +def test_check_dyadic(): + raises(TypeError, lambda: _check_dyadic(0)) + + +def test_dyadic_evalf(): + N = ReferenceFrame('N') + a = pi * (N.x | N.x) + assert a.evalf(3) == Float('3.1416', 3) * (N.x | N.x) + s = symbols('s') + a = 5 * s * pi* (N.x | N.x) + assert a.evalf(2) == Float('5', 2) * Float('3.1416', 2) * s * (N.x | N.x) + assert a.evalf(9, subs={s: 5.124}) == Float('80.48760378', 9) * (N.x | N.x) + + +def test_dyadic_xreplace(): + x, y, z = symbols('x y z') + N = ReferenceFrame('N') + D = outer(N.x, N.x) + v = x*y * D + assert v.xreplace({x : cos(x)}) == cos(x)*y * D + assert v.xreplace({x*y : pi}) == pi * D + v = (x*y)**z * D + assert v.xreplace({(x*y)**z : 1}) == D + assert v.xreplace({x:1, z:0}) == D + raises(TypeError, lambda: v.xreplace()) + raises(TypeError, lambda: v.xreplace([x, y])) diff --git a/shared/package-files/bc/bc2495f165eef0348ef414289fc84d13c99fe318aa6d302f36fea8ff78e98fe5/embedding.py b/shared/package-files/bc/bc2495f165eef0348ef414289fc84d13c99fe318aa6d302f36fea8ff78e98fe5/embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..117aed79520d9ad78c10bdd2310fb6b032c2a024 --- /dev/null +++ b/shared/package-files/bc/bc2495f165eef0348ef414289fc84d13c99fe318aa6d302f36fea8ff78e98fe5/embedding.py @@ -0,0 +1,294 @@ +# mypy: allow-untyped-defs + +import torch +import torch.distributed as dist +from torch.distributed._shard.sharded_tensor import ShardedTensor +from torch.distributed._shard.sharding_spec import ChunkShardingSpec +from torch.distributed._shard.sharding_spec.api import custom_sharding_spec_op +from torch.distributed.nn.functional import all_gather, reduce_scatter + +from ._common import ( + _all_gather_base_input, + _handle_col_wise_sharding_base, + _handle_max_norm_col_wise, + _handle_row_wise_mask, +) + + +@custom_sharding_spec_op(ChunkShardingSpec, torch.nn.functional.embedding) +def sharded_embedding(types, args, kwargs, pg): + """ + Handles ``__torch_function__`` dispatch for ``torch.nn.functional.embedding``. + This method computes a sharded embedding lookup and has the following limitations: + + 1. Supports only sharding of ``weight``. + 2. Supports only ``ChunkShardingSpec``. + 3. Supports only a single local shard per rank. + 4. Supports all specs except for scale_grad_by_freq, sparse, etc. + + Based on the dimension that the weight is sharded on, there are two + algorithms: + + ROWWISE SHARDING + ================ + For row-wise sharding the weight is sharded on dimension 0. + + The overall algorithm can be best explained with an example. Let's assume + the dims for input are (4 x 6) and W are (10 x 17) and W is sharded across + 4 GPUs creating 3 shard of (3 x 17) and 1 shard of (1 x 17). + The algorithm is as follows: + + 1. First the input is all gathered to all ranks, since this is SPMD and + input is actually sharded across all ranks. The inputs then become a + 4 (4 x 6) tensor on each rank. For example if the given input is + tensor([[6, 5, 2, 9, 6, 3], + [3, 1, 2, 4, 7, 6], + [4, 0, 4, 9, 8, 9], + [8, 6, 6, 4, 6, 1]]) + on rank 0. + Then on every rank, we will have this tensor. + If input itself is already replicated, no all-gather will be done. + 2. Next, we mask the ID which are not stored on that rank. + For example on rank 0, we store ID [0, 1, 2]. We only keep the ID + inside the set of numbers. The rest of them will be masked to an extra row. + The masked matrix will be used for embedding look up and is like: + tensor([[4, 4, 2, 4, 4, 4], + [4, 1, 2, 4, 4, 4], + [4, 0, 4, 4, 4, 4], + [4, 4, 4, 4, 4, 1]]) + The reason of having an extra row (aka, number 4 in the example) is + because when max_norm is specified only weight which has looked will + be re-normed so mask IDs whose embeddings are not stored in current + rank will to an extra row will ensure max_norm still works as expected. + 3. If max_norm is specified, the extra row guarantees that the mask ID will + not affect the behavior of weigh re-norm. + + COLWISE SHARDING + ================ + For col-wise sharding the weight is sharded on dimension 1. + + The overall algorithm can be best explained with an example. Let's assume + the dims for input are (4 x 6) and W are (16 x 17) and W is sharded across + 4 GPUs creating 3 shards of (16 x 5) and 1 shard of (16 x 2). + The algorithm is as follows: + + 1. First the input is broadcasted to all ranks, since this is SPMD we + actually do an all_gather for all the inputs resulting in 4 (4 x 6) + inputs on each rank. + 2. Next we perform local embedding lookup operation by apply each + input (4 x 6) with the local shard (16 x 5) ((16 x 2) for the last). + This results in 4 (5 x 6 x 4) ((2 x 6 x 4) for the last) matrices + on each rank. We transpose dim 0 and dim 2. + 3. Next, we concat these 4 matrices and perform an all2all to share the + appropriate (5 x 6 x 4) or (2 x 6 x 4) matrices to each rank. + 4. Now, each rank receives a (17 x 6 x 4) matrix which is basically the + size of the result we need. + 5. If placements are not in order any appropriate rearrangement of columns + are done for the (17 x 6 x 4) matrix and finally we transpose the + dim 0 and dim 2 again. + 6. If max_norm is specified, we manually sum up the norm and renorm. Because + the renorm must be in place, we need to override the local_shard to mimic + this behavior. + """ + # Validate input params + _validate_embedding_param(args, kwargs) + + input = args[0] + weight = args[1] + max_norm = kwargs.get("max_norm") + norm_type = kwargs.get("norm_type") + padding_idx = kwargs.get("padding_idx") + + local_shard = weight.local_tensor().contiguous() + sharding_dim = weight._sharding_spec.dim + world_size = dist.get_world_size(pg) + rank = dist.get_rank(pg) + + if sharding_dim == 1: + output, local_shard = _handle_col_wise_sharding( + input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, pg + ) + weight.local_shards()[0].tensor = local_shard + return output + elif sharding_dim == 0: + return _handle_row_wise_sharding( + input, + world_size, + weight, + local_shard, + max_norm, + norm_type, + padding_idx, + rank, + pg, + ) + else: + raise RuntimeError( + f"nn.Embedding weight sharded on dim {sharding_dim} not supported!" + ) + + +def _validate_embedding_param(args, kwargs): + """ + Validate input params of sharded embedding op. + + Args: + input: list of ID used for lookup. + weight: sharded weight tensor. + kwargs: same as normal Embedding. + + Return: None. + """ + + input = args[0] + weight = args[1] + max_norm = kwargs.get("max_norm") + scale_grad_by_freq = kwargs.get("scale_grad_by_freq") + sparse = kwargs.get("sparse") + + # Validate types + if not isinstance(input, torch.Tensor): + raise TypeError("input need to be torch.Tensor") + if not isinstance(weight, ShardedTensor): + raise TypeError("weight needs to be ShardedTensor") + weight_size = weight.size() + if len(weight_size) != 2: + raise ValueError("Weight needs to have exactly 2 dims") + if int(torch.min(input).item()) < 0: + raise ValueError( + "Index out of range in Input %d %d", + int(torch.min(input).item()), + weight_size[1], + ) + if int(torch.max(input).item()) >= weight_size[0]: + raise ValueError( + "Index out of range in Input %d %d", + int(torch.max(input).item()), + weight_size[1], + ) + if scale_grad_by_freq: + raise RuntimeError( + 'nn.Embedding weight sharded with flag on "scale_grad_by_freq" not supported!' + ) + if sparse: + raise RuntimeError( + 'nn.Embedding weight sharded with flag on "sparse" not supported!' + ) + if max_norm and max_norm <= 0.0: + raise ValueError('"max_norm" must be larger than zero!') + + if not isinstance(weight._sharding_spec, ChunkShardingSpec): + raise ValueError("Only ChunkShardingSpec supported for ShardedTensor ops!") + if len(weight.local_shards()) != 1: + raise ValueError("Only one local shard supported!") + + +def _handle_col_wise_sharding( + input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, pg +): + """ + Entry-point function to handle the logic of col-wise sharding of weight + for embedding. (Detailed explanations of the logic can be found in + the comment for sharded_embedding.) + + Args: + input: list of ID used for lookup and aggregation. + world_size: number of ranks. + weight: sharded weight tensor. + local_shard: col-wise shared local weight used for lookup. + max_norm: If given, each embedding vector with norm larger + than max_norm is renormalized to have norm max_norm. + Note: this will modify weight in-place. + norm_type: The p in the p-norm to compute for the max_norm option. + padding_idx: If specified, the entries at padding_idx do + not contribute to the gradient; therefore, the embedding + vector at padding_idx is not updated during training, + i.e. it remains as a fixed "pad". + pg: process group. + + Returns: final result of lookup. + """ + # allgather the inputs first for non Replicated Tensor. + gathered_inputs = all_gather(input, group=pg) + + if max_norm is not None: + # max_norm changes the weight in-place + local_shard = _handle_max_norm_col_wise( + max_norm, norm_type, local_shard, input, world_size, gathered_inputs, pg + ) + + output = _handle_col_wise_sharding_base( + torch.nn.functional.embedding, + len(input.size()), + input, + world_size, + weight, + local_shard, + pg, + gathered_inputs, + padding_idx=padding_idx, + ) + return (output, local_shard) + + +def _handle_row_wise_sharding( + input, world_size, weight, local_shard, max_norm, norm_type, padding_idx, rank, pg +): + """ + Entry-point function to handle the logic of row-wise sharding of weight + for embedding. (Detailed explanations of the logic can be found in + the comment for sharded_embedding.) + + Args: + input: list of ID used for lookup and aggregation. + world_size: number of ranks. + weight: sharded weight tensor. + local_shard: row-wise shared local weight used for lookup. + max_norm: If given, each embedding vector with norm larger + than max_norm is renormalized to have norm max_norm. + Note: this will modify weight in-place. + norm_type: The p in the p-norm to compute for the max_norm option. + padding_idx: If specified, the entries at padding_idx do + not contribute to the gradient; therefore, the embedding + vector at padding_idx is not updated during training, + i.e. it remains as a fixed "pad". + rank: # of cuda process. + pg: process group. + + Returns: final result of lookup. + """ + # allgather the inputs first for non Replicated Tensor. + gather_inp = _all_gather_base_input(input, pg) + + # Mask the input according to sharding spec. + lookup_input, padding_idx, padding_row = _handle_row_wise_mask( + gather_inp, padding_idx, weight, world_size, rank + ) + + # When input is a large tensor, the value of weight is changed. + # This is a walk-around for now. GH issue: #81717 + if max_norm is not None: + torch.nn.functional.embedding( + torch.unique(lookup_input)[:-1], + local_shard, + padding_idx=padding_idx, + max_norm=max_norm, + norm_type=norm_type, + ) + max_norm = None + + local_input_embeddings = torch.nn.functional.embedding( + lookup_input, + torch.cat([local_shard, padding_row]), + padding_idx=padding_idx, + max_norm=max_norm, + norm_type=norm_type, + ) + + # TODO: Make the result a PartialTensor. + local_shards = local_input_embeddings.chunk(pg.size()) + return reduce_scatter( + torch.empty_like(local_shards[0]), + list(local_shards), + group=pg, + ) diff --git a/shared/package-files/bc/bc26f77b3bb75a5e0f8c5b433bfd9d98c4098275e9c74d117fe5ab8b1984bfc9/test_n5.cpython-311.pyc b/shared/package-files/bc/bc26f77b3bb75a5e0f8c5b433bfd9d98c4098275e9c74d117fe5ab8b1984bfc9/test_n5.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a586f2c7cd90d27fbf915c8ac4c1b826bb5ae48 Binary files /dev/null and b/shared/package-files/bc/bc26f77b3bb75a5e0f8c5b433bfd9d98c4098275e9c74d117fe5ab8b1984bfc9/test_n5.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc2cbb539600af0974d2e86280aa92869e57d46cbcb7495b53dd074800c06ab7/alias_copy.h b/shared/package-files/bc/bc2cbb539600af0974d2e86280aa92869e57d46cbcb7495b53dd074800c06ab7/alias_copy.h new file mode 100644 index 0000000000000000000000000000000000000000..bc589300e622c86add339fffc1a3da90bf3ec7fb --- /dev/null +++ b/shared/package-files/bc/bc2cbb539600af0974d2e86280aa92869e57d46cbcb7495b53dd074800c06ab7/alias_copy.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::alias_copy(Tensor self) -> Tensor +inline at::Tensor alias_copy(const at::Tensor & self) { + return at::_ops::alias_copy::call(self); +} + +// aten::alias_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & alias_copy_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::alias_copy_out::call(self, out); +} +// aten::alias_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & alias_copy_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::alias_copy_out::call(self, out); +} + +} diff --git a/shared/package-files/bc/bc2df3fb286bc9f58b3476b1d86eab7d9a6a151a5ef8d99809c852c83b3e0d5d/__init__.cpython-311.pyc b/shared/package-files/bc/bc2df3fb286bc9f58b3476b1d86eab7d9a6a151a5ef8d99809c852c83b3e0d5d/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4902d8714188b327e9ee76227eb9398b19170b4 Binary files /dev/null and b/shared/package-files/bc/bc2df3fb286bc9f58b3476b1d86eab7d9a6a151a5ef8d99809c852c83b3e0d5d/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc2f0fdcb5657109d066951d58864ec4227c8f65ce4d1f144015062ef097e4b2/_weights_only_unpickler.py b/shared/package-files/bc/bc2f0fdcb5657109d066951d58864ec4227c8f65ce4d1f144015062ef097e4b2/_weights_only_unpickler.py new file mode 100644 index 0000000000000000000000000000000000000000..2352bb836a9d263b8732013691c17a300e481a85 --- /dev/null +++ b/shared/package-files/bc/bc2f0fdcb5657109d066951d58864ec4227c8f65ce4d1f144015062ef097e4b2/_weights_only_unpickler.py @@ -0,0 +1,573 @@ +# mypy: allow-untyped-defs +# Unpickler restricted to loading only state dicts +# Restrict constructing types to a list defined in _get_allowed_globals() +# Restrict BUILD operation to `Tensor`, `Parameter` and `OrderedDict` types only +# Restrict APPEND/APPENDS to `list` +# In `GLOBALS` operation do not do class lookup by name, but rather rely on dictionary +# defined by `_get_allowed_globals()` method, that contains: +# - torch types (Storage, dtypes, Tensor, `torch.Size`), +# - `torch._utils._rebuild` functions. +# - `torch.nn.Parameter` +# - `collections.Counter` +# - `collections.OrderedDict` +# Additionally, users can use an allowlist for adding classes they have deemed as safe using +# `_add_safe_globals()` (`torch.serialization.add_safe_globals`) +# `_clear_safe_globals()` (`torch.serialization.clear_safe_globals`) +# `_get_safe_globals()` (`torch.serialization.get_safe_globals`) + +# Based of https://github.com/python/cpython/blob/main/Lib/pickle.py +# Expected to be useful for loading PyTorch model weights +# For example: +# data = urllib.request.urlopen('https://download.pytorch.org/models/resnet50-0676ba61.pth').read() +# buf = io.BytesIO(data) +# weights = torch.load(buf, weights_only = True) + +import functools as _functools +import warnings + +from _codecs import encode +from collections import Counter, OrderedDict +from pickle import ( + APPEND, + APPENDS, + BINFLOAT, + BINGET, + BININT, + BININT1, + BININT2, + BINPERSID, + BINPUT, + BINUNICODE, + BUILD, + bytes_types, + decode_long, + EMPTY_DICT, + EMPTY_LIST, + EMPTY_SET, + EMPTY_TUPLE, + GLOBAL, + LONG1, + LONG_BINGET, + LONG_BINPUT, + MARK, + NEWFALSE, + NEWOBJ, + NEWTRUE, + NONE, + PROTO, + REDUCE, + SETITEM, + SETITEMS, + SHORT_BINSTRING, + STOP, + TUPLE, + TUPLE1, + TUPLE2, + TUPLE3, + UnpicklingError, +) +from struct import unpack +from sys import maxsize +from typing import Any, Callable, Union + +import torch +from torch._utils import _sparse_tensors_to_validate, IMPORT_MAPPING, NAME_MAPPING + + +# modules in this list are never allowed, even if the user attempts to allowlist +# functions/classes from them +_blocklisted_modules = [ + "sys", + "os", + "posix", + "nt", +] + +_marked_safe_globals_set: set[Union[Callable, tuple[Callable, str]]] = set() + + +def _add_safe_globals(safe_globals: list[Union[Callable, tuple[Callable, str]]]): + global _marked_safe_globals_set + _marked_safe_globals_set = _marked_safe_globals_set.union(set(safe_globals)) + + +def _get_safe_globals() -> list[Union[Callable, tuple[Callable, str]]]: + global _marked_safe_globals_set + return list(_marked_safe_globals_set) + + +def _clear_safe_globals(): + global _marked_safe_globals_set + _marked_safe_globals_set = set() + + +def _remove_safe_globals( + globals_to_remove: list[Union[Callable, tuple[Callable, str]]], +): + global _marked_safe_globals_set + _marked_safe_globals_set = _marked_safe_globals_set - set(globals_to_remove) + + +class _safe_globals: + def __init__(self, safe_globals: list[Union[Callable, tuple[Callable, str]]]): + self.safe_globals = safe_globals + + def __enter__(self): + _add_safe_globals(self.safe_globals) + + def __exit__(self, type, value, tb): + _remove_safe_globals(self.safe_globals) + + +# Separate from _get_allowed_globals because of the lru_cache on _get_allowed_globals +# For example if user had a script like +# torch.load(file_a) +# torch.serialization._add_safe_globals([torch.foo]) +# torch.load(file_b) +# the dynamic additions to safe_globals would not be picked up by +# _get_allowed_globals due to the lru_cache +def _get_user_allowed_globals(): + rc: dict[str, Any] = {} + for f in _marked_safe_globals_set: + if isinstance(f, tuple): + if len(f) != 2: + raise ValueError( + f"Expected tuple of length 2 (global, str of callable full path), but got tuple of length: {len(f)}" + ) + if type(f[1]) is not str: + raise TypeError( + f"Expected second item in tuple to be str of callable full path, but got: {type(f[1])}" + ) + f, name = f + rc[name] = f + else: + module, name = f.__module__, f.__qualname__ + rc[f"{module}.{name}"] = f + return rc + + +def _tensor_rebuild_functions(): + return { + torch._utils._rebuild_parameter, + torch._utils._rebuild_parameter_with_state, + torch._utils._rebuild_qtensor, + torch._utils._rebuild_tensor, + torch._utils._rebuild_tensor_v2, + torch._utils._rebuild_tensor_v3, + torch._utils._rebuild_sparse_tensor, + torch._utils._rebuild_meta_tensor_no_storage, + torch._utils._rebuild_nested_tensor, + torch._utils._rebuild_wrapper_subclass, + # Allowlisting this, but not allowlisting the numpy functions by default + # Reasoning is that we don't have control over the numpy functions, but + # this utility is provided by pytorch + torch._utils._rebuild_device_tensor_from_numpy, + # In 2.6, we should no longer have a dependency on numpy and the above + # _rebuild_device_tensor_from_numpy function. + torch._utils._rebuild_device_tensor_from_cpu_tensor, + } + + +# Unpickling machinery +@_functools.lru_cache(maxsize=1) +def _get_allowed_globals(): + rc: dict[str, Any] = { + "collections.OrderedDict": OrderedDict, + "collections.Counter": Counter, + "torch.nn.parameter.Parameter": torch.nn.Parameter, + "torch.serialization._get_layout": torch.serialization._get_layout, + "torch.Size": torch.Size, + "torch.Tensor": torch.Tensor, + "torch.device": torch.device, + "_codecs.encode": encode, # for bytes + "builtins.bytearray": bytearray, # for bytearray + "builtins.set": set, # for set + "builtins.complex": complex, # for complex + } + + # dtype + for t in torch.storage._dtype_to_storage_type_map().keys(): + rc[str(t)] = t + for t in torch.storage._new_dtypes(): + rc[str(t)] = t + for t in [getattr(torch, f"uint{x}") for x in range(1, 8)]: + rc[str(t)] = t + for t in [getattr(torch, f"int{x}") for x in range(1, 8)]: + rc[str(t)] = t + + # Tensor classes + for tt in torch._tensor_classes: + rc[f"{tt.__module__}.{tt.__name__}"] = tt + # Storage classes + for ts in torch._storage_classes: + if ts not in (torch.storage.TypedStorage, torch.storage.UntypedStorage): + # Wrap legacy storage types in a dummy class + rc[f"{ts.__module__}.{ts.__name__}"] = torch.serialization.StorageType( + ts.__name__ + ) + else: + rc[f"{ts.__module__}.{ts.__name__}"] = ts + # Quantization specific + for qt in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + torch.per_channel_affine, + torch.per_channel_symmetric, + torch.per_channel_affine_float_qparams, + ]: + rc[str(qt)] = qt + # Rebuild functions + for f in _tensor_rebuild_functions(): + rc[f"torch._utils.{f.__name__}"] = f + + # Handles Tensor Subclasses, Tensor's with attributes. + # NOTE: It calls into above rebuild functions for regular Tensor types. + rc["torch._tensor._rebuild_from_type_v2"] = torch._tensor._rebuild_from_type_v2 + return rc + + +def _read_global_instruction(readline: Callable) -> tuple[str, str]: + module = readline()[:-1].decode("utf-8") + name = readline()[:-1].decode("utf-8") + # Patch since torch.save default protocol is 2 + # users will be running this code in python > 3 + if (module, name) in NAME_MAPPING: + module, name = NAME_MAPPING[(module, name)] + elif module in IMPORT_MAPPING: + module = IMPORT_MAPPING[module] + return module, name + + +def get_globals_in_pkl(file) -> set[str]: + globals_in_checkpoint = set() + read = file.read + readline = file.readline + op_to_bytes_to_read = { + NEWOBJ[0]: 0, + REDUCE[0]: 0, + BUILD[0]: 0, + APPEND[0]: 0, + APPENDS[0]: 0, + SETITEM[0]: 0, + SETITEMS[0]: 0, + MARK[0]: 0, + TUPLE[0]: 0, + TUPLE1[0]: 0, + TUPLE2[0]: 0, + TUPLE3[0]: 0, + NONE[0]: 0, + NEWFALSE[0]: 0, + NEWTRUE[0]: 0, + EMPTY_TUPLE[0]: 0, + EMPTY_LIST[0]: 0, + EMPTY_DICT[0]: 0, + EMPTY_SET[0]: 0, + BINPERSID[0]: 0, + BININT[0]: 4, + BININT1[0]: 1, + BININT2[0]: 2, + BINFLOAT[0]: 8, + BINGET[0]: 1, + LONG_BINGET[0]: 4, + BINPUT[0]: 1, + LONG_BINPUT[0]: 4, + } + while True: + key = read(1) + if not key: + raise EOFError + assert isinstance(key, bytes_types) + if key[0] == GLOBAL[0]: + module, name = _read_global_instruction(readline) + globals_in_checkpoint.add(f"{module}.{name}") + elif key[0] in op_to_bytes_to_read: + bytes_to_read = op_to_bytes_to_read[key[0]] + if bytes_to_read: + read(bytes_to_read) + # ops where bytes to read depends on the data + elif key[0] == BINUNICODE[0]: + strlen = unpack(" maxsize: + raise UnpicklingError("String is too long") + read(strlen) + elif key[0] in {SHORT_BINSTRING[0], LONG1[0]}: + strlen = read(1)[0] + read(strlen) + # first and last op + elif key[0] == PROTO[0]: + read(1)[0] + elif key[0] == STOP[0]: + return globals_in_checkpoint + else: + raise UnpicklingError(f"Unsupported operand {key[0]}") + + +class Unpickler: + def __init__(self, file, *, encoding: str = "bytes"): + self.encoding = encoding + self.readline = file.readline + self.read = file.read + self.memo: dict[int, Any] = {} + self.proto: int = -1 + + def load(self): + """Read a pickled object representation from the open file. + + Return the reconstituted object hierarchy specified in the file. + """ + self.metastack = [] + self.stack: list[Any] = [] + self.append = self.stack.append + read = self.read + while True: + key = read(1) + if not key: + raise EOFError + assert isinstance(key, bytes_types) + # Risky operators + if key[0] == GLOBAL[0]: + module, name = _read_global_instruction(self.readline) + full_path = f"{module}.{name}" + if module in _blocklisted_modules: + raise UnpicklingError( + f"Trying to load unsupported GLOBAL {full_path} whose module {module} is blocked." + ) + if full_path in _get_allowed_globals(): + self.append(_get_allowed_globals()[full_path]) + elif full_path in _get_user_allowed_globals(): + self.append(_get_user_allowed_globals()[full_path]) + elif full_path in ( + [ + "torch.nested._internal.nested_tensor.NestedTensor", + "torch.nested._internal.nested_tensor._rebuild_njt", + "torch._dynamo.decorators._DimRange", + ] + ): + raise UnpicklingError( + "``torch.nested`` and ``torch._dynamo`` must be imported to load nested jagged tensors (NJTs)" + ) + elif full_path in ( + [ + "torch.distributed.device_mesh.DeviceMesh", + "torch.distributed.tensor._dtensor_spec.DTensorSpec", + "torch.distributed.tensor._dtensor_spec.TensorMeta", + "torch.distributed.tensor.DTensor", + "torch.distributed.tensor.placement_types.Partial", + "torch.distributed.tensor.placement_types.Replicate", + "torch.distributed.tensor.placement_types.Shard", + ] + ): + raise UnpicklingError( + "``torch.distributed.tensor`` must be imported to load DTensors" + ) + else: + builtins_name = "builtins" + if ( + builtins_name in full_path + and builtins_name == full_path[: len(builtins_name)] + ): + full_path = full_path[len(builtins_name) :] + full_path = ( + full_path[1:] + if len(full_path) > 0 and full_path[0] == "." + else builtins_name + full_path + ) + raise UnpicklingError( + f"Unsupported global: GLOBAL {full_path} was not an allowed global by default. " + f"Please use `torch.serialization.add_safe_globals([{full_path}])` or the " + f"`torch.serialization.safe_globals([{full_path}])` context manager to allowlist this global " + "if you trust this class/function." + ) + elif key[0] == NEWOBJ[0]: + args = self.stack.pop() + cls = self.stack.pop() + if cls is torch.nn.Parameter: + self.append(torch.nn.Parameter(*args)) + elif ( + cls in _get_user_allowed_globals().values() + or cls in _get_allowed_globals().values() + ): + result = cls.__new__(cls, *args) + if cls in torch._tensor_classes and "sparse" in cls.__module__: + _sparse_tensors_to_validate.append(result) + self.append(result) + else: + raise UnpicklingError( + "Can only create new object for nn.Parameter or classes allowlisted " + f"via `add_safe_globals` but got {cls}" + ) + elif key[0] == REDUCE[0]: + args = self.stack.pop() + func = self.stack[-1] + if ( + func not in _get_allowed_globals().values() + and func not in _get_user_allowed_globals().values() + ): + raise UnpicklingError( + f"Trying to call reduce for unrecognized function {func}" + ) + result = func(*args) + if func in torch._tensor_classes and "sparse" in func.__module__: + _sparse_tensors_to_validate.append(result) + self.stack[-1] = result + elif key[0] == BUILD[0]: + state = self.stack.pop() + inst = self.stack[-1] + if type(inst) is torch.Tensor: + # Legacy unpickling + inst.set_(*state) + elif type(inst) is torch.nn.Parameter: + inst.__setstate__(state) + elif type(inst) is OrderedDict: + inst.__dict__.update(state) + elif ( + type(inst) in _get_user_allowed_globals().values() + or type(inst) in _get_allowed_globals().values() + ): + if hasattr(inst, "__setstate__"): + inst.__setstate__(state) + else: + # mimics load_build in pickle + # https://github.com/python/cpython/blob/f0c6fccd08904787a39269367f09f263d496114c/Lib/pickle.py#L1854-L1867 + slotstate = None + if isinstance(state, tuple) and len(state) == 2: + state, slotstate = state + if state: + inst.__dict__.update(state) + if slotstate: + for k, v in slotstate.items(): + setattr(inst, k, v) + else: + raise UnpicklingError( + "Can only build Tensor, Parameter, OrderedDict or types allowlisted " + f"via `add_safe_globals`, but got {type(inst)}" + ) + # Stack manipulation + elif key[0] == APPEND[0]: + item = self.stack.pop() + list_obj = self.stack[-1] + if type(list_obj) is not list: + raise UnpicklingError( + f"Can only append to lists, but got {type(list_obj)}" + ) + list_obj.append(item) + elif key[0] == APPENDS[0]: + items = self.pop_mark() + list_obj = self.stack[-1] + if type(list_obj) is not list: + raise UnpicklingError( + f"Can only extend lists, but got {type(list_obj)}" + ) + list_obj.extend(items) + elif key[0] == SETITEM[0]: + (v, k) = (self.stack.pop(), self.stack.pop()) + self.stack[-1][k] = v + elif key[0] == SETITEMS[0]: + items = self.pop_mark() + for i in range(0, len(items), 2): + self.stack[-1][items[i]] = items[i + 1] + elif key[0] == MARK[0]: + self.metastack.append(self.stack) + self.stack = [] + self.append = self.stack.append + elif key[0] == TUPLE[0]: + items = self.pop_mark() + self.append(tuple(items)) + elif key[0] == TUPLE1[0]: + self.stack[-1] = (self.stack[-1],) + elif key[0] == TUPLE2[0]: + self.stack[-2:] = [(self.stack[-2], self.stack[-1])] + elif key[0] == TUPLE3[0]: + self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] + # Basic types construction + elif key[0] == NONE[0]: + self.append(None) + elif key[0] == NEWFALSE[0]: + self.append(False) + elif key[0] == NEWTRUE[0]: + self.append(True) + elif key[0] == EMPTY_TUPLE[0]: + self.append(()) + elif key[0] == EMPTY_LIST[0]: + self.append([]) + elif key[0] == EMPTY_DICT[0]: + self.append({}) + elif key[0] == EMPTY_SET[0]: + self.append(set()) + elif key[0] == BININT[0]: + self.append(unpack("d", self.read(8))[0]) + elif key[0] == BINUNICODE[0]: + strlen = unpack(" maxsize: + raise UnpicklingError("String is too long") + strval = str(read(strlen), "utf-8", "surrogatepass") + self.append(strval) + elif key[0] == SHORT_BINSTRING[0]: + strlen = read(1)[0] + strdata = read(strlen) + if self.encoding != "bytes": + strdata = strdata.decode(self.encoding, "strict") + self.append(strdata) + elif key[0] == BINPERSID[0]: + pid = self.stack.pop() + # Only allow persistent load of storage + if type(pid) is not tuple and not type(pid) is not int: + raise UnpicklingError( + f"persistent_load id must be tuple or int, but got {type(pid)}" + ) + if ( + type(pid) is tuple + and len(pid) > 0 + and torch.serialization._maybe_decode_ascii(pid[0]) != "storage" + ): + raise UnpicklingError( + f"Only persistent_load of storage is allowed, but got {pid[0]}" + ) + self.append(self.persistent_load(pid)) + elif key[0] in [BINGET[0], LONG_BINGET[0]]: + idx = (read(1) if key[0] == BINGET[0] else unpack(" +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor deg2rad(const at::Tensor & self); +TORCH_API at::Tensor & deg2rad_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & deg2rad_(at::Tensor & self); +TORCH_API at::Tensor deg2rad_sparse(const at::Tensor & self); +TORCH_API at::Tensor & deg2rad_sparse_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & deg2rad_sparse_(at::Tensor & self); +TORCH_API at::Tensor deg2rad_sparse_csr(const at::Tensor & self); +TORCH_API at::Tensor & deg2rad_sparse_csr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & deg2rad_sparse_csr_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/bc/bc3d83b3cd662ad406accac0632d45028fce3dfcb3be10ce6c5dbbea44ffb7e5/__init__.py b/shared/package-files/bc/bc3d83b3cd662ad406accac0632d45028fce3dfcb3be10ce6c5dbbea44ffb7e5/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..caabfdf243783f2161a201c6a6ec9bd6eca83b18 --- /dev/null +++ b/shared/package-files/bc/bc3d83b3cd662ad406accac0632d45028fce3dfcb3be10ce6c5dbbea44ffb7e5/__init__.py @@ -0,0 +1,65 @@ +# mypy: allow-untyped-defs +import sys +import types + +import torch + + +# This function should correspond to the enums present in c10/core/QEngine.h +def _get_qengine_id(qengine: str) -> int: + if qengine == "none" or qengine == "" or qengine is None: + ret = 0 + elif qengine == "fbgemm": + ret = 1 + elif qengine == "qnnpack": + ret = 2 + elif qengine == "onednn": + ret = 3 + elif qengine == "x86": + ret = 4 + else: + ret = -1 + raise RuntimeError(f"{qengine} is not a valid value for quantized engine") + return ret + + +# This function should correspond to the enums present in c10/core/QEngine.h +def _get_qengine_str(qengine: int) -> str: + all_engines = {0: "none", 1: "fbgemm", 2: "qnnpack", 3: "onednn", 4: "x86"} + return all_engines.get(qengine, "*undefined") + + +class _QEngineProp: + def __get__(self, obj, objtype) -> str: + return _get_qengine_str(torch._C._get_qengine()) + + def __set__(self, obj, val: str) -> None: + torch._C._set_qengine(_get_qengine_id(val)) + + +class _SupportedQEnginesProp: + def __get__(self, obj, objtype) -> list[str]: + qengines = torch._C._supported_qengines() + return [_get_qengine_str(qe) for qe in qengines] + + def __set__(self, obj, val) -> None: + raise RuntimeError("Assignment not supported") + + +class QuantizedEngine(types.ModuleType): + def __init__(self, m, name): + super().__init__(name) + self.m = m + + def __getattr__(self, attr): + return self.m.__getattribute__(attr) + + engine = _QEngineProp() + supported_engines = _SupportedQEnginesProp() + + +# This is the sys.modules replacement trick, see +# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273 +sys.modules[__name__] = QuantizedEngine(sys.modules[__name__], __name__) +engine: str +supported_engines: list[str] diff --git a/shared/package-files/bc/bc441a3429132a48239ae17197349cb8ba4c2452c26ec7031ab440d1fed63059/base.py b/shared/package-files/bc/bc441a3429132a48239ae17197349cb8ba4c2452c26ec7031ab440d1fed63059/base.py new file mode 100644 index 0000000000000000000000000000000000000000..abfe2369b0d0dba2f3ef34e48a490158ec948e90 --- /dev/null +++ b/shared/package-files/bc/bc441a3429132a48239ae17197349cb8ba4c2452c26ec7031ab440d1fed63059/base.py @@ -0,0 +1,2588 @@ +""" +An interface for extending pandas with custom arrays. + +.. warning:: + + This is an experimental API and subject to breaking changes + without warning. +""" +from __future__ import annotations + +import operator +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Literal, + cast, + overload, +) +import warnings + +import numpy as np + +from pandas._libs import ( + algos as libalgos, + lib, +) +from pandas.compat import set_function_name +from pandas.compat.numpy import function as nv +from pandas.errors import AbstractMethodError +from pandas.util._decorators import ( + Appender, + Substitution, + cache_readonly, +) +from pandas.util._exceptions import find_stack_level +from pandas.util._validators import ( + validate_bool_kwarg, + validate_fillna_kwargs, + validate_insert_loc, +) + +from pandas.core.dtypes.cast import maybe_cast_pointwise_result +from pandas.core.dtypes.common import ( + is_list_like, + is_scalar, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCIndex, + ABCSeries, +) +from pandas.core.dtypes.missing import isna + +from pandas.core import ( + arraylike, + missing, + roperator, +) +from pandas.core.algorithms import ( + duplicated, + factorize_array, + isin, + map_array, + mode, + rank, + unique, +) +from pandas.core.array_algos.quantile import quantile_with_mask +from pandas.core.missing import _fill_limit_area_1d +from pandas.core.sorting import ( + nargminmax, + nargsort, +) + +if TYPE_CHECKING: + from collections.abc import ( + Iterator, + Sequence, + ) + + from pandas._typing import ( + ArrayLike, + AstypeArg, + AxisInt, + Dtype, + DtypeObj, + FillnaOptions, + InterpolateOptions, + NumpySorter, + NumpyValueArrayLike, + PositionalIndexer, + ScalarIndexer, + Self, + SequenceIndexer, + Shape, + SortKind, + TakeIndexer, + npt, + ) + + from pandas import Index + +_extension_array_shared_docs: dict[str, str] = {} + + +class ExtensionArray: + """ + Abstract base class for custom 1-D array types. + + pandas will recognize instances of this class as proper arrays + with a custom type and will not attempt to coerce them to objects. They + may be stored directly inside a :class:`DataFrame` or :class:`Series`. + + Attributes + ---------- + dtype + nbytes + ndim + shape + + Methods + ------- + argsort + astype + copy + dropna + duplicated + factorize + fillna + equals + insert + interpolate + isin + isna + ravel + repeat + searchsorted + shift + take + tolist + unique + view + _accumulate + _concat_same_type + _explode + _formatter + _from_factorized + _from_sequence + _from_sequence_of_strings + _hash_pandas_object + _pad_or_backfill + _reduce + _values_for_argsort + _values_for_factorize + + Notes + ----- + The interface includes the following abstract methods that must be + implemented by subclasses: + + * _from_sequence + * _from_factorized + * __getitem__ + * __len__ + * __eq__ + * dtype + * nbytes + * isna + * take + * copy + * _concat_same_type + * interpolate + + A default repr displaying the type, (truncated) data, length, + and dtype is provided. It can be customized or replaced by + by overriding: + + * __repr__ : A default repr for the ExtensionArray. + * _formatter : Print scalars inside a Series or DataFrame. + + Some methods require casting the ExtensionArray to an ndarray of Python + objects with ``self.astype(object)``, which may be expensive. When + performance is a concern, we highly recommend overriding the following + methods: + + * fillna + * _pad_or_backfill + * dropna + * unique + * factorize / _values_for_factorize + * argsort, argmax, argmin / _values_for_argsort + * searchsorted + * map + + The remaining methods implemented on this class should be performant, + as they only compose abstract methods. Still, a more efficient + implementation may be available, and these methods can be overridden. + + One can implement methods to handle array accumulations or reductions. + + * _accumulate + * _reduce + + One can implement methods to handle parsing from strings that will be used + in methods such as ``pandas.io.parsers.read_csv``. + + * _from_sequence_of_strings + + This class does not inherit from 'abc.ABCMeta' for performance reasons. + Methods and properties required by the interface raise + ``pandas.errors.AbstractMethodError`` and no ``register`` method is + provided for registering virtual subclasses. + + ExtensionArrays are limited to 1 dimension. + + They may be backed by none, one, or many NumPy arrays. For example, + ``pandas.Categorical`` is an extension array backed by two arrays, + one for codes and one for categories. An array of IPv6 address may + be backed by a NumPy structured array with two fields, one for the + lower 64 bits and one for the upper 64 bits. Or they may be backed + by some other storage type, like Python lists. Pandas makes no + assumptions on how the data are stored, just that it can be converted + to a NumPy array. + The ExtensionArray interface does not impose any rules on how this data + is stored. However, currently, the backing data cannot be stored in + attributes called ``.values`` or ``._values`` to ensure full compatibility + with pandas internals. But other names as ``.data``, ``._data``, + ``._items``, ... can be freely used. + + If implementing NumPy's ``__array_ufunc__`` interface, pandas expects + that + + 1. You defer by returning ``NotImplemented`` when any Series are present + in `inputs`. Pandas will extract the arrays and call the ufunc again. + 2. You define a ``_HANDLED_TYPES`` tuple as an attribute on the class. + Pandas inspect this to determine whether the ufunc is valid for the + types present. + + See :ref:`extending.extension.ufunc` for more. + + By default, ExtensionArrays are not hashable. Immutable subclasses may + override this behavior. + + Examples + -------- + Please see the following: + + https://github.com/pandas-dev/pandas/blob/main/pandas/tests/extension/list/array.py + """ + + # '_typ' is for pandas.core.dtypes.generic.ABCExtensionArray. + # Don't override this. + _typ = "extension" + + # similar to __array_priority__, positions ExtensionArray after Index, + # Series, and DataFrame. EA subclasses may override to choose which EA + # subclass takes priority. If overriding, the value should always be + # strictly less than 2000 to be below Index.__pandas_priority__. + __pandas_priority__ = 1000 + + # ------------------------------------------------------------------------ + # Constructors + # ------------------------------------------------------------------------ + + @classmethod + def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy: bool = False): + """ + Construct a new ExtensionArray from a sequence of scalars. + + Parameters + ---------- + scalars : Sequence + Each element will be an instance of the scalar type for this + array, ``cls.dtype.type`` or be converted into this type in this method. + dtype : dtype, optional + Construct for this particular dtype. This should be a Dtype + compatible with the ExtensionArray. + copy : bool, default False + If True, copy the underlying data. + + Returns + ------- + ExtensionArray + + Examples + -------- + >>> pd.arrays.IntegerArray._from_sequence([4, 5]) + + [4, 5] + Length: 2, dtype: Int64 + """ + raise AbstractMethodError(cls) + + @classmethod + def _from_scalars(cls, scalars, *, dtype: DtypeObj) -> Self: + """ + Strict analogue to _from_sequence, allowing only sequences of scalars + that should be specifically inferred to the given dtype. + + Parameters + ---------- + scalars : sequence + dtype : ExtensionDtype + + Raises + ------ + TypeError or ValueError + + Notes + ----- + This is called in a try/except block when casting the result of a + pointwise operation. + """ + try: + return cls._from_sequence(scalars, dtype=dtype, copy=False) + except (ValueError, TypeError): + raise + except Exception: + warnings.warn( + "_from_scalars should only raise ValueError or TypeError. " + "Consider overriding _from_scalars where appropriate.", + stacklevel=find_stack_level(), + ) + raise + + @classmethod + def _from_sequence_of_strings( + cls, strings, *, dtype: Dtype | None = None, copy: bool = False + ): + """ + Construct a new ExtensionArray from a sequence of strings. + + Parameters + ---------- + strings : Sequence + Each element will be an instance of the scalar type for this + array, ``cls.dtype.type``. + dtype : dtype, optional + Construct for this particular dtype. This should be a Dtype + compatible with the ExtensionArray. + copy : bool, default False + If True, copy the underlying data. + + Returns + ------- + ExtensionArray + + Examples + -------- + >>> pd.arrays.IntegerArray._from_sequence_of_strings(["1", "2", "3"]) + + [1, 2, 3] + Length: 3, dtype: Int64 + """ + raise AbstractMethodError(cls) + + @classmethod + def _from_factorized(cls, values, original): + """ + Reconstruct an ExtensionArray after factorization. + + Parameters + ---------- + values : ndarray + An integer ndarray with the factorized values. + original : ExtensionArray + The original ExtensionArray that factorize was called on. + + See Also + -------- + factorize : Top-level factorize method that dispatches here. + ExtensionArray.factorize : Encode the extension array as an enumerated type. + + Examples + -------- + >>> interv_arr = pd.arrays.IntervalArray([pd.Interval(0, 1), + ... pd.Interval(1, 5), pd.Interval(1, 5)]) + >>> codes, uniques = pd.factorize(interv_arr) + >>> pd.arrays.IntervalArray._from_factorized(uniques, interv_arr) + + [(0, 1], (1, 5]] + Length: 2, dtype: interval[int64, right] + """ + raise AbstractMethodError(cls) + + # ------------------------------------------------------------------------ + # Must be a Sequence + # ------------------------------------------------------------------------ + @overload + def __getitem__(self, item: ScalarIndexer) -> Any: + ... + + @overload + def __getitem__(self, item: SequenceIndexer) -> Self: + ... + + def __getitem__(self, item: PositionalIndexer) -> Self | Any: + """ + Select a subset of self. + + Parameters + ---------- + item : int, slice, or ndarray + * int: The position in 'self' to get. + + * slice: A slice object, where 'start', 'stop', and 'step' are + integers or None + + * ndarray: A 1-d boolean NumPy ndarray the same length as 'self' + + * list[int]: A list of int + + Returns + ------- + item : scalar or ExtensionArray + + Notes + ----- + For scalar ``item``, return a scalar value suitable for the array's + type. This should be an instance of ``self.dtype.type``. + + For slice ``key``, return an instance of ``ExtensionArray``, even + if the slice is length 0 or 1. + + For a boolean mask, return an instance of ``ExtensionArray``, filtered + to the values where ``item`` is True. + """ + raise AbstractMethodError(self) + + def __setitem__(self, key, value) -> None: + """ + Set one or more values inplace. + + This method is not required to satisfy the pandas extension array + interface. + + Parameters + ---------- + key : int, ndarray, or slice + When called from, e.g. ``Series.__setitem__``, ``key`` will be + one of + + * scalar int + * ndarray of integers. + * boolean ndarray + * slice object + + value : ExtensionDtype.type, Sequence[ExtensionDtype.type], or object + value or values to be set of ``key``. + + Returns + ------- + None + """ + # Some notes to the ExtensionArray implementer who may have ended up + # here. While this method is not required for the interface, if you + # *do* choose to implement __setitem__, then some semantics should be + # observed: + # + # * Setting multiple values : ExtensionArrays should support setting + # multiple values at once, 'key' will be a sequence of integers and + # 'value' will be a same-length sequence. + # + # * Broadcasting : For a sequence 'key' and a scalar 'value', + # each position in 'key' should be set to 'value'. + # + # * Coercion : Most users will expect basic coercion to work. For + # example, a string like '2018-01-01' is coerced to a datetime + # when setting on a datetime64ns array. In general, if the + # __init__ method coerces that value, then so should __setitem__ + # Note, also, that Series/DataFrame.where internally use __setitem__ + # on a copy of the data. + raise NotImplementedError(f"{type(self)} does not implement __setitem__.") + + def __len__(self) -> int: + """ + Length of this array + + Returns + ------- + length : int + """ + raise AbstractMethodError(self) + + def __iter__(self) -> Iterator[Any]: + """ + Iterate over elements of the array. + """ + # This needs to be implemented so that pandas recognizes extension + # arrays as list-like. The default implementation makes successive + # calls to ``__getitem__``, which may be slower than necessary. + for i in range(len(self)): + yield self[i] + + def __contains__(self, item: object) -> bool | np.bool_: + """ + Return for `item in self`. + """ + # GH37867 + # comparisons of any item to pd.NA always return pd.NA, so e.g. "a" in [pd.NA] + # would raise a TypeError. The implementation below works around that. + if is_scalar(item) and isna(item): + if not self._can_hold_na: + return False + elif item is self.dtype.na_value or isinstance(item, self.dtype.type): + return self._hasna + else: + return False + else: + # error: Item "ExtensionArray" of "Union[ExtensionArray, ndarray]" has no + # attribute "any" + return (item == self).any() # type: ignore[union-attr] + + # error: Signature of "__eq__" incompatible with supertype "object" + def __eq__(self, other: object) -> ArrayLike: # type: ignore[override] + """ + Return for `self == other` (element-wise equality). + """ + # Implementer note: this should return a boolean numpy ndarray or + # a boolean ExtensionArray. + # When `other` is one of Series, Index, or DataFrame, this method should + # return NotImplemented (to ensure that those objects are responsible for + # first unpacking the arrays, and then dispatch the operation to the + # underlying arrays) + raise AbstractMethodError(self) + + # error: Signature of "__ne__" incompatible with supertype "object" + def __ne__(self, other: object) -> ArrayLike: # type: ignore[override] + """ + Return for `self != other` (element-wise in-equality). + """ + # error: Unsupported operand type for ~ ("ExtensionArray") + return ~(self == other) # type: ignore[operator] + + def to_numpy( + self, + dtype: npt.DTypeLike | None = None, + copy: bool = False, + na_value: object = lib.no_default, + ) -> np.ndarray: + """ + Convert to a NumPy ndarray. + + This is similar to :meth:`numpy.asarray`, but may provide additional control + over how the conversion is done. + + Parameters + ---------- + dtype : str or numpy.dtype, optional + The dtype to pass to :meth:`numpy.asarray`. + copy : bool, default False + Whether to ensure that the returned value is a not a view on + another array. Note that ``copy=False`` does not *ensure* that + ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that + a copy is made, even if not strictly necessary. + na_value : Any, optional + The value to use for missing values. The default value depends + on `dtype` and the type of the array. + + Returns + ------- + numpy.ndarray + """ + result = np.asarray(self, dtype=dtype) + if copy or na_value is not lib.no_default: + result = result.copy() + if na_value is not lib.no_default: + result[self.isna()] = na_value + return result + + # ------------------------------------------------------------------------ + # Required attributes + # ------------------------------------------------------------------------ + + @property + def dtype(self) -> ExtensionDtype: + """ + An instance of ExtensionDtype. + + Examples + -------- + >>> pd.array([1, 2, 3]).dtype + Int64Dtype() + """ + raise AbstractMethodError(self) + + @property + def shape(self) -> Shape: + """ + Return a tuple of the array dimensions. + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.shape + (3,) + """ + return (len(self),) + + @property + def size(self) -> int: + """ + The number of elements in the array. + """ + # error: Incompatible return value type (got "signedinteger[_64Bit]", + # expected "int") [return-value] + return np.prod(self.shape) # type: ignore[return-value] + + @property + def ndim(self) -> int: + """ + Extension Arrays are only allowed to be 1-dimensional. + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.ndim + 1 + """ + return 1 + + @property + def nbytes(self) -> int: + """ + The number of bytes needed to store this object in memory. + + Examples + -------- + >>> pd.array([1, 2, 3]).nbytes + 27 + """ + # If this is expensive to compute, return an approximate lower bound + # on the number of bytes needed. + raise AbstractMethodError(self) + + # ------------------------------------------------------------------------ + # Additional Methods + # ------------------------------------------------------------------------ + + @overload + def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray: + ... + + @overload + def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray: + ... + + @overload + def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike: + ... + + def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike: + """ + Cast to a NumPy array or ExtensionArray with 'dtype'. + + Parameters + ---------- + dtype : str or dtype + Typecode or data-type to which the array is cast. + copy : bool, default True + Whether to copy the data, even if not necessary. If False, + a copy is made only if the old dtype does not match the + new dtype. + + Returns + ------- + np.ndarray or pandas.api.extensions.ExtensionArray + An ``ExtensionArray`` if ``dtype`` is ``ExtensionDtype``, + otherwise a Numpy ndarray with ``dtype`` for its dtype. + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr + + [1, 2, 3] + Length: 3, dtype: Int64 + + Casting to another ``ExtensionDtype`` returns an ``ExtensionArray``: + + >>> arr1 = arr.astype('Float64') + >>> arr1 + + [1.0, 2.0, 3.0] + Length: 3, dtype: Float64 + >>> arr1.dtype + Float64Dtype() + + Otherwise, we will get a Numpy ndarray: + + >>> arr2 = arr.astype('float64') + >>> arr2 + array([1., 2., 3.]) + >>> arr2.dtype + dtype('float64') + """ + dtype = pandas_dtype(dtype) + if dtype == self.dtype: + if not copy: + return self + else: + return self.copy() + + if isinstance(dtype, ExtensionDtype): + cls = dtype.construct_array_type() + return cls._from_sequence(self, dtype=dtype, copy=copy) + + elif lib.is_np_dtype(dtype, "M"): + from pandas.core.arrays import DatetimeArray + + return DatetimeArray._from_sequence(self, dtype=dtype, copy=copy) + + elif lib.is_np_dtype(dtype, "m"): + from pandas.core.arrays import TimedeltaArray + + return TimedeltaArray._from_sequence(self, dtype=dtype, copy=copy) + + if not copy: + return np.asarray(self, dtype=dtype) + else: + return np.array(self, dtype=dtype, copy=copy) + + def isna(self) -> np.ndarray | ExtensionArraySupportsAnyAll: + """ + A 1-D array indicating if each value is missing. + + Returns + ------- + numpy.ndarray or pandas.api.extensions.ExtensionArray + In most cases, this should return a NumPy ndarray. For + exceptional cases like ``SparseArray``, where returning + an ndarray would be expensive, an ExtensionArray may be + returned. + + Notes + ----- + If returning an ExtensionArray, then + + * ``na_values._is_boolean`` should be True + * `na_values` should implement :func:`ExtensionArray._reduce` + * ``na_values.any`` and ``na_values.all`` should be implemented + + Examples + -------- + >>> arr = pd.array([1, 2, np.nan, np.nan]) + >>> arr.isna() + array([False, False, True, True]) + """ + raise AbstractMethodError(self) + + @property + def _hasna(self) -> bool: + # GH#22680 + """ + Equivalent to `self.isna().any()`. + + Some ExtensionArray subclasses may be able to optimize this check. + """ + return bool(self.isna().any()) + + def _values_for_argsort(self) -> np.ndarray: + """ + Return values for sorting. + + Returns + ------- + ndarray + The transformed values should maintain the ordering between values + within the array. + + See Also + -------- + ExtensionArray.argsort : Return the indices that would sort this array. + + Notes + ----- + The caller is responsible for *not* modifying these values in-place, so + it is safe for implementers to give views on ``self``. + + Functions that use this (e.g. ``ExtensionArray.argsort``) should ignore + entries with missing values in the original array (according to + ``self.isna()``). This means that the corresponding entries in the returned + array don't need to be modified to sort correctly. + + Examples + -------- + In most cases, this is the underlying Numpy array of the ``ExtensionArray``: + + >>> arr = pd.array([1, 2, 3]) + >>> arr._values_for_argsort() + array([1, 2, 3]) + """ + # Note: this is used in `ExtensionArray.argsort/argmin/argmax`. + return np.array(self) + + def argsort( + self, + *, + ascending: bool = True, + kind: SortKind = "quicksort", + na_position: str = "last", + **kwargs, + ) -> np.ndarray: + """ + Return the indices that would sort this array. + + Parameters + ---------- + ascending : bool, default True + Whether the indices should result in an ascending + or descending sort. + kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional + Sorting algorithm. + na_position : {'first', 'last'}, default 'last' + If ``'first'``, put ``NaN`` values at the beginning. + If ``'last'``, put ``NaN`` values at the end. + *args, **kwargs: + Passed through to :func:`numpy.argsort`. + + Returns + ------- + np.ndarray[np.intp] + Array of indices that sort ``self``. If NaN values are contained, + NaN values are placed at the end. + + See Also + -------- + numpy.argsort : Sorting implementation used internally. + + Examples + -------- + >>> arr = pd.array([3, 1, 2, 5, 4]) + >>> arr.argsort() + array([1, 2, 0, 4, 3]) + """ + # Implementer note: You have two places to override the behavior of + # argsort. + # 1. _values_for_argsort : construct the values passed to np.argsort + # 2. argsort : total control over sorting. In case of overriding this, + # it is recommended to also override argmax/argmin + ascending = nv.validate_argsort_with_ascending(ascending, (), kwargs) + + values = self._values_for_argsort() + return nargsort( + values, + kind=kind, + ascending=ascending, + na_position=na_position, + mask=np.asarray(self.isna()), + ) + + def argmin(self, skipna: bool = True) -> int: + """ + Return the index of minimum value. + + In case of multiple occurrences of the minimum value, the index + corresponding to the first occurrence is returned. + + Parameters + ---------- + skipna : bool, default True + + Returns + ------- + int + + See Also + -------- + ExtensionArray.argmax : Return the index of the maximum value. + + Examples + -------- + >>> arr = pd.array([3, 1, 2, 5, 4]) + >>> arr.argmin() + 1 + """ + # Implementer note: You have two places to override the behavior of + # argmin. + # 1. _values_for_argsort : construct the values used in nargminmax + # 2. argmin itself : total control over sorting. + validate_bool_kwarg(skipna, "skipna") + if not skipna and self._hasna: + raise NotImplementedError + return nargminmax(self, "argmin") + + def argmax(self, skipna: bool = True) -> int: + """ + Return the index of maximum value. + + In case of multiple occurrences of the maximum value, the index + corresponding to the first occurrence is returned. + + Parameters + ---------- + skipna : bool, default True + + Returns + ------- + int + + See Also + -------- + ExtensionArray.argmin : Return the index of the minimum value. + + Examples + -------- + >>> arr = pd.array([3, 1, 2, 5, 4]) + >>> arr.argmax() + 3 + """ + # Implementer note: You have two places to override the behavior of + # argmax. + # 1. _values_for_argsort : construct the values used in nargminmax + # 2. argmax itself : total control over sorting. + validate_bool_kwarg(skipna, "skipna") + if not skipna and self._hasna: + raise NotImplementedError + return nargminmax(self, "argmax") + + def interpolate( + self, + *, + method: InterpolateOptions, + axis: int, + index: Index, + limit, + limit_direction, + limit_area, + copy: bool, + **kwargs, + ) -> Self: + """ + See DataFrame.interpolate.__doc__. + + Examples + -------- + >>> arr = pd.arrays.NumpyExtensionArray(np.array([0, 1, np.nan, 3])) + >>> arr.interpolate(method="linear", + ... limit=3, + ... limit_direction="forward", + ... index=pd.Index([1, 2, 3, 4]), + ... fill_value=1, + ... copy=False, + ... axis=0, + ... limit_area="inside" + ... ) + + [0.0, 1.0, 2.0, 3.0] + Length: 4, dtype: float64 + """ + # NB: we return type(self) even if copy=False + raise NotImplementedError( + f"{type(self).__name__} does not implement interpolate" + ) + + def _pad_or_backfill( + self, + *, + method: FillnaOptions, + limit: int | None = None, + limit_area: Literal["inside", "outside"] | None = None, + copy: bool = True, + ) -> Self: + """ + Pad or backfill values, used by Series/DataFrame ffill and bfill. + + Parameters + ---------- + method : {'backfill', 'bfill', 'pad', 'ffill'} + Method to use for filling holes in reindexed Series: + + * pad / ffill: propagate last valid observation forward to next valid. + * backfill / bfill: use NEXT valid observation to fill gap. + + limit : int, default None + This is the maximum number of consecutive + NaN values to forward/backward fill. In other words, if there is + a gap with more than this number of consecutive NaNs, it will only + be partially filled. If method is not specified, this is the + maximum number of entries along the entire axis where NaNs will be + filled. + + copy : bool, default True + Whether to make a copy of the data before filling. If False, then + the original should be modified and no new memory should be allocated. + For ExtensionArray subclasses that cannot do this, it is at the + author's discretion whether to ignore "copy=False" or to raise. + The base class implementation ignores the keyword if any NAs are + present. + + Returns + ------- + Same type as self + + Examples + -------- + >>> arr = pd.array([np.nan, np.nan, 2, 3, np.nan, np.nan]) + >>> arr._pad_or_backfill(method="backfill", limit=1) + + [, 2, 2, 3, , ] + Length: 6, dtype: Int64 + """ + + # If a 3rd-party EA has implemented this functionality in fillna, + # we warn that they need to implement _pad_or_backfill instead. + if ( + type(self).fillna is not ExtensionArray.fillna + and type(self)._pad_or_backfill is ExtensionArray._pad_or_backfill + ): + # Check for _pad_or_backfill here allows us to call + # super()._pad_or_backfill without getting this warning + warnings.warn( + "ExtensionArray.fillna 'method' keyword is deprecated. " + "In a future version. arr._pad_or_backfill will be called " + "instead. 3rd-party ExtensionArray authors need to implement " + "_pad_or_backfill.", + DeprecationWarning, + stacklevel=find_stack_level(), + ) + if limit_area is not None: + raise NotImplementedError( + f"{type(self).__name__} does not implement limit_area " + "(added in pandas 2.2). 3rd-party ExtnsionArray authors " + "need to add this argument to _pad_or_backfill." + ) + return self.fillna(method=method, limit=limit) + + mask = self.isna() + + if mask.any(): + # NB: the base class does not respect the "copy" keyword + meth = missing.clean_fill_method(method) + + npmask = np.asarray(mask) + if limit_area is not None and not npmask.all(): + _fill_limit_area_1d(npmask, limit_area) + if meth == "pad": + indexer = libalgos.get_fill_indexer(npmask, limit=limit) + return self.take(indexer, allow_fill=True) + else: + # i.e. meth == "backfill" + indexer = libalgos.get_fill_indexer(npmask[::-1], limit=limit)[::-1] + return self[::-1].take(indexer, allow_fill=True) + + else: + if not copy: + return self + new_values = self.copy() + return new_values + + def fillna( + self, + value: object | ArrayLike | None = None, + method: FillnaOptions | None = None, + limit: int | None = None, + copy: bool = True, + ) -> Self: + """ + Fill NA/NaN values using the specified method. + + Parameters + ---------- + value : scalar, array-like + If a scalar value is passed it is used to fill all missing values. + Alternatively, an array-like "value" can be given. It's expected + that the array-like have the same length as 'self'. + method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None + Method to use for filling holes in reindexed Series: + + * pad / ffill: propagate last valid observation forward to next valid. + * backfill / bfill: use NEXT valid observation to fill gap. + + .. deprecated:: 2.1.0 + + limit : int, default None + If method is specified, this is the maximum number of consecutive + NaN values to forward/backward fill. In other words, if there is + a gap with more than this number of consecutive NaNs, it will only + be partially filled. If method is not specified, this is the + maximum number of entries along the entire axis where NaNs will be + filled. + + .. deprecated:: 2.1.0 + + copy : bool, default True + Whether to make a copy of the data before filling. If False, then + the original should be modified and no new memory should be allocated. + For ExtensionArray subclasses that cannot do this, it is at the + author's discretion whether to ignore "copy=False" or to raise. + The base class implementation ignores the keyword in pad/backfill + cases. + + Returns + ------- + ExtensionArray + With NA/NaN filled. + + Examples + -------- + >>> arr = pd.array([np.nan, np.nan, 2, 3, np.nan, np.nan]) + >>> arr.fillna(0) + + [0, 0, 2, 3, 0, 0] + Length: 6, dtype: Int64 + """ + if method is not None: + warnings.warn( + f"The 'method' keyword in {type(self).__name__}.fillna is " + "deprecated and will be removed in a future version.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + value, method = validate_fillna_kwargs(value, method) + + mask = self.isna() + # error: Argument 2 to "check_value_size" has incompatible type + # "ExtensionArray"; expected "ndarray" + value = missing.check_value_size( + value, mask, len(self) # type: ignore[arg-type] + ) + + if mask.any(): + if method is not None: + meth = missing.clean_fill_method(method) + + npmask = np.asarray(mask) + if meth == "pad": + indexer = libalgos.get_fill_indexer(npmask, limit=limit) + return self.take(indexer, allow_fill=True) + else: + # i.e. meth == "backfill" + indexer = libalgos.get_fill_indexer(npmask[::-1], limit=limit)[::-1] + return self[::-1].take(indexer, allow_fill=True) + else: + # fill with value + if not copy: + new_values = self[:] + else: + new_values = self.copy() + new_values[mask] = value + else: + if not copy: + new_values = self[:] + else: + new_values = self.copy() + return new_values + + def dropna(self) -> Self: + """ + Return ExtensionArray without NA values. + + Returns + ------- + + Examples + -------- + >>> pd.array([1, 2, np.nan]).dropna() + + [1, 2] + Length: 2, dtype: Int64 + """ + # error: Unsupported operand type for ~ ("ExtensionArray") + return self[~self.isna()] # type: ignore[operator] + + def duplicated( + self, keep: Literal["first", "last", False] = "first" + ) -> npt.NDArray[np.bool_]: + """ + Return boolean ndarray denoting duplicate values. + + Parameters + ---------- + keep : {'first', 'last', False}, default 'first' + - ``first`` : Mark duplicates as ``True`` except for the first occurrence. + - ``last`` : Mark duplicates as ``True`` except for the last occurrence. + - False : Mark all duplicates as ``True``. + + Returns + ------- + ndarray[bool] + + Examples + -------- + >>> pd.array([1, 1, 2, 3, 3], dtype="Int64").duplicated() + array([False, True, False, False, True]) + """ + mask = self.isna().astype(np.bool_, copy=False) + return duplicated(values=self, keep=keep, mask=mask) + + def shift(self, periods: int = 1, fill_value: object = None) -> ExtensionArray: + """ + Shift values by desired number. + + Newly introduced missing values are filled with + ``self.dtype.na_value``. + + Parameters + ---------- + periods : int, default 1 + The number of periods to shift. Negative values are allowed + for shifting backwards. + + fill_value : object, optional + The scalar value to use for newly introduced missing values. + The default is ``self.dtype.na_value``. + + Returns + ------- + ExtensionArray + Shifted. + + Notes + ----- + If ``self`` is empty or ``periods`` is 0, a copy of ``self`` is + returned. + + If ``periods > len(self)``, then an array of size + len(self) is returned, with all values filled with + ``self.dtype.na_value``. + + For 2-dimensional ExtensionArrays, we are always shifting along axis=0. + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.shift(2) + + [, , 1] + Length: 3, dtype: Int64 + """ + # Note: this implementation assumes that `self.dtype.na_value` can be + # stored in an instance of your ExtensionArray with `self.dtype`. + if not len(self) or periods == 0: + return self.copy() + + if isna(fill_value): + fill_value = self.dtype.na_value + + empty = self._from_sequence( + [fill_value] * min(abs(periods), len(self)), dtype=self.dtype + ) + if periods > 0: + a = empty + b = self[:-periods] + else: + a = self[abs(periods) :] + b = empty + return self._concat_same_type([a, b]) + + def unique(self) -> Self: + """ + Compute the ExtensionArray of unique values. + + Returns + ------- + pandas.api.extensions.ExtensionArray + + Examples + -------- + >>> arr = pd.array([1, 2, 3, 1, 2, 3]) + >>> arr.unique() + + [1, 2, 3] + Length: 3, dtype: Int64 + """ + uniques = unique(self.astype(object)) + return self._from_sequence(uniques, dtype=self.dtype) + + def searchsorted( + self, + value: NumpyValueArrayLike | ExtensionArray, + side: Literal["left", "right"] = "left", + sorter: NumpySorter | None = None, + ) -> npt.NDArray[np.intp] | np.intp: + """ + Find indices where elements should be inserted to maintain order. + + Find the indices into a sorted array `self` (a) such that, if the + corresponding elements in `value` were inserted before the indices, + the order of `self` would be preserved. + + Assuming that `self` is sorted: + + ====== ================================ + `side` returned index `i` satisfies + ====== ================================ + left ``self[i-1] < value <= self[i]`` + right ``self[i-1] <= value < self[i]`` + ====== ================================ + + Parameters + ---------- + value : array-like, list or scalar + Value(s) to insert into `self`. + side : {'left', 'right'}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `self`). + sorter : 1-D array-like, optional + Optional array of integer indices that sort array a into ascending + order. They are typically the result of argsort. + + Returns + ------- + array of ints or int + If value is array-like, array of insertion points. + If value is scalar, a single integer. + + See Also + -------- + numpy.searchsorted : Similar method from NumPy. + + Examples + -------- + >>> arr = pd.array([1, 2, 3, 5]) + >>> arr.searchsorted([4]) + array([3]) + """ + # Note: the base tests provided by pandas only test the basics. + # We do not test + # 1. Values outside the range of the `data_for_sorting` fixture + # 2. Values between the values in the `data_for_sorting` fixture + # 3. Missing values. + arr = self.astype(object) + if isinstance(value, ExtensionArray): + value = value.astype(object) + return arr.searchsorted(value, side=side, sorter=sorter) + + def equals(self, other: object) -> bool: + """ + Return if another array is equivalent to this array. + + Equivalent means that both arrays have the same shape and dtype, and + all values compare equal. Missing values in the same location are + considered equal (in contrast with normal equality). + + Parameters + ---------- + other : ExtensionArray + Array to compare to this Array. + + Returns + ------- + boolean + Whether the arrays are equivalent. + + Examples + -------- + >>> arr1 = pd.array([1, 2, np.nan]) + >>> arr2 = pd.array([1, 2, np.nan]) + >>> arr1.equals(arr2) + True + """ + if type(self) != type(other): + return False + other = cast(ExtensionArray, other) + if self.dtype != other.dtype: + return False + elif len(self) != len(other): + return False + else: + equal_values = self == other + if isinstance(equal_values, ExtensionArray): + # boolean array with NA -> fill with False + equal_values = equal_values.fillna(False) + # error: Unsupported left operand type for & ("ExtensionArray") + equal_na = self.isna() & other.isna() # type: ignore[operator] + return bool((equal_values | equal_na).all()) + + def isin(self, values: ArrayLike) -> npt.NDArray[np.bool_]: + """ + Pointwise comparison for set containment in the given values. + + Roughly equivalent to `np.array([x in values for x in self])` + + Parameters + ---------- + values : np.ndarray or ExtensionArray + + Returns + ------- + np.ndarray[bool] + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.isin([1]) + + [True, False, False] + Length: 3, dtype: boolean + """ + return isin(np.asarray(self), values) + + def _values_for_factorize(self) -> tuple[np.ndarray, Any]: + """ + Return an array and missing value suitable for factorization. + + Returns + ------- + values : ndarray + An array suitable for factorization. This should maintain order + and be a supported dtype (Float64, Int64, UInt64, String, Object). + By default, the extension array is cast to object dtype. + na_value : object + The value in `values` to consider missing. This will be treated + as NA in the factorization routines, so it will be coded as + `-1` and not included in `uniques`. By default, + ``np.nan`` is used. + + Notes + ----- + The values returned by this method are also used in + :func:`pandas.util.hash_pandas_object`. If needed, this can be + overridden in the ``self._hash_pandas_object()`` method. + + Examples + -------- + >>> pd.array([1, 2, 3])._values_for_factorize() + (array([1, 2, 3], dtype=object), nan) + """ + return self.astype(object), np.nan + + def factorize( + self, + use_na_sentinel: bool = True, + ) -> tuple[np.ndarray, ExtensionArray]: + """ + Encode the extension array as an enumerated type. + + Parameters + ---------- + use_na_sentinel : bool, default True + If True, the sentinel -1 will be used for NaN values. If False, + NaN values will be encoded as non-negative integers and will not drop the + NaN from the uniques of the values. + + .. versionadded:: 1.5.0 + + Returns + ------- + codes : ndarray + An integer NumPy array that's an indexer into the original + ExtensionArray. + uniques : ExtensionArray + An ExtensionArray containing the unique values of `self`. + + .. note:: + + uniques will *not* contain an entry for the NA value of + the ExtensionArray if there are any missing values present + in `self`. + + See Also + -------- + factorize : Top-level factorize method that dispatches here. + + Notes + ----- + :meth:`pandas.factorize` offers a `sort` keyword as well. + + Examples + -------- + >>> idx1 = pd.PeriodIndex(["2014-01", "2014-01", "2014-02", "2014-02", + ... "2014-03", "2014-03"], freq="M") + >>> arr, idx = idx1.factorize() + >>> arr + array([0, 0, 1, 1, 2, 2]) + >>> idx + PeriodIndex(['2014-01', '2014-02', '2014-03'], dtype='period[M]') + """ + # Implementer note: There are two ways to override the behavior of + # pandas.factorize + # 1. _values_for_factorize and _from_factorize. + # Specify the values passed to pandas' internal factorization + # routines, and how to convert from those values back to the + # original ExtensionArray. + # 2. ExtensionArray.factorize. + # Complete control over factorization. + arr, na_value = self._values_for_factorize() + + codes, uniques = factorize_array( + arr, use_na_sentinel=use_na_sentinel, na_value=na_value + ) + + uniques_ea = self._from_factorized(uniques, self) + return codes, uniques_ea + + _extension_array_shared_docs[ + "repeat" + ] = """ + Repeat elements of a %(klass)s. + + Returns a new %(klass)s where each element of the current %(klass)s + is repeated consecutively a given number of times. + + Parameters + ---------- + repeats : int or array of ints + The number of repetitions for each element. This should be a + non-negative integer. Repeating 0 times will return an empty + %(klass)s. + axis : None + Must be ``None``. Has no effect but is accepted for compatibility + with numpy. + + Returns + ------- + %(klass)s + Newly created %(klass)s with repeated elements. + + See Also + -------- + Series.repeat : Equivalent function for Series. + Index.repeat : Equivalent function for Index. + numpy.repeat : Similar method for :class:`numpy.ndarray`. + ExtensionArray.take : Take arbitrary positions. + + Examples + -------- + >>> cat = pd.Categorical(['a', 'b', 'c']) + >>> cat + ['a', 'b', 'c'] + Categories (3, object): ['a', 'b', 'c'] + >>> cat.repeat(2) + ['a', 'a', 'b', 'b', 'c', 'c'] + Categories (3, object): ['a', 'b', 'c'] + >>> cat.repeat([1, 2, 3]) + ['a', 'b', 'b', 'c', 'c', 'c'] + Categories (3, object): ['a', 'b', 'c'] + """ + + @Substitution(klass="ExtensionArray") + @Appender(_extension_array_shared_docs["repeat"]) + def repeat(self, repeats: int | Sequence[int], axis: AxisInt | None = None) -> Self: + nv.validate_repeat((), {"axis": axis}) + ind = np.arange(len(self)).repeat(repeats) + return self.take(ind) + + # ------------------------------------------------------------------------ + # Indexing methods + # ------------------------------------------------------------------------ + + def take( + self, + indices: TakeIndexer, + *, + allow_fill: bool = False, + fill_value: Any = None, + ) -> Self: + """ + Take elements from an array. + + Parameters + ---------- + indices : sequence of int or one-dimensional np.ndarray of int + Indices to be taken. + allow_fill : bool, default False + How to handle negative values in `indices`. + + * False: negative values in `indices` indicate positional indices + from the right (the default). This is similar to + :func:`numpy.take`. + + * True: negative values in `indices` indicate + missing values. These values are set to `fill_value`. Any other + other negative values raise a ``ValueError``. + + fill_value : any, optional + Fill value to use for NA-indices when `allow_fill` is True. + This may be ``None``, in which case the default NA value for + the type, ``self.dtype.na_value``, is used. + + For many ExtensionArrays, there will be two representations of + `fill_value`: a user-facing "boxed" scalar, and a low-level + physical NA value. `fill_value` should be the user-facing version, + and the implementation should handle translating that to the + physical version for processing the take if necessary. + + Returns + ------- + ExtensionArray + + Raises + ------ + IndexError + When the indices are out of bounds for the array. + ValueError + When `indices` contains negative values other than ``-1`` + and `allow_fill` is True. + + See Also + -------- + numpy.take : Take elements from an array along an axis. + api.extensions.take : Take elements from an array. + + Notes + ----- + ExtensionArray.take is called by ``Series.__getitem__``, ``.loc``, + ``iloc``, when `indices` is a sequence of values. Additionally, + it's called by :meth:`Series.reindex`, or any other method + that causes realignment, with a `fill_value`. + + Examples + -------- + Here's an example implementation, which relies on casting the + extension array to object dtype. This uses the helper method + :func:`pandas.api.extensions.take`. + + .. code-block:: python + + def take(self, indices, allow_fill=False, fill_value=None): + from pandas.core.algorithms import take + + # If the ExtensionArray is backed by an ndarray, then + # just pass that here instead of coercing to object. + data = self.astype(object) + + if allow_fill and fill_value is None: + fill_value = self.dtype.na_value + + # fill value should always be translated from the scalar + # type for the array, to the physical storage type for + # the data, before passing to take. + + result = take(data, indices, fill_value=fill_value, + allow_fill=allow_fill) + return self._from_sequence(result, dtype=self.dtype) + """ + # Implementer note: The `fill_value` parameter should be a user-facing + # value, an instance of self.dtype.type. When passed `fill_value=None`, + # the default of `self.dtype.na_value` should be used. + # This may differ from the physical storage type your ExtensionArray + # uses. In this case, your implementation is responsible for casting + # the user-facing type to the storage type, before using + # pandas.api.extensions.take + raise AbstractMethodError(self) + + def copy(self) -> Self: + """ + Return a copy of the array. + + Returns + ------- + ExtensionArray + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr2 = arr.copy() + >>> arr[0] = 2 + >>> arr2 + + [1, 2, 3] + Length: 3, dtype: Int64 + """ + raise AbstractMethodError(self) + + def view(self, dtype: Dtype | None = None) -> ArrayLike: + """ + Return a view on the array. + + Parameters + ---------- + dtype : str, np.dtype, or ExtensionDtype, optional + Default None. + + Returns + ------- + ExtensionArray or np.ndarray + A view on the :class:`ExtensionArray`'s data. + + Examples + -------- + This gives view on the underlying data of an ``ExtensionArray`` and is not a + copy. Modifications on either the view or the original ``ExtensionArray`` + will be reflectd on the underlying data: + + >>> arr = pd.array([1, 2, 3]) + >>> arr2 = arr.view() + >>> arr[0] = 2 + >>> arr2 + + [2, 2, 3] + Length: 3, dtype: Int64 + """ + # NB: + # - This must return a *new* object referencing the same data, not self. + # - The only case that *must* be implemented is with dtype=None, + # giving a view with the same dtype as self. + if dtype is not None: + raise NotImplementedError(dtype) + return self[:] + + # ------------------------------------------------------------------------ + # Printing + # ------------------------------------------------------------------------ + + def __repr__(self) -> str: + if self.ndim > 1: + return self._repr_2d() + + from pandas.io.formats.printing import format_object_summary + + # the short repr has no trailing newline, while the truncated + # repr does. So we include a newline in our template, and strip + # any trailing newlines from format_object_summary + data = format_object_summary( + self, self._formatter(), indent_for_name=False + ).rstrip(", \n") + class_name = f"<{type(self).__name__}>\n" + footer = self._get_repr_footer() + return f"{class_name}{data}\n{footer}" + + def _get_repr_footer(self) -> str: + # GH#24278 + if self.ndim > 1: + return f"Shape: {self.shape}, dtype: {self.dtype}" + return f"Length: {len(self)}, dtype: {self.dtype}" + + def _repr_2d(self) -> str: + from pandas.io.formats.printing import format_object_summary + + # the short repr has no trailing newline, while the truncated + # repr does. So we include a newline in our template, and strip + # any trailing newlines from format_object_summary + lines = [ + format_object_summary(x, self._formatter(), indent_for_name=False).rstrip( + ", \n" + ) + for x in self + ] + data = ",\n".join(lines) + class_name = f"<{type(self).__name__}>" + footer = self._get_repr_footer() + return f"{class_name}\n[\n{data}\n]\n{footer}" + + def _formatter(self, boxed: bool = False) -> Callable[[Any], str | None]: + """ + Formatting function for scalar values. + + This is used in the default '__repr__'. The returned formatting + function receives instances of your scalar type. + + Parameters + ---------- + boxed : bool, default False + An indicated for whether or not your array is being printed + within a Series, DataFrame, or Index (True), or just by + itself (False). This may be useful if you want scalar values + to appear differently within a Series versus on its own (e.g. + quoted or not). + + Returns + ------- + Callable[[Any], str] + A callable that gets instances of the scalar type and + returns a string. By default, :func:`repr` is used + when ``boxed=False`` and :func:`str` is used when + ``boxed=True``. + + Examples + -------- + >>> class MyExtensionArray(pd.arrays.NumpyExtensionArray): + ... def _formatter(self, boxed=False): + ... return lambda x: '*' + str(x) + '*' if boxed else repr(x) + '*' + >>> MyExtensionArray(np.array([1, 2, 3, 4])) + + [1*, 2*, 3*, 4*] + Length: 4, dtype: int64 + """ + if boxed: + return str + return repr + + # ------------------------------------------------------------------------ + # Reshaping + # ------------------------------------------------------------------------ + + def transpose(self, *axes: int) -> ExtensionArray: + """ + Return a transposed view on this array. + + Because ExtensionArrays are always 1D, this is a no-op. It is included + for compatibility with np.ndarray. + + Returns + ------- + ExtensionArray + + Examples + -------- + >>> pd.array([1, 2, 3]).transpose() + + [1, 2, 3] + Length: 3, dtype: Int64 + """ + return self[:] + + @property + def T(self) -> ExtensionArray: + return self.transpose() + + def ravel(self, order: Literal["C", "F", "A", "K"] | None = "C") -> ExtensionArray: + """ + Return a flattened view on this array. + + Parameters + ---------- + order : {None, 'C', 'F', 'A', 'K'}, default 'C' + + Returns + ------- + ExtensionArray + + Notes + ----- + - Because ExtensionArrays are 1D-only, this is a no-op. + - The "order" argument is ignored, is for compatibility with NumPy. + + Examples + -------- + >>> pd.array([1, 2, 3]).ravel() + + [1, 2, 3] + Length: 3, dtype: Int64 + """ + return self + + @classmethod + def _concat_same_type(cls, to_concat: Sequence[Self]) -> Self: + """ + Concatenate multiple array of this dtype. + + Parameters + ---------- + to_concat : sequence of this type + + Returns + ------- + ExtensionArray + + Examples + -------- + >>> arr1 = pd.array([1, 2, 3]) + >>> arr2 = pd.array([4, 5, 6]) + >>> pd.arrays.IntegerArray._concat_same_type([arr1, arr2]) + + [1, 2, 3, 4, 5, 6] + Length: 6, dtype: Int64 + """ + # Implementer note: this method will only be called with a sequence of + # ExtensionArrays of this class and with the same dtype as self. This + # should allow "easy" concatenation (no upcasting needed), and result + # in a new ExtensionArray of the same dtype. + # Note: this strict behaviour is only guaranteed starting with pandas 1.1 + raise AbstractMethodError(cls) + + # The _can_hold_na attribute is set to True so that pandas internals + # will use the ExtensionDtype.na_value as the NA value in operations + # such as take(), reindex(), shift(), etc. In addition, those results + # will then be of the ExtensionArray subclass rather than an array + # of objects + @cache_readonly + def _can_hold_na(self) -> bool: + return self.dtype._can_hold_na + + def _accumulate( + self, name: str, *, skipna: bool = True, **kwargs + ) -> ExtensionArray: + """ + Return an ExtensionArray performing an accumulation operation. + + The underlying data type might change. + + Parameters + ---------- + name : str + Name of the function, supported values are: + - cummin + - cummax + - cumsum + - cumprod + skipna : bool, default True + If True, skip NA values. + **kwargs + Additional keyword arguments passed to the accumulation function. + Currently, there is no supported kwarg. + + Returns + ------- + array + + Raises + ------ + NotImplementedError : subclass does not define accumulations + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr._accumulate(name='cumsum') + + [1, 3, 6] + Length: 3, dtype: Int64 + """ + raise NotImplementedError(f"cannot perform {name} with type {self.dtype}") + + def _reduce( + self, name: str, *, skipna: bool = True, keepdims: bool = False, **kwargs + ): + """ + Return a scalar result of performing the reduction operation. + + Parameters + ---------- + name : str + Name of the function, supported values are: + { any, all, min, max, sum, mean, median, prod, + std, var, sem, kurt, skew }. + skipna : bool, default True + If True, skip NaN values. + keepdims : bool, default False + If False, a scalar is returned. + If True, the result has dimension with size one along the reduced axis. + + .. versionadded:: 2.1 + + This parameter is not required in the _reduce signature to keep backward + compatibility, but will become required in the future. If the parameter + is not found in the method signature, a FutureWarning will be emitted. + **kwargs + Additional keyword arguments passed to the reduction function. + Currently, `ddof` is the only supported kwarg. + + Returns + ------- + scalar + + Raises + ------ + TypeError : subclass does not define reductions + + Examples + -------- + >>> pd.array([1, 2, 3])._reduce("min") + 1 + """ + meth = getattr(self, name, None) + if meth is None: + raise TypeError( + f"'{type(self).__name__}' with dtype {self.dtype} " + f"does not support reduction '{name}'" + ) + result = meth(skipna=skipna, **kwargs) + if keepdims: + result = np.array([result]) + + return result + + # https://github.com/python/typeshed/issues/2148#issuecomment-520783318 + # Incompatible types in assignment (expression has type "None", base class + # "object" defined the type as "Callable[[object], int]") + __hash__: ClassVar[None] # type: ignore[assignment] + + # ------------------------------------------------------------------------ + # Non-Optimized Default Methods; in the case of the private methods here, + # these are not guaranteed to be stable across pandas versions. + + def _values_for_json(self) -> np.ndarray: + """ + Specify how to render our entries in to_json. + + Notes + ----- + The dtype on the returned ndarray is not restricted, but for non-native + types that are not specifically handled in objToJSON.c, to_json is + liable to raise. In these cases, it may be safer to return an ndarray + of strings. + """ + return np.asarray(self) + + def _hash_pandas_object( + self, *, encoding: str, hash_key: str, categorize: bool + ) -> npt.NDArray[np.uint64]: + """ + Hook for hash_pandas_object. + + Default is to use the values returned by _values_for_factorize. + + Parameters + ---------- + encoding : str + Encoding for data & key when strings. + hash_key : str + Hash_key for string key to encode. + categorize : bool + Whether to first categorize object arrays before hashing. This is more + efficient when the array contains duplicate values. + + Returns + ------- + np.ndarray[uint64] + + Examples + -------- + >>> pd.array([1, 2])._hash_pandas_object(encoding='utf-8', + ... hash_key="1000000000000000", + ... categorize=False + ... ) + array([ 6238072747940578789, 15839785061582574730], dtype=uint64) + """ + from pandas.core.util.hashing import hash_array + + values, _ = self._values_for_factorize() + return hash_array( + values, encoding=encoding, hash_key=hash_key, categorize=categorize + ) + + def _explode(self) -> tuple[Self, npt.NDArray[np.uint64]]: + """ + Transform each element of list-like to a row. + + For arrays that do not contain list-like elements the default + implementation of this method just returns a copy and an array + of ones (unchanged index). + + Returns + ------- + ExtensionArray + Array with the exploded values. + np.ndarray[uint64] + The original lengths of each list-like for determining the + resulting index. + + See Also + -------- + Series.explode : The method on the ``Series`` object that this + extension array method is meant to support. + + Examples + -------- + >>> import pyarrow as pa + >>> a = pd.array([[1, 2, 3], [4], [5, 6]], + ... dtype=pd.ArrowDtype(pa.list_(pa.int64()))) + >>> a._explode() + ( + [1, 2, 3, 4, 5, 6] + Length: 6, dtype: int64[pyarrow], array([3, 1, 2], dtype=int32)) + """ + values = self.copy() + counts = np.ones(shape=(len(self),), dtype=np.uint64) + return values, counts + + def tolist(self) -> list: + """ + Return a list of the values. + + These are each a scalar type, which is a Python scalar + (for str, int, float) or a pandas scalar + (for Timestamp/Timedelta/Interval/Period) + + Returns + ------- + list + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.tolist() + [1, 2, 3] + """ + if self.ndim > 1: + return [x.tolist() for x in self] + return list(self) + + def delete(self, loc: PositionalIndexer) -> Self: + indexer = np.delete(np.arange(len(self)), loc) + return self.take(indexer) + + def insert(self, loc: int, item) -> Self: + """ + Insert an item at the given position. + + Parameters + ---------- + loc : int + item : scalar-like + + Returns + ------- + same type as self + + Notes + ----- + This method should be both type and dtype-preserving. If the item + cannot be held in an array of this type/dtype, either ValueError or + TypeError should be raised. + + The default implementation relies on _from_sequence to raise on invalid + items. + + Examples + -------- + >>> arr = pd.array([1, 2, 3]) + >>> arr.insert(2, -1) + + [1, 2, -1, 3] + Length: 4, dtype: Int64 + """ + loc = validate_insert_loc(loc, len(self)) + + item_arr = type(self)._from_sequence([item], dtype=self.dtype) + + return type(self)._concat_same_type([self[:loc], item_arr, self[loc:]]) + + def _putmask(self, mask: npt.NDArray[np.bool_], value) -> None: + """ + Analogue to np.putmask(self, mask, value) + + Parameters + ---------- + mask : np.ndarray[bool] + value : scalar or listlike + If listlike, must be arraylike with same length as self. + + Returns + ------- + None + + Notes + ----- + Unlike np.putmask, we do not repeat listlike values with mismatched length. + 'value' should either be a scalar or an arraylike with the same length + as self. + """ + if is_list_like(value): + val = value[mask] + else: + val = value + + self[mask] = val + + def _where(self, mask: npt.NDArray[np.bool_], value) -> Self: + """ + Analogue to np.where(mask, self, value) + + Parameters + ---------- + mask : np.ndarray[bool] + value : scalar or listlike + + Returns + ------- + same type as self + """ + result = self.copy() + + if is_list_like(value): + val = value[~mask] + else: + val = value + + result[~mask] = val + return result + + # TODO(3.0): this can be removed once GH#33302 deprecation is enforced + def _fill_mask_inplace( + self, method: str, limit: int | None, mask: npt.NDArray[np.bool_] + ) -> None: + """ + Replace values in locations specified by 'mask' using pad or backfill. + + See also + -------- + ExtensionArray.fillna + """ + func = missing.get_fill_func(method) + npvalues = self.astype(object) + # NB: if we don't copy mask here, it may be altered inplace, which + # would mess up the `self[mask] = ...` below. + func(npvalues, limit=limit, mask=mask.copy()) + new_values = self._from_sequence(npvalues, dtype=self.dtype) + self[mask] = new_values[mask] + + def _rank( + self, + *, + axis: AxisInt = 0, + method: str = "average", + na_option: str = "keep", + ascending: bool = True, + pct: bool = False, + ): + """ + See Series.rank.__doc__. + """ + if axis != 0: + raise NotImplementedError + + return rank( + self._values_for_argsort(), + axis=axis, + method=method, + na_option=na_option, + ascending=ascending, + pct=pct, + ) + + @classmethod + def _empty(cls, shape: Shape, dtype: ExtensionDtype): + """ + Create an ExtensionArray with the given shape and dtype. + + See also + -------- + ExtensionDtype.empty + ExtensionDtype.empty is the 'official' public version of this API. + """ + # Implementer note: while ExtensionDtype.empty is the public way to + # call this method, it is still required to implement this `_empty` + # method as well (it is called internally in pandas) + obj = cls._from_sequence([], dtype=dtype) + + taker = np.broadcast_to(np.intp(-1), shape) + result = obj.take(taker, allow_fill=True) + if not isinstance(result, cls) or dtype != result.dtype: + raise NotImplementedError( + f"Default 'empty' implementation is invalid for dtype='{dtype}'" + ) + return result + + def _quantile(self, qs: npt.NDArray[np.float64], interpolation: str) -> Self: + """ + Compute the quantiles of self for each quantile in `qs`. + + Parameters + ---------- + qs : np.ndarray[float64] + interpolation: str + + Returns + ------- + same type as self + """ + mask = np.asarray(self.isna()) + arr = np.asarray(self) + fill_value = np.nan + + res_values = quantile_with_mask(arr, mask, fill_value, qs, interpolation) + return type(self)._from_sequence(res_values) + + def _mode(self, dropna: bool = True) -> Self: + """ + Returns the mode(s) of the ExtensionArray. + + Always returns `ExtensionArray` even if only one value. + + Parameters + ---------- + dropna : bool, default True + Don't consider counts of NA values. + + Returns + ------- + same type as self + Sorted, if possible. + """ + # error: Incompatible return value type (got "Union[ExtensionArray, + # ndarray[Any, Any]]", expected "Self") + return mode(self, dropna=dropna) # type: ignore[return-value] + + def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs): + if any( + isinstance(other, (ABCSeries, ABCIndex, ABCDataFrame)) for other in inputs + ): + return NotImplemented + + result = arraylike.maybe_dispatch_ufunc_to_dunder_op( + self, ufunc, method, *inputs, **kwargs + ) + if result is not NotImplemented: + return result + + if "out" in kwargs: + return arraylike.dispatch_ufunc_with_out( + self, ufunc, method, *inputs, **kwargs + ) + + if method == "reduce": + result = arraylike.dispatch_reduction_ufunc( + self, ufunc, method, *inputs, **kwargs + ) + if result is not NotImplemented: + return result + + return arraylike.default_array_ufunc(self, ufunc, method, *inputs, **kwargs) + + def map(self, mapper, na_action=None): + """ + Map values using an input mapping or function. + + Parameters + ---------- + mapper : function, dict, or Series + Mapping correspondence. + na_action : {None, 'ignore'}, default None + If 'ignore', propagate NA values, without passing them to the + mapping correspondence. If 'ignore' is not supported, a + ``NotImplementedError`` should be raised. + + Returns + ------- + Union[ndarray, Index, ExtensionArray] + The output of the mapping function applied to the array. + If the function returns a tuple with more than one element + a MultiIndex will be returned. + """ + return map_array(self, mapper, na_action=na_action) + + # ------------------------------------------------------------------------ + # GroupBy Methods + + def _groupby_op( + self, + *, + how: str, + has_dropped_na: bool, + min_count: int, + ngroups: int, + ids: npt.NDArray[np.intp], + **kwargs, + ) -> ArrayLike: + """ + Dispatch GroupBy reduction or transformation operation. + + This is an *experimental* API to allow ExtensionArray authors to implement + reductions and transformations. The API is subject to change. + + Parameters + ---------- + how : {'any', 'all', 'sum', 'prod', 'min', 'max', 'mean', 'median', + 'median', 'var', 'std', 'sem', 'nth', 'last', 'ohlc', + 'cumprod', 'cumsum', 'cummin', 'cummax', 'rank'} + has_dropped_na : bool + min_count : int + ngroups : int + ids : np.ndarray[np.intp] + ids[i] gives the integer label for the group that self[i] belongs to. + **kwargs : operation-specific + 'any', 'all' -> ['skipna'] + 'var', 'std', 'sem' -> ['ddof'] + 'cumprod', 'cumsum', 'cummin', 'cummax' -> ['skipna'] + 'rank' -> ['ties_method', 'ascending', 'na_option', 'pct'] + + Returns + ------- + np.ndarray or ExtensionArray + """ + from pandas.core.arrays.string_ import StringDtype + from pandas.core.groupby.ops import WrappedCythonOp + + kind = WrappedCythonOp.get_kind_from_how(how) + op = WrappedCythonOp(how=how, kind=kind, has_dropped_na=has_dropped_na) + + # GH#43682 + if isinstance(self.dtype, StringDtype): + # StringArray + if op.how not in ["any", "all"]: + # Fail early to avoid conversion to object + op._get_cython_function(op.kind, op.how, np.dtype(object), False) + npvalues = self.to_numpy(object, na_value=np.nan) + else: + raise NotImplementedError( + f"function is not implemented for this dtype: {self.dtype}" + ) + + res_values = op._cython_op_ndim_compat( + npvalues, + min_count=min_count, + ngroups=ngroups, + comp_ids=ids, + mask=None, + **kwargs, + ) + + if op.how in op.cast_blocklist: + # i.e. how in ["rank"], since other cast_blocklist methods don't go + # through cython_operation + return res_values + + if isinstance(self.dtype, StringDtype): + dtype = self.dtype + string_array_cls = dtype.construct_array_type() + return string_array_cls._from_sequence(res_values, dtype=dtype) + + else: + raise NotImplementedError + + +class ExtensionArraySupportsAnyAll(ExtensionArray): + def any(self, *, skipna: bool = True) -> bool: + raise AbstractMethodError(self) + + def all(self, *, skipna: bool = True) -> bool: + raise AbstractMethodError(self) + + +class ExtensionOpsMixin: + """ + A base class for linking the operators to their dunder names. + + .. note:: + + You may want to set ``__array_priority__`` if you want your + implementation to be called when involved in binary operations + with NumPy arrays. + """ + + @classmethod + def _create_arithmetic_method(cls, op): + raise AbstractMethodError(cls) + + @classmethod + def _add_arithmetic_ops(cls) -> None: + setattr(cls, "__add__", cls._create_arithmetic_method(operator.add)) + setattr(cls, "__radd__", cls._create_arithmetic_method(roperator.radd)) + setattr(cls, "__sub__", cls._create_arithmetic_method(operator.sub)) + setattr(cls, "__rsub__", cls._create_arithmetic_method(roperator.rsub)) + setattr(cls, "__mul__", cls._create_arithmetic_method(operator.mul)) + setattr(cls, "__rmul__", cls._create_arithmetic_method(roperator.rmul)) + setattr(cls, "__pow__", cls._create_arithmetic_method(operator.pow)) + setattr(cls, "__rpow__", cls._create_arithmetic_method(roperator.rpow)) + setattr(cls, "__mod__", cls._create_arithmetic_method(operator.mod)) + setattr(cls, "__rmod__", cls._create_arithmetic_method(roperator.rmod)) + setattr(cls, "__floordiv__", cls._create_arithmetic_method(operator.floordiv)) + setattr( + cls, "__rfloordiv__", cls._create_arithmetic_method(roperator.rfloordiv) + ) + setattr(cls, "__truediv__", cls._create_arithmetic_method(operator.truediv)) + setattr(cls, "__rtruediv__", cls._create_arithmetic_method(roperator.rtruediv)) + setattr(cls, "__divmod__", cls._create_arithmetic_method(divmod)) + setattr(cls, "__rdivmod__", cls._create_arithmetic_method(roperator.rdivmod)) + + @classmethod + def _create_comparison_method(cls, op): + raise AbstractMethodError(cls) + + @classmethod + def _add_comparison_ops(cls) -> None: + setattr(cls, "__eq__", cls._create_comparison_method(operator.eq)) + setattr(cls, "__ne__", cls._create_comparison_method(operator.ne)) + setattr(cls, "__lt__", cls._create_comparison_method(operator.lt)) + setattr(cls, "__gt__", cls._create_comparison_method(operator.gt)) + setattr(cls, "__le__", cls._create_comparison_method(operator.le)) + setattr(cls, "__ge__", cls._create_comparison_method(operator.ge)) + + @classmethod + def _create_logical_method(cls, op): + raise AbstractMethodError(cls) + + @classmethod + def _add_logical_ops(cls) -> None: + setattr(cls, "__and__", cls._create_logical_method(operator.and_)) + setattr(cls, "__rand__", cls._create_logical_method(roperator.rand_)) + setattr(cls, "__or__", cls._create_logical_method(operator.or_)) + setattr(cls, "__ror__", cls._create_logical_method(roperator.ror_)) + setattr(cls, "__xor__", cls._create_logical_method(operator.xor)) + setattr(cls, "__rxor__", cls._create_logical_method(roperator.rxor)) + + +class ExtensionScalarOpsMixin(ExtensionOpsMixin): + """ + A mixin for defining ops on an ExtensionArray. + + It is assumed that the underlying scalar objects have the operators + already defined. + + Notes + ----- + If you have defined a subclass MyExtensionArray(ExtensionArray), then + use MyExtensionArray(ExtensionArray, ExtensionScalarOpsMixin) to + get the arithmetic operators. After the definition of MyExtensionArray, + insert the lines + + MyExtensionArray._add_arithmetic_ops() + MyExtensionArray._add_comparison_ops() + + to link the operators to your class. + + .. note:: + + You may want to set ``__array_priority__`` if you want your + implementation to be called when involved in binary operations + with NumPy arrays. + """ + + @classmethod + def _create_method(cls, op, coerce_to_dtype: bool = True, result_dtype=None): + """ + A class method that returns a method that will correspond to an + operator for an ExtensionArray subclass, by dispatching to the + relevant operator defined on the individual elements of the + ExtensionArray. + + Parameters + ---------- + op : function + An operator that takes arguments op(a, b) + coerce_to_dtype : bool, default True + boolean indicating whether to attempt to convert + the result to the underlying ExtensionArray dtype. + If it's not possible to create a new ExtensionArray with the + values, an ndarray is returned instead. + + Returns + ------- + Callable[[Any, Any], Union[ndarray, ExtensionArray]] + A method that can be bound to a class. When used, the method + receives the two arguments, one of which is the instance of + this class, and should return an ExtensionArray or an ndarray. + + Returning an ndarray may be necessary when the result of the + `op` cannot be stored in the ExtensionArray. The dtype of the + ndarray uses NumPy's normal inference rules. + + Examples + -------- + Given an ExtensionArray subclass called MyExtensionArray, use + + __add__ = cls._create_method(operator.add) + + in the class definition of MyExtensionArray to create the operator + for addition, that will be based on the operator implementation + of the underlying elements of the ExtensionArray + """ + + def _binop(self, other): + def convert_values(param): + if isinstance(param, ExtensionArray) or is_list_like(param): + ovalues = param + else: # Assume its an object + ovalues = [param] * len(self) + return ovalues + + if isinstance(other, (ABCSeries, ABCIndex, ABCDataFrame)): + # rely on pandas to unbox and dispatch to us + return NotImplemented + + lvalues = self + rvalues = convert_values(other) + + # If the operator is not defined for the underlying objects, + # a TypeError should be raised + res = [op(a, b) for (a, b) in zip(lvalues, rvalues)] + + def _maybe_convert(arr): + if coerce_to_dtype: + # https://github.com/pandas-dev/pandas/issues/22850 + # We catch all regular exceptions here, and fall back + # to an ndarray. + res = maybe_cast_pointwise_result(arr, self.dtype, same_dtype=False) + if not isinstance(res, type(self)): + # exception raised in _from_sequence; ensure we have ndarray + res = np.asarray(arr) + else: + res = np.asarray(arr, dtype=result_dtype) + return res + + if op.__name__ in {"divmod", "rdivmod"}: + a, b = zip(*res) + return _maybe_convert(a), _maybe_convert(b) + + return _maybe_convert(res) + + op_name = f"__{op.__name__}__" + return set_function_name(_binop, op_name, cls) + + @classmethod + def _create_arithmetic_method(cls, op): + return cls._create_method(op) + + @classmethod + def _create_comparison_method(cls, op): + return cls._create_method(op, coerce_to_dtype=False, result_dtype=bool) diff --git a/shared/package-files/bc/bc44250626684047dabec5f5e286f5c5562178bebbcd1cc1c550ddddf436d8c7/pixel_shuffle_native.h b/shared/package-files/bc/bc44250626684047dabec5f5e286f5c5562178bebbcd1cc1c550ddddf436d8c7/pixel_shuffle_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4d0558410fd90da9934958af21545e84d8524657 --- /dev/null +++ b/shared/package-files/bc/bc44250626684047dabec5f5e286f5c5562178bebbcd1cc1c550ddddf436d8c7/pixel_shuffle_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & pixel_shuffle_out(const at::Tensor & self, int64_t upscale_factor, at::Tensor & out); +TORCH_API at::Tensor pixel_shuffle_cpu(const at::Tensor & self, int64_t upscale_factor); +TORCH_API at::Tensor math_pixel_shuffle(const at::Tensor & self, int64_t upscale_factor); +} // namespace native +} // namespace at diff --git a/shared/package-files/bc/bc451e8c4fcdd1f06fcd71249401ad7ac6f5bbec8d5417998245ffc9207452b8/topics.py b/shared/package-files/bc/bc451e8c4fcdd1f06fcd71249401ad7ac6f5bbec8d5417998245ffc9207452b8/topics.py new file mode 100644 index 0000000000000000000000000000000000000000..0edb31b1d27a0f8b5f228e809ed601eda3fd9395 --- /dev/null +++ b/shared/package-files/bc/bc451e8c4fcdd1f06fcd71249401ad7ac6f5bbec8d5417998245ffc9207452b8/topics.py @@ -0,0 +1,15953 @@ +# -*- coding: utf-8 -*- +# Autogenerated by Sphinx on Tue Jun 3 19:38:08 2025 +# as part of the release process. +topics = {'assert': 'The "assert" statement\n' + '**********************\n' + '\n' + 'Assert statements are a convenient way to insert debugging ' + 'assertions\n' + 'into a program:\n' + '\n' + ' assert_stmt ::= "assert" expression ["," expression]\n' + '\n' + 'The simple form, "assert expression", is equivalent to\n' + '\n' + ' if __debug__:\n' + ' if not expression: raise AssertionError\n' + '\n' + 'The extended form, "assert expression1, expression2", is ' + 'equivalent to\n' + '\n' + ' if __debug__:\n' + ' if not expression1: raise AssertionError(expression2)\n' + '\n' + 'These equivalences assume that "__debug__" and "AssertionError" ' + 'refer\n' + 'to the built-in variables with those names. In the current\n' + 'implementation, the built-in variable "__debug__" is "True" under\n' + 'normal circumstances, "False" when optimization is requested ' + '(command\n' + 'line option "-O"). The current code generator emits no code for ' + 'an\n' + 'assert statement when optimization is requested at compile time. ' + 'Note\n' + 'that it is unnecessary to include the source code for the ' + 'expression\n' + 'that failed in the error message; it will be displayed as part of ' + 'the\n' + 'stack trace.\n' + '\n' + 'Assignments to "__debug__" are illegal. The value for the ' + 'built-in\n' + 'variable is determined when the interpreter starts.\n', + 'assignment': 'Assignment statements\n' + '*********************\n' + '\n' + 'Assignment statements are used to (re)bind names to values and ' + 'to\n' + 'modify attributes or items of mutable objects:\n' + '\n' + ' assignment_stmt ::= (target_list "=")+ (starred_expression ' + '| yield_expression)\n' + ' target_list ::= target ("," target)* [","]\n' + ' target ::= identifier\n' + ' | "(" [target_list] ")"\n' + ' | "[" [target_list] "]"\n' + ' | attributeref\n' + ' | subscription\n' + ' | slicing\n' + ' | "*" target\n' + '\n' + '(See section Primaries for the syntax definitions for ' + '*attributeref*,\n' + '*subscription*, and *slicing*.)\n' + '\n' + 'An assignment statement evaluates the expression list ' + '(remember that\n' + 'this can be a single expression or a comma-separated list, the ' + 'latter\n' + 'yielding a tuple) and assigns the single resulting object to ' + 'each of\n' + 'the target lists, from left to right.\n' + '\n' + 'Assignment is defined recursively depending on the form of the ' + 'target\n' + '(list). When a target is part of a mutable object (an ' + 'attribute\n' + 'reference, subscription or slicing), the mutable object must\n' + 'ultimately perform the assignment and decide about its ' + 'validity, and\n' + 'may raise an exception if the assignment is unacceptable. The ' + 'rules\n' + 'observed by various types and the exceptions raised are given ' + 'with the\n' + 'definition of the object types (see section The standard type\n' + 'hierarchy).\n' + '\n' + 'Assignment of an object to a target list, optionally enclosed ' + 'in\n' + 'parentheses or square brackets, is recursively defined as ' + 'follows.\n' + '\n' + '* If the target list is a single target with no trailing ' + 'comma,\n' + ' optionally in parentheses, the object is assigned to that ' + 'target.\n' + '\n' + '* Else:\n' + '\n' + ' * If the target list contains one target prefixed with an ' + 'asterisk,\n' + ' called a “starred” target: The object must be an iterable ' + 'with at\n' + ' least as many items as there are targets in the target ' + 'list, minus\n' + ' one. The first items of the iterable are assigned, from ' + 'left to\n' + ' right, to the targets before the starred target. The ' + 'final items\n' + ' of the iterable are assigned to the targets after the ' + 'starred\n' + ' target. A list of the remaining items in the iterable is ' + 'then\n' + ' assigned to the starred target (the list can be empty).\n' + '\n' + ' * Else: The object must be an iterable with the same number ' + 'of items\n' + ' as there are targets in the target list, and the items ' + 'are\n' + ' assigned, from left to right, to the corresponding ' + 'targets.\n' + '\n' + 'Assignment of an object to a single target is recursively ' + 'defined as\n' + 'follows.\n' + '\n' + '* If the target is an identifier (name):\n' + '\n' + ' * If the name does not occur in a "global" or "nonlocal" ' + 'statement\n' + ' in the current code block: the name is bound to the object ' + 'in the\n' + ' current local namespace.\n' + '\n' + ' * Otherwise: the name is bound to the object in the global ' + 'namespace\n' + ' or the outer namespace determined by "nonlocal", ' + 'respectively.\n' + '\n' + ' The name is rebound if it was already bound. This may cause ' + 'the\n' + ' reference count for the object previously bound to the name ' + 'to reach\n' + ' zero, causing the object to be deallocated and its ' + 'destructor (if it\n' + ' has one) to be called.\n' + '\n' + '* If the target is an attribute reference: The primary ' + 'expression in\n' + ' the reference is evaluated. It should yield an object with\n' + ' assignable attributes; if this is not the case, "TypeError" ' + 'is\n' + ' raised. That object is then asked to assign the assigned ' + 'object to\n' + ' the given attribute; if it cannot perform the assignment, it ' + 'raises\n' + ' an exception (usually but not necessarily ' + '"AttributeError").\n' + '\n' + ' Note: If the object is a class instance and the attribute ' + 'reference\n' + ' occurs on both sides of the assignment operator, the ' + 'right-hand side\n' + ' expression, "a.x" can access either an instance attribute or ' + '(if no\n' + ' instance attribute exists) a class attribute. The left-hand ' + 'side\n' + ' target "a.x" is always set as an instance attribute, ' + 'creating it if\n' + ' necessary. Thus, the two occurrences of "a.x" do not ' + 'necessarily\n' + ' refer to the same attribute: if the right-hand side ' + 'expression\n' + ' refers to a class attribute, the left-hand side creates a ' + 'new\n' + ' instance attribute as the target of the assignment:\n' + '\n' + ' class Cls:\n' + ' x = 3 # class variable\n' + ' inst = Cls()\n' + ' inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x ' + 'as 3\n' + '\n' + ' This description does not necessarily apply to descriptor\n' + ' attributes, such as properties created with "property()".\n' + '\n' + '* If the target is a subscription: The primary expression in ' + 'the\n' + ' reference is evaluated. It should yield either a mutable ' + 'sequence\n' + ' object (such as a list) or a mapping object (such as a ' + 'dictionary).\n' + ' Next, the subscript expression is evaluated.\n' + '\n' + ' If the primary is a mutable sequence object (such as a ' + 'list), the\n' + ' subscript must yield an integer. If it is negative, the ' + 'sequence’s\n' + ' length is added to it. The resulting value must be a ' + 'nonnegative\n' + ' integer less than the sequence’s length, and the sequence is ' + 'asked\n' + ' to assign the assigned object to its item with that index. ' + 'If the\n' + ' index is out of range, "IndexError" is raised (assignment to ' + 'a\n' + ' subscripted sequence cannot add new items to a list).\n' + '\n' + ' If the primary is a mapping object (such as a dictionary), ' + 'the\n' + ' subscript must have a type compatible with the mapping’s key ' + 'type,\n' + ' and the mapping is then asked to create a key/value pair ' + 'which maps\n' + ' the subscript to the assigned object. This can either ' + 'replace an\n' + ' existing key/value pair with the same key value, or insert a ' + 'new\n' + ' key/value pair (if no key with the same value existed).\n' + '\n' + ' For user-defined objects, the "__setitem__()" method is ' + 'called with\n' + ' appropriate arguments.\n' + '\n' + '* If the target is a slicing: The primary expression in the ' + 'reference\n' + ' is evaluated. It should yield a mutable sequence object ' + '(such as a\n' + ' list). The assigned object should be a sequence object of ' + 'the same\n' + ' type. Next, the lower and upper bound expressions are ' + 'evaluated,\n' + ' insofar they are present; defaults are zero and the ' + 'sequence’s\n' + ' length. The bounds should evaluate to integers. If either ' + 'bound is\n' + ' negative, the sequence’s length is added to it. The ' + 'resulting\n' + ' bounds are clipped to lie between zero and the sequence’s ' + 'length,\n' + ' inclusive. Finally, the sequence object is asked to replace ' + 'the\n' + ' slice with the items of the assigned sequence. The length ' + 'of the\n' + ' slice may be different from the length of the assigned ' + 'sequence,\n' + ' thus changing the length of the target sequence, if the ' + 'target\n' + ' sequence allows it.\n' + '\n' + '**CPython implementation detail:** In the current ' + 'implementation, the\n' + 'syntax for targets is taken to be the same as for expressions, ' + 'and\n' + 'invalid syntax is rejected during the code generation phase, ' + 'causing\n' + 'less detailed error messages.\n' + '\n' + 'Although the definition of assignment implies that overlaps ' + 'between\n' + 'the left-hand side and the right-hand side are ‘simultaneous’ ' + '(for\n' + 'example "a, b = b, a" swaps two variables), overlaps *within* ' + 'the\n' + 'collection of assigned-to variables occur left-to-right, ' + 'sometimes\n' + 'resulting in confusion. For instance, the following program ' + 'prints\n' + '"[0, 2]":\n' + '\n' + ' x = [0, 1]\n' + ' i = 0\n' + ' i, x[i] = 1, 2 # i is updated, then x[i] is ' + 'updated\n' + ' print(x)\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3132** - Extended Iterable Unpacking\n' + ' The specification for the "*target" feature.\n' + '\n' + '\n' + 'Augmented assignment statements\n' + '===============================\n' + '\n' + 'Augmented assignment is the combination, in a single ' + 'statement, of a\n' + 'binary operation and an assignment statement:\n' + '\n' + ' augmented_assignment_stmt ::= augtarget augop ' + '(expression_list | yield_expression)\n' + ' augtarget ::= identifier | attributeref | ' + 'subscription | slicing\n' + ' augop ::= "+=" | "-=" | "*=" | "@=" | ' + '"/=" | "//=" | "%=" | "**="\n' + ' | ">>=" | "<<=" | "&=" | "^=" | "|="\n' + '\n' + '(See section Primaries for the syntax definitions of the last ' + 'three\n' + 'symbols.)\n' + '\n' + 'An augmented assignment evaluates the target (which, unlike ' + 'normal\n' + 'assignment statements, cannot be an unpacking) and the ' + 'expression\n' + 'list, performs the binary operation specific to the type of ' + 'assignment\n' + 'on the two operands, and assigns the result to the original ' + 'target.\n' + 'The target is only evaluated once.\n' + '\n' + 'An augmented assignment expression like "x += 1" can be ' + 'rewritten as\n' + '"x = x + 1" to achieve a similar, but not exactly equal ' + 'effect. In the\n' + 'augmented version, "x" is only evaluated once. Also, when ' + 'possible,\n' + 'the actual operation is performed *in-place*, meaning that ' + 'rather than\n' + 'creating a new object and assigning that to the target, the ' + 'old object\n' + 'is modified instead.\n' + '\n' + 'Unlike normal assignments, augmented assignments evaluate the ' + 'left-\n' + 'hand side *before* evaluating the right-hand side. For ' + 'example, "a[i]\n' + '+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and ' + 'performs\n' + 'the addition, and lastly, it writes the result back to ' + '"a[i]".\n' + '\n' + 'With the exception of assigning to tuples and multiple targets ' + 'in a\n' + 'single statement, the assignment done by augmented assignment\n' + 'statements is handled the same way as normal assignments. ' + 'Similarly,\n' + 'with the exception of the possible *in-place* behavior, the ' + 'binary\n' + 'operation performed by augmented assignment is the same as the ' + 'normal\n' + 'binary operations.\n' + '\n' + 'For targets which are attribute references, the same caveat ' + 'about\n' + 'class and instance attributes applies as for regular ' + 'assignments.\n' + '\n' + '\n' + 'Annotated assignment statements\n' + '===============================\n' + '\n' + '*Annotation* assignment is the combination, in a single ' + 'statement, of\n' + 'a variable or attribute annotation and an optional assignment\n' + 'statement:\n' + '\n' + ' annotated_assignment_stmt ::= augtarget ":" expression\n' + ' ["=" (starred_expression | ' + 'yield_expression)]\n' + '\n' + 'The difference from normal Assignment statements is that only ' + 'a single\n' + 'target is allowed.\n' + '\n' + 'For simple names as assignment targets, if in class or module ' + 'scope,\n' + 'the annotations are evaluated and stored in a special class or ' + 'module\n' + 'attribute "__annotations__" that is a dictionary mapping from ' + 'variable\n' + 'names (mangled if private) to evaluated annotations. This ' + 'attribute is\n' + 'writable and is automatically created at the start of class or ' + 'module\n' + 'body execution, if annotations are found statically.\n' + '\n' + 'For expressions as assignment targets, the annotations are ' + 'evaluated\n' + 'if in class or module scope, but not stored.\n' + '\n' + 'If a name is annotated in a function scope, then this name is ' + 'local\n' + 'for that scope. Annotations are never evaluated and stored in ' + 'function\n' + 'scopes.\n' + '\n' + 'If the right hand side is present, an annotated assignment ' + 'performs\n' + 'the actual assignment before evaluating annotations (where\n' + 'applicable). If the right hand side is not present for an ' + 'expression\n' + 'target, then the interpreter evaluates the target except for ' + 'the last\n' + '"__setitem__()" or "__setattr__()" call.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 526** - Syntax for Variable Annotations\n' + ' The proposal that added syntax for annotating the types ' + 'of\n' + ' variables (including class variables and instance ' + 'variables),\n' + ' instead of expressing them through comments.\n' + '\n' + ' **PEP 484** - Type hints\n' + ' The proposal that added the "typing" module to provide a ' + 'standard\n' + ' syntax for type annotations that can be used in static ' + 'analysis\n' + ' tools and IDEs.\n' + '\n' + 'Changed in version 3.8: Now annotated assignments allow the ' + 'same\n' + 'expressions in the right hand side as regular assignments. ' + 'Previously,\n' + 'some expressions (like un-parenthesized tuple expressions) ' + 'caused a\n' + 'syntax error.\n', + 'async': 'Coroutines\n' + '**********\n' + '\n' + 'New in version 3.5.\n' + '\n' + '\n' + 'Coroutine function definition\n' + '=============================\n' + '\n' + ' async_funcdef ::= [decorators] "async" "def" funcname "(" ' + '[parameter_list] ")"\n' + ' ["->" expression] ":" suite\n' + '\n' + 'Execution of Python coroutines can be suspended and resumed at ' + 'many\n' + 'points (see *coroutine*). "await" expressions, "async for" and ' + '"async\n' + 'with" can only be used in the body of a coroutine function.\n' + '\n' + 'Functions defined with "async def" syntax are always coroutine\n' + 'functions, even if they do not contain "await" or "async" ' + 'keywords.\n' + '\n' + 'It is a "SyntaxError" to use a "yield from" expression inside the ' + 'body\n' + 'of a coroutine function.\n' + '\n' + 'An example of a coroutine function:\n' + '\n' + ' async def func(param1, param2):\n' + ' do_stuff()\n' + ' await some_coroutine()\n' + '\n' + 'Changed in version 3.7: "await" and "async" are now keywords;\n' + 'previously they were only treated as such inside the body of a\n' + 'coroutine function.\n' + '\n' + '\n' + 'The "async for" statement\n' + '=========================\n' + '\n' + ' async_for_stmt ::= "async" for_stmt\n' + '\n' + 'An *asynchronous iterable* provides an "__aiter__" method that\n' + 'directly returns an *asynchronous iterator*, which can call\n' + 'asynchronous code in its "__anext__" method.\n' + '\n' + 'The "async for" statement allows convenient iteration over\n' + 'asynchronous iterables.\n' + '\n' + 'The following code:\n' + '\n' + ' async for TARGET in ITER:\n' + ' SUITE\n' + ' else:\n' + ' SUITE2\n' + '\n' + 'Is semantically equivalent to:\n' + '\n' + ' iter = (ITER)\n' + ' iter = type(iter).__aiter__(iter)\n' + ' running = True\n' + '\n' + ' while running:\n' + ' try:\n' + ' TARGET = await type(iter).__anext__(iter)\n' + ' except StopAsyncIteration:\n' + ' running = False\n' + ' else:\n' + ' SUITE\n' + ' else:\n' + ' SUITE2\n' + '\n' + 'See also "__aiter__()" and "__anext__()" for details.\n' + '\n' + 'It is a "SyntaxError" to use an "async for" statement outside the ' + 'body\n' + 'of a coroutine function.\n' + '\n' + '\n' + 'The "async with" statement\n' + '==========================\n' + '\n' + ' async_with_stmt ::= "async" with_stmt\n' + '\n' + 'An *asynchronous context manager* is a *context manager* that is ' + 'able\n' + 'to suspend execution in its *enter* and *exit* methods.\n' + '\n' + 'The following code:\n' + '\n' + ' async with EXPRESSION as TARGET:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' manager = (EXPRESSION)\n' + ' aenter = type(manager).__aenter__\n' + ' aexit = type(manager).__aexit__\n' + ' value = await aenter(manager)\n' + ' hit_except = False\n' + '\n' + ' try:\n' + ' TARGET = value\n' + ' SUITE\n' + ' except:\n' + ' hit_except = True\n' + ' if not await aexit(manager, *sys.exc_info()):\n' + ' raise\n' + ' finally:\n' + ' if not hit_except:\n' + ' await aexit(manager, None, None, None)\n' + '\n' + 'See also "__aenter__()" and "__aexit__()" for details.\n' + '\n' + 'It is a "SyntaxError" to use an "async with" statement outside the\n' + 'body of a coroutine function.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 492** - Coroutines with async and await syntax\n' + ' The proposal that made coroutines a proper standalone concept ' + 'in\n' + ' Python, and added supporting syntax.\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] The exception is propagated to the invocation stack unless ' + 'there\n' + ' is a "finally" clause which happens to raise another ' + 'exception.\n' + ' That new exception causes the old one to be lost.\n' + '\n' + '[2] In pattern matching, a sequence is defined as one of the\n' + ' following:\n' + '\n' + ' * a class that inherits from "collections.abc.Sequence"\n' + '\n' + ' * a Python class that has been registered as\n' + ' "collections.abc.Sequence"\n' + '\n' + ' * a builtin class that has its (CPython) "Py_TPFLAGS_SEQUENCE" ' + 'bit\n' + ' set\n' + '\n' + ' * a class that inherits from any of the above\n' + '\n' + ' The following standard library classes are sequences:\n' + '\n' + ' * "array.array"\n' + '\n' + ' * "collections.deque"\n' + '\n' + ' * "list"\n' + '\n' + ' * "memoryview"\n' + '\n' + ' * "range"\n' + '\n' + ' * "tuple"\n' + '\n' + ' Note:\n' + '\n' + ' Subject values of type "str", "bytes", and "bytearray" do ' + 'not\n' + ' match sequence patterns.\n' + '\n' + '[3] In pattern matching, a mapping is defined as one of the ' + 'following:\n' + '\n' + ' * a class that inherits from "collections.abc.Mapping"\n' + '\n' + ' * a Python class that has been registered as\n' + ' "collections.abc.Mapping"\n' + '\n' + ' * a builtin class that has its (CPython) "Py_TPFLAGS_MAPPING" ' + 'bit\n' + ' set\n' + '\n' + ' * a class that inherits from any of the above\n' + '\n' + ' The standard library classes "dict" and ' + '"types.MappingProxyType"\n' + ' are mappings.\n' + '\n' + '[4] A string literal appearing as the first statement in the ' + 'function\n' + ' body is transformed into the function’s "__doc__" attribute ' + 'and\n' + ' therefore the function’s *docstring*.\n' + '\n' + '[5] A string literal appearing as the first statement in the class\n' + ' body is transformed into the namespace’s "__doc__" item and\n' + ' therefore the class’s *docstring*.\n', + 'atom-identifiers': 'Identifiers (Names)\n' + '*******************\n' + '\n' + 'An identifier occurring as an atom is a name. See ' + 'section Identifiers\n' + 'and keywords for lexical definition and section Naming ' + 'and binding for\n' + 'documentation of naming and binding.\n' + '\n' + 'When the name is bound to an object, evaluation of the ' + 'atom yields\n' + 'that object. When a name is not bound, an attempt to ' + 'evaluate it\n' + 'raises a "NameError" exception.\n' + '\n' + '**Private name mangling:** When an identifier that ' + 'textually occurs in\n' + 'a class definition begins with two or more underscore ' + 'characters and\n' + 'does not end in two or more underscores, it is ' + 'considered a *private\n' + 'name* of that class. Private names are transformed to a ' + 'longer form\n' + 'before code is generated for them. The transformation ' + 'inserts the\n' + 'class name, with leading underscores removed and a ' + 'single underscore\n' + 'inserted, in front of the name. For example, the ' + 'identifier "__spam"\n' + 'occurring in a class named "Ham" will be transformed to ' + '"_Ham__spam".\n' + 'This transformation is independent of the syntactical ' + 'context in which\n' + 'the identifier is used. If the transformed name is ' + 'extremely long\n' + '(longer than 255 characters), implementation defined ' + 'truncation may\n' + 'happen. If the class name consists only of underscores, ' + 'no\n' + 'transformation is done.\n', + 'atom-literals': 'Literals\n' + '********\n' + '\n' + 'Python supports string and bytes literals and various ' + 'numeric\n' + 'literals:\n' + '\n' + ' literal ::= stringliteral | bytesliteral\n' + ' | integer | floatnumber | imagnumber\n' + '\n' + 'Evaluation of a literal yields an object of the given type ' + '(string,\n' + 'bytes, integer, floating point number, complex number) with ' + 'the given\n' + 'value. The value may be approximated in the case of ' + 'floating point\n' + 'and imaginary (complex) literals. See section Literals for ' + 'details.\n' + '\n' + 'All literals correspond to immutable data types, and hence ' + 'the\n' + 'object’s identity is less important than its value. ' + 'Multiple\n' + 'evaluations of literals with the same value (either the ' + 'same\n' + 'occurrence in the program text or a different occurrence) ' + 'may obtain\n' + 'the same object or a different object with the same ' + 'value.\n', + 'attribute-access': 'Customizing attribute access\n' + '****************************\n' + '\n' + 'The following methods can be defined to customize the ' + 'meaning of\n' + 'attribute access (use of, assignment to, or deletion of ' + '"x.name") for\n' + 'class instances.\n' + '\n' + 'object.__getattr__(self, name)\n' + '\n' + ' Called when the default attribute access fails with ' + 'an\n' + ' "AttributeError" (either "__getattribute__()" raises ' + 'an\n' + ' "AttributeError" because *name* is not an instance ' + 'attribute or an\n' + ' attribute in the class tree for "self"; or ' + '"__get__()" of a *name*\n' + ' property raises "AttributeError"). This method ' + 'should either\n' + ' return the (computed) attribute value or raise an ' + '"AttributeError"\n' + ' exception.\n' + '\n' + ' Note that if the attribute is found through the ' + 'normal mechanism,\n' + ' "__getattr__()" is not called. (This is an ' + 'intentional asymmetry\n' + ' between "__getattr__()" and "__setattr__()".) This is ' + 'done both for\n' + ' efficiency reasons and because otherwise ' + '"__getattr__()" would have\n' + ' no way to access other attributes of the instance. ' + 'Note that at\n' + ' least for instance variables, you can fake total ' + 'control by not\n' + ' inserting any values in the instance attribute ' + 'dictionary (but\n' + ' instead inserting them in another object). See the\n' + ' "__getattribute__()" method below for a way to ' + 'actually get total\n' + ' control over attribute access.\n' + '\n' + 'object.__getattribute__(self, name)\n' + '\n' + ' Called unconditionally to implement attribute ' + 'accesses for\n' + ' instances of the class. If the class also defines ' + '"__getattr__()",\n' + ' the latter will not be called unless ' + '"__getattribute__()" either\n' + ' calls it explicitly or raises an "AttributeError". ' + 'This method\n' + ' should return the (computed) attribute value or raise ' + 'an\n' + ' "AttributeError" exception. In order to avoid ' + 'infinite recursion in\n' + ' this method, its implementation should always call ' + 'the base class\n' + ' method with the same name to access any attributes it ' + 'needs, for\n' + ' example, "object.__getattribute__(self, name)".\n' + '\n' + ' Note:\n' + '\n' + ' This method may still be bypassed when looking up ' + 'special methods\n' + ' as the result of implicit invocation via language ' + 'syntax or\n' + ' built-in functions. See Special method lookup.\n' + '\n' + ' For certain sensitive attribute accesses, raises an ' + 'auditing event\n' + ' "object.__getattr__" with arguments "obj" and ' + '"name".\n' + '\n' + 'object.__setattr__(self, name, value)\n' + '\n' + ' Called when an attribute assignment is attempted. ' + 'This is called\n' + ' instead of the normal mechanism (i.e. store the value ' + 'in the\n' + ' instance dictionary). *name* is the attribute name, ' + '*value* is the\n' + ' value to be assigned to it.\n' + '\n' + ' If "__setattr__()" wants to assign to an instance ' + 'attribute, it\n' + ' should call the base class method with the same name, ' + 'for example,\n' + ' "object.__setattr__(self, name, value)".\n' + '\n' + ' For certain sensitive attribute assignments, raises ' + 'an auditing\n' + ' event "object.__setattr__" with arguments "obj", ' + '"name", "value".\n' + '\n' + 'object.__delattr__(self, name)\n' + '\n' + ' Like "__setattr__()" but for attribute deletion ' + 'instead of\n' + ' assignment. This should only be implemented if "del ' + 'obj.name" is\n' + ' meaningful for the object.\n' + '\n' + ' For certain sensitive attribute deletions, raises an ' + 'auditing event\n' + ' "object.__delattr__" with arguments "obj" and ' + '"name".\n' + '\n' + 'object.__dir__(self)\n' + '\n' + ' Called when "dir()" is called on the object. An ' + 'iterable must be\n' + ' returned. "dir()" converts the returned iterable to a ' + 'list and\n' + ' sorts it.\n' + '\n' + '\n' + 'Customizing module attribute access\n' + '===================================\n' + '\n' + 'Special names "__getattr__" and "__dir__" can be also ' + 'used to\n' + 'customize access to module attributes. The "__getattr__" ' + 'function at\n' + 'the module level should accept one argument which is the ' + 'name of an\n' + 'attribute and return the computed value or raise an ' + '"AttributeError".\n' + 'If an attribute is not found on a module object through ' + 'the normal\n' + 'lookup, i.e. "object.__getattribute__()", then ' + '"__getattr__" is\n' + 'searched in the module "__dict__" before raising an ' + '"AttributeError".\n' + 'If found, it is called with the attribute name and the ' + 'result is\n' + 'returned.\n' + '\n' + 'The "__dir__" function should accept no arguments, and ' + 'return an\n' + 'iterable of strings that represents the names accessible ' + 'on module. If\n' + 'present, this function overrides the standard "dir()" ' + 'search on a\n' + 'module.\n' + '\n' + 'For a more fine grained customization of the module ' + 'behavior (setting\n' + 'attributes, properties, etc.), one can set the ' + '"__class__" attribute\n' + 'of a module object to a subclass of "types.ModuleType". ' + 'For example:\n' + '\n' + ' import sys\n' + ' from types import ModuleType\n' + '\n' + ' class VerboseModule(ModuleType):\n' + ' def __repr__(self):\n' + " return f'Verbose {self.__name__}'\n" + '\n' + ' def __setattr__(self, attr, value):\n' + " print(f'Setting {attr}...')\n" + ' super().__setattr__(attr, value)\n' + '\n' + ' sys.modules[__name__].__class__ = VerboseModule\n' + '\n' + 'Note:\n' + '\n' + ' Defining module "__getattr__" and setting module ' + '"__class__" only\n' + ' affect lookups made using the attribute access syntax ' + '– directly\n' + ' accessing the module globals (whether by code within ' + 'the module, or\n' + ' via a reference to the module’s globals dictionary) is ' + 'unaffected.\n' + '\n' + 'Changed in version 3.5: "__class__" module attribute is ' + 'now writable.\n' + '\n' + 'New in version 3.7: "__getattr__" and "__dir__" module ' + 'attributes.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 562** - Module __getattr__ and __dir__\n' + ' Describes the "__getattr__" and "__dir__" functions ' + 'on modules.\n' + '\n' + '\n' + 'Implementing Descriptors\n' + '========================\n' + '\n' + 'The following methods only apply when an instance of the ' + 'class\n' + 'containing the method (a so-called *descriptor* class) ' + 'appears in an\n' + '*owner* class (the descriptor must be in either the ' + 'owner’s class\n' + 'dictionary or in the class dictionary for one of its ' + 'parents). In the\n' + 'examples below, “the attribute” refers to the attribute ' + 'whose name is\n' + 'the key of the property in the owner class’ "__dict__".\n' + '\n' + 'object.__get__(self, instance, owner=None)\n' + '\n' + ' Called to get the attribute of the owner class (class ' + 'attribute\n' + ' access) or of an instance of that class (instance ' + 'attribute\n' + ' access). The optional *owner* argument is the owner ' + 'class, while\n' + ' *instance* is the instance that the attribute was ' + 'accessed through,\n' + ' or "None" when the attribute is accessed through the ' + '*owner*.\n' + '\n' + ' This method should return the computed attribute ' + 'value or raise an\n' + ' "AttributeError" exception.\n' + '\n' + ' **PEP 252** specifies that "__get__()" is callable ' + 'with one or two\n' + ' arguments. Python’s own built-in descriptors support ' + 'this\n' + ' specification; however, it is likely that some ' + 'third-party tools\n' + ' have descriptors that require both arguments. ' + 'Python’s own\n' + ' "__getattribute__()" implementation always passes in ' + 'both arguments\n' + ' whether they are required or not.\n' + '\n' + 'object.__set__(self, instance, value)\n' + '\n' + ' Called to set the attribute on an instance *instance* ' + 'of the owner\n' + ' class to a new value, *value*.\n' + '\n' + ' Note, adding "__set__()" or "__delete__()" changes ' + 'the kind of\n' + ' descriptor to a “data descriptor”. See Invoking ' + 'Descriptors for\n' + ' more details.\n' + '\n' + 'object.__delete__(self, instance)\n' + '\n' + ' Called to delete the attribute on an instance ' + '*instance* of the\n' + ' owner class.\n' + '\n' + 'Instances of descriptors may also have the ' + '"__objclass__" attribute\n' + 'present:\n' + '\n' + 'object.__objclass__\n' + '\n' + ' The attribute "__objclass__" is interpreted by the ' + '"inspect" module\n' + ' as specifying the class where this object was defined ' + '(setting this\n' + ' appropriately can assist in runtime introspection of ' + 'dynamic class\n' + ' attributes). For callables, it may indicate that an ' + 'instance of the\n' + ' given type (or a subclass) is expected or required as ' + 'the first\n' + ' positional argument (for example, CPython sets this ' + 'attribute for\n' + ' unbound methods that are implemented in C).\n' + '\n' + '\n' + 'Invoking Descriptors\n' + '====================\n' + '\n' + 'In general, a descriptor is an object attribute with ' + '“binding\n' + 'behavior”, one whose attribute access has been ' + 'overridden by methods\n' + 'in the descriptor protocol: "__get__()", "__set__()", ' + 'and\n' + '"__delete__()". If any of those methods are defined for ' + 'an object, it\n' + 'is said to be a descriptor.\n' + '\n' + 'The default behavior for attribute access is to get, ' + 'set, or delete\n' + 'the attribute from an object’s dictionary. For instance, ' + '"a.x" has a\n' + 'lookup chain starting with "a.__dict__[\'x\']", then\n' + '"type(a).__dict__[\'x\']", and continuing through the ' + 'base classes of\n' + '"type(a)" excluding metaclasses.\n' + '\n' + 'However, if the looked-up value is an object defining ' + 'one of the\n' + 'descriptor methods, then Python may override the default ' + 'behavior and\n' + 'invoke the descriptor method instead. Where this occurs ' + 'in the\n' + 'precedence chain depends on which descriptor methods ' + 'were defined and\n' + 'how they were called.\n' + '\n' + 'The starting point for descriptor invocation is a ' + 'binding, "a.x". How\n' + 'the arguments are assembled depends on "a":\n' + '\n' + 'Direct Call\n' + ' The simplest and least common call is when user code ' + 'directly\n' + ' invokes a descriptor method: "x.__get__(a)".\n' + '\n' + 'Instance Binding\n' + ' If binding to an object instance, "a.x" is ' + 'transformed into the\n' + ' call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n' + '\n' + 'Class Binding\n' + ' If binding to a class, "A.x" is transformed into the ' + 'call:\n' + ' "A.__dict__[\'x\'].__get__(None, A)".\n' + '\n' + 'Super Binding\n' + ' A dotted lookup such as "super(A, a).x" searches\n' + ' "a.__class__.__mro__" for a base class "B" following ' + '"A" and then\n' + ' returns "B.__dict__[\'x\'].__get__(a, A)". If not a ' + 'descriptor, "x"\n' + ' is returned unchanged.\n' + '\n' + 'For instance bindings, the precedence of descriptor ' + 'invocation depends\n' + 'on which descriptor methods are defined. A descriptor ' + 'can define any\n' + 'combination of "__get__()", "__set__()" and ' + '"__delete__()". If it\n' + 'does not define "__get__()", then accessing the ' + 'attribute will return\n' + 'the descriptor object itself unless there is a value in ' + 'the object’s\n' + 'instance dictionary. If the descriptor defines ' + '"__set__()" and/or\n' + '"__delete__()", it is a data descriptor; if it defines ' + 'neither, it is\n' + 'a non-data descriptor. Normally, data descriptors ' + 'define both\n' + '"__get__()" and "__set__()", while non-data descriptors ' + 'have just the\n' + '"__get__()" method. Data descriptors with "__get__()" ' + 'and "__set__()"\n' + '(and/or "__delete__()") defined always override a ' + 'redefinition in an\n' + 'instance dictionary. In contrast, non-data descriptors ' + 'can be\n' + 'overridden by instances.\n' + '\n' + 'Python methods (including those decorated with ' + '"@staticmethod" and\n' + '"@classmethod") are implemented as non-data ' + 'descriptors. Accordingly,\n' + 'instances can redefine and override methods. This ' + 'allows individual\n' + 'instances to acquire behaviors that differ from other ' + 'instances of the\n' + 'same class.\n' + '\n' + 'The "property()" function is implemented as a data ' + 'descriptor.\n' + 'Accordingly, instances cannot override the behavior of a ' + 'property.\n' + '\n' + '\n' + '__slots__\n' + '=========\n' + '\n' + '*__slots__* allow us to explicitly declare data members ' + '(like\n' + 'properties) and deny the creation of "__dict__" and ' + '*__weakref__*\n' + '(unless explicitly declared in *__slots__* or available ' + 'in a parent.)\n' + '\n' + 'The space saved over using "__dict__" can be ' + 'significant. Attribute\n' + 'lookup speed can be significantly improved as well.\n' + '\n' + 'object.__slots__\n' + '\n' + ' This class variable can be assigned a string, ' + 'iterable, or sequence\n' + ' of strings with variable names used by instances. ' + '*__slots__*\n' + ' reserves space for the declared variables and ' + 'prevents the\n' + ' automatic creation of "__dict__" and *__weakref__* ' + 'for each\n' + ' instance.\n' + '\n' + 'Notes on using *__slots__*:\n' + '\n' + '* When inheriting from a class without *__slots__*, the ' + '"__dict__" and\n' + ' *__weakref__* attribute of the instances will always ' + 'be accessible.\n' + '\n' + '* Without a "__dict__" variable, instances cannot be ' + 'assigned new\n' + ' variables not listed in the *__slots__* definition. ' + 'Attempts to\n' + ' assign to an unlisted variable name raises ' + '"AttributeError". If\n' + ' dynamic assignment of new variables is desired, then ' + 'add\n' + ' "\'__dict__\'" to the sequence of strings in the ' + '*__slots__*\n' + ' declaration.\n' + '\n' + '* Without a *__weakref__* variable for each instance, ' + 'classes defining\n' + ' *__slots__* do not support "weak references" to its ' + 'instances. If\n' + ' weak reference support is needed, then add ' + '"\'__weakref__\'" to the\n' + ' sequence of strings in the *__slots__* declaration.\n' + '\n' + '* *__slots__* are implemented at the class level by ' + 'creating\n' + ' descriptors for each variable name. As a result, ' + 'class attributes\n' + ' cannot be used to set default values for instance ' + 'variables defined\n' + ' by *__slots__*; otherwise, the class attribute would ' + 'overwrite the\n' + ' descriptor assignment.\n' + '\n' + '* The action of a *__slots__* declaration is not limited ' + 'to the class\n' + ' where it is defined. *__slots__* declared in parents ' + 'are available\n' + ' in child classes. However, child subclasses will get a ' + '"__dict__"\n' + ' and *__weakref__* unless they also define *__slots__* ' + '(which should\n' + ' only contain names of any *additional* slots).\n' + '\n' + '* If a class defines a slot also defined in a base ' + 'class, the instance\n' + ' variable defined by the base class slot is ' + 'inaccessible (except by\n' + ' retrieving its descriptor directly from the base ' + 'class). This\n' + ' renders the meaning of the program undefined. In the ' + 'future, a\n' + ' check may be added to prevent this.\n' + '\n' + '* "TypeError" will be raised if nonempty *__slots__* are ' + 'defined for a\n' + ' class derived from a ""variable-length" built-in type" ' + 'such as\n' + ' "int", "bytes", and "tuple".\n' + '\n' + '* Any non-string *iterable* may be assigned to ' + '*__slots__*.\n' + '\n' + '* If a "dictionary" is used to assign *__slots__*, the ' + 'dictionary keys\n' + ' will be used as the slot names. The values of the ' + 'dictionary can be\n' + ' used to provide per-attribute docstrings that will be ' + 'recognised by\n' + ' "inspect.getdoc()" and displayed in the output of ' + '"help()".\n' + '\n' + '* "__class__" assignment works only if both classes have ' + 'the same\n' + ' *__slots__*.\n' + '\n' + '* Multiple inheritance with multiple slotted parent ' + 'classes can be\n' + ' used, but only one parent is allowed to have ' + 'attributes created by\n' + ' slots (the other bases must have empty slot layouts) - ' + 'violations\n' + ' raise "TypeError".\n' + '\n' + '* If an *iterator* is used for *__slots__* then a ' + '*descriptor* is\n' + ' created for each of the iterator’s values. However, ' + 'the *__slots__*\n' + ' attribute will be an empty iterator.\n', + 'attribute-references': 'Attribute references\n' + '********************\n' + '\n' + 'An attribute reference is a primary followed by a ' + 'period and a name:\n' + '\n' + ' attributeref ::= primary "." identifier\n' + '\n' + 'The primary must evaluate to an object of a type ' + 'that supports\n' + 'attribute references, which most objects do. This ' + 'object is then\n' + 'asked to produce the attribute whose name is the ' + 'identifier. The type\n' + 'and value produced is determined by the object. ' + 'Multiple evaluations\n' + 'of the same attribute reference may yield different ' + 'objects.\n' + '\n' + 'This production can be customized by overriding the\n' + '"__getattribute__()" method or the "__getattr__()" ' + 'method. The\n' + '"__getattribute__()" method is called first and ' + 'either returns a value\n' + 'or raises "AttributeError" if the attribute is not ' + 'available.\n' + '\n' + 'If an "AttributeError" is raised and the object has ' + 'a "__getattr__()"\n' + 'method, that method is called as a fallback.\n', + 'augassign': 'Augmented assignment statements\n' + '*******************************\n' + '\n' + 'Augmented assignment is the combination, in a single statement, ' + 'of a\n' + 'binary operation and an assignment statement:\n' + '\n' + ' augmented_assignment_stmt ::= augtarget augop ' + '(expression_list | yield_expression)\n' + ' augtarget ::= identifier | attributeref | ' + 'subscription | slicing\n' + ' augop ::= "+=" | "-=" | "*=" | "@=" | ' + '"/=" | "//=" | "%=" | "**="\n' + ' | ">>=" | "<<=" | "&=" | "^=" | "|="\n' + '\n' + '(See section Primaries for the syntax definitions of the last ' + 'three\n' + 'symbols.)\n' + '\n' + 'An augmented assignment evaluates the target (which, unlike ' + 'normal\n' + 'assignment statements, cannot be an unpacking) and the ' + 'expression\n' + 'list, performs the binary operation specific to the type of ' + 'assignment\n' + 'on the two operands, and assigns the result to the original ' + 'target.\n' + 'The target is only evaluated once.\n' + '\n' + 'An augmented assignment expression like "x += 1" can be ' + 'rewritten as\n' + '"x = x + 1" to achieve a similar, but not exactly equal effect. ' + 'In the\n' + 'augmented version, "x" is only evaluated once. Also, when ' + 'possible,\n' + 'the actual operation is performed *in-place*, meaning that ' + 'rather than\n' + 'creating a new object and assigning that to the target, the old ' + 'object\n' + 'is modified instead.\n' + '\n' + 'Unlike normal assignments, augmented assignments evaluate the ' + 'left-\n' + 'hand side *before* evaluating the right-hand side. For ' + 'example, "a[i]\n' + '+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and ' + 'performs\n' + 'the addition, and lastly, it writes the result back to "a[i]".\n' + '\n' + 'With the exception of assigning to tuples and multiple targets ' + 'in a\n' + 'single statement, the assignment done by augmented assignment\n' + 'statements is handled the same way as normal assignments. ' + 'Similarly,\n' + 'with the exception of the possible *in-place* behavior, the ' + 'binary\n' + 'operation performed by augmented assignment is the same as the ' + 'normal\n' + 'binary operations.\n' + '\n' + 'For targets which are attribute references, the same caveat ' + 'about\n' + 'class and instance attributes applies as for regular ' + 'assignments.\n', + 'await': 'Await expression\n' + '****************\n' + '\n' + 'Suspend the execution of *coroutine* on an *awaitable* object. Can\n' + 'only be used inside a *coroutine function*.\n' + '\n' + ' await_expr ::= "await" primary\n' + '\n' + 'New in version 3.5.\n', + 'binary': 'Binary arithmetic operations\n' + '****************************\n' + '\n' + 'The binary arithmetic operations have the conventional priority\n' + 'levels. Note that some of these operations also apply to certain ' + 'non-\n' + 'numeric types. Apart from the power operator, there are only two\n' + 'levels, one for multiplicative operators and one for additive\n' + 'operators:\n' + '\n' + ' m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |\n' + ' m_expr "//" u_expr | m_expr "/" u_expr |\n' + ' m_expr "%" u_expr\n' + ' a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr\n' + '\n' + 'The "*" (multiplication) operator yields the product of its ' + 'arguments.\n' + 'The arguments must either both be numbers, or one argument must be ' + 'an\n' + 'integer and the other must be a sequence. In the former case, the\n' + 'numbers are converted to a common type and then multiplied ' + 'together.\n' + 'In the latter case, sequence repetition is performed; a negative\n' + 'repetition factor yields an empty sequence.\n' + '\n' + 'This operation can be customized using the special "__mul__()" ' + 'and\n' + '"__rmul__()" methods.\n' + '\n' + 'The "@" (at) operator is intended to be used for matrix\n' + 'multiplication. No builtin Python types implement this operator.\n' + '\n' + 'New in version 3.5.\n' + '\n' + 'The "/" (division) and "//" (floor division) operators yield the\n' + 'quotient of their arguments. The numeric arguments are first\n' + 'converted to a common type. Division of integers yields a float, ' + 'while\n' + 'floor division of integers results in an integer; the result is ' + 'that\n' + 'of mathematical division with the ‘floor’ function applied to the\n' + 'result. Division by zero raises the "ZeroDivisionError" ' + 'exception.\n' + '\n' + 'This operation can be customized using the special "__truediv__()" ' + 'and\n' + '"__floordiv__()" methods.\n' + '\n' + 'The "%" (modulo) operator yields the remainder from the division ' + 'of\n' + 'the first argument by the second. The numeric arguments are ' + 'first\n' + 'converted to a common type. A zero right argument raises the\n' + '"ZeroDivisionError" exception. The arguments may be floating ' + 'point\n' + 'numbers, e.g., "3.14%0.7" equals "0.34" (since "3.14" equals ' + '"4*0.7 +\n' + '0.34".) The modulo operator always yields a result with the same ' + 'sign\n' + 'as its second operand (or zero); the absolute value of the result ' + 'is\n' + 'strictly smaller than the absolute value of the second operand ' + '[1].\n' + '\n' + 'The floor division and modulo operators are connected by the ' + 'following\n' + 'identity: "x == (x//y)*y + (x%y)". Floor division and modulo are ' + 'also\n' + 'connected with the built-in function "divmod()": "divmod(x, y) ==\n' + '(x//y, x%y)". [2].\n' + '\n' + 'In addition to performing the modulo operation on numbers, the ' + '"%"\n' + 'operator is also overloaded by string objects to perform ' + 'old-style\n' + 'string formatting (also known as interpolation). The syntax for\n' + 'string formatting is described in the Python Library Reference,\n' + 'section printf-style String Formatting.\n' + '\n' + 'The *modulo* operation can be customized using the special ' + '"__mod__()"\n' + 'method.\n' + '\n' + 'The floor division operator, the modulo operator, and the ' + '"divmod()"\n' + 'function are not defined for complex numbers. Instead, convert to ' + 'a\n' + 'floating point number using the "abs()" function if appropriate.\n' + '\n' + 'The "+" (addition) operator yields the sum of its arguments. The\n' + 'arguments must either both be numbers or both be sequences of the ' + 'same\n' + 'type. In the former case, the numbers are converted to a common ' + 'type\n' + 'and then added together. In the latter case, the sequences are\n' + 'concatenated.\n' + '\n' + 'This operation can be customized using the special "__add__()" ' + 'and\n' + '"__radd__()" methods.\n' + '\n' + 'The "-" (subtraction) operator yields the difference of its ' + 'arguments.\n' + 'The numeric arguments are first converted to a common type.\n' + '\n' + 'This operation can be customized using the special "__sub__()" ' + 'method.\n', + 'bitwise': 'Binary bitwise operations\n' + '*************************\n' + '\n' + 'Each of the three bitwise operations has a different priority ' + 'level:\n' + '\n' + ' and_expr ::= shift_expr | and_expr "&" shift_expr\n' + ' xor_expr ::= and_expr | xor_expr "^" and_expr\n' + ' or_expr ::= xor_expr | or_expr "|" xor_expr\n' + '\n' + 'The "&" operator yields the bitwise AND of its arguments, which ' + 'must\n' + 'be integers or one of them must be a custom object overriding\n' + '"__and__()" or "__rand__()" special methods.\n' + '\n' + 'The "^" operator yields the bitwise XOR (exclusive OR) of its\n' + 'arguments, which must be integers or one of them must be a ' + 'custom\n' + 'object overriding "__xor__()" or "__rxor__()" special methods.\n' + '\n' + 'The "|" operator yields the bitwise (inclusive) OR of its ' + 'arguments,\n' + 'which must be integers or one of them must be a custom object\n' + 'overriding "__or__()" or "__ror__()" special methods.\n', + 'bltin-code-objects': 'Code Objects\n' + '************\n' + '\n' + 'Code objects are used by the implementation to ' + 'represent “pseudo-\n' + 'compiled” executable Python code such as a function ' + 'body. They differ\n' + 'from function objects because they don’t contain a ' + 'reference to their\n' + 'global execution environment. Code objects are ' + 'returned by the built-\n' + 'in "compile()" function and can be extracted from ' + 'function objects\n' + 'through their "__code__" attribute. See also the ' + '"code" module.\n' + '\n' + 'Accessing "__code__" raises an auditing event ' + '"object.__getattr__"\n' + 'with arguments "obj" and ""__code__"".\n' + '\n' + 'A code object can be executed or evaluated by passing ' + 'it (instead of a\n' + 'source string) to the "exec()" or "eval()" built-in ' + 'functions.\n' + '\n' + 'See The standard type hierarchy for more ' + 'information.\n', + 'bltin-ellipsis-object': 'The Ellipsis Object\n' + '*******************\n' + '\n' + 'This object is commonly used by slicing (see ' + 'Slicings). It supports\n' + 'no special operations. There is exactly one ' + 'ellipsis object, named\n' + '"Ellipsis" (a built-in name). "type(Ellipsis)()" ' + 'produces the\n' + '"Ellipsis" singleton.\n' + '\n' + 'It is written as "Ellipsis" or "...".\n', + 'bltin-null-object': 'The Null Object\n' + '***************\n' + '\n' + 'This object is returned by functions that don’t ' + 'explicitly return a\n' + 'value. It supports no special operations. There is ' + 'exactly one null\n' + 'object, named "None" (a built-in name). "type(None)()" ' + 'produces the\n' + 'same singleton.\n' + '\n' + 'It is written as "None".\n', + 'bltin-type-objects': 'Type Objects\n' + '************\n' + '\n' + 'Type objects represent the various object types. An ' + 'object’s type is\n' + 'accessed by the built-in function "type()". There are ' + 'no special\n' + 'operations on types. The standard module "types" ' + 'defines names for\n' + 'all standard built-in types.\n' + '\n' + 'Types are written like this: "".\n', + 'booleans': 'Boolean operations\n' + '******************\n' + '\n' + ' or_test ::= and_test | or_test "or" and_test\n' + ' and_test ::= not_test | and_test "and" not_test\n' + ' not_test ::= comparison | "not" not_test\n' + '\n' + 'In the context of Boolean operations, and also when expressions ' + 'are\n' + 'used by control flow statements, the following values are ' + 'interpreted\n' + 'as false: "False", "None", numeric zero of all types, and empty\n' + 'strings and containers (including strings, tuples, lists,\n' + 'dictionaries, sets and frozensets). All other values are ' + 'interpreted\n' + 'as true. User-defined objects can customize their truth value ' + 'by\n' + 'providing a "__bool__()" method.\n' + '\n' + 'The operator "not" yields "True" if its argument is false, ' + '"False"\n' + 'otherwise.\n' + '\n' + 'The expression "x and y" first evaluates *x*; if *x* is false, ' + 'its\n' + 'value is returned; otherwise, *y* is evaluated and the resulting ' + 'value\n' + 'is returned.\n' + '\n' + 'The expression "x or y" first evaluates *x*; if *x* is true, its ' + 'value\n' + 'is returned; otherwise, *y* is evaluated and the resulting value ' + 'is\n' + 'returned.\n' + '\n' + 'Note that neither "and" nor "or" restrict the value and type ' + 'they\n' + 'return to "False" and "True", but rather return the last ' + 'evaluated\n' + 'argument. This is sometimes useful, e.g., if "s" is a string ' + 'that\n' + 'should be replaced by a default value if it is empty, the ' + 'expression\n' + '"s or \'foo\'" yields the desired value. Because "not" has to ' + 'create a\n' + 'new value, it returns a boolean value regardless of the type of ' + 'its\n' + 'argument (for example, "not \'foo\'" produces "False" rather ' + 'than "\'\'".)\n', + 'break': 'The "break" statement\n' + '*********************\n' + '\n' + ' break_stmt ::= "break"\n' + '\n' + '"break" may only occur syntactically nested in a "for" or "while"\n' + 'loop, but not nested in a function or class definition within that\n' + 'loop.\n' + '\n' + 'It terminates the nearest enclosing loop, skipping the optional ' + '"else"\n' + 'clause if the loop has one.\n' + '\n' + 'If a "for" loop is terminated by "break", the loop control target\n' + 'keeps its current value.\n' + '\n' + 'When "break" passes control out of a "try" statement with a ' + '"finally"\n' + 'clause, that "finally" clause is executed before really leaving ' + 'the\n' + 'loop.\n', + 'callable-types': 'Emulating callable objects\n' + '**************************\n' + '\n' + 'object.__call__(self[, args...])\n' + '\n' + ' Called when the instance is “called” as a function; if ' + 'this method\n' + ' is defined, "x(arg1, arg2, ...)" roughly translates to\n' + ' "type(x).__call__(x, arg1, ...)".\n', + 'calls': 'Calls\n' + '*****\n' + '\n' + 'A call calls a callable object (e.g., a *function*) with a ' + 'possibly\n' + 'empty series of *arguments*:\n' + '\n' + ' call ::= primary "(" [argument_list [","] | ' + 'comprehension] ")"\n' + ' argument_list ::= positional_arguments ["," ' + 'starred_and_keywords]\n' + ' ["," keywords_arguments]\n' + ' | starred_and_keywords ["," ' + 'keywords_arguments]\n' + ' | keywords_arguments\n' + ' positional_arguments ::= positional_item ("," positional_item)*\n' + ' positional_item ::= assignment_expression | "*" expression\n' + ' starred_and_keywords ::= ("*" expression | keyword_item)\n' + ' ("," "*" expression | "," ' + 'keyword_item)*\n' + ' keywords_arguments ::= (keyword_item | "**" expression)\n' + ' ("," keyword_item | "," "**" ' + 'expression)*\n' + ' keyword_item ::= identifier "=" expression\n' + '\n' + 'An optional trailing comma may be present after the positional and\n' + 'keyword arguments but does not affect the semantics.\n' + '\n' + 'The primary must evaluate to a callable object (user-defined\n' + 'functions, built-in functions, methods of built-in objects, class\n' + 'objects, methods of class instances, and all objects having a\n' + '"__call__()" method are callable). All argument expressions are\n' + 'evaluated before the call is attempted. Please refer to section\n' + 'Function definitions for the syntax of formal *parameter* lists.\n' + '\n' + 'If keyword arguments are present, they are first converted to\n' + 'positional arguments, as follows. First, a list of unfilled slots ' + 'is\n' + 'created for the formal parameters. If there are N positional\n' + 'arguments, they are placed in the first N slots. Next, for each\n' + 'keyword argument, the identifier is used to determine the\n' + 'corresponding slot (if the identifier is the same as the first ' + 'formal\n' + 'parameter name, the first slot is used, and so on). If the slot ' + 'is\n' + 'already filled, a "TypeError" exception is raised. Otherwise, the\n' + 'argument is placed in the slot, filling it (even if the expression ' + 'is\n' + '"None", it fills the slot). When all arguments have been ' + 'processed,\n' + 'the slots that are still unfilled are filled with the ' + 'corresponding\n' + 'default value from the function definition. (Default values are\n' + 'calculated, once, when the function is defined; thus, a mutable ' + 'object\n' + 'such as a list or dictionary used as default value will be shared ' + 'by\n' + 'all calls that don’t specify an argument value for the ' + 'corresponding\n' + 'slot; this should usually be avoided.) If there are any unfilled\n' + 'slots for which no default value is specified, a "TypeError" ' + 'exception\n' + 'is raised. Otherwise, the list of filled slots is used as the\n' + 'argument list for the call.\n' + '\n' + '**CPython implementation detail:** An implementation may provide\n' + 'built-in functions whose positional parameters do not have names, ' + 'even\n' + 'if they are ‘named’ for the purpose of documentation, and which\n' + 'therefore cannot be supplied by keyword. In CPython, this is the ' + 'case\n' + 'for functions implemented in C that use "PyArg_ParseTuple()" to ' + 'parse\n' + 'their arguments.\n' + '\n' + 'If there are more positional arguments than there are formal ' + 'parameter\n' + 'slots, a "TypeError" exception is raised, unless a formal ' + 'parameter\n' + 'using the syntax "*identifier" is present; in this case, that ' + 'formal\n' + 'parameter receives a tuple containing the excess positional ' + 'arguments\n' + '(or an empty tuple if there were no excess positional arguments).\n' + '\n' + 'If any keyword argument does not correspond to a formal parameter\n' + 'name, a "TypeError" exception is raised, unless a formal parameter\n' + 'using the syntax "**identifier" is present; in this case, that ' + 'formal\n' + 'parameter receives a dictionary containing the excess keyword\n' + 'arguments (using the keywords as keys and the argument values as\n' + 'corresponding values), or a (new) empty dictionary if there were ' + 'no\n' + 'excess keyword arguments.\n' + '\n' + 'If the syntax "*expression" appears in the function call, ' + '"expression"\n' + 'must evaluate to an *iterable*. Elements from these iterables are\n' + 'treated as if they were additional positional arguments. For the ' + 'call\n' + '"f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, …, ' + '*yM*,\n' + 'this is equivalent to a call with M+4 positional arguments *x1*, ' + '*x2*,\n' + '*y1*, …, *yM*, *x3*, *x4*.\n' + '\n' + 'A consequence of this is that although the "*expression" syntax ' + 'may\n' + 'appear *after* explicit keyword arguments, it is processed ' + '*before*\n' + 'the keyword arguments (and any "**expression" arguments – see ' + 'below).\n' + 'So:\n' + '\n' + ' >>> def f(a, b):\n' + ' ... print(a, b)\n' + ' ...\n' + ' >>> f(b=1, *(2,))\n' + ' 2 1\n' + ' >>> f(a=1, *(2,))\n' + ' Traceback (most recent call last):\n' + ' File "", line 1, in \n' + " TypeError: f() got multiple values for keyword argument 'a'\n" + ' >>> f(1, *(2,))\n' + ' 1 2\n' + '\n' + 'It is unusual for both keyword arguments and the "*expression" ' + 'syntax\n' + 'to be used in the same call, so in practice this confusion does ' + 'not\n' + 'often arise.\n' + '\n' + 'If the syntax "**expression" appears in the function call,\n' + '"expression" must evaluate to a *mapping*, the contents of which ' + 'are\n' + 'treated as additional keyword arguments. If a parameter matching a ' + 'key\n' + 'has already been given a value (by an explicit keyword argument, ' + 'or\n' + 'from another unpacking), a "TypeError" exception is raised.\n' + '\n' + 'When "**expression" is used, each key in this mapping must be a\n' + 'string. Each value from the mapping is assigned to the first ' + 'formal\n' + 'parameter eligible for keyword assignment whose name is equal to ' + 'the\n' + 'key. A key need not be a Python identifier (e.g. ""max-temp °F"" ' + 'is\n' + 'acceptable, although it will not match any formal parameter that ' + 'could\n' + 'be declared). If there is no match to a formal parameter the ' + 'key-value\n' + 'pair is collected by the "**" parameter, if there is one, or if ' + 'there\n' + 'is not, a "TypeError" exception is raised.\n' + '\n' + 'Formal parameters using the syntax "*identifier" or "**identifier"\n' + 'cannot be used as positional argument slots or as keyword argument\n' + 'names.\n' + '\n' + 'Changed in version 3.5: Function calls accept any number of "*" ' + 'and\n' + '"**" unpackings, positional arguments may follow iterable ' + 'unpackings\n' + '("*"), and keyword arguments may follow dictionary unpackings ' + '("**").\n' + 'Originally proposed by **PEP 448**.\n' + '\n' + 'A call always returns some value, possibly "None", unless it raises ' + 'an\n' + 'exception. How this value is computed depends on the type of the\n' + 'callable object.\n' + '\n' + 'If it is—\n' + '\n' + 'a user-defined function:\n' + ' The code block for the function is executed, passing it the\n' + ' argument list. The first thing the code block will do is bind ' + 'the\n' + ' formal parameters to the arguments; this is described in ' + 'section\n' + ' Function definitions. When the code block executes a "return"\n' + ' statement, this specifies the return value of the function ' + 'call.\n' + '\n' + 'a built-in function or method:\n' + ' The result is up to the interpreter; see Built-in Functions for ' + 'the\n' + ' descriptions of built-in functions and methods.\n' + '\n' + 'a class object:\n' + ' A new instance of that class is returned.\n' + '\n' + 'a class instance method:\n' + ' The corresponding user-defined function is called, with an ' + 'argument\n' + ' list that is one longer than the argument list of the call: the\n' + ' instance becomes the first argument.\n' + '\n' + 'a class instance:\n' + ' The class must define a "__call__()" method; the effect is then ' + 'the\n' + ' same as if that method was called.\n', + 'class': 'Class definitions\n' + '*****************\n' + '\n' + 'A class definition defines a class object (see section The ' + 'standard\n' + 'type hierarchy):\n' + '\n' + ' classdef ::= [decorators] "class" classname [inheritance] ":" ' + 'suite\n' + ' inheritance ::= "(" [argument_list] ")"\n' + ' classname ::= identifier\n' + '\n' + 'A class definition is an executable statement. The inheritance ' + 'list\n' + 'usually gives a list of base classes (see Metaclasses for more\n' + 'advanced uses), so each item in the list should evaluate to a ' + 'class\n' + 'object which allows subclassing. Classes without an inheritance ' + 'list\n' + 'inherit, by default, from the base class "object"; hence,\n' + '\n' + ' class Foo:\n' + ' pass\n' + '\n' + 'is equivalent to\n' + '\n' + ' class Foo(object):\n' + ' pass\n' + '\n' + 'The class’s suite is then executed in a new execution frame (see\n' + 'Naming and binding), using a newly created local namespace and the\n' + 'original global namespace. (Usually, the suite contains mostly\n' + 'function definitions.) When the class’s suite finishes execution, ' + 'its\n' + 'execution frame is discarded but its local namespace is saved. [5] ' + 'A\n' + 'class object is then created using the inheritance list for the ' + 'base\n' + 'classes and the saved local namespace for the attribute ' + 'dictionary.\n' + 'The class name is bound to this class object in the original local\n' + 'namespace.\n' + '\n' + 'The order in which attributes are defined in the class body is\n' + 'preserved in the new class’s "__dict__". Note that this is ' + 'reliable\n' + 'only right after the class is created and only for classes that ' + 'were\n' + 'defined using the definition syntax.\n' + '\n' + 'Class creation can be customized heavily using metaclasses.\n' + '\n' + 'Classes can also be decorated: just like when decorating ' + 'functions,\n' + '\n' + ' @f1(arg)\n' + ' @f2\n' + ' class Foo: pass\n' + '\n' + 'is roughly equivalent to\n' + '\n' + ' class Foo: pass\n' + ' Foo = f1(arg)(f2(Foo))\n' + '\n' + 'The evaluation rules for the decorator expressions are the same as ' + 'for\n' + 'function decorators. The result is then bound to the class name.\n' + '\n' + 'Changed in version 3.9: Classes may be decorated with any valid\n' + '"assignment_expression". Previously, the grammar was much more\n' + 'restrictive; see **PEP 614** for details.\n' + '\n' + '**Programmer’s note:** Variables defined in the class definition ' + 'are\n' + 'class attributes; they are shared by instances. Instance ' + 'attributes\n' + 'can be set in a method with "self.name = value". Both class and\n' + 'instance attributes are accessible through the notation ' + '“"self.name"”,\n' + 'and an instance attribute hides a class attribute with the same ' + 'name\n' + 'when accessed in this way. Class attributes can be used as ' + 'defaults\n' + 'for instance attributes, but using mutable values there can lead ' + 'to\n' + 'unexpected results. Descriptors can be used to create instance\n' + 'variables with different implementation details.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3115** - Metaclasses in Python 3000\n' + ' The proposal that changed the declaration of metaclasses to ' + 'the\n' + ' current syntax, and the semantics for how classes with\n' + ' metaclasses are constructed.\n' + '\n' + ' **PEP 3129** - Class Decorators\n' + ' The proposal that added class decorators. Function and ' + 'method\n' + ' decorators were introduced in **PEP 318**.\n', + 'comparisons': 'Comparisons\n' + '***********\n' + '\n' + 'Unlike C, all comparison operations in Python have the same ' + 'priority,\n' + 'which is lower than that of any arithmetic, shifting or ' + 'bitwise\n' + 'operation. Also unlike C, expressions like "a < b < c" have ' + 'the\n' + 'interpretation that is conventional in mathematics:\n' + '\n' + ' comparison ::= or_expr (comp_operator or_expr)*\n' + ' comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n' + ' | "is" ["not"] | ["not"] "in"\n' + '\n' + 'Comparisons yield boolean values: "True" or "False". Custom ' + '*rich\n' + 'comparison methods* may return non-boolean values. In this ' + 'case Python\n' + 'will call "bool()" on such value in boolean contexts.\n' + '\n' + 'Comparisons can be chained arbitrarily, e.g., "x < y <= z" ' + 'is\n' + 'equivalent to "x < y and y <= z", except that "y" is ' + 'evaluated only\n' + 'once (but in both cases "z" is not evaluated at all when "x < ' + 'y" is\n' + 'found to be false).\n' + '\n' + 'Formally, if *a*, *b*, *c*, …, *y*, *z* are expressions and ' + '*op1*,\n' + '*op2*, …, *opN* are comparison operators, then "a op1 b op2 c ' + '... y\n' + 'opN z" is equivalent to "a op1 b and b op2 c and ... y opN ' + 'z", except\n' + 'that each expression is evaluated at most once.\n' + '\n' + 'Note that "a op1 b op2 c" doesn’t imply any kind of ' + 'comparison between\n' + '*a* and *c*, so that, e.g., "x < y > z" is perfectly legal ' + '(though\n' + 'perhaps not pretty).\n' + '\n' + '\n' + 'Value comparisons\n' + '=================\n' + '\n' + 'The operators "<", ">", "==", ">=", "<=", and "!=" compare ' + 'the values\n' + 'of two objects. The objects do not need to have the same ' + 'type.\n' + '\n' + 'Chapter Objects, values and types states that objects have a ' + 'value (in\n' + 'addition to type and identity). The value of an object is a ' + 'rather\n' + 'abstract notion in Python: For example, there is no canonical ' + 'access\n' + 'method for an object’s value. Also, there is no requirement ' + 'that the\n' + 'value of an object should be constructed in a particular way, ' + 'e.g.\n' + 'comprised of all its data attributes. Comparison operators ' + 'implement a\n' + 'particular notion of what the value of an object is. One can ' + 'think of\n' + 'them as defining the value of an object indirectly, by means ' + 'of their\n' + 'comparison implementation.\n' + '\n' + 'Because all types are (direct or indirect) subtypes of ' + '"object", they\n' + 'inherit the default comparison behavior from "object". Types ' + 'can\n' + 'customize their comparison behavior by implementing *rich ' + 'comparison\n' + 'methods* like "__lt__()", described in Basic customization.\n' + '\n' + 'The default behavior for equality comparison ("==" and "!=") ' + 'is based\n' + 'on the identity of the objects. Hence, equality comparison ' + 'of\n' + 'instances with the same identity results in equality, and ' + 'equality\n' + 'comparison of instances with different identities results in\n' + 'inequality. A motivation for this default behavior is the ' + 'desire that\n' + 'all objects should be reflexive (i.e. "x is y" implies "x == ' + 'y").\n' + '\n' + 'A default order comparison ("<", ">", "<=", and ">=") is not ' + 'provided;\n' + 'an attempt raises "TypeError". A motivation for this default ' + 'behavior\n' + 'is the lack of a similar invariant as for equality.\n' + '\n' + 'The behavior of the default equality comparison, that ' + 'instances with\n' + 'different identities are always unequal, may be in contrast ' + 'to what\n' + 'types will need that have a sensible definition of object ' + 'value and\n' + 'value-based equality. Such types will need to customize ' + 'their\n' + 'comparison behavior, and in fact, a number of built-in types ' + 'have done\n' + 'that.\n' + '\n' + 'The following list describes the comparison behavior of the ' + 'most\n' + 'important built-in types.\n' + '\n' + '* Numbers of built-in numeric types (Numeric Types — int, ' + 'float,\n' + ' complex) and of the standard library types ' + '"fractions.Fraction" and\n' + ' "decimal.Decimal" can be compared within and across their ' + 'types,\n' + ' with the restriction that complex numbers do not support ' + 'order\n' + ' comparison. Within the limits of the types involved, they ' + 'compare\n' + ' mathematically (algorithmically) correct without loss of ' + 'precision.\n' + '\n' + ' The not-a-number values "float(\'NaN\')" and ' + '"decimal.Decimal(\'NaN\')"\n' + ' are special. Any ordered comparison of a number to a ' + 'not-a-number\n' + ' value is false. A counter-intuitive implication is that ' + 'not-a-number\n' + ' values are not equal to themselves. For example, if "x =\n' + ' float(\'NaN\')", "3 < x", "x < 3" and "x == x" are all ' + 'false, while "x\n' + ' != x" is true. This behavior is compliant with IEEE 754.\n' + '\n' + '* "None" and "NotImplemented" are singletons. **PEP 8** ' + 'advises that\n' + ' comparisons for singletons should always be done with "is" ' + 'or "is\n' + ' not", never the equality operators.\n' + '\n' + '* Binary sequences (instances of "bytes" or "bytearray") can ' + 'be\n' + ' compared within and across their types. They compare\n' + ' lexicographically using the numeric values of their ' + 'elements.\n' + '\n' + '* Strings (instances of "str") compare lexicographically ' + 'using the\n' + ' numerical Unicode code points (the result of the built-in ' + 'function\n' + ' "ord()") of their characters. [3]\n' + '\n' + ' Strings and binary sequences cannot be directly compared.\n' + '\n' + '* Sequences (instances of "tuple", "list", or "range") can be ' + 'compared\n' + ' only within each of their types, with the restriction that ' + 'ranges do\n' + ' not support order comparison. Equality comparison across ' + 'these\n' + ' types results in inequality, and ordering comparison across ' + 'these\n' + ' types raises "TypeError".\n' + '\n' + ' Sequences compare lexicographically using comparison of\n' + ' corresponding elements. The built-in containers typically ' + 'assume\n' + ' identical objects are equal to themselves. That lets them ' + 'bypass\n' + ' equality tests for identical objects to improve performance ' + 'and to\n' + ' maintain their internal invariants.\n' + '\n' + ' Lexicographical comparison between built-in collections ' + 'works as\n' + ' follows:\n' + '\n' + ' * For two collections to compare equal, they must be of the ' + 'same\n' + ' type, have the same length, and each pair of ' + 'corresponding\n' + ' elements must compare equal (for example, "[1,2] == ' + '(1,2)" is\n' + ' false because the type is not the same).\n' + '\n' + ' * Collections that support order comparison are ordered the ' + 'same as\n' + ' their first unequal elements (for example, "[1,2,x] <= ' + '[1,2,y]"\n' + ' has the same value as "x <= y"). If a corresponding ' + 'element does\n' + ' not exist, the shorter collection is ordered first (for ' + 'example,\n' + ' "[1,2] < [1,2,3]" is true).\n' + '\n' + '* Mappings (instances of "dict") compare equal if and only if ' + 'they\n' + ' have equal "(key, value)" pairs. Equality comparison of the ' + 'keys and\n' + ' values enforces reflexivity.\n' + '\n' + ' Order comparisons ("<", ">", "<=", and ">=") raise ' + '"TypeError".\n' + '\n' + '* Sets (instances of "set" or "frozenset") can be compared ' + 'within and\n' + ' across their types.\n' + '\n' + ' They define order comparison operators to mean subset and ' + 'superset\n' + ' tests. Those relations do not define total orderings (for ' + 'example,\n' + ' the two sets "{1,2}" and "{2,3}" are not equal, nor subsets ' + 'of one\n' + ' another, nor supersets of one another). Accordingly, sets ' + 'are not\n' + ' appropriate arguments for functions which depend on total ' + 'ordering\n' + ' (for example, "min()", "max()", and "sorted()" produce ' + 'undefined\n' + ' results given a list of sets as inputs).\n' + '\n' + ' Comparison of sets enforces reflexivity of its elements.\n' + '\n' + '* Most other built-in types have no comparison methods ' + 'implemented, so\n' + ' they inherit the default comparison behavior.\n' + '\n' + 'User-defined classes that customize their comparison behavior ' + 'should\n' + 'follow some consistency rules, if possible:\n' + '\n' + '* Equality comparison should be reflexive. In other words, ' + 'identical\n' + ' objects should compare equal:\n' + '\n' + ' "x is y" implies "x == y"\n' + '\n' + '* Comparison should be symmetric. In other words, the ' + 'following\n' + ' expressions should have the same result:\n' + '\n' + ' "x == y" and "y == x"\n' + '\n' + ' "x != y" and "y != x"\n' + '\n' + ' "x < y" and "y > x"\n' + '\n' + ' "x <= y" and "y >= x"\n' + '\n' + '* Comparison should be transitive. The following ' + '(non-exhaustive)\n' + ' examples illustrate that:\n' + '\n' + ' "x > y and y > z" implies "x > z"\n' + '\n' + ' "x < y and y <= z" implies "x < z"\n' + '\n' + '* Inverse comparison should result in the boolean negation. ' + 'In other\n' + ' words, the following expressions should have the same ' + 'result:\n' + '\n' + ' "x == y" and "not x != y"\n' + '\n' + ' "x < y" and "not x >= y" (for total ordering)\n' + '\n' + ' "x > y" and "not x <= y" (for total ordering)\n' + '\n' + ' The last two expressions apply to totally ordered ' + 'collections (e.g.\n' + ' to sequences, but not to sets or mappings). See also the\n' + ' "total_ordering()" decorator.\n' + '\n' + '* The "hash()" result should be consistent with equality. ' + 'Objects that\n' + ' are equal should either have the same hash value, or be ' + 'marked as\n' + ' unhashable.\n' + '\n' + 'Python does not enforce these consistency rules. In fact, ' + 'the\n' + 'not-a-number values are an example for not following these ' + 'rules.\n' + '\n' + '\n' + 'Membership test operations\n' + '==========================\n' + '\n' + 'The operators "in" and "not in" test for membership. "x in ' + 's"\n' + 'evaluates to "True" if *x* is a member of *s*, and "False" ' + 'otherwise.\n' + '"x not in s" returns the negation of "x in s". All built-in ' + 'sequences\n' + 'and set types support this as well as dictionary, for which ' + '"in" tests\n' + 'whether the dictionary has a given key. For container types ' + 'such as\n' + 'list, tuple, set, frozenset, dict, or collections.deque, the\n' + 'expression "x in y" is equivalent to "any(x is e or x == e ' + 'for e in\n' + 'y)".\n' + '\n' + 'For the string and bytes types, "x in y" is "True" if and ' + 'only if *x*\n' + 'is a substring of *y*. An equivalent test is "y.find(x) != ' + '-1".\n' + 'Empty strings are always considered to be a substring of any ' + 'other\n' + 'string, so """ in "abc"" will return "True".\n' + '\n' + 'For user-defined classes which define the "__contains__()" ' + 'method, "x\n' + 'in y" returns "True" if "y.__contains__(x)" returns a true ' + 'value, and\n' + '"False" otherwise.\n' + '\n' + 'For user-defined classes which do not define "__contains__()" ' + 'but do\n' + 'define "__iter__()", "x in y" is "True" if some value "z", ' + 'for which\n' + 'the expression "x is z or x == z" is true, is produced while ' + 'iterating\n' + 'over "y". If an exception is raised during the iteration, it ' + 'is as if\n' + '"in" raised that exception.\n' + '\n' + 'Lastly, the old-style iteration protocol is tried: if a class ' + 'defines\n' + '"__getitem__()", "x in y" is "True" if and only if there is a ' + 'non-\n' + 'negative integer index *i* such that "x is y[i] or x == ' + 'y[i]", and no\n' + 'lower integer index raises the "IndexError" exception. (If ' + 'any other\n' + 'exception is raised, it is as if "in" raised that ' + 'exception).\n' + '\n' + 'The operator "not in" is defined to have the inverse truth ' + 'value of\n' + '"in".\n' + '\n' + '\n' + 'Identity comparisons\n' + '====================\n' + '\n' + 'The operators "is" and "is not" test for an object’s ' + 'identity: "x is\n' + 'y" is true if and only if *x* and *y* are the same object. ' + 'An\n' + 'Object’s identity is determined using the "id()" function. ' + '"x is not\n' + 'y" yields the inverse truth value. [4]\n', + 'compound': 'Compound statements\n' + '*******************\n' + '\n' + 'Compound statements contain (groups of) other statements; they ' + 'affect\n' + 'or control the execution of those other statements in some way. ' + 'In\n' + 'general, compound statements span multiple lines, although in ' + 'simple\n' + 'incarnations a whole compound statement may be contained in one ' + 'line.\n' + '\n' + 'The "if", "while" and "for" statements implement traditional ' + 'control\n' + 'flow constructs. "try" specifies exception handlers and/or ' + 'cleanup\n' + 'code for a group of statements, while the "with" statement ' + 'allows the\n' + 'execution of initialization and finalization code around a block ' + 'of\n' + 'code. Function and class definitions are also syntactically ' + 'compound\n' + 'statements.\n' + '\n' + 'A compound statement consists of one or more ‘clauses.’ A ' + 'clause\n' + 'consists of a header and a ‘suite.’ The clause headers of a\n' + 'particular compound statement are all at the same indentation ' + 'level.\n' + 'Each clause header begins with a uniquely identifying keyword ' + 'and ends\n' + 'with a colon. A suite is a group of statements controlled by a\n' + 'clause. A suite can be one or more semicolon-separated simple\n' + 'statements on the same line as the header, following the ' + 'header’s\n' + 'colon, or it can be one or more indented statements on ' + 'subsequent\n' + 'lines. Only the latter form of a suite can contain nested ' + 'compound\n' + 'statements; the following is illegal, mostly because it wouldn’t ' + 'be\n' + 'clear to which "if" clause a following "else" clause would ' + 'belong:\n' + '\n' + ' if test1: if test2: print(x)\n' + '\n' + 'Also note that the semicolon binds tighter than the colon in ' + 'this\n' + 'context, so that in the following example, either all or none of ' + 'the\n' + '"print()" calls are executed:\n' + '\n' + ' if x < y < z: print(x); print(y); print(z)\n' + '\n' + 'Summarizing:\n' + '\n' + ' compound_stmt ::= if_stmt\n' + ' | while_stmt\n' + ' | for_stmt\n' + ' | try_stmt\n' + ' | with_stmt\n' + ' | match_stmt\n' + ' | funcdef\n' + ' | classdef\n' + ' | async_with_stmt\n' + ' | async_for_stmt\n' + ' | async_funcdef\n' + ' suite ::= stmt_list NEWLINE | NEWLINE INDENT ' + 'statement+ DEDENT\n' + ' statement ::= stmt_list NEWLINE | compound_stmt\n' + ' stmt_list ::= simple_stmt (";" simple_stmt)* [";"]\n' + '\n' + 'Note that statements always end in a "NEWLINE" possibly followed ' + 'by a\n' + '"DEDENT". Also note that optional continuation clauses always ' + 'begin\n' + 'with a keyword that cannot start a statement, thus there are no\n' + 'ambiguities (the ‘dangling "else"’ problem is solved in Python ' + 'by\n' + 'requiring nested "if" statements to be indented).\n' + '\n' + 'The formatting of the grammar rules in the following sections ' + 'places\n' + 'each clause on a separate line for clarity.\n' + '\n' + '\n' + 'The "if" statement\n' + '==================\n' + '\n' + 'The "if" statement is used for conditional execution:\n' + '\n' + ' if_stmt ::= "if" assignment_expression ":" suite\n' + ' ("elif" assignment_expression ":" suite)*\n' + ' ["else" ":" suite]\n' + '\n' + 'It selects exactly one of the suites by evaluating the ' + 'expressions one\n' + 'by one until one is found to be true (see section Boolean ' + 'operations\n' + 'for the definition of true and false); then that suite is ' + 'executed\n' + '(and no other part of the "if" statement is executed or ' + 'evaluated).\n' + 'If all expressions are false, the suite of the "else" clause, ' + 'if\n' + 'present, is executed.\n' + '\n' + '\n' + 'The "while" statement\n' + '=====================\n' + '\n' + 'The "while" statement is used for repeated execution as long as ' + 'an\n' + 'expression is true:\n' + '\n' + ' while_stmt ::= "while" assignment_expression ":" suite\n' + ' ["else" ":" suite]\n' + '\n' + 'This repeatedly tests the expression and, if it is true, ' + 'executes the\n' + 'first suite; if the expression is false (which may be the first ' + 'time\n' + 'it is tested) the suite of the "else" clause, if present, is ' + 'executed\n' + 'and the loop terminates.\n' + '\n' + 'A "break" statement executed in the first suite terminates the ' + 'loop\n' + 'without executing the "else" clause’s suite. A "continue" ' + 'statement\n' + 'executed in the first suite skips the rest of the suite and goes ' + 'back\n' + 'to testing the expression.\n' + '\n' + '\n' + 'The "for" statement\n' + '===================\n' + '\n' + 'The "for" statement is used to iterate over the elements of a ' + 'sequence\n' + '(such as a string, tuple or list) or other iterable object:\n' + '\n' + ' for_stmt ::= "for" target_list "in" starred_list ":" suite\n' + ' ["else" ":" suite]\n' + '\n' + 'The "starred_list" expression is evaluated once; it should yield ' + 'an\n' + '*iterable* object. An *iterator* is created for that iterable. ' + 'The\n' + 'first item provided by the iterator is then assigned to the ' + 'target\n' + 'list using the standard rules for assignments (see Assignment\n' + 'statements), and the suite is executed. This repeats for each ' + 'item\n' + 'provided by the iterator. When the iterator is exhausted, the ' + 'suite\n' + 'in the "else" clause, if present, is executed, and the loop\n' + 'terminates.\n' + '\n' + 'A "break" statement executed in the first suite terminates the ' + 'loop\n' + 'without executing the "else" clause’s suite. A "continue" ' + 'statement\n' + 'executed in the first suite skips the rest of the suite and ' + 'continues\n' + 'with the next item, or with the "else" clause if there is no ' + 'next\n' + 'item.\n' + '\n' + 'The for-loop makes assignments to the variables in the target ' + 'list.\n' + 'This overwrites all previous assignments to those variables ' + 'including\n' + 'those made in the suite of the for-loop:\n' + '\n' + ' for i in range(10):\n' + ' print(i)\n' + ' i = 5 # this will not affect the for-loop\n' + ' # because i will be overwritten with ' + 'the next\n' + ' # index in the range\n' + '\n' + 'Names in the target list are not deleted when the loop is ' + 'finished,\n' + 'but if the sequence is empty, they will not have been assigned ' + 'to at\n' + 'all by the loop. Hint: the built-in type "range()" represents\n' + 'immutable arithmetic sequences of integers. For instance, ' + 'iterating\n' + '"range(3)" successively yields 0, 1, and then 2.\n' + '\n' + 'Changed in version 3.11: Starred elements are now allowed in ' + 'the\n' + 'expression list.\n' + '\n' + '\n' + 'The "try" statement\n' + '===================\n' + '\n' + 'The "try" statement specifies exception handlers and/or cleanup ' + 'code\n' + 'for a group of statements:\n' + '\n' + ' try_stmt ::= try1_stmt | try2_stmt | try3_stmt\n' + ' try1_stmt ::= "try" ":" suite\n' + ' ("except" [expression ["as" identifier]] ":" ' + 'suite)+\n' + ' ["else" ":" suite]\n' + ' ["finally" ":" suite]\n' + ' try2_stmt ::= "try" ":" suite\n' + ' ("except" "*" expression ["as" identifier] ":" ' + 'suite)+\n' + ' ["else" ":" suite]\n' + ' ["finally" ":" suite]\n' + ' try3_stmt ::= "try" ":" suite\n' + ' "finally" ":" suite\n' + '\n' + 'Additional information on exceptions can be found in section\n' + 'Exceptions, and information on using the "raise" statement to ' + 'generate\n' + 'exceptions may be found in section The raise statement.\n' + '\n' + '\n' + '"except" clause\n' + '---------------\n' + '\n' + 'The "except" clause(s) specify one or more exception handlers. ' + 'When no\n' + 'exception occurs in the "try" clause, no exception handler is\n' + 'executed. When an exception occurs in the "try" suite, a search ' + 'for an\n' + 'exception handler is started. This search inspects the "except"\n' + 'clauses in turn until one is found that matches the exception. ' + 'An\n' + 'expression-less "except" clause, if present, must be last; it ' + 'matches\n' + 'any exception. For an "except" clause with an expression, that\n' + 'expression is evaluated, and the clause matches the exception if ' + 'the\n' + 'resulting object is “compatible” with the exception. An object ' + 'is\n' + 'compatible with an exception if the object is the class or a ' + '*non-\n' + 'virtual base class* of the exception object, or a tuple ' + 'containing an\n' + 'item that is the class or a non-virtual base class of the ' + 'exception\n' + 'object.\n' + '\n' + 'If no "except" clause matches the exception, the search for an\n' + 'exception handler continues in the surrounding code and on the\n' + 'invocation stack. [1]\n' + '\n' + 'If the evaluation of an expression in the header of an "except" ' + 'clause\n' + 'raises an exception, the original search for a handler is ' + 'canceled and\n' + 'a search starts for the new exception in the surrounding code ' + 'and on\n' + 'the call stack (it is treated as if the entire "try" statement ' + 'raised\n' + 'the exception).\n' + '\n' + 'When a matching "except" clause is found, the exception is ' + 'assigned to\n' + 'the target specified after the "as" keyword in that "except" ' + 'clause,\n' + 'if present, and the "except" clause’s suite is executed. All ' + '"except"\n' + 'clauses must have an executable block. When the end of this ' + 'block is\n' + 'reached, execution continues normally after the entire "try"\n' + 'statement. (This means that if two nested handlers exist for the ' + 'same\n' + 'exception, and the exception occurs in the "try" clause of the ' + 'inner\n' + 'handler, the outer handler will not handle the exception.)\n' + '\n' + 'When an exception has been assigned using "as target", it is ' + 'cleared\n' + 'at the end of the "except" clause. This is as if\n' + '\n' + ' except E as N:\n' + ' foo\n' + '\n' + 'was translated to\n' + '\n' + ' except E as N:\n' + ' try:\n' + ' foo\n' + ' finally:\n' + ' del N\n' + '\n' + 'This means the exception must be assigned to a different name to ' + 'be\n' + 'able to refer to it after the "except" clause. Exceptions are ' + 'cleared\n' + 'because with the traceback attached to them, they form a ' + 'reference\n' + 'cycle with the stack frame, keeping all locals in that frame ' + 'alive\n' + 'until the next garbage collection occurs.\n' + '\n' + 'Before an "except" clause’s suite is executed, the exception is ' + 'stored\n' + 'in the "sys" module, where it can be accessed from within the ' + 'body of\n' + 'the "except" clause by calling "sys.exception()". When leaving ' + 'an\n' + 'exception handler, the exception stored in the "sys" module is ' + 'reset\n' + 'to its previous value:\n' + '\n' + ' >>> print(sys.exception())\n' + ' None\n' + ' >>> try:\n' + ' ... raise TypeError\n' + ' ... except:\n' + ' ... print(repr(sys.exception()))\n' + ' ... try:\n' + ' ... raise ValueError\n' + ' ... except:\n' + ' ... print(repr(sys.exception()))\n' + ' ... print(repr(sys.exception()))\n' + ' ...\n' + ' TypeError()\n' + ' ValueError()\n' + ' TypeError()\n' + ' >>> print(sys.exception())\n' + ' None\n' + '\n' + '\n' + '"except*" clause\n' + '----------------\n' + '\n' + 'The "except*" clause(s) are used for handling "ExceptionGroup"s. ' + 'The\n' + 'exception type for matching is interpreted as in the case of ' + '"except",\n' + 'but in the case of exception groups we can have partial matches ' + 'when\n' + 'the type matches some of the exceptions in the group. This means ' + 'that\n' + 'multiple "except*" clauses can execute, each handling part of ' + 'the\n' + 'exception group. Each clause executes at most once and handles ' + 'an\n' + 'exception group of all matching exceptions. Each exception in ' + 'the\n' + 'group is handled by at most one "except*" clause, the first ' + 'that\n' + 'matches it.\n' + '\n' + ' >>> try:\n' + ' ... raise ExceptionGroup("eg",\n' + ' ... [ValueError(1), TypeError(2), OSError(3), ' + 'OSError(4)])\n' + ' ... except* TypeError as e:\n' + " ... print(f'caught {type(e)} with nested " + "{e.exceptions}')\n" + ' ... except* OSError as e:\n' + " ... print(f'caught {type(e)} with nested " + "{e.exceptions}')\n" + ' ...\n' + " caught with nested (TypeError(2),)\n" + " caught with nested (OSError(3), " + 'OSError(4))\n' + ' + Exception Group Traceback (most recent call last):\n' + ' | File "", line 2, in \n' + ' | ExceptionGroup: eg\n' + ' +-+---------------- 1 ----------------\n' + ' | ValueError: 1\n' + ' +------------------------------------\n' + '\n' + 'Any remaining exceptions that were not handled by any "except*" ' + 'clause\n' + 'are re-raised at the end, combined into an exception group along ' + 'with\n' + 'all exceptions that were raised from within "except*" clauses.\n' + '\n' + 'From version 3.11.4, when the entire "ExceptionGroup" is handled ' + 'and\n' + 'only one exception is raised from an "except*" clause, this ' + 'exception\n' + 'is no longer wrapped to form a new "ExceptionGroup".\n' + '\n' + 'If the raised exception is not an exception group and its type ' + 'matches\n' + 'one of the "except*" clauses, it is caught and wrapped by an ' + 'exception\n' + 'group with an empty message string.\n' + '\n' + ' >>> try:\n' + ' ... raise BlockingIOError\n' + ' ... except* BlockingIOError as e:\n' + ' ... print(repr(e))\n' + ' ...\n' + " ExceptionGroup('', (BlockingIOError()))\n" + '\n' + 'An "except*" clause must have a matching type, and this type ' + 'cannot be\n' + 'a subclass of "BaseExceptionGroup". It is not possible to mix ' + '"except"\n' + 'and "except*" in the same "try". "break", "continue" and ' + '"return"\n' + 'cannot appear in an "except*" clause.\n' + '\n' + '\n' + '"else" clause\n' + '-------------\n' + '\n' + 'The optional "else" clause is executed if the control flow ' + 'leaves the\n' + '"try" suite, no exception was raised, and no "return", ' + '"continue", or\n' + '"break" statement was executed. Exceptions in the "else" clause ' + 'are\n' + 'not handled by the preceding "except" clauses.\n' + '\n' + '\n' + '"finally" clause\n' + '----------------\n' + '\n' + 'If "finally" is present, it specifies a ‘cleanup’ handler. The ' + '"try"\n' + 'clause is executed, including any "except" and "else" clauses. ' + 'If an\n' + 'exception occurs in any of the clauses and is not handled, the\n' + 'exception is temporarily saved. The "finally" clause is ' + 'executed. If\n' + 'there is a saved exception it is re-raised at the end of the ' + '"finally"\n' + 'clause. If the "finally" clause raises another exception, the ' + 'saved\n' + 'exception is set as the context of the new exception. If the ' + '"finally"\n' + 'clause executes a "return", "break" or "continue" statement, the ' + 'saved\n' + 'exception is discarded:\n' + '\n' + ' >>> def f():\n' + ' ... try:\n' + ' ... 1/0\n' + ' ... finally:\n' + ' ... return 42\n' + ' ...\n' + ' >>> f()\n' + ' 42\n' + '\n' + 'The exception information is not available to the program ' + 'during\n' + 'execution of the "finally" clause.\n' + '\n' + 'When a "return", "break" or "continue" statement is executed in ' + 'the\n' + '"try" suite of a "try"…"finally" statement, the "finally" clause ' + 'is\n' + 'also executed ‘on the way out.’\n' + '\n' + 'The return value of a function is determined by the last ' + '"return"\n' + 'statement executed. Since the "finally" clause always executes, ' + 'a\n' + '"return" statement executed in the "finally" clause will always ' + 'be the\n' + 'last one executed:\n' + '\n' + ' >>> def foo():\n' + ' ... try:\n' + " ... return 'try'\n" + ' ... finally:\n' + " ... return 'finally'\n" + ' ...\n' + ' >>> foo()\n' + " 'finally'\n" + '\n' + 'Changed in version 3.8: Prior to Python 3.8, a "continue" ' + 'statement\n' + 'was illegal in the "finally" clause due to a problem with the\n' + 'implementation.\n' + '\n' + '\n' + 'The "with" statement\n' + '====================\n' + '\n' + 'The "with" statement is used to wrap the execution of a block ' + 'with\n' + 'methods defined by a context manager (see section With ' + 'Statement\n' + 'Context Managers). This allows common "try"…"except"…"finally" ' + 'usage\n' + 'patterns to be encapsulated for convenient reuse.\n' + '\n' + ' with_stmt ::= "with" ( "(" with_stmt_contents ","? ' + '")" | with_stmt_contents ) ":" suite\n' + ' with_stmt_contents ::= with_item ("," with_item)*\n' + ' with_item ::= expression ["as" target]\n' + '\n' + 'The execution of the "with" statement with one “item” proceeds ' + 'as\n' + 'follows:\n' + '\n' + '1. The context expression (the expression given in the ' + '"with_item") is\n' + ' evaluated to obtain a context manager.\n' + '\n' + '2. The context manager’s "__enter__()" is loaded for later use.\n' + '\n' + '3. The context manager’s "__exit__()" is loaded for later use.\n' + '\n' + '4. The context manager’s "__enter__()" method is invoked.\n' + '\n' + '5. If a target was included in the "with" statement, the return ' + 'value\n' + ' from "__enter__()" is assigned to it.\n' + '\n' + ' Note:\n' + '\n' + ' The "with" statement guarantees that if the "__enter__()" ' + 'method\n' + ' returns without an error, then "__exit__()" will always be\n' + ' called. Thus, if an error occurs during the assignment to ' + 'the\n' + ' target list, it will be treated the same as an error ' + 'occurring\n' + ' within the suite would be. See step 7 below.\n' + '\n' + '6. The suite is executed.\n' + '\n' + '7. The context manager’s "__exit__()" method is invoked. If an\n' + ' exception caused the suite to be exited, its type, value, ' + 'and\n' + ' traceback are passed as arguments to "__exit__()". Otherwise, ' + 'three\n' + ' "None" arguments are supplied.\n' + '\n' + ' If the suite was exited due to an exception, and the return ' + 'value\n' + ' from the "__exit__()" method was false, the exception is ' + 'reraised.\n' + ' If the return value was true, the exception is suppressed, ' + 'and\n' + ' execution continues with the statement following the "with"\n' + ' statement.\n' + '\n' + ' If the suite was exited for any reason other than an ' + 'exception, the\n' + ' return value from "__exit__()" is ignored, and execution ' + 'proceeds\n' + ' at the normal location for the kind of exit that was taken.\n' + '\n' + 'The following code:\n' + '\n' + ' with EXPRESSION as TARGET:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' manager = (EXPRESSION)\n' + ' enter = type(manager).__enter__\n' + ' exit = type(manager).__exit__\n' + ' value = enter(manager)\n' + ' hit_except = False\n' + '\n' + ' try:\n' + ' TARGET = value\n' + ' SUITE\n' + ' except:\n' + ' hit_except = True\n' + ' if not exit(manager, *sys.exc_info()):\n' + ' raise\n' + ' finally:\n' + ' if not hit_except:\n' + ' exit(manager, None, None, None)\n' + '\n' + 'With more than one item, the context managers are processed as ' + 'if\n' + 'multiple "with" statements were nested:\n' + '\n' + ' with A() as a, B() as b:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' with A() as a:\n' + ' with B() as b:\n' + ' SUITE\n' + '\n' + 'You can also write multi-item context managers in multiple lines ' + 'if\n' + 'the items are surrounded by parentheses. For example:\n' + '\n' + ' with (\n' + ' A() as a,\n' + ' B() as b,\n' + ' ):\n' + ' SUITE\n' + '\n' + 'Changed in version 3.1: Support for multiple context ' + 'expressions.\n' + '\n' + 'Changed in version 3.10: Support for using grouping parentheses ' + 'to\n' + 'break the statement in multiple lines.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 343** - The “with” statement\n' + ' The specification, background, and examples for the Python ' + '"with"\n' + ' statement.\n' + '\n' + '\n' + 'The "match" statement\n' + '=====================\n' + '\n' + 'New in version 3.10.\n' + '\n' + 'The match statement is used for pattern matching. Syntax:\n' + '\n' + ' match_stmt ::= \'match\' subject_expr ":" NEWLINE INDENT ' + 'case_block+ DEDENT\n' + ' subject_expr ::= star_named_expression "," ' + 'star_named_expressions?\n' + ' | named_expression\n' + ' case_block ::= \'case\' patterns [guard] ":" block\n' + '\n' + 'Note:\n' + '\n' + ' This section uses single quotes to denote soft keywords.\n' + '\n' + 'Pattern matching takes a pattern as input (following "case") and ' + 'a\n' + 'subject value (following "match"). The pattern (which may ' + 'contain\n' + 'subpatterns) is matched against the subject value. The outcomes ' + 'are:\n' + '\n' + '* A match success or failure (also termed a pattern success or\n' + ' failure).\n' + '\n' + '* Possible binding of matched values to a name. The ' + 'prerequisites for\n' + ' this are further discussed below.\n' + '\n' + 'The "match" and "case" keywords are soft keywords.\n' + '\n' + 'See also:\n' + '\n' + ' * **PEP 634** – Structural Pattern Matching: Specification\n' + '\n' + ' * **PEP 636** – Structural Pattern Matching: Tutorial\n' + '\n' + '\n' + 'Overview\n' + '--------\n' + '\n' + 'Here’s an overview of the logical flow of a match statement:\n' + '\n' + '1. The subject expression "subject_expr" is evaluated and a ' + 'resulting\n' + ' subject value obtained. If the subject expression contains a ' + 'comma,\n' + ' a tuple is constructed using the standard rules.\n' + '\n' + '2. Each pattern in a "case_block" is attempted to match with ' + 'the\n' + ' subject value. The specific rules for success or failure are\n' + ' described below. The match attempt can also bind some or all ' + 'of the\n' + ' standalone names within the pattern. The precise pattern ' + 'binding\n' + ' rules vary per pattern type and are specified below. **Name\n' + ' bindings made during a successful pattern match outlive the\n' + ' executed block and can be used after the match statement**.\n' + '\n' + ' Note:\n' + '\n' + ' During failed pattern matches, some subpatterns may ' + 'succeed. Do\n' + ' not rely on bindings being made for a failed match. ' + 'Conversely,\n' + ' do not rely on variables remaining unchanged after a ' + 'failed\n' + ' match. The exact behavior is dependent on implementation ' + 'and may\n' + ' vary. This is an intentional decision made to allow ' + 'different\n' + ' implementations to add optimizations.\n' + '\n' + '3. If the pattern succeeds, the corresponding guard (if present) ' + 'is\n' + ' evaluated. In this case all name bindings are guaranteed to ' + 'have\n' + ' happened.\n' + '\n' + ' * If the guard evaluates as true or is missing, the "block" ' + 'inside\n' + ' "case_block" is executed.\n' + '\n' + ' * Otherwise, the next "case_block" is attempted as described ' + 'above.\n' + '\n' + ' * If there are no further case blocks, the match statement ' + 'is\n' + ' completed.\n' + '\n' + 'Note:\n' + '\n' + ' Users should generally never rely on a pattern being ' + 'evaluated.\n' + ' Depending on implementation, the interpreter may cache values ' + 'or use\n' + ' other optimizations which skip repeated evaluations.\n' + '\n' + 'A sample match statement:\n' + '\n' + ' >>> flag = False\n' + ' >>> match (100, 200):\n' + ' ... case (100, 300): # Mismatch: 200 != 300\n' + " ... print('Case 1')\n" + ' ... case (100, 200) if flag: # Successful match, but ' + 'guard fails\n' + " ... print('Case 2')\n" + ' ... case (100, y): # Matches and binds y to 200\n' + " ... print(f'Case 3, y: {y}')\n" + ' ... case _: # Pattern not attempted\n' + " ... print('Case 4, I match anything!')\n" + ' ...\n' + ' Case 3, y: 200\n' + '\n' + 'In this case, "if flag" is a guard. Read more about that in the ' + 'next\n' + 'section.\n' + '\n' + '\n' + 'Guards\n' + '------\n' + '\n' + ' guard ::= "if" named_expression\n' + '\n' + 'A "guard" (which is part of the "case") must succeed for code ' + 'inside\n' + 'the "case" block to execute. It takes the form: "if" followed ' + 'by an\n' + 'expression.\n' + '\n' + 'The logical flow of a "case" block with a "guard" follows:\n' + '\n' + '1. Check that the pattern in the "case" block succeeded. If ' + 'the\n' + ' pattern failed, the "guard" is not evaluated and the next ' + '"case"\n' + ' block is checked.\n' + '\n' + '2. If the pattern succeeded, evaluate the "guard".\n' + '\n' + ' * If the "guard" condition evaluates as true, the case block ' + 'is\n' + ' selected.\n' + '\n' + ' * If the "guard" condition evaluates as false, the case block ' + 'is\n' + ' not selected.\n' + '\n' + ' * If the "guard" raises an exception during evaluation, the\n' + ' exception bubbles up.\n' + '\n' + 'Guards are allowed to have side effects as they are ' + 'expressions.\n' + 'Guard evaluation must proceed from the first to the last case ' + 'block,\n' + 'one at a time, skipping case blocks whose pattern(s) don’t all\n' + 'succeed. (I.e., guard evaluation must happen in order.) Guard\n' + 'evaluation must stop once a case block is selected.\n' + '\n' + '\n' + 'Irrefutable Case Blocks\n' + '-----------------------\n' + '\n' + 'An irrefutable case block is a match-all case block. A match\n' + 'statement may have at most one irrefutable case block, and it ' + 'must be\n' + 'last.\n' + '\n' + 'A case block is considered irrefutable if it has no guard and ' + 'its\n' + 'pattern is irrefutable. A pattern is considered irrefutable if ' + 'we can\n' + 'prove from its syntax alone that it will always succeed. Only ' + 'the\n' + 'following patterns are irrefutable:\n' + '\n' + '* AS Patterns whose left-hand side is irrefutable\n' + '\n' + '* OR Patterns containing at least one irrefutable pattern\n' + '\n' + '* Capture Patterns\n' + '\n' + '* Wildcard Patterns\n' + '\n' + '* parenthesized irrefutable patterns\n' + '\n' + '\n' + 'Patterns\n' + '--------\n' + '\n' + 'Note:\n' + '\n' + ' This section uses grammar notations beyond standard EBNF:\n' + '\n' + ' * the notation "SEP.RULE+" is shorthand for "RULE (SEP ' + 'RULE)*"\n' + '\n' + ' * the notation "!RULE" is shorthand for a negative lookahead\n' + ' assertion\n' + '\n' + 'The top-level syntax for "patterns" is:\n' + '\n' + ' patterns ::= open_sequence_pattern | pattern\n' + ' pattern ::= as_pattern | or_pattern\n' + ' closed_pattern ::= | literal_pattern\n' + ' | capture_pattern\n' + ' | wildcard_pattern\n' + ' | value_pattern\n' + ' | group_pattern\n' + ' | sequence_pattern\n' + ' | mapping_pattern\n' + ' | class_pattern\n' + '\n' + 'The descriptions below will include a description “in simple ' + 'terms” of\n' + 'what a pattern does for illustration purposes (credits to ' + 'Raymond\n' + 'Hettinger for a document that inspired most of the ' + 'descriptions). Note\n' + 'that these descriptions are purely for illustration purposes and ' + '**may\n' + 'not** reflect the underlying implementation. Furthermore, they ' + 'do not\n' + 'cover all valid forms.\n' + '\n' + '\n' + 'OR Patterns\n' + '~~~~~~~~~~~\n' + '\n' + 'An OR pattern is two or more patterns separated by vertical bars ' + '"|".\n' + 'Syntax:\n' + '\n' + ' or_pattern ::= "|".closed_pattern+\n' + '\n' + 'Only the final subpattern may be irrefutable, and each ' + 'subpattern must\n' + 'bind the same set of names to avoid ambiguity.\n' + '\n' + 'An OR pattern matches each of its subpatterns in turn to the ' + 'subject\n' + 'value, until one succeeds. The OR pattern is then considered\n' + 'successful. Otherwise, if none of the subpatterns succeed, the ' + 'OR\n' + 'pattern fails.\n' + '\n' + 'In simple terms, "P1 | P2 | ..." will try to match "P1", if it ' + 'fails\n' + 'it will try to match "P2", succeeding immediately if any ' + 'succeeds,\n' + 'failing otherwise.\n' + '\n' + '\n' + 'AS Patterns\n' + '~~~~~~~~~~~\n' + '\n' + 'An AS pattern matches an OR pattern on the left of the "as" ' + 'keyword\n' + 'against a subject. Syntax:\n' + '\n' + ' as_pattern ::= or_pattern "as" capture_pattern\n' + '\n' + 'If the OR pattern fails, the AS pattern fails. Otherwise, the ' + 'AS\n' + 'pattern binds the subject to the name on the right of the as ' + 'keyword\n' + 'and succeeds. "capture_pattern" cannot be a "_".\n' + '\n' + 'In simple terms "P as NAME" will match with "P", and on success ' + 'it\n' + 'will set "NAME = ".\n' + '\n' + '\n' + 'Literal Patterns\n' + '~~~~~~~~~~~~~~~~\n' + '\n' + 'A literal pattern corresponds to most literals in Python. ' + 'Syntax:\n' + '\n' + ' literal_pattern ::= signed_number\n' + ' | signed_number "+" NUMBER\n' + ' | signed_number "-" NUMBER\n' + ' | strings\n' + ' | "None"\n' + ' | "True"\n' + ' | "False"\n' + ' | signed_number: NUMBER | "-" NUMBER\n' + '\n' + 'The rule "strings" and the token "NUMBER" are defined in the ' + 'standard\n' + 'Python grammar. Triple-quoted strings are supported. Raw ' + 'strings and\n' + 'byte strings are supported. f-strings are not supported.\n' + '\n' + 'The forms "signed_number \'+\' NUMBER" and "signed_number \'-\' ' + 'NUMBER"\n' + 'are for expressing complex numbers; they require a real number ' + 'on the\n' + 'left and an imaginary number on the right. E.g. "3 + 4j".\n' + '\n' + 'In simple terms, "LITERAL" will succeed only if " ==\n' + 'LITERAL". For the singletons "None", "True" and "False", the ' + '"is"\n' + 'operator is used.\n' + '\n' + '\n' + 'Capture Patterns\n' + '~~~~~~~~~~~~~~~~\n' + '\n' + 'A capture pattern binds the subject value to a name. Syntax:\n' + '\n' + " capture_pattern ::= !'_' NAME\n" + '\n' + 'A single underscore "_" is not a capture pattern (this is what ' + '"!\'_\'"\n' + 'expresses). It is instead treated as a "wildcard_pattern".\n' + '\n' + 'In a given pattern, a given name can only be bound once. E.g. ' + '"case\n' + 'x, x: ..." is invalid while "case [x] | x: ..." is allowed.\n' + '\n' + 'Capture patterns always succeed. The binding follows scoping ' + 'rules\n' + 'established by the assignment expression operator in **PEP ' + '572**; the\n' + 'name becomes a local variable in the closest containing function ' + 'scope\n' + 'unless there’s an applicable "global" or "nonlocal" statement.\n' + '\n' + 'In simple terms "NAME" will always succeed and it will set "NAME ' + '=\n' + '".\n' + '\n' + '\n' + 'Wildcard Patterns\n' + '~~~~~~~~~~~~~~~~~\n' + '\n' + 'A wildcard pattern always succeeds (matches anything) and binds ' + 'no\n' + 'name. Syntax:\n' + '\n' + " wildcard_pattern ::= '_'\n" + '\n' + '"_" is a soft keyword within any pattern, but only within ' + 'patterns.\n' + 'It is an identifier, as usual, even within "match" subject\n' + 'expressions, "guard"s, and "case" blocks.\n' + '\n' + 'In simple terms, "_" will always succeed.\n' + '\n' + '\n' + 'Value Patterns\n' + '~~~~~~~~~~~~~~\n' + '\n' + 'A value pattern represents a named value in Python. Syntax:\n' + '\n' + ' value_pattern ::= attr\n' + ' attr ::= name_or_attr "." NAME\n' + ' name_or_attr ::= attr | NAME\n' + '\n' + 'The dotted name in the pattern is looked up using standard ' + 'Python name\n' + 'resolution rules. The pattern succeeds if the value found ' + 'compares\n' + 'equal to the subject value (using the "==" equality operator).\n' + '\n' + 'In simple terms "NAME1.NAME2" will succeed only if " ' + '==\n' + 'NAME1.NAME2"\n' + '\n' + 'Note:\n' + '\n' + ' If the same value occurs multiple times in the same match ' + 'statement,\n' + ' the interpreter may cache the first value found and reuse it ' + 'rather\n' + ' than repeat the same lookup. This cache is strictly tied to a ' + 'given\n' + ' execution of a given match statement.\n' + '\n' + '\n' + 'Group Patterns\n' + '~~~~~~~~~~~~~~\n' + '\n' + 'A group pattern allows users to add parentheses around patterns ' + 'to\n' + 'emphasize the intended grouping. Otherwise, it has no ' + 'additional\n' + 'syntax. Syntax:\n' + '\n' + ' group_pattern ::= "(" pattern ")"\n' + '\n' + 'In simple terms "(P)" has the same effect as "P".\n' + '\n' + '\n' + 'Sequence Patterns\n' + '~~~~~~~~~~~~~~~~~\n' + '\n' + 'A sequence pattern contains several subpatterns to be matched ' + 'against\n' + 'sequence elements. The syntax is similar to the unpacking of a ' + 'list or\n' + 'tuple.\n' + '\n' + ' sequence_pattern ::= "[" [maybe_sequence_pattern] "]"\n' + ' | "(" [open_sequence_pattern] ")"\n' + ' open_sequence_pattern ::= maybe_star_pattern "," ' + '[maybe_sequence_pattern]\n' + ' maybe_sequence_pattern ::= ",".maybe_star_pattern+ ","?\n' + ' maybe_star_pattern ::= star_pattern | pattern\n' + ' star_pattern ::= "*" (capture_pattern | ' + 'wildcard_pattern)\n' + '\n' + 'There is no difference if parentheses or square brackets are ' + 'used for\n' + 'sequence patterns (i.e. "(...)" vs "[...]" ).\n' + '\n' + 'Note:\n' + '\n' + ' A single pattern enclosed in parentheses without a trailing ' + 'comma\n' + ' (e.g. "(3 | 4)") is a group pattern. While a single pattern ' + 'enclosed\n' + ' in square brackets (e.g. "[3 | 4]") is still a sequence ' + 'pattern.\n' + '\n' + 'At most one star subpattern may be in a sequence pattern. The ' + 'star\n' + 'subpattern may occur in any position. If no star subpattern is\n' + 'present, the sequence pattern is a fixed-length sequence ' + 'pattern;\n' + 'otherwise it is a variable-length sequence pattern.\n' + '\n' + 'The following is the logical flow for matching a sequence ' + 'pattern\n' + 'against a subject value:\n' + '\n' + '1. If the subject value is not a sequence [2], the sequence ' + 'pattern\n' + ' fails.\n' + '\n' + '2. If the subject value is an instance of "str", "bytes" or\n' + ' "bytearray" the sequence pattern fails.\n' + '\n' + '3. The subsequent steps depend on whether the sequence pattern ' + 'is\n' + ' fixed or variable-length.\n' + '\n' + ' If the sequence pattern is fixed-length:\n' + '\n' + ' 1. If the length of the subject sequence is not equal to the ' + 'number\n' + ' of subpatterns, the sequence pattern fails\n' + '\n' + ' 2. Subpatterns in the sequence pattern are matched to their\n' + ' corresponding items in the subject sequence from left to ' + 'right.\n' + ' Matching stops as soon as a subpattern fails. If all\n' + ' subpatterns succeed in matching their corresponding item, ' + 'the\n' + ' sequence pattern succeeds.\n' + '\n' + ' Otherwise, if the sequence pattern is variable-length:\n' + '\n' + ' 1. If the length of the subject sequence is less than the ' + 'number of\n' + ' non-star subpatterns, the sequence pattern fails.\n' + '\n' + ' 2. The leading non-star subpatterns are matched to their\n' + ' corresponding items as for fixed-length sequences.\n' + '\n' + ' 3. If the previous step succeeds, the star subpattern matches ' + 'a\n' + ' list formed of the remaining subject items, excluding the\n' + ' remaining items corresponding to non-star subpatterns ' + 'following\n' + ' the star subpattern.\n' + '\n' + ' 4. Remaining non-star subpatterns are matched to their\n' + ' corresponding subject items, as for a fixed-length ' + 'sequence.\n' + '\n' + ' Note:\n' + '\n' + ' The length of the subject sequence is obtained via "len()" ' + '(i.e.\n' + ' via the "__len__()" protocol). This length may be cached ' + 'by the\n' + ' interpreter in a similar manner as value patterns.\n' + '\n' + 'In simple terms "[P1, P2, P3," … ", P]" matches only if all ' + 'the\n' + 'following happens:\n' + '\n' + '* check "" is a sequence\n' + '\n' + '* "len(subject) == "\n' + '\n' + '* "P1" matches "[0]" (note that this match can also ' + 'bind\n' + ' names)\n' + '\n' + '* "P2" matches "[1]" (note that this match can also ' + 'bind\n' + ' names)\n' + '\n' + '* … and so on for the corresponding pattern/element.\n' + '\n' + '\n' + 'Mapping Patterns\n' + '~~~~~~~~~~~~~~~~\n' + '\n' + 'A mapping pattern contains one or more key-value patterns. The ' + 'syntax\n' + 'is similar to the construction of a dictionary. Syntax:\n' + '\n' + ' mapping_pattern ::= "{" [items_pattern] "}"\n' + ' items_pattern ::= ",".key_value_pattern+ ","?\n' + ' key_value_pattern ::= (literal_pattern | value_pattern) ":" ' + 'pattern\n' + ' | double_star_pattern\n' + ' double_star_pattern ::= "**" capture_pattern\n' + '\n' + 'At most one double star pattern may be in a mapping pattern. ' + 'The\n' + 'double star pattern must be the last subpattern in the mapping\n' + 'pattern.\n' + '\n' + 'Duplicate keys in mapping patterns are disallowed. Duplicate ' + 'literal\n' + 'keys will raise a "SyntaxError". Two keys that otherwise have ' + 'the same\n' + 'value will raise a "ValueError" at runtime.\n' + '\n' + 'The following is the logical flow for matching a mapping ' + 'pattern\n' + 'against a subject value:\n' + '\n' + '1. If the subject value is not a mapping [3],the mapping ' + 'pattern\n' + ' fails.\n' + '\n' + '2. If every key given in the mapping pattern is present in the ' + 'subject\n' + ' mapping, and the pattern for each key matches the ' + 'corresponding\n' + ' item of the subject mapping, the mapping pattern succeeds.\n' + '\n' + '3. If duplicate keys are detected in the mapping pattern, the ' + 'pattern\n' + ' is considered invalid. A "SyntaxError" is raised for ' + 'duplicate\n' + ' literal values; or a "ValueError" for named keys of the same ' + 'value.\n' + '\n' + 'Note:\n' + '\n' + ' Key-value pairs are matched using the two-argument form of ' + 'the\n' + ' mapping subject’s "get()" method. Matched key-value pairs ' + 'must\n' + ' already be present in the mapping, and not created on-the-fly ' + 'via\n' + ' "__missing__()" or "__getitem__()".\n' + '\n' + 'In simple terms "{KEY1: P1, KEY2: P2, ... }" matches only if all ' + 'the\n' + 'following happens:\n' + '\n' + '* check "" is a mapping\n' + '\n' + '* "KEY1 in "\n' + '\n' + '* "P1" matches "[KEY1]"\n' + '\n' + '* … and so on for the corresponding KEY/pattern pair.\n' + '\n' + '\n' + 'Class Patterns\n' + '~~~~~~~~~~~~~~\n' + '\n' + 'A class pattern represents a class and its positional and ' + 'keyword\n' + 'arguments (if any). Syntax:\n' + '\n' + ' class_pattern ::= name_or_attr "(" [pattern_arguments ' + '","?] ")"\n' + ' pattern_arguments ::= positional_patterns ["," ' + 'keyword_patterns]\n' + ' | keyword_patterns\n' + ' positional_patterns ::= ",".pattern+\n' + ' keyword_patterns ::= ",".keyword_pattern+\n' + ' keyword_pattern ::= NAME "=" pattern\n' + '\n' + 'The same keyword should not be repeated in class patterns.\n' + '\n' + 'The following is the logical flow for matching a class pattern ' + 'against\n' + 'a subject value:\n' + '\n' + '1. If "name_or_attr" is not an instance of the builtin "type" , ' + 'raise\n' + ' "TypeError".\n' + '\n' + '2. If the subject value is not an instance of "name_or_attr" ' + '(tested\n' + ' via "isinstance()"), the class pattern fails.\n' + '\n' + '3. If no pattern arguments are present, the pattern succeeds.\n' + ' Otherwise, the subsequent steps depend on whether keyword or\n' + ' positional argument patterns are present.\n' + '\n' + ' For a number of built-in types (specified below), a single\n' + ' positional subpattern is accepted which will match the ' + 'entire\n' + ' subject; for these types keyword patterns also work as for ' + 'other\n' + ' types.\n' + '\n' + ' If only keyword patterns are present, they are processed as\n' + ' follows, one by one:\n' + '\n' + ' I. The keyword is looked up as an attribute on the subject.\n' + '\n' + ' * If this raises an exception other than "AttributeError", ' + 'the\n' + ' exception bubbles up.\n' + '\n' + ' * If this raises "AttributeError", the class pattern has ' + 'failed.\n' + '\n' + ' * Else, the subpattern associated with the keyword pattern ' + 'is\n' + ' matched against the subject’s attribute value. If this ' + 'fails,\n' + ' the class pattern fails; if this succeeds, the match ' + 'proceeds\n' + ' to the next keyword.\n' + '\n' + ' II. If all keyword patterns succeed, the class pattern ' + 'succeeds.\n' + '\n' + ' If any positional patterns are present, they are converted ' + 'to\n' + ' keyword patterns using the "__match_args__" attribute on the ' + 'class\n' + ' "name_or_attr" before matching:\n' + '\n' + ' I. The equivalent of "getattr(cls, "__match_args__", ())" is\n' + ' called.\n' + '\n' + ' * If this raises an exception, the exception bubbles up.\n' + '\n' + ' * If the returned value is not a tuple, the conversion ' + 'fails and\n' + ' "TypeError" is raised.\n' + '\n' + ' * If there are more positional patterns than\n' + ' "len(cls.__match_args__)", "TypeError" is raised.\n' + '\n' + ' * Otherwise, positional pattern "i" is converted to a ' + 'keyword\n' + ' pattern using "__match_args__[i]" as the keyword.\n' + ' "__match_args__[i]" must be a string; if not "TypeError" ' + 'is\n' + ' raised.\n' + '\n' + ' * If there are duplicate keywords, "TypeError" is raised.\n' + '\n' + ' See also:\n' + '\n' + ' Customizing positional arguments in class pattern ' + 'matching\n' + '\n' + ' II. Once all positional patterns have been converted to ' + 'keyword\n' + ' patterns,\n' + ' the match proceeds as if there were only keyword ' + 'patterns.\n' + '\n' + ' For the following built-in types the handling of positional\n' + ' subpatterns is different:\n' + '\n' + ' * "bool"\n' + '\n' + ' * "bytearray"\n' + '\n' + ' * "bytes"\n' + '\n' + ' * "dict"\n' + '\n' + ' * "float"\n' + '\n' + ' * "frozenset"\n' + '\n' + ' * "int"\n' + '\n' + ' * "list"\n' + '\n' + ' * "set"\n' + '\n' + ' * "str"\n' + '\n' + ' * "tuple"\n' + '\n' + ' These classes accept a single positional argument, and the ' + 'pattern\n' + ' there is matched against the whole object rather than an ' + 'attribute.\n' + ' For example "int(0|1)" matches the value "0", but not the ' + 'value\n' + ' "0.0".\n' + '\n' + 'In simple terms "CLS(P1, attr=P2)" matches only if the ' + 'following\n' + 'happens:\n' + '\n' + '* "isinstance(, CLS)"\n' + '\n' + '* convert "P1" to a keyword pattern using "CLS.__match_args__"\n' + '\n' + '* For each keyword argument "attr=P2":\n' + '\n' + ' * "hasattr(, "attr")"\n' + '\n' + ' * "P2" matches ".attr"\n' + '\n' + '* … and so on for the corresponding keyword argument/pattern ' + 'pair.\n' + '\n' + 'See also:\n' + '\n' + ' * **PEP 634** – Structural Pattern Matching: Specification\n' + '\n' + ' * **PEP 636** – Structural Pattern Matching: Tutorial\n' + '\n' + '\n' + 'Function definitions\n' + '====================\n' + '\n' + 'A function definition defines a user-defined function object ' + '(see\n' + 'section The standard type hierarchy):\n' + '\n' + ' funcdef ::= [decorators] "def" funcname "(" ' + '[parameter_list] ")"\n' + ' ["->" expression] ":" suite\n' + ' decorators ::= decorator+\n' + ' decorator ::= "@" assignment_expression ' + 'NEWLINE\n' + ' parameter_list ::= defparameter ("," ' + 'defparameter)* "," "/" ["," [parameter_list_no_posonly]]\n' + ' | parameter_list_no_posonly\n' + ' parameter_list_no_posonly ::= defparameter ("," ' + 'defparameter)* ["," [parameter_list_starargs]]\n' + ' | parameter_list_starargs\n' + ' parameter_list_starargs ::= "*" [parameter] ("," ' + 'defparameter)* ["," ["**" parameter [","]]]\n' + ' | "**" parameter [","]\n' + ' parameter ::= identifier [":" expression]\n' + ' defparameter ::= parameter ["=" expression]\n' + ' funcname ::= identifier\n' + '\n' + 'A function definition is an executable statement. Its execution ' + 'binds\n' + 'the function name in the current local namespace to a function ' + 'object\n' + '(a wrapper around the executable code for the function). This\n' + 'function object contains a reference to the current global ' + 'namespace\n' + 'as the global namespace to be used when the function is called.\n' + '\n' + 'The function definition does not execute the function body; this ' + 'gets\n' + 'executed only when the function is called. [4]\n' + '\n' + 'A function definition may be wrapped by one or more *decorator*\n' + 'expressions. Decorator expressions are evaluated when the ' + 'function is\n' + 'defined, in the scope that contains the function definition. ' + 'The\n' + 'result must be a callable, which is invoked with the function ' + 'object\n' + 'as the only argument. The returned value is bound to the ' + 'function name\n' + 'instead of the function object. Multiple decorators are applied ' + 'in\n' + 'nested fashion. For example, the following code\n' + '\n' + ' @f1(arg)\n' + ' @f2\n' + ' def func(): pass\n' + '\n' + 'is roughly equivalent to\n' + '\n' + ' def func(): pass\n' + ' func = f1(arg)(f2(func))\n' + '\n' + 'except that the original function is not temporarily bound to ' + 'the name\n' + '"func".\n' + '\n' + 'Changed in version 3.9: Functions may be decorated with any ' + 'valid\n' + '"assignment_expression". Previously, the grammar was much more\n' + 'restrictive; see **PEP 614** for details.\n' + '\n' + 'When one or more *parameters* have the form *parameter* "="\n' + '*expression*, the function is said to have “default parameter ' + 'values.”\n' + 'For a parameter with a default value, the corresponding ' + '*argument* may\n' + 'be omitted from a call, in which case the parameter’s default ' + 'value is\n' + 'substituted. If a parameter has a default value, all following\n' + 'parameters up until the “"*"” must also have a default value — ' + 'this is\n' + 'a syntactic restriction that is not expressed by the grammar.\n' + '\n' + '**Default parameter values are evaluated from left to right when ' + 'the\n' + 'function definition is executed.** This means that the ' + 'expression is\n' + 'evaluated once, when the function is defined, and that the same ' + '“pre-\n' + 'computed” value is used for each call. This is especially ' + 'important\n' + 'to understand when a default parameter value is a mutable ' + 'object, such\n' + 'as a list or a dictionary: if the function modifies the object ' + '(e.g.\n' + 'by appending an item to a list), the default parameter value is ' + 'in\n' + 'effect modified. This is generally not what was intended. A ' + 'way\n' + 'around this is to use "None" as the default, and explicitly test ' + 'for\n' + 'it in the body of the function, e.g.:\n' + '\n' + ' def whats_on_the_telly(penguin=None):\n' + ' if penguin is None:\n' + ' penguin = []\n' + ' penguin.append("property of the zoo")\n' + ' return penguin\n' + '\n' + 'Function call semantics are described in more detail in section ' + 'Calls.\n' + 'A function call always assigns values to all parameters ' + 'mentioned in\n' + 'the parameter list, either from positional arguments, from ' + 'keyword\n' + 'arguments, or from default values. If the form “"*identifier"” ' + 'is\n' + 'present, it is initialized to a tuple receiving any excess ' + 'positional\n' + 'parameters, defaulting to the empty tuple. If the form\n' + '“"**identifier"” is present, it is initialized to a new ordered\n' + 'mapping receiving any excess keyword arguments, defaulting to a ' + 'new\n' + 'empty mapping of the same type. Parameters after “"*"” or\n' + '“"*identifier"” are keyword-only parameters and may only be ' + 'passed by\n' + 'keyword arguments. Parameters before “"/"” are positional-only\n' + 'parameters and may only be passed by positional arguments.\n' + '\n' + 'Changed in version 3.8: The "/" function parameter syntax may be ' + 'used\n' + 'to indicate positional-only parameters. See **PEP 570** for ' + 'details.\n' + '\n' + 'Parameters may have an *annotation* of the form “": ' + 'expression"”\n' + 'following the parameter name. Any parameter may have an ' + 'annotation,\n' + 'even those of the form "*identifier" or "**identifier". ' + 'Functions may\n' + 'have “return” annotation of the form “"-> expression"” after ' + 'the\n' + 'parameter list. These annotations can be any valid Python ' + 'expression.\n' + 'The presence of annotations does not change the semantics of a\n' + 'function. The annotation values are available as values of a\n' + 'dictionary keyed by the parameters’ names in the ' + '"__annotations__"\n' + 'attribute of the function object. If the "annotations" import ' + 'from\n' + '"__future__" is used, annotations are preserved as strings at ' + 'runtime\n' + 'which enables postponed evaluation. Otherwise, they are ' + 'evaluated\n' + 'when the function definition is executed. In this case ' + 'annotations\n' + 'may be evaluated in a different order than they appear in the ' + 'source\n' + 'code.\n' + '\n' + 'It is also possible to create anonymous functions (functions not ' + 'bound\n' + 'to a name), for immediate use in expressions. This uses lambda\n' + 'expressions, described in section Lambdas. Note that the ' + 'lambda\n' + 'expression is merely a shorthand for a simplified function ' + 'definition;\n' + 'a function defined in a “"def"” statement can be passed around ' + 'or\n' + 'assigned to another name just like a function defined by a ' + 'lambda\n' + 'expression. The “"def"” form is actually more powerful since ' + 'it\n' + 'allows the execution of multiple statements and annotations.\n' + '\n' + '**Programmer’s note:** Functions are first-class objects. A ' + '“"def"”\n' + 'statement executed inside a function definition defines a local\n' + 'function that can be returned or passed around. Free variables ' + 'used\n' + 'in the nested function can access the local variables of the ' + 'function\n' + 'containing the def. See section Naming and binding for ' + 'details.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3107** - Function Annotations\n' + ' The original specification for function annotations.\n' + '\n' + ' **PEP 484** - Type Hints\n' + ' Definition of a standard meaning for annotations: type ' + 'hints.\n' + '\n' + ' **PEP 526** - Syntax for Variable Annotations\n' + ' Ability to type hint variable declarations, including ' + 'class\n' + ' variables and instance variables.\n' + '\n' + ' **PEP 563** - Postponed Evaluation of Annotations\n' + ' Support for forward references within annotations by ' + 'preserving\n' + ' annotations in a string form at runtime instead of eager\n' + ' evaluation.\n' + '\n' + ' **PEP 318** - Decorators for Functions and Methods\n' + ' Function and method decorators were introduced. Class ' + 'decorators\n' + ' were introduced in **PEP 3129**.\n' + '\n' + '\n' + 'Class definitions\n' + '=================\n' + '\n' + 'A class definition defines a class object (see section The ' + 'standard\n' + 'type hierarchy):\n' + '\n' + ' classdef ::= [decorators] "class" classname [inheritance] ' + '":" suite\n' + ' inheritance ::= "(" [argument_list] ")"\n' + ' classname ::= identifier\n' + '\n' + 'A class definition is an executable statement. The inheritance ' + 'list\n' + 'usually gives a list of base classes (see Metaclasses for more\n' + 'advanced uses), so each item in the list should evaluate to a ' + 'class\n' + 'object which allows subclassing. Classes without an inheritance ' + 'list\n' + 'inherit, by default, from the base class "object"; hence,\n' + '\n' + ' class Foo:\n' + ' pass\n' + '\n' + 'is equivalent to\n' + '\n' + ' class Foo(object):\n' + ' pass\n' + '\n' + 'The class’s suite is then executed in a new execution frame ' + '(see\n' + 'Naming and binding), using a newly created local namespace and ' + 'the\n' + 'original global namespace. (Usually, the suite contains mostly\n' + 'function definitions.) When the class’s suite finishes ' + 'execution, its\n' + 'execution frame is discarded but its local namespace is saved. ' + '[5] A\n' + 'class object is then created using the inheritance list for the ' + 'base\n' + 'classes and the saved local namespace for the attribute ' + 'dictionary.\n' + 'The class name is bound to this class object in the original ' + 'local\n' + 'namespace.\n' + '\n' + 'The order in which attributes are defined in the class body is\n' + 'preserved in the new class’s "__dict__". Note that this is ' + 'reliable\n' + 'only right after the class is created and only for classes that ' + 'were\n' + 'defined using the definition syntax.\n' + '\n' + 'Class creation can be customized heavily using metaclasses.\n' + '\n' + 'Classes can also be decorated: just like when decorating ' + 'functions,\n' + '\n' + ' @f1(arg)\n' + ' @f2\n' + ' class Foo: pass\n' + '\n' + 'is roughly equivalent to\n' + '\n' + ' class Foo: pass\n' + ' Foo = f1(arg)(f2(Foo))\n' + '\n' + 'The evaluation rules for the decorator expressions are the same ' + 'as for\n' + 'function decorators. The result is then bound to the class ' + 'name.\n' + '\n' + 'Changed in version 3.9: Classes may be decorated with any valid\n' + '"assignment_expression". Previously, the grammar was much more\n' + 'restrictive; see **PEP 614** for details.\n' + '\n' + '**Programmer’s note:** Variables defined in the class definition ' + 'are\n' + 'class attributes; they are shared by instances. Instance ' + 'attributes\n' + 'can be set in a method with "self.name = value". Both class ' + 'and\n' + 'instance attributes are accessible through the notation ' + '“"self.name"”,\n' + 'and an instance attribute hides a class attribute with the same ' + 'name\n' + 'when accessed in this way. Class attributes can be used as ' + 'defaults\n' + 'for instance attributes, but using mutable values there can lead ' + 'to\n' + 'unexpected results. Descriptors can be used to create instance\n' + 'variables with different implementation details.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3115** - Metaclasses in Python 3000\n' + ' The proposal that changed the declaration of metaclasses to ' + 'the\n' + ' current syntax, and the semantics for how classes with\n' + ' metaclasses are constructed.\n' + '\n' + ' **PEP 3129** - Class Decorators\n' + ' The proposal that added class decorators. Function and ' + 'method\n' + ' decorators were introduced in **PEP 318**.\n' + '\n' + '\n' + 'Coroutines\n' + '==========\n' + '\n' + 'New in version 3.5.\n' + '\n' + '\n' + 'Coroutine function definition\n' + '-----------------------------\n' + '\n' + ' async_funcdef ::= [decorators] "async" "def" funcname "(" ' + '[parameter_list] ")"\n' + ' ["->" expression] ":" suite\n' + '\n' + 'Execution of Python coroutines can be suspended and resumed at ' + 'many\n' + 'points (see *coroutine*). "await" expressions, "async for" and ' + '"async\n' + 'with" can only be used in the body of a coroutine function.\n' + '\n' + 'Functions defined with "async def" syntax are always coroutine\n' + 'functions, even if they do not contain "await" or "async" ' + 'keywords.\n' + '\n' + 'It is a "SyntaxError" to use a "yield from" expression inside ' + 'the body\n' + 'of a coroutine function.\n' + '\n' + 'An example of a coroutine function:\n' + '\n' + ' async def func(param1, param2):\n' + ' do_stuff()\n' + ' await some_coroutine()\n' + '\n' + 'Changed in version 3.7: "await" and "async" are now keywords;\n' + 'previously they were only treated as such inside the body of a\n' + 'coroutine function.\n' + '\n' + '\n' + 'The "async for" statement\n' + '-------------------------\n' + '\n' + ' async_for_stmt ::= "async" for_stmt\n' + '\n' + 'An *asynchronous iterable* provides an "__aiter__" method that\n' + 'directly returns an *asynchronous iterator*, which can call\n' + 'asynchronous code in its "__anext__" method.\n' + '\n' + 'The "async for" statement allows convenient iteration over\n' + 'asynchronous iterables.\n' + '\n' + 'The following code:\n' + '\n' + ' async for TARGET in ITER:\n' + ' SUITE\n' + ' else:\n' + ' SUITE2\n' + '\n' + 'Is semantically equivalent to:\n' + '\n' + ' iter = (ITER)\n' + ' iter = type(iter).__aiter__(iter)\n' + ' running = True\n' + '\n' + ' while running:\n' + ' try:\n' + ' TARGET = await type(iter).__anext__(iter)\n' + ' except StopAsyncIteration:\n' + ' running = False\n' + ' else:\n' + ' SUITE\n' + ' else:\n' + ' SUITE2\n' + '\n' + 'See also "__aiter__()" and "__anext__()" for details.\n' + '\n' + 'It is a "SyntaxError" to use an "async for" statement outside ' + 'the body\n' + 'of a coroutine function.\n' + '\n' + '\n' + 'The "async with" statement\n' + '--------------------------\n' + '\n' + ' async_with_stmt ::= "async" with_stmt\n' + '\n' + 'An *asynchronous context manager* is a *context manager* that is ' + 'able\n' + 'to suspend execution in its *enter* and *exit* methods.\n' + '\n' + 'The following code:\n' + '\n' + ' async with EXPRESSION as TARGET:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' manager = (EXPRESSION)\n' + ' aenter = type(manager).__aenter__\n' + ' aexit = type(manager).__aexit__\n' + ' value = await aenter(manager)\n' + ' hit_except = False\n' + '\n' + ' try:\n' + ' TARGET = value\n' + ' SUITE\n' + ' except:\n' + ' hit_except = True\n' + ' if not await aexit(manager, *sys.exc_info()):\n' + ' raise\n' + ' finally:\n' + ' if not hit_except:\n' + ' await aexit(manager, None, None, None)\n' + '\n' + 'See also "__aenter__()" and "__aexit__()" for details.\n' + '\n' + 'It is a "SyntaxError" to use an "async with" statement outside ' + 'the\n' + 'body of a coroutine function.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 492** - Coroutines with async and await syntax\n' + ' The proposal that made coroutines a proper standalone ' + 'concept in\n' + ' Python, and added supporting syntax.\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] The exception is propagated to the invocation stack unless ' + 'there\n' + ' is a "finally" clause which happens to raise another ' + 'exception.\n' + ' That new exception causes the old one to be lost.\n' + '\n' + '[2] In pattern matching, a sequence is defined as one of the\n' + ' following:\n' + '\n' + ' * a class that inherits from "collections.abc.Sequence"\n' + '\n' + ' * a Python class that has been registered as\n' + ' "collections.abc.Sequence"\n' + '\n' + ' * a builtin class that has its (CPython) ' + '"Py_TPFLAGS_SEQUENCE" bit\n' + ' set\n' + '\n' + ' * a class that inherits from any of the above\n' + '\n' + ' The following standard library classes are sequences:\n' + '\n' + ' * "array.array"\n' + '\n' + ' * "collections.deque"\n' + '\n' + ' * "list"\n' + '\n' + ' * "memoryview"\n' + '\n' + ' * "range"\n' + '\n' + ' * "tuple"\n' + '\n' + ' Note:\n' + '\n' + ' Subject values of type "str", "bytes", and "bytearray" do ' + 'not\n' + ' match sequence patterns.\n' + '\n' + '[3] In pattern matching, a mapping is defined as one of the ' + 'following:\n' + '\n' + ' * a class that inherits from "collections.abc.Mapping"\n' + '\n' + ' * a Python class that has been registered as\n' + ' "collections.abc.Mapping"\n' + '\n' + ' * a builtin class that has its (CPython) ' + '"Py_TPFLAGS_MAPPING" bit\n' + ' set\n' + '\n' + ' * a class that inherits from any of the above\n' + '\n' + ' The standard library classes "dict" and ' + '"types.MappingProxyType"\n' + ' are mappings.\n' + '\n' + '[4] A string literal appearing as the first statement in the ' + 'function\n' + ' body is transformed into the function’s "__doc__" attribute ' + 'and\n' + ' therefore the function’s *docstring*.\n' + '\n' + '[5] A string literal appearing as the first statement in the ' + 'class\n' + ' body is transformed into the namespace’s "__doc__" item and\n' + ' therefore the class’s *docstring*.\n', + 'context-managers': 'With Statement Context Managers\n' + '*******************************\n' + '\n' + 'A *context manager* is an object that defines the ' + 'runtime context to\n' + 'be established when executing a "with" statement. The ' + 'context manager\n' + 'handles the entry into, and the exit from, the desired ' + 'runtime context\n' + 'for the execution of the block of code. Context ' + 'managers are normally\n' + 'invoked using the "with" statement (described in section ' + 'The with\n' + 'statement), but can also be used by directly invoking ' + 'their methods.\n' + '\n' + 'Typical uses of context managers include saving and ' + 'restoring various\n' + 'kinds of global state, locking and unlocking resources, ' + 'closing opened\n' + 'files, etc.\n' + '\n' + 'For more information on context managers, see Context ' + 'Manager Types.\n' + '\n' + 'object.__enter__(self)\n' + '\n' + ' Enter the runtime context related to this object. The ' + '"with"\n' + ' statement will bind this method’s return value to the ' + 'target(s)\n' + ' specified in the "as" clause of the statement, if ' + 'any.\n' + '\n' + 'object.__exit__(self, exc_type, exc_value, traceback)\n' + '\n' + ' Exit the runtime context related to this object. The ' + 'parameters\n' + ' describe the exception that caused the context to be ' + 'exited. If the\n' + ' context was exited without an exception, all three ' + 'arguments will\n' + ' be "None".\n' + '\n' + ' If an exception is supplied, and the method wishes to ' + 'suppress the\n' + ' exception (i.e., prevent it from being propagated), ' + 'it should\n' + ' return a true value. Otherwise, the exception will be ' + 'processed\n' + ' normally upon exit from this method.\n' + '\n' + ' Note that "__exit__()" methods should not reraise the ' + 'passed-in\n' + ' exception; this is the caller’s responsibility.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 343** - The “with” statement\n' + ' The specification, background, and examples for the ' + 'Python "with"\n' + ' statement.\n', + 'continue': 'The "continue" statement\n' + '************************\n' + '\n' + ' continue_stmt ::= "continue"\n' + '\n' + '"continue" may only occur syntactically nested in a "for" or ' + '"while"\n' + 'loop, but not nested in a function or class definition within ' + 'that\n' + 'loop. It continues with the next cycle of the nearest enclosing ' + 'loop.\n' + '\n' + 'When "continue" passes control out of a "try" statement with a\n' + '"finally" clause, that "finally" clause is executed before ' + 'really\n' + 'starting the next loop cycle.\n', + 'conversions': 'Arithmetic conversions\n' + '**********************\n' + '\n' + 'When a description of an arithmetic operator below uses the ' + 'phrase\n' + '“the numeric arguments are converted to a common type”, this ' + 'means\n' + 'that the operator implementation for built-in types works as ' + 'follows:\n' + '\n' + '* If either argument is a complex number, the other is ' + 'converted to\n' + ' complex;\n' + '\n' + '* otherwise, if either argument is a floating point number, ' + 'the other\n' + ' is converted to floating point;\n' + '\n' + '* otherwise, both must be integers and no conversion is ' + 'necessary.\n' + '\n' + 'Some additional rules apply for certain operators (e.g., a ' + 'string as a\n' + 'left argument to the ‘%’ operator). Extensions must define ' + 'their own\n' + 'conversion behavior.\n', + 'customization': 'Basic customization\n' + '*******************\n' + '\n' + 'object.__new__(cls[, ...])\n' + '\n' + ' Called to create a new instance of class *cls*. ' + '"__new__()" is a\n' + ' static method (special-cased so you need not declare it ' + 'as such)\n' + ' that takes the class of which an instance was requested ' + 'as its\n' + ' first argument. The remaining arguments are those ' + 'passed to the\n' + ' object constructor expression (the call to the class). ' + 'The return\n' + ' value of "__new__()" should be the new object instance ' + '(usually an\n' + ' instance of *cls*).\n' + '\n' + ' Typical implementations create a new instance of the ' + 'class by\n' + ' invoking the superclass’s "__new__()" method using\n' + ' "super().__new__(cls[, ...])" with appropriate arguments ' + 'and then\n' + ' modifying the newly created instance as necessary before ' + 'returning\n' + ' it.\n' + '\n' + ' If "__new__()" is invoked during object construction and ' + 'it returns\n' + ' an instance of *cls*, then the new instance’s ' + '"__init__()" method\n' + ' will be invoked like "__init__(self[, ...])", where ' + '*self* is the\n' + ' new instance and the remaining arguments are the same as ' + 'were\n' + ' passed to the object constructor.\n' + '\n' + ' If "__new__()" does not return an instance of *cls*, ' + 'then the new\n' + ' instance’s "__init__()" method will not be invoked.\n' + '\n' + ' "__new__()" is intended mainly to allow subclasses of ' + 'immutable\n' + ' types (like int, str, or tuple) to customize instance ' + 'creation. It\n' + ' is also commonly overridden in custom metaclasses in ' + 'order to\n' + ' customize class creation.\n' + '\n' + 'object.__init__(self[, ...])\n' + '\n' + ' Called after the instance has been created (by ' + '"__new__()"), but\n' + ' before it is returned to the caller. The arguments are ' + 'those\n' + ' passed to the class constructor expression. If a base ' + 'class has an\n' + ' "__init__()" method, the derived class’s "__init__()" ' + 'method, if\n' + ' any, must explicitly call it to ensure proper ' + 'initialization of the\n' + ' base class part of the instance; for example:\n' + ' "super().__init__([args...])".\n' + '\n' + ' Because "__new__()" and "__init__()" work together in ' + 'constructing\n' + ' objects ("__new__()" to create it, and "__init__()" to ' + 'customize\n' + ' it), no non-"None" value may be returned by ' + '"__init__()"; doing so\n' + ' will cause a "TypeError" to be raised at runtime.\n' + '\n' + 'object.__del__(self)\n' + '\n' + ' Called when the instance is about to be destroyed. This ' + 'is also\n' + ' called a finalizer or (improperly) a destructor. If a ' + 'base class\n' + ' has a "__del__()" method, the derived class’s ' + '"__del__()" method,\n' + ' if any, must explicitly call it to ensure proper ' + 'deletion of the\n' + ' base class part of the instance.\n' + '\n' + ' It is possible (though not recommended!) for the ' + '"__del__()" method\n' + ' to postpone destruction of the instance by creating a ' + 'new reference\n' + ' to it. This is called object *resurrection*. It is\n' + ' implementation-dependent whether "__del__()" is called a ' + 'second\n' + ' time when a resurrected object is about to be destroyed; ' + 'the\n' + ' current *CPython* implementation only calls it once.\n' + '\n' + ' It is not guaranteed that "__del__()" methods are called ' + 'for\n' + ' objects that still exist when the interpreter exits.\n' + '\n' + ' Note:\n' + '\n' + ' "del x" doesn’t directly call "x.__del__()" — the ' + 'former\n' + ' decrements the reference count for "x" by one, and the ' + 'latter is\n' + ' only called when "x"’s reference count reaches zero.\n' + '\n' + ' **CPython implementation detail:** It is possible for a ' + 'reference\n' + ' cycle to prevent the reference count of an object from ' + 'going to\n' + ' zero. In this case, the cycle will be later detected ' + 'and deleted\n' + ' by the *cyclic garbage collector*. A common cause of ' + 'reference\n' + ' cycles is when an exception has been caught in a local ' + 'variable.\n' + ' The frame’s locals then reference the exception, which ' + 'references\n' + ' its own traceback, which references the locals of all ' + 'frames caught\n' + ' in the traceback.\n' + '\n' + ' See also: Documentation for the "gc" module.\n' + '\n' + ' Warning:\n' + '\n' + ' Due to the precarious circumstances under which ' + '"__del__()"\n' + ' methods are invoked, exceptions that occur during ' + 'their execution\n' + ' are ignored, and a warning is printed to "sys.stderr" ' + 'instead.\n' + ' In particular:\n' + '\n' + ' * "__del__()" can be invoked when arbitrary code is ' + 'being\n' + ' executed, including from any arbitrary thread. If ' + '"__del__()"\n' + ' needs to take a lock or invoke any other blocking ' + 'resource, it\n' + ' may deadlock as the resource may already be taken by ' + 'the code\n' + ' that gets interrupted to execute "__del__()".\n' + '\n' + ' * "__del__()" can be executed during interpreter ' + 'shutdown. As a\n' + ' consequence, the global variables it needs to access ' + '(including\n' + ' other modules) may already have been deleted or set ' + 'to "None".\n' + ' Python guarantees that globals whose name begins ' + 'with a single\n' + ' underscore are deleted from their module before ' + 'other globals\n' + ' are deleted; if no other references to such globals ' + 'exist, this\n' + ' may help in assuring that imported modules are still ' + 'available\n' + ' at the time when the "__del__()" method is called.\n' + '\n' + 'object.__repr__(self)\n' + '\n' + ' Called by the "repr()" built-in function to compute the ' + '“official”\n' + ' string representation of an object. If at all possible, ' + 'this\n' + ' should look like a valid Python expression that could be ' + 'used to\n' + ' recreate an object with the same value (given an ' + 'appropriate\n' + ' environment). If this is not possible, a string of the ' + 'form\n' + ' "<...some useful description...>" should be returned. ' + 'The return\n' + ' value must be a string object. If a class defines ' + '"__repr__()" but\n' + ' not "__str__()", then "__repr__()" is also used when an ' + '“informal”\n' + ' string representation of instances of that class is ' + 'required.\n' + '\n' + ' This is typically used for debugging, so it is important ' + 'that the\n' + ' representation is information-rich and unambiguous.\n' + '\n' + 'object.__str__(self)\n' + '\n' + ' Called by "str(object)" and the built-in functions ' + '"format()" and\n' + ' "print()" to compute the “informal” or nicely printable ' + 'string\n' + ' representation of an object. The return value must be a ' + 'string\n' + ' object.\n' + '\n' + ' This method differs from "object.__repr__()" in that ' + 'there is no\n' + ' expectation that "__str__()" return a valid Python ' + 'expression: a\n' + ' more convenient or concise representation can be used.\n' + '\n' + ' The default implementation defined by the built-in type ' + '"object"\n' + ' calls "object.__repr__()".\n' + '\n' + 'object.__bytes__(self)\n' + '\n' + ' Called by bytes to compute a byte-string representation ' + 'of an\n' + ' object. This should return a "bytes" object.\n' + '\n' + 'object.__format__(self, format_spec)\n' + '\n' + ' Called by the "format()" built-in function, and by ' + 'extension,\n' + ' evaluation of formatted string literals and the ' + '"str.format()"\n' + ' method, to produce a “formatted” string representation ' + 'of an\n' + ' object. The *format_spec* argument is a string that ' + 'contains a\n' + ' description of the formatting options desired. The ' + 'interpretation\n' + ' of the *format_spec* argument is up to the type ' + 'implementing\n' + ' "__format__()", however most classes will either ' + 'delegate\n' + ' formatting to one of the built-in types, or use a ' + 'similar\n' + ' formatting option syntax.\n' + '\n' + ' See Format Specification Mini-Language for a description ' + 'of the\n' + ' standard formatting syntax.\n' + '\n' + ' The return value must be a string object.\n' + '\n' + ' Changed in version 3.4: The __format__ method of ' + '"object" itself\n' + ' raises a "TypeError" if passed any non-empty string.\n' + '\n' + ' Changed in version 3.7: "object.__format__(x, \'\')" is ' + 'now\n' + ' equivalent to "str(x)" rather than "format(str(x), ' + '\'\')".\n' + '\n' + 'object.__lt__(self, other)\n' + 'object.__le__(self, other)\n' + 'object.__eq__(self, other)\n' + 'object.__ne__(self, other)\n' + 'object.__gt__(self, other)\n' + 'object.__ge__(self, other)\n' + '\n' + ' These are the so-called “rich comparison” methods. The\n' + ' correspondence between operator symbols and method names ' + 'is as\n' + ' follows: "xy" calls\n' + ' "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n' + '\n' + ' A rich comparison method may return the singleton ' + '"NotImplemented"\n' + ' if it does not implement the operation for a given pair ' + 'of\n' + ' arguments. By convention, "False" and "True" are ' + 'returned for a\n' + ' successful comparison. However, these methods can return ' + 'any value,\n' + ' so if the comparison operator is used in a Boolean ' + 'context (e.g.,\n' + ' in the condition of an "if" statement), Python will call ' + '"bool()"\n' + ' on the value to determine if the result is true or ' + 'false.\n' + '\n' + ' By default, "object" implements "__eq__()" by using ' + '"is", returning\n' + ' "NotImplemented" in the case of a false comparison: ' + '"True if x is y\n' + ' else NotImplemented". For "__ne__()", by default it ' + 'delegates to\n' + ' "__eq__()" and inverts the result unless it is ' + '"NotImplemented".\n' + ' There are no other implied relationships among the ' + 'comparison\n' + ' operators or default implementations; for example, the ' + 'truth of\n' + ' "(x.__hash__".\n' + '\n' + ' If a class that does not override "__eq__()" wishes to ' + 'suppress\n' + ' hash support, it should include "__hash__ = None" in the ' + 'class\n' + ' definition. A class which defines its own "__hash__()" ' + 'that\n' + ' explicitly raises a "TypeError" would be incorrectly ' + 'identified as\n' + ' hashable by an "isinstance(obj, ' + 'collections.abc.Hashable)" call.\n' + '\n' + ' Note:\n' + '\n' + ' By default, the "__hash__()" values of str and bytes ' + 'objects are\n' + ' “salted” with an unpredictable random value. Although ' + 'they\n' + ' remain constant within an individual Python process, ' + 'they are not\n' + ' predictable between repeated invocations of ' + 'Python.This is\n' + ' intended to provide protection against a ' + 'denial-of-service caused\n' + ' by carefully chosen inputs that exploit the worst ' + 'case\n' + ' performance of a dict insertion, *O*(*n*^2) ' + 'complexity. See\n' + ' http://ocert.org/advisories/ocert-2011-003.html for\n' + ' details.Changing hash values affects the iteration ' + 'order of sets.\n' + ' Python has never made guarantees about this ordering ' + '(and it\n' + ' typically varies between 32-bit and 64-bit builds).See ' + 'also\n' + ' "PYTHONHASHSEED".\n' + '\n' + ' Changed in version 3.3: Hash randomization is enabled by ' + 'default.\n' + '\n' + 'object.__bool__(self)\n' + '\n' + ' Called to implement truth value testing and the built-in ' + 'operation\n' + ' "bool()"; should return "False" or "True". When this ' + 'method is not\n' + ' defined, "__len__()" is called, if it is defined, and ' + 'the object is\n' + ' considered true if its result is nonzero. If a class ' + 'defines\n' + ' neither "__len__()" nor "__bool__()", all its instances ' + 'are\n' + ' considered true.\n', + 'debugger': '"pdb" — The Python Debugger\n' + '***************************\n' + '\n' + '**Source code:** Lib/pdb.py\n' + '\n' + '======================================================================\n' + '\n' + 'The module "pdb" defines an interactive source code debugger ' + 'for\n' + 'Python programs. It supports setting (conditional) breakpoints ' + 'and\n' + 'single stepping at the source line level, inspection of stack ' + 'frames,\n' + 'source code listing, and evaluation of arbitrary Python code in ' + 'the\n' + 'context of any stack frame. It also supports post-mortem ' + 'debugging\n' + 'and can be called under program control.\n' + '\n' + 'The debugger is extensible – it is actually defined as the ' + 'class\n' + '"Pdb". This is currently undocumented but easily understood by ' + 'reading\n' + 'the source. The extension interface uses the modules "bdb" and ' + '"cmd".\n' + '\n' + 'See also:\n' + '\n' + ' Module "faulthandler"\n' + ' Used to dump Python tracebacks explicitly, on a fault, ' + 'after a\n' + ' timeout, or on a user signal.\n' + '\n' + ' Module "traceback"\n' + ' Standard interface to extract, format and print stack ' + 'traces of\n' + ' Python programs.\n' + '\n' + 'The typical usage to break into the debugger is to insert:\n' + '\n' + ' import pdb; pdb.set_trace()\n' + '\n' + 'Or:\n' + '\n' + ' breakpoint()\n' + '\n' + 'at the location you want to break into the debugger, and then ' + 'run the\n' + 'program. You can then step through the code following this ' + 'statement,\n' + 'and continue running without the debugger using the "continue"\n' + 'command.\n' + '\n' + 'Changed in version 3.7: The built-in "breakpoint()", when called ' + 'with\n' + 'defaults, can be used instead of "import pdb; pdb.set_trace()".\n' + '\n' + ' def double(x):\n' + ' breakpoint()\n' + ' return x * 2\n' + ' val = 3\n' + ' print(f"{val} * 2 is {double(val)}")\n' + '\n' + 'The debugger’s prompt is "(Pdb)", which is the indicator that ' + 'you are\n' + 'in debug mode:\n' + '\n' + ' > ...(3)double()\n' + ' -> return x * 2\n' + ' (Pdb) p x\n' + ' 3\n' + ' (Pdb) continue\n' + ' 3 * 2 is 6\n' + '\n' + 'Changed in version 3.3: Tab-completion via the "readline" module ' + 'is\n' + 'available for commands and command arguments, e.g. the current ' + 'global\n' + 'and local names are offered as arguments of the "p" command.\n' + '\n' + 'You can also invoke "pdb" from the command line to debug other\n' + 'scripts. For example:\n' + '\n' + ' python -m pdb myscript.py\n' + '\n' + 'When invoked as a module, pdb will automatically enter ' + 'post-mortem\n' + 'debugging if the program being debugged exits abnormally. After ' + 'post-\n' + 'mortem debugging (or after normal exit of the program), pdb ' + 'will\n' + 'restart the program. Automatic restarting preserves pdb’s state ' + '(such\n' + 'as breakpoints) and in most cases is more useful than quitting ' + 'the\n' + 'debugger upon program’s exit.\n' + '\n' + 'Changed in version 3.2: Added the "-c" option to execute ' + 'commands as\n' + 'if given in a ".pdbrc" file; see Debugger Commands.\n' + '\n' + 'Changed in version 3.7: Added the "-m" option to execute ' + 'modules\n' + 'similar to the way "python -m" does. As with a script, the ' + 'debugger\n' + 'will pause execution just before the first line of the module.\n' + '\n' + 'Typical usage to execute a statement under control of the ' + 'debugger is:\n' + '\n' + ' >>> import pdb\n' + ' >>> def f(x):\n' + ' ... print(1 / x)\n' + ' >>> pdb.run("f(2)")\n' + ' > (1)()\n' + ' (Pdb) continue\n' + ' 0.5\n' + ' >>>\n' + '\n' + 'The typical usage to inspect a crashed program is:\n' + '\n' + ' >>> import pdb\n' + ' >>> def f(x):\n' + ' ... print(1 / x)\n' + ' ...\n' + ' >>> f(0)\n' + ' Traceback (most recent call last):\n' + ' File "", line 1, in \n' + ' File "", line 2, in f\n' + ' ZeroDivisionError: division by zero\n' + ' >>> pdb.pm()\n' + ' > (2)f()\n' + ' (Pdb) p x\n' + ' 0\n' + ' (Pdb)\n' + '\n' + 'The module defines the following functions; each enters the ' + 'debugger\n' + 'in a slightly different way:\n' + '\n' + 'pdb.run(statement, globals=None, locals=None)\n' + '\n' + ' Execute the *statement* (given as a string or a code object) ' + 'under\n' + ' debugger control. The debugger prompt appears before any ' + 'code is\n' + ' executed; you can set breakpoints and type "continue", or you ' + 'can\n' + ' step through the statement using "step" or "next" (all these\n' + ' commands are explained below). The optional *globals* and ' + '*locals*\n' + ' arguments specify the environment in which the code is ' + 'executed; by\n' + ' default the dictionary of the module "__main__" is used. ' + '(See the\n' + ' explanation of the built-in "exec()" or "eval()" functions.)\n' + '\n' + 'pdb.runeval(expression, globals=None, locals=None)\n' + '\n' + ' Evaluate the *expression* (given as a string or a code ' + 'object)\n' + ' under debugger control. When "runeval()" returns, it returns ' + 'the\n' + ' value of the *expression*. Otherwise this function is ' + 'similar to\n' + ' "run()".\n' + '\n' + 'pdb.runcall(function, *args, **kwds)\n' + '\n' + ' Call the *function* (a function or method object, not a ' + 'string)\n' + ' with the given arguments. When "runcall()" returns, it ' + 'returns\n' + ' whatever the function call returned. The debugger prompt ' + 'appears\n' + ' as soon as the function is entered.\n' + '\n' + 'pdb.set_trace(*, header=None)\n' + '\n' + ' Enter the debugger at the calling stack frame. This is ' + 'useful to\n' + ' hard-code a breakpoint at a given point in a program, even if ' + 'the\n' + ' code is not otherwise being debugged (e.g. when an assertion\n' + ' fails). If given, *header* is printed to the console just ' + 'before\n' + ' debugging begins.\n' + '\n' + ' Changed in version 3.7: The keyword-only argument *header*.\n' + '\n' + 'pdb.post_mortem(traceback=None)\n' + '\n' + ' Enter post-mortem debugging of the given *traceback* object. ' + 'If no\n' + ' *traceback* is given, it uses the one of the exception that ' + 'is\n' + ' currently being handled (an exception must be being handled ' + 'if the\n' + ' default is to be used).\n' + '\n' + 'pdb.pm()\n' + '\n' + ' Enter post-mortem debugging of the traceback found in\n' + ' "sys.last_traceback".\n' + '\n' + 'The "run*" functions and "set_trace()" are aliases for ' + 'instantiating\n' + 'the "Pdb" class and calling the method of the same name. If you ' + 'want\n' + 'to access further features, you have to do this yourself:\n' + '\n' + "class pdb.Pdb(completekey='tab', stdin=None, stdout=None, " + 'skip=None, nosigint=False, readrc=True)\n' + '\n' + ' "Pdb" is the debugger class.\n' + '\n' + ' The *completekey*, *stdin* and *stdout* arguments are passed ' + 'to the\n' + ' underlying "cmd.Cmd" class; see the description there.\n' + '\n' + ' The *skip* argument, if given, must be an iterable of ' + 'glob-style\n' + ' module name patterns. The debugger will not step into frames ' + 'that\n' + ' originate in a module that matches one of these patterns. ' + '[1]\n' + '\n' + ' By default, Pdb sets a handler for the SIGINT signal (which ' + 'is sent\n' + ' when the user presses "Ctrl-C" on the console) when you give ' + 'a\n' + ' "continue" command. This allows you to break into the ' + 'debugger\n' + ' again by pressing "Ctrl-C". If you want Pdb not to touch ' + 'the\n' + ' SIGINT handler, set *nosigint* to true.\n' + '\n' + ' The *readrc* argument defaults to true and controls whether ' + 'Pdb\n' + ' will load .pdbrc files from the filesystem.\n' + '\n' + ' Example call to enable tracing with *skip*:\n' + '\n' + " import pdb; pdb.Pdb(skip=['django.*']).set_trace()\n" + '\n' + ' Raises an auditing event "pdb.Pdb" with no arguments.\n' + '\n' + ' Changed in version 3.1: Added the *skip* parameter.\n' + '\n' + ' Changed in version 3.2: Added the *nosigint* parameter. ' + 'Previously,\n' + ' a SIGINT handler was never set by Pdb.\n' + '\n' + ' Changed in version 3.6: The *readrc* argument.\n' + '\n' + ' run(statement, globals=None, locals=None)\n' + ' runeval(expression, globals=None, locals=None)\n' + ' runcall(function, *args, **kwds)\n' + ' set_trace()\n' + '\n' + ' See the documentation for the functions explained above.\n' + '\n' + '\n' + 'Debugger Commands\n' + '=================\n' + '\n' + 'The commands recognized by the debugger are listed below. Most\n' + 'commands can be abbreviated to one or two letters as indicated; ' + 'e.g.\n' + '"h(elp)" means that either "h" or "help" can be used to enter ' + 'the help\n' + 'command (but not "he" or "hel", nor "H" or "Help" or "HELP").\n' + 'Arguments to commands must be separated by whitespace (spaces ' + 'or\n' + 'tabs). Optional arguments are enclosed in square brackets ' + '("[]") in\n' + 'the command syntax; the square brackets must not be typed.\n' + 'Alternatives in the command syntax are separated by a vertical ' + 'bar\n' + '("|").\n' + '\n' + 'Entering a blank line repeats the last command entered. ' + 'Exception: if\n' + 'the last command was a "list" command, the next 11 lines are ' + 'listed.\n' + '\n' + 'Commands that the debugger doesn’t recognize are assumed to be ' + 'Python\n' + 'statements and are executed in the context of the program being\n' + 'debugged. Python statements can also be prefixed with an ' + 'exclamation\n' + 'point ("!"). This is a powerful way to inspect the program ' + 'being\n' + 'debugged; it is even possible to change a variable or call a ' + 'function.\n' + 'When an exception occurs in such a statement, the exception name ' + 'is\n' + 'printed but the debugger’s state is not changed.\n' + '\n' + 'The debugger supports aliases. Aliases can have parameters ' + 'which\n' + 'allows one a certain level of adaptability to the context under\n' + 'examination.\n' + '\n' + 'Multiple commands may be entered on a single line, separated by ' + '";;".\n' + '(A single ";" is not used as it is the separator for multiple ' + 'commands\n' + 'in a line that is passed to the Python parser.) No intelligence ' + 'is\n' + 'applied to separating the commands; the input is split at the ' + 'first\n' + '";;" pair, even if it is in the middle of a quoted string. A\n' + 'workaround for strings with double semicolons is to use ' + 'implicit\n' + 'string concatenation "\';\'\';\'" or "";"";"".\n' + '\n' + 'If a file ".pdbrc" exists in the user’s home directory or in ' + 'the\n' + 'current directory, it is read with "\'utf-8\'" encoding and ' + 'executed as\n' + 'if it had been typed at the debugger prompt, with the exception ' + 'that\n' + 'empty lines and lines starting with "#" are ignored. This is\n' + 'particularly useful for aliases. If both files exist, the one ' + 'in the\n' + 'home directory is read first and aliases defined there can be\n' + 'overridden by the local file.\n' + '\n' + 'Changed in version 3.2: ".pdbrc" can now contain commands that\n' + 'continue debugging, such as "continue" or "next". Previously, ' + 'these\n' + 'commands had no effect.\n' + '\n' + 'Changed in version 3.11: ".pdbrc" is now read with "\'utf-8\'" ' + 'encoding.\n' + 'Previously, it was read with the system locale encoding.\n' + '\n' + 'h(elp) [command]\n' + '\n' + ' Without argument, print the list of available commands. With ' + 'a\n' + ' *command* as argument, print help about that command. "help ' + 'pdb"\n' + ' displays the full documentation (the docstring of the "pdb"\n' + ' module). Since the *command* argument must be an identifier, ' + '"help\n' + ' exec" must be entered to get help on the "!" command.\n' + '\n' + 'w(here)\n' + '\n' + ' Print a stack trace, with the most recent frame at the ' + 'bottom. An\n' + ' arrow (">") indicates the current frame, which determines ' + 'the\n' + ' context of most commands.\n' + '\n' + 'd(own) [count]\n' + '\n' + ' Move the current frame *count* (default one) levels down in ' + 'the\n' + ' stack trace (to a newer frame).\n' + '\n' + 'u(p) [count]\n' + '\n' + ' Move the current frame *count* (default one) levels up in the ' + 'stack\n' + ' trace (to an older frame).\n' + '\n' + 'b(reak) [([filename:]lineno | function) [, condition]]\n' + '\n' + ' With a *lineno* argument, set a break there in the current ' + 'file.\n' + ' With a *function* argument, set a break at the first ' + 'executable\n' + ' statement within that function. The line number may be ' + 'prefixed\n' + ' with a filename and a colon, to specify a breakpoint in ' + 'another\n' + ' file (probably one that hasn’t been loaded yet). The file ' + 'is\n' + ' searched on "sys.path". Note that each breakpoint is ' + 'assigned a\n' + ' number to which all the other breakpoint commands refer.\n' + '\n' + ' If a second argument is present, it is an expression which ' + 'must\n' + ' evaluate to true before the breakpoint is honored.\n' + '\n' + ' Without argument, list all breaks, including for each ' + 'breakpoint,\n' + ' the number of times that breakpoint has been hit, the ' + 'current\n' + ' ignore count, and the associated condition if any.\n' + '\n' + 'tbreak [([filename:]lineno | function) [, condition]]\n' + '\n' + ' Temporary breakpoint, which is removed automatically when it ' + 'is\n' + ' first hit. The arguments are the same as for "break".\n' + '\n' + 'cl(ear) [filename:lineno | bpnumber ...]\n' + '\n' + ' With a *filename:lineno* argument, clear all the breakpoints ' + 'at\n' + ' this line. With a space separated list of breakpoint numbers, ' + 'clear\n' + ' those breakpoints. Without argument, clear all breaks (but ' + 'first\n' + ' ask confirmation).\n' + '\n' + 'disable [bpnumber ...]\n' + '\n' + ' Disable the breakpoints given as a space separated list of\n' + ' breakpoint numbers. Disabling a breakpoint means it cannot ' + 'cause\n' + ' the program to stop execution, but unlike clearing a ' + 'breakpoint, it\n' + ' remains in the list of breakpoints and can be (re-)enabled.\n' + '\n' + 'enable [bpnumber ...]\n' + '\n' + ' Enable the breakpoints specified.\n' + '\n' + 'ignore bpnumber [count]\n' + '\n' + ' Set the ignore count for the given breakpoint number. If ' + '*count*\n' + ' is omitted, the ignore count is set to 0. A breakpoint ' + 'becomes\n' + ' active when the ignore count is zero. When non-zero, the ' + '*count*\n' + ' is decremented each time the breakpoint is reached and the\n' + ' breakpoint is not disabled and any associated condition ' + 'evaluates\n' + ' to true.\n' + '\n' + 'condition bpnumber [condition]\n' + '\n' + ' Set a new *condition* for the breakpoint, an expression which ' + 'must\n' + ' evaluate to true before the breakpoint is honored. If ' + '*condition*\n' + ' is absent, any existing condition is removed; i.e., the ' + 'breakpoint\n' + ' is made unconditional.\n' + '\n' + 'commands [bpnumber]\n' + '\n' + ' Specify a list of commands for breakpoint number *bpnumber*. ' + 'The\n' + ' commands themselves appear on the following lines. Type a ' + 'line\n' + ' containing just "end" to terminate the commands. An example:\n' + '\n' + ' (Pdb) commands 1\n' + ' (com) p some_variable\n' + ' (com) end\n' + ' (Pdb)\n' + '\n' + ' To remove all commands from a breakpoint, type "commands" ' + 'and\n' + ' follow it immediately with "end"; that is, give no commands.\n' + '\n' + ' With no *bpnumber* argument, "commands" refers to the last\n' + ' breakpoint set.\n' + '\n' + ' You can use breakpoint commands to start your program up ' + 'again.\n' + ' Simply use the "continue" command, or "step", or any other ' + 'command\n' + ' that resumes execution.\n' + '\n' + ' Specifying any command resuming execution (currently ' + '"continue",\n' + ' "step", "next", "return", "jump", "quit" and their ' + 'abbreviations)\n' + ' terminates the command list (as if that command was ' + 'immediately\n' + ' followed by end). This is because any time you resume ' + 'execution\n' + ' (even with a simple next or step), you may encounter another\n' + ' breakpoint—which could have its own command list, leading to\n' + ' ambiguities about which list to execute.\n' + '\n' + ' If you use the "silent" command in the command list, the ' + 'usual\n' + ' message about stopping at a breakpoint is not printed. This ' + 'may be\n' + ' desirable for breakpoints that are to print a specific ' + 'message and\n' + ' then continue. If none of the other commands print anything, ' + 'you\n' + ' see no sign that the breakpoint was reached.\n' + '\n' + 's(tep)\n' + '\n' + ' Execute the current line, stop at the first possible ' + 'occasion\n' + ' (either in a function that is called or on the next line in ' + 'the\n' + ' current function).\n' + '\n' + 'n(ext)\n' + '\n' + ' Continue execution until the next line in the current ' + 'function is\n' + ' reached or it returns. (The difference between "next" and ' + '"step"\n' + ' is that "step" stops inside a called function, while "next"\n' + ' executes called functions at (nearly) full speed, only ' + 'stopping at\n' + ' the next line in the current function.)\n' + '\n' + 'unt(il) [lineno]\n' + '\n' + ' Without argument, continue execution until the line with a ' + 'number\n' + ' greater than the current one is reached.\n' + '\n' + ' With *lineno*, continue execution until a line with a number\n' + ' greater or equal to *lineno* is reached. In both cases, also ' + 'stop\n' + ' when the current frame returns.\n' + '\n' + ' Changed in version 3.2: Allow giving an explicit line ' + 'number.\n' + '\n' + 'r(eturn)\n' + '\n' + ' Continue execution until the current function returns.\n' + '\n' + 'c(ont(inue))\n' + '\n' + ' Continue execution, only stop when a breakpoint is ' + 'encountered.\n' + '\n' + 'j(ump) lineno\n' + '\n' + ' Set the next line that will be executed. Only available in ' + 'the\n' + ' bottom-most frame. This lets you jump back and execute code ' + 'again,\n' + ' or jump forward to skip code that you don’t want to run.\n' + '\n' + ' It should be noted that not all jumps are allowed – for ' + 'instance it\n' + ' is not possible to jump into the middle of a "for" loop or ' + 'out of a\n' + ' "finally" clause.\n' + '\n' + 'l(ist) [first[, last]]\n' + '\n' + ' List source code for the current file. Without arguments, ' + 'list 11\n' + ' lines around the current line or continue the previous ' + 'listing.\n' + ' With "." as argument, list 11 lines around the current line. ' + 'With\n' + ' one argument, list 11 lines around at that line. With two\n' + ' arguments, list the given range; if the second argument is ' + 'less\n' + ' than the first, it is interpreted as a count.\n' + '\n' + ' The current line in the current frame is indicated by "->". ' + 'If an\n' + ' exception is being debugged, the line where the exception ' + 'was\n' + ' originally raised or propagated is indicated by ">>", if it ' + 'differs\n' + ' from the current line.\n' + '\n' + ' Changed in version 3.2: Added the ">>" marker.\n' + '\n' + 'll | longlist\n' + '\n' + ' List all source code for the current function or frame.\n' + ' Interesting lines are marked as for "list".\n' + '\n' + ' New in version 3.2.\n' + '\n' + 'a(rgs)\n' + '\n' + ' Print the arguments of the current function and their ' + 'current\n' + ' values.\n' + '\n' + 'p expression\n' + '\n' + ' Evaluate *expression* in the current context and print its ' + 'value.\n' + '\n' + ' Note:\n' + '\n' + ' "print()" can also be used, but is not a debugger command — ' + 'this\n' + ' executes the Python "print()" function.\n' + '\n' + 'pp expression\n' + '\n' + ' Like the "p" command, except the value of *expression* is ' + 'pretty-\n' + ' printed using the "pprint" module.\n' + '\n' + 'whatis expression\n' + '\n' + ' Print the type of *expression*.\n' + '\n' + 'source expression\n' + '\n' + ' Try to get source code of *expression* and display it.\n' + '\n' + ' New in version 3.2.\n' + '\n' + 'display [expression]\n' + '\n' + ' Display the value of *expression* if it changed, each time\n' + ' execution stops in the current frame.\n' + '\n' + ' Without *expression*, list all display expressions for the ' + 'current\n' + ' frame.\n' + '\n' + ' Note:\n' + '\n' + ' Display evaluates *expression* and compares to the result ' + 'of the\n' + ' previous evaluation of *expression*, so when the result is\n' + ' mutable, display may not be able to pick up the changes.\n' + '\n' + ' Example:\n' + '\n' + ' lst = []\n' + ' breakpoint()\n' + ' pass\n' + ' lst.append(1)\n' + ' print(lst)\n' + '\n' + ' Display won’t realize "lst" has been changed because the ' + 'result of\n' + ' evaluation is modified in place by "lst.append(1)" before ' + 'being\n' + ' compared:\n' + '\n' + ' > example.py(3)()\n' + ' -> pass\n' + ' (Pdb) display lst\n' + ' display lst: []\n' + ' (Pdb) n\n' + ' > example.py(4)()\n' + ' -> lst.append(1)\n' + ' (Pdb) n\n' + ' > example.py(5)()\n' + ' -> print(lst)\n' + ' (Pdb)\n' + '\n' + ' You can do some tricks with copy mechanism to make it work:\n' + '\n' + ' > example.py(3)()\n' + ' -> pass\n' + ' (Pdb) display lst[:]\n' + ' display lst[:]: []\n' + ' (Pdb) n\n' + ' > example.py(4)()\n' + ' -> lst.append(1)\n' + ' (Pdb) n\n' + ' > example.py(5)()\n' + ' -> print(lst)\n' + ' display lst[:]: [1] [old: []]\n' + ' (Pdb)\n' + '\n' + ' New in version 3.2.\n' + '\n' + 'undisplay [expression]\n' + '\n' + ' Do not display *expression* anymore in the current frame. ' + 'Without\n' + ' *expression*, clear all display expressions for the current ' + 'frame.\n' + '\n' + ' New in version 3.2.\n' + '\n' + 'interact\n' + '\n' + ' Start an interactive interpreter (using the "code" module) ' + 'whose\n' + ' global namespace contains all the (global and local) names ' + 'found in\n' + ' the current scope.\n' + '\n' + ' New in version 3.2.\n' + '\n' + 'alias [name [command]]\n' + '\n' + ' Create an alias called *name* that executes *command*. The\n' + ' *command* must *not* be enclosed in quotes. Replaceable ' + 'parameters\n' + ' can be indicated by "%1", "%2", and so on, while "%*" is ' + 'replaced\n' + ' by all the parameters. If *command* is omitted, the current ' + 'alias\n' + ' for *name* is shown. If no arguments are given, all aliases ' + 'are\n' + ' listed.\n' + '\n' + ' Aliases may be nested and can contain anything that can be ' + 'legally\n' + ' typed at the pdb prompt. Note that internal pdb commands ' + '*can* be\n' + ' overridden by aliases. Such a command is then hidden until ' + 'the\n' + ' alias is removed. Aliasing is recursively applied to the ' + 'first\n' + ' word of the command line; all other words in the line are ' + 'left\n' + ' alone.\n' + '\n' + ' As an example, here are two useful aliases (especially when ' + 'placed\n' + ' in the ".pdbrc" file):\n' + '\n' + ' # Print instance variables (usage "pi classInst")\n' + ' alias pi for k in %1.__dict__.keys(): print(f"%1.{k} = ' + '{%1.__dict__[k]}")\n' + ' # Print instance variables in self\n' + ' alias ps pi self\n' + '\n' + 'unalias name\n' + '\n' + ' Delete the specified alias *name*.\n' + '\n' + '! statement\n' + '\n' + ' Execute the (one-line) *statement* in the context of the ' + 'current\n' + ' stack frame. The exclamation point can be omitted unless the ' + 'first\n' + ' word of the statement resembles a debugger command. To set ' + 'a\n' + ' global variable, you can prefix the assignment command with ' + 'a\n' + ' "global" statement on the same line, e.g.:\n' + '\n' + " (Pdb) global list_options; list_options = ['-l']\n" + ' (Pdb)\n' + '\n' + 'run [args ...]\n' + 'restart [args ...]\n' + '\n' + ' Restart the debugged Python program. If *args* is supplied, ' + 'it is\n' + ' split with "shlex" and the result is used as the new ' + '"sys.argv".\n' + ' History, breakpoints, actions and debugger options are ' + 'preserved.\n' + ' "restart" is an alias for "run".\n' + '\n' + 'q(uit)\n' + '\n' + ' Quit from the debugger. The program being executed is ' + 'aborted.\n' + '\n' + 'debug code\n' + '\n' + ' Enter a recursive debugger that steps through *code* (which ' + 'is an\n' + ' arbitrary expression or statement to be executed in the ' + 'current\n' + ' environment).\n' + '\n' + 'retval\n' + '\n' + ' Print the return value for the last return of the current ' + 'function.\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] Whether a frame is considered to originate in a certain ' + 'module is\n' + ' determined by the "__name__" in the frame globals.\n', + 'del': 'The "del" statement\n' + '*******************\n' + '\n' + ' del_stmt ::= "del" target_list\n' + '\n' + 'Deletion is recursively defined very similar to the way assignment ' + 'is\n' + 'defined. Rather than spelling it out in full details, here are some\n' + 'hints.\n' + '\n' + 'Deletion of a target list recursively deletes each target, from left\n' + 'to right.\n' + '\n' + 'Deletion of a name removes the binding of that name from the local ' + 'or\n' + 'global namespace, depending on whether the name occurs in a "global"\n' + 'statement in the same code block. If the name is unbound, a\n' + '"NameError" exception will be raised.\n' + '\n' + 'Deletion of attribute references, subscriptions and slicings is ' + 'passed\n' + 'to the primary object involved; deletion of a slicing is in general\n' + 'equivalent to assignment of an empty slice of the right type (but ' + 'even\n' + 'this is determined by the sliced object).\n' + '\n' + 'Changed in version 3.2: Previously it was illegal to delete a name\n' + 'from the local namespace if it occurs as a free variable in a nested\n' + 'block.\n', + 'dict': 'Dictionary displays\n' + '*******************\n' + '\n' + 'A dictionary display is a possibly empty series of dict items\n' + '(key/value pairs) enclosed in curly braces:\n' + '\n' + ' dict_display ::= "{" [dict_item_list | dict_comprehension] ' + '"}"\n' + ' dict_item_list ::= dict_item ("," dict_item)* [","]\n' + ' dict_item ::= expression ":" expression | "**" or_expr\n' + ' dict_comprehension ::= expression ":" expression comp_for\n' + '\n' + 'A dictionary display yields a new dictionary object.\n' + '\n' + 'If a comma-separated sequence of dict items is given, they are\n' + 'evaluated from left to right to define the entries of the ' + 'dictionary:\n' + 'each key object is used as a key into the dictionary to store the\n' + 'corresponding value. This means that you can specify the same key\n' + 'multiple times in the dict item list, and the final dictionary’s ' + 'value\n' + 'for that key will be the last one given.\n' + '\n' + 'A double asterisk "**" denotes *dictionary unpacking*. Its operand\n' + 'must be a *mapping*. Each mapping item is added to the new\n' + 'dictionary. Later values replace values already set by earlier ' + 'dict\n' + 'items and earlier dictionary unpackings.\n' + '\n' + 'New in version 3.5: Unpacking into dictionary displays, originally\n' + 'proposed by **PEP 448**.\n' + '\n' + 'A dict comprehension, in contrast to list and set comprehensions,\n' + 'needs two expressions separated with a colon followed by the usual\n' + '“for” and “if” clauses. When the comprehension is run, the ' + 'resulting\n' + 'key and value elements are inserted in the new dictionary in the ' + 'order\n' + 'they are produced.\n' + '\n' + 'Restrictions on the types of the key values are listed earlier in\n' + 'section The standard type hierarchy. (To summarize, the key type\n' + 'should be *hashable*, which excludes all mutable objects.) Clashes\n' + 'between duplicate keys are not detected; the last value (textually\n' + 'rightmost in the display) stored for a given key value prevails.\n' + '\n' + 'Changed in version 3.8: Prior to Python 3.8, in dict ' + 'comprehensions,\n' + 'the evaluation order of key and value was not well-defined. In\n' + 'CPython, the value was evaluated before the key. Starting with ' + '3.8,\n' + 'the key is evaluated before the value, as proposed by **PEP 572**.\n', + 'dynamic-features': 'Interaction with dynamic features\n' + '*********************************\n' + '\n' + 'Name resolution of free variables occurs at runtime, not ' + 'at compile\n' + 'time. This means that the following code will print 42:\n' + '\n' + ' i = 10\n' + ' def f():\n' + ' print(i)\n' + ' i = 42\n' + ' f()\n' + '\n' + 'The "eval()" and "exec()" functions do not have access ' + 'to the full\n' + 'environment for resolving names. Names may be resolved ' + 'in the local\n' + 'and global namespaces of the caller. Free variables are ' + 'not resolved\n' + 'in the nearest enclosing namespace, but in the global ' + 'namespace. [1]\n' + 'The "exec()" and "eval()" functions have optional ' + 'arguments to\n' + 'override the global and local namespace. If only one ' + 'namespace is\n' + 'specified, it is used for both.\n', + 'else': 'The "if" statement\n' + '******************\n' + '\n' + 'The "if" statement is used for conditional execution:\n' + '\n' + ' if_stmt ::= "if" assignment_expression ":" suite\n' + ' ("elif" assignment_expression ":" suite)*\n' + ' ["else" ":" suite]\n' + '\n' + 'It selects exactly one of the suites by evaluating the expressions ' + 'one\n' + 'by one until one is found to be true (see section Boolean ' + 'operations\n' + 'for the definition of true and false); then that suite is executed\n' + '(and no other part of the "if" statement is executed or evaluated).\n' + 'If all expressions are false, the suite of the "else" clause, if\n' + 'present, is executed.\n', + 'exceptions': 'Exceptions\n' + '**********\n' + '\n' + 'Exceptions are a means of breaking out of the normal flow of ' + 'control\n' + 'of a code block in order to handle errors or other ' + 'exceptional\n' + 'conditions. An exception is *raised* at the point where the ' + 'error is\n' + 'detected; it may be *handled* by the surrounding code block or ' + 'by any\n' + 'code block that directly or indirectly invoked the code block ' + 'where\n' + 'the error occurred.\n' + '\n' + 'The Python interpreter raises an exception when it detects a ' + 'run-time\n' + 'error (such as division by zero). A Python program can also\n' + 'explicitly raise an exception with the "raise" statement. ' + 'Exception\n' + 'handlers are specified with the "try" … "except" statement. ' + 'The\n' + '"finally" clause of such a statement can be used to specify ' + 'cleanup\n' + 'code which does not handle the exception, but is executed ' + 'whether an\n' + 'exception occurred or not in the preceding code.\n' + '\n' + 'Python uses the “termination” model of error handling: an ' + 'exception\n' + 'handler can find out what happened and continue execution at ' + 'an outer\n' + 'level, but it cannot repair the cause of the error and retry ' + 'the\n' + 'failing operation (except by re-entering the offending piece ' + 'of code\n' + 'from the top).\n' + '\n' + 'When an exception is not handled at all, the interpreter ' + 'terminates\n' + 'execution of the program, or returns to its interactive main ' + 'loop. In\n' + 'either case, it prints a stack traceback, except when the ' + 'exception is\n' + '"SystemExit".\n' + '\n' + 'Exceptions are identified by class instances. The "except" ' + 'clause is\n' + 'selected depending on the class of the instance: it must ' + 'reference the\n' + 'class of the instance or a *non-virtual base class* thereof. ' + 'The\n' + 'instance can be received by the handler and can carry ' + 'additional\n' + 'information about the exceptional condition.\n' + '\n' + 'Note:\n' + '\n' + ' Exception messages are not part of the Python API. Their ' + 'contents\n' + ' may change from one version of Python to the next without ' + 'warning\n' + ' and should not be relied on by code which will run under ' + 'multiple\n' + ' versions of the interpreter.\n' + '\n' + 'See also the description of the "try" statement in section The ' + 'try\n' + 'statement and "raise" statement in section The raise ' + 'statement.\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] This limitation occurs because the code that is executed ' + 'by these\n' + ' operations is not available at the time the module is ' + 'compiled.\n', + 'execmodel': 'Execution model\n' + '***************\n' + '\n' + '\n' + 'Structure of a program\n' + '======================\n' + '\n' + 'A Python program is constructed from code blocks. A *block* is ' + 'a piece\n' + 'of Python program text that is executed as a unit. The ' + 'following are\n' + 'blocks: a module, a function body, and a class definition. ' + 'Each\n' + 'command typed interactively is a block. A script file (a file ' + 'given\n' + 'as standard input to the interpreter or specified as a command ' + 'line\n' + 'argument to the interpreter) is a code block. A script command ' + '(a\n' + 'command specified on the interpreter command line with the ' + '"-c"\n' + 'option) is a code block. A module run as a top level script (as ' + 'module\n' + '"__main__") from the command line using a "-m" argument is also ' + 'a code\n' + 'block. The string argument passed to the built-in functions ' + '"eval()"\n' + 'and "exec()" is a code block.\n' + '\n' + 'A code block is executed in an *execution frame*. A frame ' + 'contains\n' + 'some administrative information (used for debugging) and ' + 'determines\n' + 'where and how execution continues after the code block’s ' + 'execution has\n' + 'completed.\n' + '\n' + '\n' + 'Naming and binding\n' + '==================\n' + '\n' + '\n' + 'Binding of names\n' + '----------------\n' + '\n' + '*Names* refer to objects. Names are introduced by name ' + 'binding\n' + 'operations.\n' + '\n' + 'The following constructs bind names:\n' + '\n' + '* formal parameters to functions,\n' + '\n' + '* class definitions,\n' + '\n' + '* function definitions,\n' + '\n' + '* assignment expressions,\n' + '\n' + '* targets that are identifiers if occurring in an assignment:\n' + '\n' + ' * "for" loop header,\n' + '\n' + ' * after "as" in a "with" statement, "except" clause, ' + '"except*"\n' + ' clause, or in the as-pattern in structural pattern ' + 'matching,\n' + '\n' + ' * in a capture pattern in structural pattern matching\n' + '\n' + '* "import" statements.\n' + '\n' + 'The "import" statement of the form "from ... import *" binds ' + 'all names\n' + 'defined in the imported module, except those beginning with an\n' + 'underscore. This form may only be used at the module level.\n' + '\n' + 'A target occurring in a "del" statement is also considered ' + 'bound for\n' + 'this purpose (though the actual semantics are to unbind the ' + 'name).\n' + '\n' + 'Each assignment or import statement occurs within a block ' + 'defined by a\n' + 'class or function definition or at the module level (the ' + 'top-level\n' + 'code block).\n' + '\n' + 'If a name is bound in a block, it is a local variable of that ' + 'block,\n' + 'unless declared as "nonlocal" or "global". If a name is bound ' + 'at the\n' + 'module level, it is a global variable. (The variables of the ' + 'module\n' + 'code block are local and global.) If a variable is used in a ' + 'code\n' + 'block but not defined there, it is a *free variable*.\n' + '\n' + 'Each occurrence of a name in the program text refers to the ' + '*binding*\n' + 'of that name established by the following name resolution ' + 'rules.\n' + '\n' + '\n' + 'Resolution of names\n' + '-------------------\n' + '\n' + 'A *scope* defines the visibility of a name within a block. If ' + 'a local\n' + 'variable is defined in a block, its scope includes that block. ' + 'If the\n' + 'definition occurs in a function block, the scope extends to any ' + 'blocks\n' + 'contained within the defining one, unless a contained block ' + 'introduces\n' + 'a different binding for the name.\n' + '\n' + 'When a name is used in a code block, it is resolved using the ' + 'nearest\n' + 'enclosing scope. The set of all such scopes visible to a code ' + 'block\n' + 'is called the block’s *environment*.\n' + '\n' + 'When a name is not found at all, a "NameError" exception is ' + 'raised. If\n' + 'the current scope is a function scope, and the name refers to a ' + 'local\n' + 'variable that has not yet been bound to a value at the point ' + 'where the\n' + 'name is used, an "UnboundLocalError" exception is raised.\n' + '"UnboundLocalError" is a subclass of "NameError".\n' + '\n' + 'If a name binding operation occurs anywhere within a code ' + 'block, all\n' + 'uses of the name within the block are treated as references to ' + 'the\n' + 'current block. This can lead to errors when a name is used ' + 'within a\n' + 'block before it is bound. This rule is subtle. Python lacks\n' + 'declarations and allows name binding operations to occur ' + 'anywhere\n' + 'within a code block. The local variables of a code block can ' + 'be\n' + 'determined by scanning the entire text of the block for name ' + 'binding\n' + 'operations. See the FAQ entry on UnboundLocalError for ' + 'examples.\n' + '\n' + 'If the "global" statement occurs within a block, all uses of ' + 'the names\n' + 'specified in the statement refer to the bindings of those names ' + 'in the\n' + 'top-level namespace. Names are resolved in the top-level ' + 'namespace by\n' + 'searching the global namespace, i.e. the namespace of the ' + 'module\n' + 'containing the code block, and the builtins namespace, the ' + 'namespace\n' + 'of the module "builtins". The global namespace is searched ' + 'first. If\n' + 'the names are not found there, the builtins namespace is ' + 'searched.\n' + 'The "global" statement must precede all uses of the listed ' + 'names.\n' + '\n' + 'The "global" statement has the same scope as a name binding ' + 'operation\n' + 'in the same block. If the nearest enclosing scope for a free ' + 'variable\n' + 'contains a global statement, the free variable is treated as a ' + 'global.\n' + '\n' + 'The "nonlocal" statement causes corresponding names to refer ' + 'to\n' + 'previously bound variables in the nearest enclosing function ' + 'scope.\n' + '"SyntaxError" is raised at compile time if the given name does ' + 'not\n' + 'exist in any enclosing function scope.\n' + '\n' + 'The namespace for a module is automatically created the first ' + 'time a\n' + 'module is imported. The main module for a script is always ' + 'called\n' + '"__main__".\n' + '\n' + 'Class definition blocks and arguments to "exec()" and "eval()" ' + 'are\n' + 'special in the context of name resolution. A class definition ' + 'is an\n' + 'executable statement that may use and define names. These ' + 'references\n' + 'follow the normal rules for name resolution with an exception ' + 'that\n' + 'unbound local variables are looked up in the global namespace. ' + 'The\n' + 'namespace of the class definition becomes the attribute ' + 'dictionary of\n' + 'the class. The scope of names defined in a class block is ' + 'limited to\n' + 'the class block; it does not extend to the code blocks of ' + 'methods –\n' + 'this includes comprehensions and generator expressions since ' + 'they are\n' + 'implemented using a function scope. This means that the ' + 'following\n' + 'will fail:\n' + '\n' + ' class A:\n' + ' a = 42\n' + ' b = list(a + i for i in range(10))\n' + '\n' + '\n' + 'Builtins and restricted execution\n' + '---------------------------------\n' + '\n' + '**CPython implementation detail:** Users should not touch\n' + '"__builtins__"; it is strictly an implementation detail. ' + 'Users\n' + 'wanting to override values in the builtins namespace should ' + '"import"\n' + 'the "builtins" module and modify its attributes appropriately.\n' + '\n' + 'The builtins namespace associated with the execution of a code ' + 'block\n' + 'is actually found by looking up the name "__builtins__" in its ' + 'global\n' + 'namespace; this should be a dictionary or a module (in the ' + 'latter case\n' + 'the module’s dictionary is used). By default, when in the ' + '"__main__"\n' + 'module, "__builtins__" is the built-in module "builtins"; when ' + 'in any\n' + 'other module, "__builtins__" is an alias for the dictionary of ' + 'the\n' + '"builtins" module itself.\n' + '\n' + '\n' + 'Interaction with dynamic features\n' + '---------------------------------\n' + '\n' + 'Name resolution of free variables occurs at runtime, not at ' + 'compile\n' + 'time. This means that the following code will print 42:\n' + '\n' + ' i = 10\n' + ' def f():\n' + ' print(i)\n' + ' i = 42\n' + ' f()\n' + '\n' + 'The "eval()" and "exec()" functions do not have access to the ' + 'full\n' + 'environment for resolving names. Names may be resolved in the ' + 'local\n' + 'and global namespaces of the caller. Free variables are not ' + 'resolved\n' + 'in the nearest enclosing namespace, but in the global ' + 'namespace. [1]\n' + 'The "exec()" and "eval()" functions have optional arguments to\n' + 'override the global and local namespace. If only one namespace ' + 'is\n' + 'specified, it is used for both.\n' + '\n' + '\n' + 'Exceptions\n' + '==========\n' + '\n' + 'Exceptions are a means of breaking out of the normal flow of ' + 'control\n' + 'of a code block in order to handle errors or other exceptional\n' + 'conditions. An exception is *raised* at the point where the ' + 'error is\n' + 'detected; it may be *handled* by the surrounding code block or ' + 'by any\n' + 'code block that directly or indirectly invoked the code block ' + 'where\n' + 'the error occurred.\n' + '\n' + 'The Python interpreter raises an exception when it detects a ' + 'run-time\n' + 'error (such as division by zero). A Python program can also\n' + 'explicitly raise an exception with the "raise" statement. ' + 'Exception\n' + 'handlers are specified with the "try" … "except" statement. ' + 'The\n' + '"finally" clause of such a statement can be used to specify ' + 'cleanup\n' + 'code which does not handle the exception, but is executed ' + 'whether an\n' + 'exception occurred or not in the preceding code.\n' + '\n' + 'Python uses the “termination” model of error handling: an ' + 'exception\n' + 'handler can find out what happened and continue execution at an ' + 'outer\n' + 'level, but it cannot repair the cause of the error and retry ' + 'the\n' + 'failing operation (except by re-entering the offending piece of ' + 'code\n' + 'from the top).\n' + '\n' + 'When an exception is not handled at all, the interpreter ' + 'terminates\n' + 'execution of the program, or returns to its interactive main ' + 'loop. In\n' + 'either case, it prints a stack traceback, except when the ' + 'exception is\n' + '"SystemExit".\n' + '\n' + 'Exceptions are identified by class instances. The "except" ' + 'clause is\n' + 'selected depending on the class of the instance: it must ' + 'reference the\n' + 'class of the instance or a *non-virtual base class* thereof. ' + 'The\n' + 'instance can be received by the handler and can carry ' + 'additional\n' + 'information about the exceptional condition.\n' + '\n' + 'Note:\n' + '\n' + ' Exception messages are not part of the Python API. Their ' + 'contents\n' + ' may change from one version of Python to the next without ' + 'warning\n' + ' and should not be relied on by code which will run under ' + 'multiple\n' + ' versions of the interpreter.\n' + '\n' + 'See also the description of the "try" statement in section The ' + 'try\n' + 'statement and "raise" statement in section The raise ' + 'statement.\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] This limitation occurs because the code that is executed by ' + 'these\n' + ' operations is not available at the time the module is ' + 'compiled.\n', + 'exprlists': 'Expression lists\n' + '****************\n' + '\n' + ' expression_list ::= expression ("," expression)* [","]\n' + ' starred_list ::= starred_item ("," starred_item)* ' + '[","]\n' + ' starred_expression ::= expression | (starred_item ",")* ' + '[starred_item]\n' + ' starred_item ::= assignment_expression | "*" or_expr\n' + '\n' + 'Except when part of a list or set display, an expression list\n' + 'containing at least one comma yields a tuple. The length of ' + 'the tuple\n' + 'is the number of expressions in the list. The expressions are\n' + 'evaluated from left to right.\n' + '\n' + 'An asterisk "*" denotes *iterable unpacking*. Its operand must ' + 'be an\n' + '*iterable*. The iterable is expanded into a sequence of items, ' + 'which\n' + 'are included in the new tuple, list, or set, at the site of ' + 'the\n' + 'unpacking.\n' + '\n' + 'New in version 3.5: Iterable unpacking in expression lists, ' + 'originally\n' + 'proposed by **PEP 448**.\n' + '\n' + 'A trailing comma is required only to create a one-item tuple, ' + 'such as\n' + '"1,"; it is optional in all other cases. A single expression ' + 'without a\n' + 'trailing comma doesn’t create a tuple, but rather yields the ' + 'value of\n' + 'that expression. (To create an empty tuple, use an empty pair ' + 'of\n' + 'parentheses: "()".)\n', + 'floating': 'Floating point literals\n' + '***********************\n' + '\n' + 'Floating point literals are described by the following lexical\n' + 'definitions:\n' + '\n' + ' floatnumber ::= pointfloat | exponentfloat\n' + ' pointfloat ::= [digitpart] fraction | digitpart "."\n' + ' exponentfloat ::= (digitpart | pointfloat) exponent\n' + ' digitpart ::= digit (["_"] digit)*\n' + ' fraction ::= "." digitpart\n' + ' exponent ::= ("e" | "E") ["+" | "-"] digitpart\n' + '\n' + 'Note that the integer and exponent parts are always interpreted ' + 'using\n' + 'radix 10. For example, "077e010" is legal, and denotes the same ' + 'number\n' + 'as "77e10". The allowed range of floating point literals is\n' + 'implementation-dependent. As in integer literals, underscores ' + 'are\n' + 'supported for digit grouping.\n' + '\n' + 'Some examples of floating point literals:\n' + '\n' + ' 3.14 10. .001 1e100 3.14e-10 0e0 ' + '3.14_15_93\n' + '\n' + 'Changed in version 3.6: Underscores are now allowed for ' + 'grouping\n' + 'purposes in literals.\n', + 'for': 'The "for" statement\n' + '*******************\n' + '\n' + 'The "for" statement is used to iterate over the elements of a ' + 'sequence\n' + '(such as a string, tuple or list) or other iterable object:\n' + '\n' + ' for_stmt ::= "for" target_list "in" starred_list ":" suite\n' + ' ["else" ":" suite]\n' + '\n' + 'The "starred_list" expression is evaluated once; it should yield an\n' + '*iterable* object. An *iterator* is created for that iterable. The\n' + 'first item provided by the iterator is then assigned to the target\n' + 'list using the standard rules for assignments (see Assignment\n' + 'statements), and the suite is executed. This repeats for each item\n' + 'provided by the iterator. When the iterator is exhausted, the suite\n' + 'in the "else" clause, if present, is executed, and the loop\n' + 'terminates.\n' + '\n' + 'A "break" statement executed in the first suite terminates the loop\n' + 'without executing the "else" clause’s suite. A "continue" statement\n' + 'executed in the first suite skips the rest of the suite and ' + 'continues\n' + 'with the next item, or with the "else" clause if there is no next\n' + 'item.\n' + '\n' + 'The for-loop makes assignments to the variables in the target list.\n' + 'This overwrites all previous assignments to those variables ' + 'including\n' + 'those made in the suite of the for-loop:\n' + '\n' + ' for i in range(10):\n' + ' print(i)\n' + ' i = 5 # this will not affect the for-loop\n' + ' # because i will be overwritten with the ' + 'next\n' + ' # index in the range\n' + '\n' + 'Names in the target list are not deleted when the loop is finished,\n' + 'but if the sequence is empty, they will not have been assigned to at\n' + 'all by the loop. Hint: the built-in type "range()" represents\n' + 'immutable arithmetic sequences of integers. For instance, iterating\n' + '"range(3)" successively yields 0, 1, and then 2.\n' + '\n' + 'Changed in version 3.11: Starred elements are now allowed in the\n' + 'expression list.\n', + 'formatstrings': 'Format String Syntax\n' + '********************\n' + '\n' + 'The "str.format()" method and the "Formatter" class share ' + 'the same\n' + 'syntax for format strings (although in the case of ' + '"Formatter",\n' + 'subclasses can define their own format string syntax). The ' + 'syntax is\n' + 'related to that of formatted string literals, but it is ' + 'less\n' + 'sophisticated and, in particular, does not support ' + 'arbitrary\n' + 'expressions.\n' + '\n' + 'Format strings contain “replacement fields” surrounded by ' + 'curly braces\n' + '"{}". Anything that is not contained in braces is ' + 'considered literal\n' + 'text, which is copied unchanged to the output. If you need ' + 'to include\n' + 'a brace character in the literal text, it can be escaped by ' + 'doubling:\n' + '"{{" and "}}".\n' + '\n' + 'The grammar for a replacement field is as follows:\n' + '\n' + ' replacement_field ::= "{" [field_name] ["!" conversion] ' + '[":" format_spec] "}"\n' + ' field_name ::= arg_name ("." attribute_name | "[" ' + 'element_index "]")*\n' + ' arg_name ::= [identifier | digit+]\n' + ' attribute_name ::= identifier\n' + ' element_index ::= digit+ | index_string\n' + ' index_string ::= ' + '+\n' + ' conversion ::= "r" | "s" | "a"\n' + ' format_spec ::= format-spec:format_spec\n' + '\n' + 'In less formal terms, the replacement field can start with ' + 'a\n' + '*field_name* that specifies the object whose value is to be ' + 'formatted\n' + 'and inserted into the output instead of the replacement ' + 'field. The\n' + '*field_name* is optionally followed by a *conversion* ' + 'field, which is\n' + 'preceded by an exclamation point "\'!\'", and a ' + '*format_spec*, which is\n' + 'preceded by a colon "\':\'". These specify a non-default ' + 'format for the\n' + 'replacement value.\n' + '\n' + 'See also the Format Specification Mini-Language section.\n' + '\n' + 'The *field_name* itself begins with an *arg_name* that is ' + 'either a\n' + 'number or a keyword. If it’s a number, it refers to a ' + 'positional\n' + 'argument, and if it’s a keyword, it refers to a named ' + 'keyword\n' + 'argument. An *arg_name* is treated as a number if a call ' + 'to\n' + '"str.isdecimal()" on the string would return true. If the ' + 'numerical\n' + 'arg_names in a format string are 0, 1, 2, … in sequence, ' + 'they can all\n' + 'be omitted (not just some) and the numbers 0, 1, 2, … will ' + 'be\n' + 'automatically inserted in that order. Because *arg_name* is ' + 'not quote-\n' + 'delimited, it is not possible to specify arbitrary ' + 'dictionary keys\n' + '(e.g., the strings "\'10\'" or "\':-]\'") within a format ' + 'string. The\n' + '*arg_name* can be followed by any number of index or ' + 'attribute\n' + 'expressions. An expression of the form "\'.name\'" selects ' + 'the named\n' + 'attribute using "getattr()", while an expression of the ' + 'form\n' + '"\'[index]\'" does an index lookup using "__getitem__()".\n' + '\n' + 'Changed in version 3.1: The positional argument specifiers ' + 'can be\n' + 'omitted for "str.format()", so "\'{} {}\'.format(a, b)" is ' + 'equivalent to\n' + '"\'{0} {1}\'.format(a, b)".\n' + '\n' + 'Changed in version 3.4: The positional argument specifiers ' + 'can be\n' + 'omitted for "Formatter".\n' + '\n' + 'Some simple format string examples:\n' + '\n' + ' "First, thou shalt count to {0}" # References first ' + 'positional argument\n' + ' "Bring me a {}" # Implicitly ' + 'references the first positional argument\n' + ' "From {} to {}" # Same as "From {0} to ' + '{1}"\n' + ' "My quest is {name}" # References keyword ' + "argument 'name'\n" + ' "Weight in tons {0.weight}" # \'weight\' attribute ' + 'of first positional arg\n' + ' "Units destroyed: {players[0]}" # First element of ' + "keyword argument 'players'.\n" + '\n' + 'The *conversion* field causes a type coercion before ' + 'formatting.\n' + 'Normally, the job of formatting a value is done by the ' + '"__format__()"\n' + 'method of the value itself. However, in some cases it is ' + 'desirable to\n' + 'force a type to be formatted as a string, overriding its ' + 'own\n' + 'definition of formatting. By converting the value to a ' + 'string before\n' + 'calling "__format__()", the normal formatting logic is ' + 'bypassed.\n' + '\n' + 'Three conversion flags are currently supported: "\'!s\'" ' + 'which calls\n' + '"str()" on the value, "\'!r\'" which calls "repr()" and ' + '"\'!a\'" which\n' + 'calls "ascii()".\n' + '\n' + 'Some examples:\n' + '\n' + ' "Harold\'s a clever {0!s}" # Calls str() on the ' + 'argument first\n' + ' "Bring out the holy {name!r}" # Calls repr() on the ' + 'argument first\n' + ' "More {!a}" # Calls ascii() on the ' + 'argument first\n' + '\n' + 'The *format_spec* field contains a specification of how the ' + 'value\n' + 'should be presented, including such details as field width, ' + 'alignment,\n' + 'padding, decimal precision and so on. Each value type can ' + 'define its\n' + 'own “formatting mini-language” or interpretation of the ' + '*format_spec*.\n' + '\n' + 'Most built-in types support a common formatting ' + 'mini-language, which\n' + 'is described in the next section.\n' + '\n' + 'A *format_spec* field can also include nested replacement ' + 'fields\n' + 'within it. These nested replacement fields may contain a ' + 'field name,\n' + 'conversion flag and format specification, but deeper ' + 'nesting is not\n' + 'allowed. The replacement fields within the format_spec ' + 'are\n' + 'substituted before the *format_spec* string is interpreted. ' + 'This\n' + 'allows the formatting of a value to be dynamically ' + 'specified.\n' + '\n' + 'See the Format examples section for some examples.\n' + '\n' + '\n' + 'Format Specification Mini-Language\n' + '==================================\n' + '\n' + '“Format specifications” are used within replacement fields ' + 'contained\n' + 'within a format string to define how individual values are ' + 'presented\n' + '(see Format String Syntax and f-strings). They can also be ' + 'passed\n' + 'directly to the built-in "format()" function. Each ' + 'formattable type\n' + 'may define how the format specification is to be ' + 'interpreted.\n' + '\n' + 'Most built-in types implement the following options for ' + 'format\n' + 'specifications, although some of the formatting options are ' + 'only\n' + 'supported by the numeric types.\n' + '\n' + 'A general convention is that an empty format specification ' + 'produces\n' + 'the same result as if you had called "str()" on the value. ' + 'A non-empty\n' + 'format specification typically modifies the result.\n' + '\n' + 'The general form of a *standard format specifier* is:\n' + '\n' + ' format_spec ::= ' + '[[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." ' + 'precision][type]\n' + ' fill ::= \n' + ' align ::= "<" | ">" | "=" | "^"\n' + ' sign ::= "+" | "-" | " "\n' + ' width ::= digit+\n' + ' grouping_option ::= "_" | ","\n' + ' precision ::= digit+\n' + ' type ::= "b" | "c" | "d" | "e" | "E" | "f" | ' + '"F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n' + '\n' + 'If a valid *align* value is specified, it can be preceded ' + 'by a *fill*\n' + 'character that can be any character and defaults to a space ' + 'if\n' + 'omitted. It is not possible to use a literal curly brace ' + '(”"{"” or\n' + '“"}"”) as the *fill* character in a formatted string ' + 'literal or when\n' + 'using the "str.format()" method. However, it is possible ' + 'to insert a\n' + 'curly brace with a nested replacement field. This ' + 'limitation doesn’t\n' + 'affect the "format()" function.\n' + '\n' + 'The meaning of the various alignment options is as ' + 'follows:\n' + '\n' + '+-----------+------------------------------------------------------------+\n' + '| Option | ' + 'Meaning ' + '|\n' + '|===========|============================================================|\n' + '| "\'<\'" | Forces the field to be left-aligned within ' + 'the available |\n' + '| | space (this is the default for most ' + 'objects). |\n' + '+-----------+------------------------------------------------------------+\n' + '| "\'>\'" | Forces the field to be right-aligned within ' + 'the available |\n' + '| | space (this is the default for ' + 'numbers). |\n' + '+-----------+------------------------------------------------------------+\n' + '| "\'=\'" | Forces the padding to be placed after the ' + 'sign (if any) |\n' + '| | but before the digits. This is used for ' + 'printing fields |\n' + '| | in the form ‘+000000120’. This alignment ' + 'option is only |\n' + '| | valid for numeric types. It becomes the ' + 'default for |\n' + '| | numbers when ‘0’ immediately precedes the ' + 'field width. |\n' + '+-----------+------------------------------------------------------------+\n' + '| "\'^\'" | Forces the field to be centered within the ' + 'available |\n' + '| | ' + 'space. ' + '|\n' + '+-----------+------------------------------------------------------------+\n' + '\n' + 'Note that unless a minimum field width is defined, the ' + 'field width\n' + 'will always be the same size as the data to fill it, so ' + 'that the\n' + 'alignment option has no meaning in this case.\n' + '\n' + 'The *sign* option is only valid for number types, and can ' + 'be one of\n' + 'the following:\n' + '\n' + '+-----------+------------------------------------------------------------+\n' + '| Option | ' + 'Meaning ' + '|\n' + '|===========|============================================================|\n' + '| "\'+\'" | indicates that a sign should be used for ' + 'both positive as |\n' + '| | well as negative ' + 'numbers. |\n' + '+-----------+------------------------------------------------------------+\n' + '| "\'-\'" | indicates that a sign should be used only ' + 'for negative |\n' + '| | numbers (this is the default ' + 'behavior). |\n' + '+-----------+------------------------------------------------------------+\n' + '| space | indicates that a leading space should be used ' + 'on positive |\n' + '| | numbers, and a minus sign on negative ' + 'numbers. |\n' + '+-----------+------------------------------------------------------------+\n' + '\n' + 'The "\'z\'" option coerces negative zero floating-point ' + 'values to\n' + 'positive zero after rounding to the format precision. This ' + 'option is\n' + 'only valid for floating-point presentation types.\n' + '\n' + 'Changed in version 3.11: Added the "\'z\'" option (see also ' + '**PEP\n' + '682**).\n' + '\n' + 'The "\'#\'" option causes the “alternate form” to be used ' + 'for the\n' + 'conversion. The alternate form is defined differently for ' + 'different\n' + 'types. This option is only valid for integer, float and ' + 'complex\n' + 'types. For integers, when binary, octal, or hexadecimal ' + 'output is\n' + 'used, this option adds the respective prefix "\'0b\'", ' + '"\'0o\'", "\'0x\'",\n' + 'or "\'0X\'" to the output value. For float and complex the ' + 'alternate\n' + 'form causes the result of the conversion to always contain ' + 'a decimal-\n' + 'point character, even if no digits follow it. Normally, a ' + 'decimal-\n' + 'point character appears in the result of these conversions ' + 'only if a\n' + 'digit follows it. In addition, for "\'g\'" and "\'G\'" ' + 'conversions,\n' + 'trailing zeros are not removed from the result.\n' + '\n' + 'The "\',\'" option signals the use of a comma for a ' + 'thousands separator.\n' + 'For a locale aware separator, use the "\'n\'" integer ' + 'presentation type\n' + 'instead.\n' + '\n' + 'Changed in version 3.1: Added the "\',\'" option (see also ' + '**PEP 378**).\n' + '\n' + 'The "\'_\'" option signals the use of an underscore for a ' + 'thousands\n' + 'separator for floating point presentation types and for ' + 'integer\n' + 'presentation type "\'d\'". For integer presentation types ' + '"\'b\'", "\'o\'",\n' + '"\'x\'", and "\'X\'", underscores will be inserted every 4 ' + 'digits. For\n' + 'other presentation types, specifying this option is an ' + 'error.\n' + '\n' + 'Changed in version 3.6: Added the "\'_\'" option (see also ' + '**PEP 515**).\n' + '\n' + '*width* is a decimal integer defining the minimum total ' + 'field width,\n' + 'including any prefixes, separators, and other formatting ' + 'characters.\n' + 'If not specified, then the field width will be determined ' + 'by the\n' + 'content.\n' + '\n' + 'When no explicit alignment is given, preceding the *width* ' + 'field by a\n' + 'zero ("\'0\'") character enables sign-aware zero-padding ' + 'for numeric\n' + 'types. This is equivalent to a *fill* character of "\'0\'" ' + 'with an\n' + '*alignment* type of "\'=\'".\n' + '\n' + 'Changed in version 3.10: Preceding the *width* field by ' + '"\'0\'" no\n' + 'longer affects the default alignment for strings.\n' + '\n' + 'The *precision* is a decimal integer indicating how many ' + 'digits should\n' + 'be displayed after the decimal point for presentation types ' + '"\'f\'" and\n' + '"\'F\'", or before and after the decimal point for ' + 'presentation types\n' + '"\'g\'" or "\'G\'". For string presentation types the ' + 'field indicates the\n' + 'maximum field size - in other words, how many characters ' + 'will be used\n' + 'from the field content. The *precision* is not allowed for ' + 'integer\n' + 'presentation types.\n' + '\n' + 'Finally, the *type* determines how the data should be ' + 'presented.\n' + '\n' + 'The available string presentation types are:\n' + '\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | Type | ' + 'Meaning ' + '|\n' + ' ' + '|===========|============================================================|\n' + ' | "\'s\'" | String format. This is the default type ' + 'for strings and |\n' + ' | | may be ' + 'omitted. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | None | The same as ' + '"\'s\'". |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + '\n' + 'The available integer presentation types are:\n' + '\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | Type | ' + 'Meaning ' + '|\n' + ' ' + '|===========|============================================================|\n' + ' | "\'b\'" | Binary format. Outputs the number in ' + 'base 2. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'c\'" | Character. Converts the integer to the ' + 'corresponding |\n' + ' | | unicode character before ' + 'printing. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'d\'" | Decimal Integer. Outputs the number in ' + 'base 10. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'o\'" | Octal format. Outputs the number in base ' + '8. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'x\'" | Hex format. Outputs the number in base ' + '16, using lower- |\n' + ' | | case letters for the digits above ' + '9. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'X\'" | Hex format. Outputs the number in base ' + '16, using upper- |\n' + ' | | case letters for the digits above 9. In ' + 'case "\'#\'" is |\n' + ' | | specified, the prefix "\'0x\'" will be ' + 'upper-cased to "\'0X\'" |\n' + ' | | as ' + 'well. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'n\'" | Number. This is the same as "\'d\'", ' + 'except that it uses the |\n' + ' | | current locale setting to insert the ' + 'appropriate number |\n' + ' | | separator ' + 'characters. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | None | The same as ' + '"\'d\'". |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + '\n' + 'In addition to the above presentation types, integers can ' + 'be formatted\n' + 'with the floating point presentation types listed below ' + '(except "\'n\'"\n' + 'and "None"). When doing so, "float()" is used to convert ' + 'the integer\n' + 'to a floating point number before formatting.\n' + '\n' + 'The available presentation types for "float" and "Decimal" ' + 'values are:\n' + '\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | Type | ' + 'Meaning ' + '|\n' + ' ' + '|===========|============================================================|\n' + ' | "\'e\'" | Scientific notation. For a given ' + 'precision "p", formats |\n' + ' | | the number in scientific notation with the ' + 'letter ‘e’ |\n' + ' | | separating the coefficient from the ' + 'exponent. The |\n' + ' | | coefficient has one digit before and "p" ' + 'digits after the |\n' + ' | | decimal point, for a total of "p + 1" ' + 'significant digits. |\n' + ' | | With no precision given, uses a precision ' + 'of "6" digits |\n' + ' | | after the decimal point for "float", and ' + 'shows all |\n' + ' | | coefficient digits for "Decimal". If no ' + 'digits follow the |\n' + ' | | decimal point, the decimal point is also ' + 'removed unless |\n' + ' | | the "#" option is ' + 'used. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'E\'" | Scientific notation. Same as "\'e\'" ' + 'except it uses an upper |\n' + ' | | case ‘E’ as the separator ' + 'character. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'f\'" | Fixed-point notation. For a given ' + 'precision "p", formats |\n' + ' | | the number as a decimal number with ' + 'exactly "p" digits |\n' + ' | | following the decimal point. With no ' + 'precision given, uses |\n' + ' | | a precision of "6" digits after the ' + 'decimal point for |\n' + ' | | "float", and uses a precision large enough ' + 'to show all |\n' + ' | | coefficient digits for "Decimal". If no ' + 'digits follow the |\n' + ' | | decimal point, the decimal point is also ' + 'removed unless |\n' + ' | | the "#" option is ' + 'used. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'F\'" | Fixed-point notation. Same as "\'f\'", ' + 'but converts "nan" to |\n' + ' | | "NAN" and "inf" to ' + '"INF". |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'g\'" | General format. For a given precision ' + '"p >= 1", this |\n' + ' | | rounds the number to "p" significant ' + 'digits and then |\n' + ' | | formats the result in either fixed-point ' + 'format or in |\n' + ' | | scientific notation, depending on its ' + 'magnitude. A |\n' + ' | | precision of "0" is treated as equivalent ' + 'to a precision |\n' + ' | | of "1". The precise rules are as follows: ' + 'suppose that |\n' + ' | | the result formatted with presentation ' + 'type "\'e\'" and |\n' + ' | | precision "p-1" would have exponent ' + '"exp". Then, if "m <= |\n' + ' | | exp < p", where "m" is -4 for floats and ' + '-6 for |\n' + ' | | "Decimals", the number is formatted with ' + 'presentation type |\n' + ' | | "\'f\'" and precision "p-1-exp". ' + 'Otherwise, the number is |\n' + ' | | formatted with presentation type "\'e\'" ' + 'and precision |\n' + ' | | "p-1". In both cases insignificant ' + 'trailing zeros are |\n' + ' | | removed from the significand, and the ' + 'decimal point is |\n' + ' | | also removed if there are no remaining ' + 'digits following |\n' + ' | | it, unless the "\'#\'" option is used. ' + 'With no precision |\n' + ' | | given, uses a precision of "6" significant ' + 'digits for |\n' + ' | | "float". For "Decimal", the coefficient of ' + 'the result is |\n' + ' | | formed from the coefficient digits of the ' + 'value; |\n' + ' | | scientific notation is used for values ' + 'smaller than "1e-6" |\n' + ' | | in absolute value and values where the ' + 'place value of the |\n' + ' | | least significant digit is larger than 1, ' + 'and fixed-point |\n' + ' | | notation is used otherwise. Positive and ' + 'negative |\n' + ' | | infinity, positive and negative zero, and ' + 'nans, are |\n' + ' | | formatted as "inf", "-inf", "0", "-0" and ' + '"nan" |\n' + ' | | respectively, regardless of the ' + 'precision. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'G\'" | General format. Same as "\'g\'" except ' + 'switches to "\'E\'" if |\n' + ' | | the number gets too large. The ' + 'representations of infinity |\n' + ' | | and NaN are uppercased, ' + 'too. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'n\'" | Number. This is the same as "\'g\'", ' + 'except that it uses the |\n' + ' | | current locale setting to insert the ' + 'appropriate number |\n' + ' | | separator ' + 'characters. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | "\'%\'" | Percentage. Multiplies the number by 100 ' + 'and displays in |\n' + ' | | fixed ("\'f\'") format, followed by a ' + 'percent sign. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + ' | None | For "float" this is the same as "\'g\'", ' + 'except that when |\n' + ' | | fixed-point notation is used to format the ' + 'result, it |\n' + ' | | always includes at least one digit past ' + 'the decimal point. |\n' + ' | | The precision used is as large as needed ' + 'to represent the |\n' + ' | | given value faithfully. For "Decimal", ' + 'this is the same |\n' + ' | | as either "\'g\'" or "\'G\'" depending on ' + 'the value of |\n' + ' | | "context.capitals" for the current decimal ' + 'context. The |\n' + ' | | overall effect is to match the output of ' + '"str()" as |\n' + ' | | altered by the other format ' + 'modifiers. |\n' + ' ' + '+-----------+------------------------------------------------------------+\n' + '\n' + '\n' + 'Format examples\n' + '===============\n' + '\n' + 'This section contains examples of the "str.format()" syntax ' + 'and\n' + 'comparison with the old "%"-formatting.\n' + '\n' + 'In most of the cases the syntax is similar to the old ' + '"%"-formatting,\n' + 'with the addition of the "{}" and with ":" used instead of ' + '"%". For\n' + 'example, "\'%03.2f\'" can be translated to "\'{:03.2f}\'".\n' + '\n' + 'The new format syntax also supports new and different ' + 'options, shown\n' + 'in the following examples.\n' + '\n' + 'Accessing arguments by position:\n' + '\n' + " >>> '{0}, {1}, {2}'.format('a', 'b', 'c')\n" + " 'a, b, c'\n" + " >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only\n" + " 'a, b, c'\n" + " >>> '{2}, {1}, {0}'.format('a', 'b', 'c')\n" + " 'c, b, a'\n" + " >>> '{2}, {1}, {0}'.format(*'abc') # unpacking " + 'argument sequence\n' + " 'c, b, a'\n" + " >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' " + 'indices can be repeated\n' + " 'abracadabra'\n" + '\n' + 'Accessing arguments by name:\n' + '\n' + " >>> 'Coordinates: {latitude}, " + "{longitude}'.format(latitude='37.24N', " + "longitude='-115.81W')\n" + " 'Coordinates: 37.24N, -115.81W'\n" + " >>> coord = {'latitude': '37.24N', 'longitude': " + "'-115.81W'}\n" + " >>> 'Coordinates: {latitude}, " + "{longitude}'.format(**coord)\n" + " 'Coordinates: 37.24N, -115.81W'\n" + '\n' + 'Accessing arguments’ attributes:\n' + '\n' + ' >>> c = 3-5j\n' + " >>> ('The complex number {0} is formed from the real " + "part {0.real} '\n" + " ... 'and the imaginary part {0.imag}.').format(c)\n" + " 'The complex number (3-5j) is formed from the real part " + "3.0 and the imaginary part -5.0.'\n" + ' >>> class Point:\n' + ' ... def __init__(self, x, y):\n' + ' ... self.x, self.y = x, y\n' + ' ... def __str__(self):\n' + " ... return 'Point({self.x}, " + "{self.y})'.format(self=self)\n" + ' ...\n' + ' >>> str(Point(4, 2))\n' + " 'Point(4, 2)'\n" + '\n' + 'Accessing arguments’ items:\n' + '\n' + ' >>> coord = (3, 5)\n' + " >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)\n" + " 'X: 3; Y: 5'\n" + '\n' + 'Replacing "%s" and "%r":\n' + '\n' + ' >>> "repr() shows quotes: {!r}; str() doesn\'t: ' + '{!s}".format(\'test1\', \'test2\')\n' + ' "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n' + '\n' + 'Aligning the text and specifying a width:\n' + '\n' + " >>> '{:<30}'.format('left aligned')\n" + " 'left aligned '\n" + " >>> '{:>30}'.format('right aligned')\n" + " ' right aligned'\n" + " >>> '{:^30}'.format('centered')\n" + " ' centered '\n" + " >>> '{:*^30}'.format('centered') # use '*' as a fill " + 'char\n' + " '***********centered***********'\n" + '\n' + 'Replacing "%+f", "%-f", and "% f" and specifying a sign:\n' + '\n' + " >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it " + 'always\n' + " '+3.140000; -3.140000'\n" + " >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space " + 'for positive numbers\n' + " ' 3.140000; -3.140000'\n" + " >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the " + "minus -- same as '{:f}; {:f}'\n" + " '3.140000; -3.140000'\n" + '\n' + 'Replacing "%x" and "%o" and converting the value to ' + 'different bases:\n' + '\n' + ' >>> # format also supports binary numbers\n' + ' >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: ' + '{0:b}".format(42)\n' + " 'int: 42; hex: 2a; oct: 52; bin: 101010'\n" + ' >>> # with 0x, 0o, or 0b as prefix:\n' + ' >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: ' + '{0:#b}".format(42)\n' + " 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'\n" + '\n' + 'Using the comma as a thousands separator:\n' + '\n' + " >>> '{:,}'.format(1234567890)\n" + " '1,234,567,890'\n" + '\n' + 'Expressing a percentage:\n' + '\n' + ' >>> points = 19\n' + ' >>> total = 22\n' + " >>> 'Correct answers: {:.2%}'.format(points/total)\n" + " 'Correct answers: 86.36%'\n" + '\n' + 'Using type-specific formatting:\n' + '\n' + ' >>> import datetime\n' + ' >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n' + " >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)\n" + " '2010-07-04 12:15:58'\n" + '\n' + 'Nesting arguments and more complex examples:\n' + '\n' + " >>> for align, text in zip('<^>', ['left', 'center', " + "'right']):\n" + " ... '{0:{fill}{align}16}'.format(text, fill=align, " + 'align=align)\n' + ' ...\n' + " 'left<<<<<<<<<<<<'\n" + " '^^^^^center^^^^^'\n" + " '>>>>>>>>>>>right'\n" + ' >>>\n' + ' >>> octets = [192, 168, 0, 1]\n' + " >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)\n" + " 'C0A80001'\n" + ' >>> int(_, 16)\n' + ' 3232235521\n' + ' >>>\n' + ' >>> width = 5\n' + ' >>> for num in range(5,12): \n' + " ... for base in 'dXob':\n" + " ... print('{0:{width}{base}}'.format(num, " + "base=base, width=width), end=' ')\n" + ' ... print()\n' + ' ...\n' + ' 5 5 5 101\n' + ' 6 6 6 110\n' + ' 7 7 7 111\n' + ' 8 8 10 1000\n' + ' 9 9 11 1001\n' + ' 10 A 12 1010\n' + ' 11 B 13 1011\n', + 'function': 'Function definitions\n' + '********************\n' + '\n' + 'A function definition defines a user-defined function object ' + '(see\n' + 'section The standard type hierarchy):\n' + '\n' + ' funcdef ::= [decorators] "def" funcname "(" ' + '[parameter_list] ")"\n' + ' ["->" expression] ":" suite\n' + ' decorators ::= decorator+\n' + ' decorator ::= "@" assignment_expression ' + 'NEWLINE\n' + ' parameter_list ::= defparameter ("," ' + 'defparameter)* "," "/" ["," [parameter_list_no_posonly]]\n' + ' | parameter_list_no_posonly\n' + ' parameter_list_no_posonly ::= defparameter ("," ' + 'defparameter)* ["," [parameter_list_starargs]]\n' + ' | parameter_list_starargs\n' + ' parameter_list_starargs ::= "*" [parameter] ("," ' + 'defparameter)* ["," ["**" parameter [","]]]\n' + ' | "**" parameter [","]\n' + ' parameter ::= identifier [":" expression]\n' + ' defparameter ::= parameter ["=" expression]\n' + ' funcname ::= identifier\n' + '\n' + 'A function definition is an executable statement. Its execution ' + 'binds\n' + 'the function name in the current local namespace to a function ' + 'object\n' + '(a wrapper around the executable code for the function). This\n' + 'function object contains a reference to the current global ' + 'namespace\n' + 'as the global namespace to be used when the function is called.\n' + '\n' + 'The function definition does not execute the function body; this ' + 'gets\n' + 'executed only when the function is called. [4]\n' + '\n' + 'A function definition may be wrapped by one or more *decorator*\n' + 'expressions. Decorator expressions are evaluated when the ' + 'function is\n' + 'defined, in the scope that contains the function definition. ' + 'The\n' + 'result must be a callable, which is invoked with the function ' + 'object\n' + 'as the only argument. The returned value is bound to the ' + 'function name\n' + 'instead of the function object. Multiple decorators are applied ' + 'in\n' + 'nested fashion. For example, the following code\n' + '\n' + ' @f1(arg)\n' + ' @f2\n' + ' def func(): pass\n' + '\n' + 'is roughly equivalent to\n' + '\n' + ' def func(): pass\n' + ' func = f1(arg)(f2(func))\n' + '\n' + 'except that the original function is not temporarily bound to ' + 'the name\n' + '"func".\n' + '\n' + 'Changed in version 3.9: Functions may be decorated with any ' + 'valid\n' + '"assignment_expression". Previously, the grammar was much more\n' + 'restrictive; see **PEP 614** for details.\n' + '\n' + 'When one or more *parameters* have the form *parameter* "="\n' + '*expression*, the function is said to have “default parameter ' + 'values.”\n' + 'For a parameter with a default value, the corresponding ' + '*argument* may\n' + 'be omitted from a call, in which case the parameter’s default ' + 'value is\n' + 'substituted. If a parameter has a default value, all following\n' + 'parameters up until the “"*"” must also have a default value — ' + 'this is\n' + 'a syntactic restriction that is not expressed by the grammar.\n' + '\n' + '**Default parameter values are evaluated from left to right when ' + 'the\n' + 'function definition is executed.** This means that the ' + 'expression is\n' + 'evaluated once, when the function is defined, and that the same ' + '“pre-\n' + 'computed” value is used for each call. This is especially ' + 'important\n' + 'to understand when a default parameter value is a mutable ' + 'object, such\n' + 'as a list or a dictionary: if the function modifies the object ' + '(e.g.\n' + 'by appending an item to a list), the default parameter value is ' + 'in\n' + 'effect modified. This is generally not what was intended. A ' + 'way\n' + 'around this is to use "None" as the default, and explicitly test ' + 'for\n' + 'it in the body of the function, e.g.:\n' + '\n' + ' def whats_on_the_telly(penguin=None):\n' + ' if penguin is None:\n' + ' penguin = []\n' + ' penguin.append("property of the zoo")\n' + ' return penguin\n' + '\n' + 'Function call semantics are described in more detail in section ' + 'Calls.\n' + 'A function call always assigns values to all parameters ' + 'mentioned in\n' + 'the parameter list, either from positional arguments, from ' + 'keyword\n' + 'arguments, or from default values. If the form “"*identifier"” ' + 'is\n' + 'present, it is initialized to a tuple receiving any excess ' + 'positional\n' + 'parameters, defaulting to the empty tuple. If the form\n' + '“"**identifier"” is present, it is initialized to a new ordered\n' + 'mapping receiving any excess keyword arguments, defaulting to a ' + 'new\n' + 'empty mapping of the same type. Parameters after “"*"” or\n' + '“"*identifier"” are keyword-only parameters and may only be ' + 'passed by\n' + 'keyword arguments. Parameters before “"/"” are positional-only\n' + 'parameters and may only be passed by positional arguments.\n' + '\n' + 'Changed in version 3.8: The "/" function parameter syntax may be ' + 'used\n' + 'to indicate positional-only parameters. See **PEP 570** for ' + 'details.\n' + '\n' + 'Parameters may have an *annotation* of the form “": ' + 'expression"”\n' + 'following the parameter name. Any parameter may have an ' + 'annotation,\n' + 'even those of the form "*identifier" or "**identifier". ' + 'Functions may\n' + 'have “return” annotation of the form “"-> expression"” after ' + 'the\n' + 'parameter list. These annotations can be any valid Python ' + 'expression.\n' + 'The presence of annotations does not change the semantics of a\n' + 'function. The annotation values are available as values of a\n' + 'dictionary keyed by the parameters’ names in the ' + '"__annotations__"\n' + 'attribute of the function object. If the "annotations" import ' + 'from\n' + '"__future__" is used, annotations are preserved as strings at ' + 'runtime\n' + 'which enables postponed evaluation. Otherwise, they are ' + 'evaluated\n' + 'when the function definition is executed. In this case ' + 'annotations\n' + 'may be evaluated in a different order than they appear in the ' + 'source\n' + 'code.\n' + '\n' + 'It is also possible to create anonymous functions (functions not ' + 'bound\n' + 'to a name), for immediate use in expressions. This uses lambda\n' + 'expressions, described in section Lambdas. Note that the ' + 'lambda\n' + 'expression is merely a shorthand for a simplified function ' + 'definition;\n' + 'a function defined in a “"def"” statement can be passed around ' + 'or\n' + 'assigned to another name just like a function defined by a ' + 'lambda\n' + 'expression. The “"def"” form is actually more powerful since ' + 'it\n' + 'allows the execution of multiple statements and annotations.\n' + '\n' + '**Programmer’s note:** Functions are first-class objects. A ' + '“"def"”\n' + 'statement executed inside a function definition defines a local\n' + 'function that can be returned or passed around. Free variables ' + 'used\n' + 'in the nested function can access the local variables of the ' + 'function\n' + 'containing the def. See section Naming and binding for ' + 'details.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3107** - Function Annotations\n' + ' The original specification for function annotations.\n' + '\n' + ' **PEP 484** - Type Hints\n' + ' Definition of a standard meaning for annotations: type ' + 'hints.\n' + '\n' + ' **PEP 526** - Syntax for Variable Annotations\n' + ' Ability to type hint variable declarations, including ' + 'class\n' + ' variables and instance variables.\n' + '\n' + ' **PEP 563** - Postponed Evaluation of Annotations\n' + ' Support for forward references within annotations by ' + 'preserving\n' + ' annotations in a string form at runtime instead of eager\n' + ' evaluation.\n' + '\n' + ' **PEP 318** - Decorators for Functions and Methods\n' + ' Function and method decorators were introduced. Class ' + 'decorators\n' + ' were introduced in **PEP 3129**.\n', + 'global': 'The "global" statement\n' + '**********************\n' + '\n' + ' global_stmt ::= "global" identifier ("," identifier)*\n' + '\n' + 'The "global" statement is a declaration which holds for the ' + 'entire\n' + 'current code block. It means that the listed identifiers are to ' + 'be\n' + 'interpreted as globals. It would be impossible to assign to a ' + 'global\n' + 'variable without "global", although free variables may refer to\n' + 'globals without being declared global.\n' + '\n' + 'Names listed in a "global" statement must not be used in the same ' + 'code\n' + 'block textually preceding that "global" statement.\n' + '\n' + 'Names listed in a "global" statement must not be defined as ' + 'formal\n' + 'parameters, or as targets in "with" statements or "except" ' + 'clauses, or\n' + 'in a "for" target list, "class" definition, function definition,\n' + '"import" statement, or variable annotation.\n' + '\n' + '**CPython implementation detail:** The current implementation does ' + 'not\n' + 'enforce some of these restrictions, but programs should not abuse ' + 'this\n' + 'freedom, as future implementations may enforce them or silently ' + 'change\n' + 'the meaning of the program.\n' + '\n' + '**Programmer’s note:** "global" is a directive to the parser. It\n' + 'applies only to code parsed at the same time as the "global"\n' + 'statement. In particular, a "global" statement contained in a ' + 'string\n' + 'or code object supplied to the built-in "exec()" function does ' + 'not\n' + 'affect the code block *containing* the function call, and code\n' + 'contained in such a string is unaffected by "global" statements in ' + 'the\n' + 'code containing the function call. The same applies to the ' + '"eval()"\n' + 'and "compile()" functions.\n', + 'id-classes': 'Reserved classes of identifiers\n' + '*******************************\n' + '\n' + 'Certain classes of identifiers (besides keywords) have ' + 'special\n' + 'meanings. These classes are identified by the patterns of ' + 'leading and\n' + 'trailing underscore characters:\n' + '\n' + '"_*"\n' + ' Not imported by "from module import *".\n' + '\n' + '"_"\n' + ' In a "case" pattern within a "match" statement, "_" is a ' + 'soft\n' + ' keyword that denotes a wildcard.\n' + '\n' + ' Separately, the interactive interpreter makes the result of ' + 'the\n' + ' last evaluation available in the variable "_". (It is ' + 'stored in the\n' + ' "builtins" module, alongside built-in functions like ' + '"print".)\n' + '\n' + ' Elsewhere, "_" is a regular identifier. It is often used to ' + 'name\n' + ' “special” items, but it is not special to Python itself.\n' + '\n' + ' Note:\n' + '\n' + ' The name "_" is often used in conjunction with\n' + ' internationalization; refer to the documentation for the\n' + ' "gettext" module for more information on this ' + 'convention.It is\n' + ' also commonly used for unused variables.\n' + '\n' + '"__*__"\n' + ' System-defined names, informally known as “dunder” names. ' + 'These\n' + ' names are defined by the interpreter and its ' + 'implementation\n' + ' (including the standard library). Current system names are\n' + ' discussed in the Special method names section and ' + 'elsewhere. More\n' + ' will likely be defined in future versions of Python. *Any* ' + 'use of\n' + ' "__*__" names, in any context, that does not follow ' + 'explicitly\n' + ' documented use, is subject to breakage without warning.\n' + '\n' + '"__*"\n' + ' Class-private names. Names in this category, when used ' + 'within the\n' + ' context of a class definition, are re-written to use a ' + 'mangled form\n' + ' to help avoid name clashes between “private” attributes of ' + 'base and\n' + ' derived classes. See section Identifiers (Names).\n', + 'identifiers': 'Identifiers and keywords\n' + '************************\n' + '\n' + 'Identifiers (also referred to as *names*) are described by ' + 'the\n' + 'following lexical definitions.\n' + '\n' + 'The syntax of identifiers in Python is based on the Unicode ' + 'standard\n' + 'annex UAX-31, with elaboration and changes as defined below; ' + 'see also\n' + '**PEP 3131** for further details.\n' + '\n' + 'Within the ASCII range (U+0001..U+007F), the valid characters ' + 'for\n' + 'identifiers are the same as in Python 2.x: the uppercase and ' + 'lowercase\n' + 'letters "A" through "Z", the underscore "_" and, except for ' + 'the first\n' + 'character, the digits "0" through "9".\n' + '\n' + 'Python 3.0 introduces additional characters from outside the ' + 'ASCII\n' + 'range (see **PEP 3131**). For these characters, the ' + 'classification\n' + 'uses the version of the Unicode Character Database as ' + 'included in the\n' + '"unicodedata" module.\n' + '\n' + 'Identifiers are unlimited in length. Case is significant.\n' + '\n' + ' identifier ::= xid_start xid_continue*\n' + ' id_start ::= \n' + ' id_continue ::= \n' + ' xid_start ::= \n' + ' xid_continue ::= \n' + '\n' + 'The Unicode category codes mentioned above stand for:\n' + '\n' + '* *Lu* - uppercase letters\n' + '\n' + '* *Ll* - lowercase letters\n' + '\n' + '* *Lt* - titlecase letters\n' + '\n' + '* *Lm* - modifier letters\n' + '\n' + '* *Lo* - other letters\n' + '\n' + '* *Nl* - letter numbers\n' + '\n' + '* *Mn* - nonspacing marks\n' + '\n' + '* *Mc* - spacing combining marks\n' + '\n' + '* *Nd* - decimal numbers\n' + '\n' + '* *Pc* - connector punctuations\n' + '\n' + '* *Other_ID_Start* - explicit list of characters in ' + 'PropList.txt to\n' + ' support backwards compatibility\n' + '\n' + '* *Other_ID_Continue* - likewise\n' + '\n' + 'All identifiers are converted into the normal form NFKC while ' + 'parsing;\n' + 'comparison of identifiers is based on NFKC.\n' + '\n' + 'A non-normative HTML file listing all valid identifier ' + 'characters for\n' + 'Unicode 14.0.0 can be found at\n' + 'https://www.unicode.org/Public/14.0.0/ucd/DerivedCoreProperties.txt\n' + '\n' + '\n' + 'Keywords\n' + '========\n' + '\n' + 'The following identifiers are used as reserved words, or ' + '*keywords* of\n' + 'the language, and cannot be used as ordinary identifiers. ' + 'They must\n' + 'be spelled exactly as written here:\n' + '\n' + ' False await else import pass\n' + ' None break except in raise\n' + ' True class finally is return\n' + ' and continue for lambda try\n' + ' as def from nonlocal while\n' + ' assert del global not with\n' + ' async elif if or yield\n' + '\n' + '\n' + 'Soft Keywords\n' + '=============\n' + '\n' + 'New in version 3.10.\n' + '\n' + 'Some identifiers are only reserved under specific contexts. ' + 'These are\n' + 'known as *soft keywords*. The identifiers "match", "case" ' + 'and "_" can\n' + 'syntactically act as keywords in contexts related to the ' + 'pattern\n' + 'matching statement, but this distinction is done at the ' + 'parser level,\n' + 'not when tokenizing.\n' + '\n' + 'As soft keywords, their use with pattern matching is possible ' + 'while\n' + 'still preserving compatibility with existing code that uses ' + '"match",\n' + '"case" and "_" as identifier names.\n' + '\n' + '\n' + 'Reserved classes of identifiers\n' + '===============================\n' + '\n' + 'Certain classes of identifiers (besides keywords) have ' + 'special\n' + 'meanings. These classes are identified by the patterns of ' + 'leading and\n' + 'trailing underscore characters:\n' + '\n' + '"_*"\n' + ' Not imported by "from module import *".\n' + '\n' + '"_"\n' + ' In a "case" pattern within a "match" statement, "_" is a ' + 'soft\n' + ' keyword that denotes a wildcard.\n' + '\n' + ' Separately, the interactive interpreter makes the result ' + 'of the\n' + ' last evaluation available in the variable "_". (It is ' + 'stored in the\n' + ' "builtins" module, alongside built-in functions like ' + '"print".)\n' + '\n' + ' Elsewhere, "_" is a regular identifier. It is often used ' + 'to name\n' + ' “special” items, but it is not special to Python itself.\n' + '\n' + ' Note:\n' + '\n' + ' The name "_" is often used in conjunction with\n' + ' internationalization; refer to the documentation for ' + 'the\n' + ' "gettext" module for more information on this ' + 'convention.It is\n' + ' also commonly used for unused variables.\n' + '\n' + '"__*__"\n' + ' System-defined names, informally known as “dunder” names. ' + 'These\n' + ' names are defined by the interpreter and its ' + 'implementation\n' + ' (including the standard library). Current system names ' + 'are\n' + ' discussed in the Special method names section and ' + 'elsewhere. More\n' + ' will likely be defined in future versions of Python. ' + '*Any* use of\n' + ' "__*__" names, in any context, that does not follow ' + 'explicitly\n' + ' documented use, is subject to breakage without warning.\n' + '\n' + '"__*"\n' + ' Class-private names. Names in this category, when used ' + 'within the\n' + ' context of a class definition, are re-written to use a ' + 'mangled form\n' + ' to help avoid name clashes between “private” attributes of ' + 'base and\n' + ' derived classes. See section Identifiers (Names).\n', + 'if': 'The "if" statement\n' + '******************\n' + '\n' + 'The "if" statement is used for conditional execution:\n' + '\n' + ' if_stmt ::= "if" assignment_expression ":" suite\n' + ' ("elif" assignment_expression ":" suite)*\n' + ' ["else" ":" suite]\n' + '\n' + 'It selects exactly one of the suites by evaluating the expressions ' + 'one\n' + 'by one until one is found to be true (see section Boolean operations\n' + 'for the definition of true and false); then that suite is executed\n' + '(and no other part of the "if" statement is executed or evaluated).\n' + 'If all expressions are false, the suite of the "else" clause, if\n' + 'present, is executed.\n', + 'imaginary': 'Imaginary literals\n' + '******************\n' + '\n' + 'Imaginary literals are described by the following lexical ' + 'definitions:\n' + '\n' + ' imagnumber ::= (floatnumber | digitpart) ("j" | "J")\n' + '\n' + 'An imaginary literal yields a complex number with a real part ' + 'of 0.0.\n' + 'Complex numbers are represented as a pair of floating point ' + 'numbers\n' + 'and have the same restrictions on their range. To create a ' + 'complex\n' + 'number with a nonzero real part, add a floating point number to ' + 'it,\n' + 'e.g., "(3+4j)". Some examples of imaginary literals:\n' + '\n' + ' 3.14j 10.j 10j .001j 1e100j 3.14e-10j ' + '3.14_15_93j\n', + 'import': 'The "import" statement\n' + '**********************\n' + '\n' + ' import_stmt ::= "import" module ["as" identifier] ("," ' + 'module ["as" identifier])*\n' + ' | "from" relative_module "import" identifier ' + '["as" identifier]\n' + ' ("," identifier ["as" identifier])*\n' + ' | "from" relative_module "import" "(" ' + 'identifier ["as" identifier]\n' + ' ("," identifier ["as" identifier])* [","] ")"\n' + ' | "from" relative_module "import" "*"\n' + ' module ::= (identifier ".")* identifier\n' + ' relative_module ::= "."* module | "."+\n' + '\n' + 'The basic import statement (no "from" clause) is executed in two\n' + 'steps:\n' + '\n' + '1. find a module, loading and initializing it if necessary\n' + '\n' + '2. define a name or names in the local namespace for the scope ' + 'where\n' + ' the "import" statement occurs.\n' + '\n' + 'When the statement contains multiple clauses (separated by commas) ' + 'the\n' + 'two steps are carried out separately for each clause, just as ' + 'though\n' + 'the clauses had been separated out into individual import ' + 'statements.\n' + '\n' + 'The details of the first step, finding and loading modules, are\n' + 'described in greater detail in the section on the import system, ' + 'which\n' + 'also describes the various types of packages and modules that can ' + 'be\n' + 'imported, as well as all the hooks that can be used to customize ' + 'the\n' + 'import system. Note that failures in this step may indicate ' + 'either\n' + 'that the module could not be located, *or* that an error occurred\n' + 'while initializing the module, which includes execution of the\n' + 'module’s code.\n' + '\n' + 'If the requested module is retrieved successfully, it will be ' + 'made\n' + 'available in the local namespace in one of three ways:\n' + '\n' + '* If the module name is followed by "as", then the name following ' + '"as"\n' + ' is bound directly to the imported module.\n' + '\n' + '* If no other name is specified, and the module being imported is ' + 'a\n' + ' top level module, the module’s name is bound in the local ' + 'namespace\n' + ' as a reference to the imported module\n' + '\n' + '* If the module being imported is *not* a top level module, then ' + 'the\n' + ' name of the top level package that contains the module is bound ' + 'in\n' + ' the local namespace as a reference to the top level package. ' + 'The\n' + ' imported module must be accessed using its full qualified name\n' + ' rather than directly\n' + '\n' + 'The "from" form uses a slightly more complex process:\n' + '\n' + '1. find the module specified in the "from" clause, loading and\n' + ' initializing it if necessary;\n' + '\n' + '2. for each of the identifiers specified in the "import" clauses:\n' + '\n' + ' 1. check if the imported module has an attribute by that name\n' + '\n' + ' 2. if not, attempt to import a submodule with that name and ' + 'then\n' + ' check the imported module again for that attribute\n' + '\n' + ' 3. if the attribute is not found, "ImportError" is raised.\n' + '\n' + ' 4. otherwise, a reference to that value is stored in the local\n' + ' namespace, using the name in the "as" clause if it is ' + 'present,\n' + ' otherwise using the attribute name\n' + '\n' + 'Examples:\n' + '\n' + ' import foo # foo imported and bound locally\n' + ' import foo.bar.baz # foo, foo.bar, and foo.bar.baz ' + 'imported, foo bound locally\n' + ' import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz ' + 'imported, foo.bar.baz bound as fbb\n' + ' from foo.bar import baz # foo, foo.bar, and foo.bar.baz ' + 'imported, foo.bar.baz bound as baz\n' + ' from foo import attr # foo imported and foo.attr bound as ' + 'attr\n' + '\n' + 'If the list of identifiers is replaced by a star ("\'*\'"), all ' + 'public\n' + 'names defined in the module are bound in the local namespace for ' + 'the\n' + 'scope where the "import" statement occurs.\n' + '\n' + 'The *public names* defined by a module are determined by checking ' + 'the\n' + 'module’s namespace for a variable named "__all__"; if defined, it ' + 'must\n' + 'be a sequence of strings which are names defined or imported by ' + 'that\n' + 'module. The names given in "__all__" are all considered public ' + 'and\n' + 'are required to exist. If "__all__" is not defined, the set of ' + 'public\n' + 'names includes all names found in the module’s namespace which do ' + 'not\n' + 'begin with an underscore character ("\'_\'"). "__all__" should ' + 'contain\n' + 'the entire public API. It is intended to avoid accidentally ' + 'exporting\n' + 'items that are not part of the API (such as library modules which ' + 'were\n' + 'imported and used within the module).\n' + '\n' + 'The wild card form of import — "from module import *" — is only\n' + 'allowed at the module level. Attempting to use it in class or\n' + 'function definitions will raise a "SyntaxError".\n' + '\n' + 'When specifying what module to import you do not have to specify ' + 'the\n' + 'absolute name of the module. When a module or package is ' + 'contained\n' + 'within another package it is possible to make a relative import ' + 'within\n' + 'the same top package without having to mention the package name. ' + 'By\n' + 'using leading dots in the specified module or package after "from" ' + 'you\n' + 'can specify how high to traverse up the current package hierarchy\n' + 'without specifying exact names. One leading dot means the current\n' + 'package where the module making the import exists. Two dots means ' + 'up\n' + 'one package level. Three dots is up two levels, etc. So if you ' + 'execute\n' + '"from . import mod" from a module in the "pkg" package then you ' + 'will\n' + 'end up importing "pkg.mod". If you execute "from ..subpkg2 import ' + 'mod"\n' + 'from within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\n' + 'specification for relative imports is contained in the Package\n' + 'Relative Imports section.\n' + '\n' + '"importlib.import_module()" is provided to support applications ' + 'that\n' + 'determine dynamically the modules to be loaded.\n' + '\n' + 'Raises an auditing event "import" with arguments "module", ' + '"filename",\n' + '"sys.path", "sys.meta_path", "sys.path_hooks".\n' + '\n' + '\n' + 'Future statements\n' + '=================\n' + '\n' + 'A *future statement* is a directive to the compiler that a ' + 'particular\n' + 'module should be compiled using syntax or semantics that will be\n' + 'available in a specified future release of Python where the ' + 'feature\n' + 'becomes standard.\n' + '\n' + 'The future statement is intended to ease migration to future ' + 'versions\n' + 'of Python that introduce incompatible changes to the language. ' + 'It\n' + 'allows use of the new features on a per-module basis before the\n' + 'release in which the feature becomes standard.\n' + '\n' + ' future_stmt ::= "from" "__future__" "import" feature ["as" ' + 'identifier]\n' + ' ("," feature ["as" identifier])*\n' + ' | "from" "__future__" "import" "(" feature ' + '["as" identifier]\n' + ' ("," feature ["as" identifier])* [","] ")"\n' + ' feature ::= identifier\n' + '\n' + 'A future statement must appear near the top of the module. The ' + 'only\n' + 'lines that can appear before a future statement are:\n' + '\n' + '* the module docstring (if any),\n' + '\n' + '* comments,\n' + '\n' + '* blank lines, and\n' + '\n' + '* other future statements.\n' + '\n' + 'The only feature that requires using the future statement is\n' + '"annotations" (see **PEP 563**).\n' + '\n' + 'All historical features enabled by the future statement are still\n' + 'recognized by Python 3. The list includes "absolute_import",\n' + '"division", "generators", "generator_stop", "unicode_literals",\n' + '"print_function", "nested_scopes" and "with_statement". They are ' + 'all\n' + 'redundant because they are always enabled, and only kept for ' + 'backwards\n' + 'compatibility.\n' + '\n' + 'A future statement is recognized and treated specially at compile\n' + 'time: Changes to the semantics of core constructs are often\n' + 'implemented by generating different code. It may even be the ' + 'case\n' + 'that a new feature introduces new incompatible syntax (such as a ' + 'new\n' + 'reserved word), in which case the compiler may need to parse the\n' + 'module differently. Such decisions cannot be pushed off until\n' + 'runtime.\n' + '\n' + 'For any given release, the compiler knows which feature names ' + 'have\n' + 'been defined, and raises a compile-time error if a future ' + 'statement\n' + 'contains a feature not known to it.\n' + '\n' + 'The direct runtime semantics are the same as for any import ' + 'statement:\n' + 'there is a standard module "__future__", described later, and it ' + 'will\n' + 'be imported in the usual way at the time the future statement is\n' + 'executed.\n' + '\n' + 'The interesting runtime semantics depend on the specific feature\n' + 'enabled by the future statement.\n' + '\n' + 'Note that there is nothing special about the statement:\n' + '\n' + ' import __future__ [as name]\n' + '\n' + 'That is not a future statement; it’s an ordinary import statement ' + 'with\n' + 'no special semantics or syntax restrictions.\n' + '\n' + 'Code compiled by calls to the built-in functions "exec()" and\n' + '"compile()" that occur in a module "M" containing a future ' + 'statement\n' + 'will, by default, use the new syntax or semantics associated with ' + 'the\n' + 'future statement. This can be controlled by optional arguments ' + 'to\n' + '"compile()" — see the documentation of that function for details.\n' + '\n' + 'A future statement typed at an interactive interpreter prompt ' + 'will\n' + 'take effect for the rest of the interpreter session. If an\n' + 'interpreter is started with the "-i" option, is passed a script ' + 'name\n' + 'to execute, and the script includes a future statement, it will be ' + 'in\n' + 'effect in the interactive session started after the script is\n' + 'executed.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 236** - Back to the __future__\n' + ' The original proposal for the __future__ mechanism.\n', + 'in': 'Membership test operations\n' + '**************************\n' + '\n' + 'The operators "in" and "not in" test for membership. "x in s"\n' + 'evaluates to "True" if *x* is a member of *s*, and "False" otherwise.\n' + '"x not in s" returns the negation of "x in s". All built-in ' + 'sequences\n' + 'and set types support this as well as dictionary, for which "in" ' + 'tests\n' + 'whether the dictionary has a given key. For container types such as\n' + 'list, tuple, set, frozenset, dict, or collections.deque, the\n' + 'expression "x in y" is equivalent to "any(x is e or x == e for e in\n' + 'y)".\n' + '\n' + 'For the string and bytes types, "x in y" is "True" if and only if *x*\n' + 'is a substring of *y*. An equivalent test is "y.find(x) != -1".\n' + 'Empty strings are always considered to be a substring of any other\n' + 'string, so """ in "abc"" will return "True".\n' + '\n' + 'For user-defined classes which define the "__contains__()" method, "x\n' + 'in y" returns "True" if "y.__contains__(x)" returns a true value, and\n' + '"False" otherwise.\n' + '\n' + 'For user-defined classes which do not define "__contains__()" but do\n' + 'define "__iter__()", "x in y" is "True" if some value "z", for which\n' + 'the expression "x is z or x == z" is true, is produced while ' + 'iterating\n' + 'over "y". If an exception is raised during the iteration, it is as if\n' + '"in" raised that exception.\n' + '\n' + 'Lastly, the old-style iteration protocol is tried: if a class defines\n' + '"__getitem__()", "x in y" is "True" if and only if there is a non-\n' + 'negative integer index *i* such that "x is y[i] or x == y[i]", and no\n' + 'lower integer index raises the "IndexError" exception. (If any other\n' + 'exception is raised, it is as if "in" raised that exception).\n' + '\n' + 'The operator "not in" is defined to have the inverse truth value of\n' + '"in".\n', + 'integers': 'Integer literals\n' + '****************\n' + '\n' + 'Integer literals are described by the following lexical ' + 'definitions:\n' + '\n' + ' integer ::= decinteger | bininteger | octinteger | ' + 'hexinteger\n' + ' decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] ' + '"0")*\n' + ' bininteger ::= "0" ("b" | "B") (["_"] bindigit)+\n' + ' octinteger ::= "0" ("o" | "O") (["_"] octdigit)+\n' + ' hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+\n' + ' nonzerodigit ::= "1"..."9"\n' + ' digit ::= "0"..."9"\n' + ' bindigit ::= "0" | "1"\n' + ' octdigit ::= "0"..."7"\n' + ' hexdigit ::= digit | "a"..."f" | "A"..."F"\n' + '\n' + 'There is no limit for the length of integer literals apart from ' + 'what\n' + 'can be stored in available memory.\n' + '\n' + 'Underscores are ignored for determining the numeric value of ' + 'the\n' + 'literal. They can be used to group digits for enhanced ' + 'readability.\n' + 'One underscore can occur between digits, and after base ' + 'specifiers\n' + 'like "0x".\n' + '\n' + 'Note that leading zeros in a non-zero decimal number are not ' + 'allowed.\n' + 'This is for disambiguation with C-style octal literals, which ' + 'Python\n' + 'used before version 3.0.\n' + '\n' + 'Some examples of integer literals:\n' + '\n' + ' 7 2147483647 0o177 0b100110111\n' + ' 3 79228162514264337593543950336 0o377 0xdeadbeef\n' + ' 100_000_000_000 0b_1110_0101\n' + '\n' + 'Changed in version 3.6: Underscores are now allowed for ' + 'grouping\n' + 'purposes in literals.\n', + 'lambda': 'Lambdas\n' + '*******\n' + '\n' + ' lambda_expr ::= "lambda" [parameter_list] ":" expression\n' + '\n' + 'Lambda expressions (sometimes called lambda forms) are used to ' + 'create\n' + 'anonymous functions. The expression "lambda parameters: ' + 'expression"\n' + 'yields a function object. The unnamed object behaves like a ' + 'function\n' + 'object defined with:\n' + '\n' + ' def (parameters):\n' + ' return expression\n' + '\n' + 'See section Function definitions for the syntax of parameter ' + 'lists.\n' + 'Note that functions created with lambda expressions cannot ' + 'contain\n' + 'statements or annotations.\n', + 'lists': 'List displays\n' + '*************\n' + '\n' + 'A list display is a possibly empty series of expressions enclosed ' + 'in\n' + 'square brackets:\n' + '\n' + ' list_display ::= "[" [starred_list | comprehension] "]"\n' + '\n' + 'A list display yields a new list object, the contents being ' + 'specified\n' + 'by either a list of expressions or a comprehension. When a comma-\n' + 'separated list of expressions is supplied, its elements are ' + 'evaluated\n' + 'from left to right and placed into the list object in that order.\n' + 'When a comprehension is supplied, the list is constructed from the\n' + 'elements resulting from the comprehension.\n', + 'naming': 'Naming and binding\n' + '******************\n' + '\n' + '\n' + 'Binding of names\n' + '================\n' + '\n' + '*Names* refer to objects. Names are introduced by name binding\n' + 'operations.\n' + '\n' + 'The following constructs bind names:\n' + '\n' + '* formal parameters to functions,\n' + '\n' + '* class definitions,\n' + '\n' + '* function definitions,\n' + '\n' + '* assignment expressions,\n' + '\n' + '* targets that are identifiers if occurring in an assignment:\n' + '\n' + ' * "for" loop header,\n' + '\n' + ' * after "as" in a "with" statement, "except" clause, "except*"\n' + ' clause, or in the as-pattern in structural pattern matching,\n' + '\n' + ' * in a capture pattern in structural pattern matching\n' + '\n' + '* "import" statements.\n' + '\n' + 'The "import" statement of the form "from ... import *" binds all ' + 'names\n' + 'defined in the imported module, except those beginning with an\n' + 'underscore. This form may only be used at the module level.\n' + '\n' + 'A target occurring in a "del" statement is also considered bound ' + 'for\n' + 'this purpose (though the actual semantics are to unbind the ' + 'name).\n' + '\n' + 'Each assignment or import statement occurs within a block defined ' + 'by a\n' + 'class or function definition or at the module level (the ' + 'top-level\n' + 'code block).\n' + '\n' + 'If a name is bound in a block, it is a local variable of that ' + 'block,\n' + 'unless declared as "nonlocal" or "global". If a name is bound at ' + 'the\n' + 'module level, it is a global variable. (The variables of the ' + 'module\n' + 'code block are local and global.) If a variable is used in a ' + 'code\n' + 'block but not defined there, it is a *free variable*.\n' + '\n' + 'Each occurrence of a name in the program text refers to the ' + '*binding*\n' + 'of that name established by the following name resolution rules.\n' + '\n' + '\n' + 'Resolution of names\n' + '===================\n' + '\n' + 'A *scope* defines the visibility of a name within a block. If a ' + 'local\n' + 'variable is defined in a block, its scope includes that block. If ' + 'the\n' + 'definition occurs in a function block, the scope extends to any ' + 'blocks\n' + 'contained within the defining one, unless a contained block ' + 'introduces\n' + 'a different binding for the name.\n' + '\n' + 'When a name is used in a code block, it is resolved using the ' + 'nearest\n' + 'enclosing scope. The set of all such scopes visible to a code ' + 'block\n' + 'is called the block’s *environment*.\n' + '\n' + 'When a name is not found at all, a "NameError" exception is ' + 'raised. If\n' + 'the current scope is a function scope, and the name refers to a ' + 'local\n' + 'variable that has not yet been bound to a value at the point where ' + 'the\n' + 'name is used, an "UnboundLocalError" exception is raised.\n' + '"UnboundLocalError" is a subclass of "NameError".\n' + '\n' + 'If a name binding operation occurs anywhere within a code block, ' + 'all\n' + 'uses of the name within the block are treated as references to ' + 'the\n' + 'current block. This can lead to errors when a name is used within ' + 'a\n' + 'block before it is bound. This rule is subtle. Python lacks\n' + 'declarations and allows name binding operations to occur anywhere\n' + 'within a code block. The local variables of a code block can be\n' + 'determined by scanning the entire text of the block for name ' + 'binding\n' + 'operations. See the FAQ entry on UnboundLocalError for examples.\n' + '\n' + 'If the "global" statement occurs within a block, all uses of the ' + 'names\n' + 'specified in the statement refer to the bindings of those names in ' + 'the\n' + 'top-level namespace. Names are resolved in the top-level ' + 'namespace by\n' + 'searching the global namespace, i.e. the namespace of the module\n' + 'containing the code block, and the builtins namespace, the ' + 'namespace\n' + 'of the module "builtins". The global namespace is searched ' + 'first. If\n' + 'the names are not found there, the builtins namespace is ' + 'searched.\n' + 'The "global" statement must precede all uses of the listed names.\n' + '\n' + 'The "global" statement has the same scope as a name binding ' + 'operation\n' + 'in the same block. If the nearest enclosing scope for a free ' + 'variable\n' + 'contains a global statement, the free variable is treated as a ' + 'global.\n' + '\n' + 'The "nonlocal" statement causes corresponding names to refer to\n' + 'previously bound variables in the nearest enclosing function ' + 'scope.\n' + '"SyntaxError" is raised at compile time if the given name does ' + 'not\n' + 'exist in any enclosing function scope.\n' + '\n' + 'The namespace for a module is automatically created the first time ' + 'a\n' + 'module is imported. The main module for a script is always ' + 'called\n' + '"__main__".\n' + '\n' + 'Class definition blocks and arguments to "exec()" and "eval()" ' + 'are\n' + 'special in the context of name resolution. A class definition is ' + 'an\n' + 'executable statement that may use and define names. These ' + 'references\n' + 'follow the normal rules for name resolution with an exception ' + 'that\n' + 'unbound local variables are looked up in the global namespace. ' + 'The\n' + 'namespace of the class definition becomes the attribute dictionary ' + 'of\n' + 'the class. The scope of names defined in a class block is limited ' + 'to\n' + 'the class block; it does not extend to the code blocks of methods ' + '–\n' + 'this includes comprehensions and generator expressions since they ' + 'are\n' + 'implemented using a function scope. This means that the ' + 'following\n' + 'will fail:\n' + '\n' + ' class A:\n' + ' a = 42\n' + ' b = list(a + i for i in range(10))\n' + '\n' + '\n' + 'Builtins and restricted execution\n' + '=================================\n' + '\n' + '**CPython implementation detail:** Users should not touch\n' + '"__builtins__"; it is strictly an implementation detail. Users\n' + 'wanting to override values in the builtins namespace should ' + '"import"\n' + 'the "builtins" module and modify its attributes appropriately.\n' + '\n' + 'The builtins namespace associated with the execution of a code ' + 'block\n' + 'is actually found by looking up the name "__builtins__" in its ' + 'global\n' + 'namespace; this should be a dictionary or a module (in the latter ' + 'case\n' + 'the module’s dictionary is used). By default, when in the ' + '"__main__"\n' + 'module, "__builtins__" is the built-in module "builtins"; when in ' + 'any\n' + 'other module, "__builtins__" is an alias for the dictionary of ' + 'the\n' + '"builtins" module itself.\n' + '\n' + '\n' + 'Interaction with dynamic features\n' + '=================================\n' + '\n' + 'Name resolution of free variables occurs at runtime, not at ' + 'compile\n' + 'time. This means that the following code will print 42:\n' + '\n' + ' i = 10\n' + ' def f():\n' + ' print(i)\n' + ' i = 42\n' + ' f()\n' + '\n' + 'The "eval()" and "exec()" functions do not have access to the ' + 'full\n' + 'environment for resolving names. Names may be resolved in the ' + 'local\n' + 'and global namespaces of the caller. Free variables are not ' + 'resolved\n' + 'in the nearest enclosing namespace, but in the global namespace. ' + '[1]\n' + 'The "exec()" and "eval()" functions have optional arguments to\n' + 'override the global and local namespace. If only one namespace ' + 'is\n' + 'specified, it is used for both.\n', + 'nonlocal': 'The "nonlocal" statement\n' + '************************\n' + '\n' + ' nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*\n' + '\n' + 'The "nonlocal" statement causes the listed identifiers to refer ' + 'to\n' + 'previously bound variables in the nearest enclosing scope ' + 'excluding\n' + 'globals. This is important because the default behavior for ' + 'binding is\n' + 'to search the local namespace first. The statement allows\n' + 'encapsulated code to rebind variables outside of the local ' + 'scope\n' + 'besides the global (module) scope.\n' + '\n' + 'Names listed in a "nonlocal" statement, unlike those listed in ' + 'a\n' + '"global" statement, must refer to pre-existing bindings in an\n' + 'enclosing scope (the scope in which a new binding should be ' + 'created\n' + 'cannot be determined unambiguously).\n' + '\n' + 'Names listed in a "nonlocal" statement must not collide with ' + 'pre-\n' + 'existing bindings in the local scope.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3104** - Access to Names in Outer Scopes\n' + ' The specification for the "nonlocal" statement.\n', + 'numbers': 'Numeric literals\n' + '****************\n' + '\n' + 'There are three types of numeric literals: integers, floating ' + 'point\n' + 'numbers, and imaginary numbers. There are no complex literals\n' + '(complex numbers can be formed by adding a real number and an\n' + 'imaginary number).\n' + '\n' + 'Note that numeric literals do not include a sign; a phrase like ' + '"-1"\n' + 'is actually an expression composed of the unary operator ‘"-"’ ' + 'and the\n' + 'literal "1".\n', + 'numeric-types': 'Emulating numeric types\n' + '***********************\n' + '\n' + 'The following methods can be defined to emulate numeric ' + 'objects.\n' + 'Methods corresponding to operations that are not supported ' + 'by the\n' + 'particular kind of number implemented (e.g., bitwise ' + 'operations for\n' + 'non-integral numbers) should be left undefined.\n' + '\n' + 'object.__add__(self, other)\n' + 'object.__sub__(self, other)\n' + 'object.__mul__(self, other)\n' + 'object.__matmul__(self, other)\n' + 'object.__truediv__(self, other)\n' + 'object.__floordiv__(self, other)\n' + 'object.__mod__(self, other)\n' + 'object.__divmod__(self, other)\n' + 'object.__pow__(self, other[, modulo])\n' + 'object.__lshift__(self, other)\n' + 'object.__rshift__(self, other)\n' + 'object.__and__(self, other)\n' + 'object.__xor__(self, other)\n' + 'object.__or__(self, other)\n' + '\n' + ' These methods are called to implement the binary ' + 'arithmetic\n' + ' operations ("+", "-", "*", "@", "/", "//", "%", ' + '"divmod()",\n' + ' "pow()", "**", "<<", ">>", "&", "^", "|"). For ' + 'instance, to\n' + ' evaluate the expression "x + y", where *x* is an ' + 'instance of a\n' + ' class that has an "__add__()" method, ' + '"type(x).__add__(x, y)" is\n' + ' called. The "__divmod__()" method should be the ' + 'equivalent to\n' + ' using "__floordiv__()" and "__mod__()"; it should not be ' + 'related to\n' + ' "__truediv__()". Note that "__pow__()" should be ' + 'defined to accept\n' + ' an optional third argument if the ternary version of the ' + 'built-in\n' + ' "pow()" function is to be supported.\n' + '\n' + ' If one of those methods does not support the operation ' + 'with the\n' + ' supplied arguments, it should return "NotImplemented".\n' + '\n' + 'object.__radd__(self, other)\n' + 'object.__rsub__(self, other)\n' + 'object.__rmul__(self, other)\n' + 'object.__rmatmul__(self, other)\n' + 'object.__rtruediv__(self, other)\n' + 'object.__rfloordiv__(self, other)\n' + 'object.__rmod__(self, other)\n' + 'object.__rdivmod__(self, other)\n' + 'object.__rpow__(self, other[, modulo])\n' + 'object.__rlshift__(self, other)\n' + 'object.__rrshift__(self, other)\n' + 'object.__rand__(self, other)\n' + 'object.__rxor__(self, other)\n' + 'object.__ror__(self, other)\n' + '\n' + ' These methods are called to implement the binary ' + 'arithmetic\n' + ' operations ("+", "-", "*", "@", "/", "//", "%", ' + '"divmod()",\n' + ' "pow()", "**", "<<", ">>", "&", "^", "|") with reflected ' + '(swapped)\n' + ' operands. These functions are only called if the left ' + 'operand does\n' + ' not support the corresponding operation [3] and the ' + 'operands are of\n' + ' different types. [4] For instance, to evaluate the ' + 'expression "x -\n' + ' y", where *y* is an instance of a class that has an ' + '"__rsub__()"\n' + ' method, "type(y).__rsub__(y, x)" is called if ' + '"type(x).__sub__(x,\n' + ' y)" returns "NotImplemented".\n' + '\n' + ' Note that ternary "pow()" will not try calling ' + '"__rpow__()" (the\n' + ' coercion rules would become too complicated).\n' + '\n' + ' Note:\n' + '\n' + ' If the right operand’s type is a subclass of the left ' + 'operand’s\n' + ' type and that subclass provides a different ' + 'implementation of the\n' + ' reflected method for the operation, this method will ' + 'be called\n' + ' before the left operand’s non-reflected method. This ' + 'behavior\n' + ' allows subclasses to override their ancestors’ ' + 'operations.\n' + '\n' + 'object.__iadd__(self, other)\n' + 'object.__isub__(self, other)\n' + 'object.__imul__(self, other)\n' + 'object.__imatmul__(self, other)\n' + 'object.__itruediv__(self, other)\n' + 'object.__ifloordiv__(self, other)\n' + 'object.__imod__(self, other)\n' + 'object.__ipow__(self, other[, modulo])\n' + 'object.__ilshift__(self, other)\n' + 'object.__irshift__(self, other)\n' + 'object.__iand__(self, other)\n' + 'object.__ixor__(self, other)\n' + 'object.__ior__(self, other)\n' + '\n' + ' These methods are called to implement the augmented ' + 'arithmetic\n' + ' assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", ' + '"**=",\n' + ' "<<=", ">>=", "&=", "^=", "|="). These methods should ' + 'attempt to\n' + ' do the operation in-place (modifying *self*) and return ' + 'the result\n' + ' (which could be, but does not have to be, *self*). If a ' + 'specific\n' + ' method is not defined, or if that method returns ' + '"NotImplemented",\n' + ' the augmented assignment falls back to the normal ' + 'methods. For\n' + ' instance, if *x* is an instance of a class with an ' + '"__iadd__()"\n' + ' method, "x += y" is equivalent to "x = x.__iadd__(y)" . ' + 'If\n' + ' "__iadd__()" does not exist, or if "x.__iadd__(y)" ' + 'returns\n' + ' "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" ' + 'are\n' + ' considered, as with the evaluation of "x + y". In ' + 'certain\n' + ' situations, augmented assignment can result in ' + 'unexpected errors\n' + ' (see Why does a_tuple[i] += [‘item’] raise an exception ' + 'when the\n' + ' addition works?), but this behavior is in fact part of ' + 'the data\n' + ' model.\n' + '\n' + 'object.__neg__(self)\n' + 'object.__pos__(self)\n' + 'object.__abs__(self)\n' + 'object.__invert__(self)\n' + '\n' + ' Called to implement the unary arithmetic operations ' + '("-", "+",\n' + ' "abs()" and "~").\n' + '\n' + 'object.__complex__(self)\n' + 'object.__int__(self)\n' + 'object.__float__(self)\n' + '\n' + ' Called to implement the built-in functions "complex()", ' + '"int()" and\n' + ' "float()". Should return a value of the appropriate ' + 'type.\n' + '\n' + 'object.__index__(self)\n' + '\n' + ' Called to implement "operator.index()", and whenever ' + 'Python needs\n' + ' to losslessly convert the numeric object to an integer ' + 'object (such\n' + ' as in slicing, or in the built-in "bin()", "hex()" and ' + '"oct()"\n' + ' functions). Presence of this method indicates that the ' + 'numeric\n' + ' object is an integer type. Must return an integer.\n' + '\n' + ' If "__int__()", "__float__()" and "__complex__()" are ' + 'not defined\n' + ' then corresponding built-in functions "int()", "float()" ' + 'and\n' + ' "complex()" fall back to "__index__()".\n' + '\n' + 'object.__round__(self[, ndigits])\n' + 'object.__trunc__(self)\n' + 'object.__floor__(self)\n' + 'object.__ceil__(self)\n' + '\n' + ' Called to implement the built-in function "round()" and ' + '"math"\n' + ' functions "trunc()", "floor()" and "ceil()". Unless ' + '*ndigits* is\n' + ' passed to "__round__()" all these methods should return ' + 'the value\n' + ' of the object truncated to an "Integral" (typically an ' + '"int").\n' + '\n' + ' The built-in function "int()" falls back to ' + '"__trunc__()" if\n' + ' neither "__int__()" nor "__index__()" is defined.\n' + '\n' + ' Changed in version 3.11: The delegation of "int()" to ' + '"__trunc__()"\n' + ' is deprecated.\n', + 'objects': 'Objects, values and types\n' + '*************************\n' + '\n' + '*Objects* are Python’s abstraction for data. All data in a ' + 'Python\n' + 'program is represented by objects or by relations between ' + 'objects. (In\n' + 'a sense, and in conformance to Von Neumann’s model of a “stored\n' + 'program computer”, code is also represented by objects.)\n' + '\n' + 'Every object has an identity, a type and a value. An object’s\n' + '*identity* never changes once it has been created; you may think ' + 'of it\n' + 'as the object’s address in memory. The "is" operator compares ' + 'the\n' + 'identity of two objects; the "id()" function returns an integer\n' + 'representing its identity.\n' + '\n' + '**CPython implementation detail:** For CPython, "id(x)" is the ' + 'memory\n' + 'address where "x" is stored.\n' + '\n' + 'An object’s type determines the operations that the object ' + 'supports\n' + '(e.g., “does it have a length?”) and also defines the possible ' + 'values\n' + 'for objects of that type. The "type()" function returns an ' + 'object’s\n' + 'type (which is an object itself). Like its identity, an ' + 'object’s\n' + '*type* is also unchangeable. [1]\n' + '\n' + 'The *value* of some objects can change. Objects whose value can\n' + 'change are said to be *mutable*; objects whose value is ' + 'unchangeable\n' + 'once they are created are called *immutable*. (The value of an\n' + 'immutable container object that contains a reference to a ' + 'mutable\n' + 'object can change when the latter’s value is changed; however ' + 'the\n' + 'container is still considered immutable, because the collection ' + 'of\n' + 'objects it contains cannot be changed. So, immutability is not\n' + 'strictly the same as having an unchangeable value, it is more ' + 'subtle.)\n' + 'An object’s mutability is determined by its type; for instance,\n' + 'numbers, strings and tuples are immutable, while dictionaries ' + 'and\n' + 'lists are mutable.\n' + '\n' + 'Objects are never explicitly destroyed; however, when they ' + 'become\n' + 'unreachable they may be garbage-collected. An implementation is\n' + 'allowed to postpone garbage collection or omit it altogether — it ' + 'is a\n' + 'matter of implementation quality how garbage collection is\n' + 'implemented, as long as no objects are collected that are still\n' + 'reachable.\n' + '\n' + '**CPython implementation detail:** CPython currently uses a ' + 'reference-\n' + 'counting scheme with (optional) delayed detection of cyclically ' + 'linked\n' + 'garbage, which collects most objects as soon as they become\n' + 'unreachable, but is not guaranteed to collect garbage containing\n' + 'circular references. See the documentation of the "gc" module ' + 'for\n' + 'information on controlling the collection of cyclic garbage. ' + 'Other\n' + 'implementations act differently and CPython may change. Do not ' + 'depend\n' + 'on immediate finalization of objects when they become unreachable ' + '(so\n' + 'you should always close files explicitly).\n' + '\n' + 'Note that the use of the implementation’s tracing or debugging\n' + 'facilities may keep objects alive that would normally be ' + 'collectable.\n' + 'Also note that catching an exception with a "try"…"except" ' + 'statement\n' + 'may keep objects alive.\n' + '\n' + 'Some objects contain references to “external” resources such as ' + 'open\n' + 'files or windows. It is understood that these resources are ' + 'freed\n' + 'when the object is garbage-collected, but since garbage ' + 'collection is\n' + 'not guaranteed to happen, such objects also provide an explicit ' + 'way to\n' + 'release the external resource, usually a "close()" method. ' + 'Programs\n' + 'are strongly recommended to explicitly close such objects. The\n' + '"try"…"finally" statement and the "with" statement provide ' + 'convenient\n' + 'ways to do this.\n' + '\n' + 'Some objects contain references to other objects; these are ' + 'called\n' + '*containers*. Examples of containers are tuples, lists and\n' + 'dictionaries. The references are part of a container’s value. ' + 'In\n' + 'most cases, when we talk about the value of a container, we imply ' + 'the\n' + 'values, not the identities of the contained objects; however, ' + 'when we\n' + 'talk about the mutability of a container, only the identities of ' + 'the\n' + 'immediately contained objects are implied. So, if an immutable\n' + 'container (like a tuple) contains a reference to a mutable ' + 'object, its\n' + 'value changes if that mutable object is changed.\n' + '\n' + 'Types affect almost all aspects of object behavior. Even the\n' + 'importance of object identity is affected in some sense: for ' + 'immutable\n' + 'types, operations that compute new values may actually return a\n' + 'reference to any existing object with the same type and value, ' + 'while\n' + 'for mutable objects this is not allowed. E.g., after "a = 1; b = ' + '1",\n' + '"a" and "b" may or may not refer to the same object with the ' + 'value\n' + 'one, depending on the implementation, but after "c = []; d = []", ' + '"c"\n' + 'and "d" are guaranteed to refer to two different, unique, newly\n' + 'created empty lists. (Note that "c = d = []" assigns the same ' + 'object\n' + 'to both "c" and "d".)\n', + 'operator-summary': 'Operator precedence\n' + '*******************\n' + '\n' + 'The following table summarizes the operator precedence ' + 'in Python, from\n' + 'highest precedence (most binding) to lowest precedence ' + '(least\n' + 'binding). Operators in the same box have the same ' + 'precedence. Unless\n' + 'the syntax is explicitly given, operators are binary. ' + 'Operators in\n' + 'the same box group left to right (except for ' + 'exponentiation and\n' + 'conditional expressions, which group from right to ' + 'left).\n' + '\n' + 'Note that comparisons, membership tests, and identity ' + 'tests, all have\n' + 'the same precedence and have a left-to-right chaining ' + 'feature as\n' + 'described in the Comparisons section.\n' + '\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| Operator | ' + 'Description |\n' + '|=================================================|=======================================|\n' + '| "(expressions...)", "[expressions...]", "{key: | ' + 'Binding or parenthesized expression, |\n' + '| value...}", "{expressions...}" | list ' + 'display, dictionary display, set |\n' + '| | ' + 'display |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "x[index]", "x[index:index]", | ' + 'Subscription, slicing, call, |\n' + '| "x(arguments...)", "x.attribute" | ' + 'attribute reference |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "await x" | ' + 'Await expression |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "**" | ' + 'Exponentiation [5] |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "+x", "-x", "~x" | ' + 'Positive, negative, bitwise NOT |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "*", "@", "/", "//", "%" | ' + 'Multiplication, matrix |\n' + '| | ' + 'multiplication, division, floor |\n' + '| | ' + 'division, remainder [6] |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "+", "-" | ' + 'Addition and subtraction |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "<<", ">>" | ' + 'Shifts |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "&" | ' + 'Bitwise AND |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "^" | ' + 'Bitwise XOR |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "|" | ' + 'Bitwise OR |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "in", "not in", "is", "is not", "<", "<=", ">", | ' + 'Comparisons, including membership |\n' + '| ">=", "!=", "==" | ' + 'tests and identity tests |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "not x" | ' + 'Boolean NOT |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "and" | ' + 'Boolean AND |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "or" | ' + 'Boolean OR |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "if" – "else" | ' + 'Conditional expression |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| "lambda" | ' + 'Lambda expression |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '| ":=" | ' + 'Assignment expression |\n' + '+-------------------------------------------------+---------------------------------------+\n' + '\n' + '-[ Footnotes ]-\n' + '\n' + '[1] While "abs(x%y) < abs(y)" is true mathematically, ' + 'for floats it\n' + ' may not be true numerically due to roundoff. For ' + 'example, and\n' + ' assuming a platform on which a Python float is an ' + 'IEEE 754 double-\n' + ' precision number, in order that "-1e-100 % 1e100" ' + 'have the same\n' + ' sign as "1e100", the computed result is "-1e-100 + ' + '1e100", which\n' + ' is numerically exactly equal to "1e100". The ' + 'function\n' + ' "math.fmod()" returns a result whose sign matches ' + 'the sign of the\n' + ' first argument instead, and so returns "-1e-100" in ' + 'this case.\n' + ' Which approach is more appropriate depends on the ' + 'application.\n' + '\n' + '[2] If x is very close to an exact integer multiple of ' + 'y, it’s\n' + ' possible for "x//y" to be one larger than ' + '"(x-x%y)//y" due to\n' + ' rounding. In such cases, Python returns the latter ' + 'result, in\n' + ' order to preserve that "divmod(x,y)[0] * y + x % y" ' + 'be very close\n' + ' to "x".\n' + '\n' + '[3] The Unicode standard distinguishes between *code ' + 'points* (e.g.\n' + ' U+0041) and *abstract characters* (e.g. “LATIN ' + 'CAPITAL LETTER A”).\n' + ' While most abstract characters in Unicode are only ' + 'represented\n' + ' using one code point, there is a number of abstract ' + 'characters\n' + ' that can in addition be represented using a sequence ' + 'of more than\n' + ' one code point. For example, the abstract character ' + '“LATIN\n' + ' CAPITAL LETTER C WITH CEDILLA” can be represented as ' + 'a single\n' + ' *precomposed character* at code position U+00C7, or ' + 'as a sequence\n' + ' of a *base character* at code position U+0043 (LATIN ' + 'CAPITAL\n' + ' LETTER C), followed by a *combining character* at ' + 'code position\n' + ' U+0327 (COMBINING CEDILLA).\n' + '\n' + ' The comparison operators on strings compare at the ' + 'level of\n' + ' Unicode code points. This may be counter-intuitive ' + 'to humans. For\n' + ' example, ""\\u00C7" == "\\u0043\\u0327"" is "False", ' + 'even though both\n' + ' strings represent the same abstract character “LATIN ' + 'CAPITAL\n' + ' LETTER C WITH CEDILLA”.\n' + '\n' + ' To compare strings at the level of abstract ' + 'characters (that is,\n' + ' in a way intuitive to humans), use ' + '"unicodedata.normalize()".\n' + '\n' + '[4] Due to automatic garbage-collection, free lists, and ' + 'the dynamic\n' + ' nature of descriptors, you may notice seemingly ' + 'unusual behaviour\n' + ' in certain uses of the "is" operator, like those ' + 'involving\n' + ' comparisons between instance methods, or constants. ' + 'Check their\n' + ' documentation for more info.\n' + '\n' + '[5] The power operator "**" binds less tightly than an ' + 'arithmetic or\n' + ' bitwise unary operator on its right, that is, ' + '"2**-1" is "0.5".\n' + '\n' + '[6] The "%" operator is also used for string formatting; ' + 'the same\n' + ' precedence applies.\n', + 'pass': 'The "pass" statement\n' + '********************\n' + '\n' + ' pass_stmt ::= "pass"\n' + '\n' + '"pass" is a null operation — when it is executed, nothing happens. ' + 'It\n' + 'is useful as a placeholder when a statement is required ' + 'syntactically,\n' + 'but no code needs to be executed, for example:\n' + '\n' + ' def f(arg): pass # a function that does nothing (yet)\n' + '\n' + ' class C: pass # a class with no methods (yet)\n', + 'power': 'The power operator\n' + '******************\n' + '\n' + 'The power operator binds more tightly than unary operators on its\n' + 'left; it binds less tightly than unary operators on its right. ' + 'The\n' + 'syntax is:\n' + '\n' + ' power ::= (await_expr | primary) ["**" u_expr]\n' + '\n' + 'Thus, in an unparenthesized sequence of power and unary operators, ' + 'the\n' + 'operators are evaluated from right to left (this does not ' + 'constrain\n' + 'the evaluation order for the operands): "-1**2" results in "-1".\n' + '\n' + 'The power operator has the same semantics as the built-in "pow()"\n' + 'function, when called with two arguments: it yields its left ' + 'argument\n' + 'raised to the power of its right argument. The numeric arguments ' + 'are\n' + 'first converted to a common type, and the result is of that type.\n' + '\n' + 'For int operands, the result has the same type as the operands ' + 'unless\n' + 'the second argument is negative; in that case, all arguments are\n' + 'converted to float and a float result is delivered. For example,\n' + '"10**2" returns "100", but "10**-2" returns "0.01".\n' + '\n' + 'Raising "0.0" to a negative power results in a ' + '"ZeroDivisionError".\n' + 'Raising a negative number to a fractional power results in a ' + '"complex"\n' + 'number. (In earlier versions it raised a "ValueError".)\n' + '\n' + 'This operation can be customized using the special "__pow__()" ' + 'method.\n', + 'raise': 'The "raise" statement\n' + '*********************\n' + '\n' + ' raise_stmt ::= "raise" [expression ["from" expression]]\n' + '\n' + 'If no expressions are present, "raise" re-raises the exception that ' + 'is\n' + 'currently being handled, which is also known as the *active\n' + 'exception*. If there isn’t currently an active exception, a\n' + '"RuntimeError" exception is raised indicating that this is an ' + 'error.\n' + '\n' + 'Otherwise, "raise" evaluates the first expression as the exception\n' + 'object. It must be either a subclass or an instance of\n' + '"BaseException". If it is a class, the exception instance will be\n' + 'obtained when needed by instantiating the class with no arguments.\n' + '\n' + 'The *type* of the exception is the exception instance’s class, the\n' + '*value* is the instance itself.\n' + '\n' + 'A traceback object is normally created automatically when an ' + 'exception\n' + 'is raised and attached to it as the "__traceback__" attribute. You ' + 'can\n' + 'create an exception and set your own traceback in one step using ' + 'the\n' + '"with_traceback()" exception method (which returns the same ' + 'exception\n' + 'instance, with its traceback set to its argument), like so:\n' + '\n' + ' raise Exception("foo occurred").with_traceback(tracebackobj)\n' + '\n' + 'The "from" clause is used for exception chaining: if given, the ' + 'second\n' + '*expression* must be another exception class or instance. If the\n' + 'second expression is an exception instance, it will be attached to ' + 'the\n' + 'raised exception as the "__cause__" attribute (which is writable). ' + 'If\n' + 'the expression is an exception class, the class will be ' + 'instantiated\n' + 'and the resulting exception instance will be attached to the ' + 'raised\n' + 'exception as the "__cause__" attribute. If the raised exception is ' + 'not\n' + 'handled, both exceptions will be printed:\n' + '\n' + ' >>> try:\n' + ' ... print(1 / 0)\n' + ' ... except Exception as exc:\n' + ' ... raise RuntimeError("Something bad happened") from exc\n' + ' ...\n' + ' Traceback (most recent call last):\n' + ' File "", line 2, in \n' + ' print(1 / 0)\n' + ' ~~^~~\n' + ' ZeroDivisionError: division by zero\n' + '\n' + ' The above exception was the direct cause of the following ' + 'exception:\n' + '\n' + ' Traceback (most recent call last):\n' + ' File "", line 4, in \n' + ' raise RuntimeError("Something bad happened") from exc\n' + ' RuntimeError: Something bad happened\n' + '\n' + 'A similar mechanism works implicitly if a new exception is raised ' + 'when\n' + 'an exception is already being handled. An exception may be ' + 'handled\n' + 'when an "except" or "finally" clause, or a "with" statement, is ' + 'used.\n' + 'The previous exception is then attached as the new exception’s\n' + '"__context__" attribute:\n' + '\n' + ' >>> try:\n' + ' ... print(1 / 0)\n' + ' ... except:\n' + ' ... raise RuntimeError("Something bad happened")\n' + ' ...\n' + ' Traceback (most recent call last):\n' + ' File "", line 2, in \n' + ' print(1 / 0)\n' + ' ~~^~~\n' + ' ZeroDivisionError: division by zero\n' + '\n' + ' During handling of the above exception, another exception ' + 'occurred:\n' + '\n' + ' Traceback (most recent call last):\n' + ' File "", line 4, in \n' + ' raise RuntimeError("Something bad happened")\n' + ' RuntimeError: Something bad happened\n' + '\n' + 'Exception chaining can be explicitly suppressed by specifying ' + '"None"\n' + 'in the "from" clause:\n' + '\n' + ' >>> try:\n' + ' ... print(1 / 0)\n' + ' ... except:\n' + ' ... raise RuntimeError("Something bad happened") from None\n' + ' ...\n' + ' Traceback (most recent call last):\n' + ' File "", line 4, in \n' + ' RuntimeError: Something bad happened\n' + '\n' + 'Additional information on exceptions can be found in section\n' + 'Exceptions, and information about handling exceptions is in ' + 'section\n' + 'The try statement.\n' + '\n' + 'Changed in version 3.3: "None" is now permitted as "Y" in "raise X\n' + 'from Y".Added the "__suppress_context__" attribute to suppress\n' + 'automatic display of the exception context.\n' + '\n' + 'Changed in version 3.11: If the traceback of the active exception ' + 'is\n' + 'modified in an "except" clause, a subsequent "raise" statement re-\n' + 'raises the exception with the modified traceback. Previously, the\n' + 'exception was re-raised with the traceback it had when it was ' + 'caught.\n', + 'return': 'The "return" statement\n' + '**********************\n' + '\n' + ' return_stmt ::= "return" [expression_list]\n' + '\n' + '"return" may only occur syntactically nested in a function ' + 'definition,\n' + 'not within a nested class definition.\n' + '\n' + 'If an expression list is present, it is evaluated, else "None" is\n' + 'substituted.\n' + '\n' + '"return" leaves the current function call with the expression list ' + '(or\n' + '"None") as return value.\n' + '\n' + 'When "return" passes control out of a "try" statement with a ' + '"finally"\n' + 'clause, that "finally" clause is executed before really leaving ' + 'the\n' + 'function.\n' + '\n' + 'In a generator function, the "return" statement indicates that ' + 'the\n' + 'generator is done and will cause "StopIteration" to be raised. ' + 'The\n' + 'returned value (if any) is used as an argument to construct\n' + '"StopIteration" and becomes the "StopIteration.value" attribute.\n' + '\n' + 'In an asynchronous generator function, an empty "return" ' + 'statement\n' + 'indicates that the asynchronous generator is done and will cause\n' + '"StopAsyncIteration" to be raised. A non-empty "return" statement ' + 'is\n' + 'a syntax error in an asynchronous generator function.\n', + 'sequence-types': 'Emulating container types\n' + '*************************\n' + '\n' + 'The following methods can be defined to implement ' + 'container objects.\n' + 'Containers usually are *sequences* (such as "lists" or ' + '"tuples") or\n' + '*mappings* (like "dictionaries"), but can represent other ' + 'containers\n' + 'as well. The first set of methods is used either to ' + 'emulate a\n' + 'sequence or to emulate a mapping; the difference is that ' + 'for a\n' + 'sequence, the allowable keys should be the integers *k* ' + 'for which "0\n' + '<= k < N" where *N* is the length of the sequence, or ' + '"slice" objects,\n' + 'which define a range of items. It is also recommended ' + 'that mappings\n' + 'provide the methods "keys()", "values()", "items()", ' + '"get()",\n' + '"clear()", "setdefault()", "pop()", "popitem()", "copy()", ' + 'and\n' + '"update()" behaving similar to those for Python’s ' + 'standard\n' + '"dictionary" objects. The "collections.abc" module ' + 'provides a\n' + '"MutableMapping" *abstract base class* to help create ' + 'those methods\n' + 'from a base set of "__getitem__()", "__setitem__()", ' + '"__delitem__()",\n' + 'and "keys()". Mutable sequences should provide methods ' + '"append()",\n' + '"count()", "index()", "extend()", "insert()", "pop()", ' + '"remove()",\n' + '"reverse()" and "sort()", like Python standard "list" ' + 'objects.\n' + 'Finally, sequence types should implement addition ' + '(meaning\n' + 'concatenation) and multiplication (meaning repetition) by ' + 'defining the\n' + 'methods "__add__()", "__radd__()", "__iadd__()", ' + '"__mul__()",\n' + '"__rmul__()" and "__imul__()" described below; they should ' + 'not define\n' + 'other numerical operators. It is recommended that both ' + 'mappings and\n' + 'sequences implement the "__contains__()" method to allow ' + 'efficient use\n' + 'of the "in" operator; for mappings, "in" should search the ' + 'mapping’s\n' + 'keys; for sequences, it should search through the values. ' + 'It is\n' + 'further recommended that both mappings and sequences ' + 'implement the\n' + '"__iter__()" method to allow efficient iteration through ' + 'the\n' + 'container; for mappings, "__iter__()" should iterate ' + 'through the\n' + 'object’s keys; for sequences, it should iterate through ' + 'the values.\n' + '\n' + 'object.__len__(self)\n' + '\n' + ' Called to implement the built-in function "len()". ' + 'Should return\n' + ' the length of the object, an integer ">=" 0. Also, an ' + 'object that\n' + ' doesn’t define a "__bool__()" method and whose ' + '"__len__()" method\n' + ' returns zero is considered to be false in a Boolean ' + 'context.\n' + '\n' + ' **CPython implementation detail:** In CPython, the ' + 'length is\n' + ' required to be at most "sys.maxsize". If the length is ' + 'larger than\n' + ' "sys.maxsize" some features (such as "len()") may ' + 'raise\n' + ' "OverflowError". To prevent raising "OverflowError" by ' + 'truth value\n' + ' testing, an object must define a "__bool__()" method.\n' + '\n' + 'object.__length_hint__(self)\n' + '\n' + ' Called to implement "operator.length_hint()". Should ' + 'return an\n' + ' estimated length for the object (which may be greater ' + 'or less than\n' + ' the actual length). The length must be an integer ">=" ' + '0. The\n' + ' return value may also be "NotImplemented", which is ' + 'treated the\n' + ' same as if the "__length_hint__" method didn’t exist at ' + 'all. This\n' + ' method is purely an optimization and is never required ' + 'for\n' + ' correctness.\n' + '\n' + ' New in version 3.4.\n' + '\n' + 'Note:\n' + '\n' + ' Slicing is done exclusively with the following three ' + 'methods. A\n' + ' call like\n' + '\n' + ' a[1:2] = b\n' + '\n' + ' is translated to\n' + '\n' + ' a[slice(1, 2, None)] = b\n' + '\n' + ' and so forth. Missing slice items are always filled in ' + 'with "None".\n' + '\n' + 'object.__getitem__(self, key)\n' + '\n' + ' Called to implement evaluation of "self[key]". For ' + '*sequence*\n' + ' types, the accepted keys should be integers. ' + 'Optionally, they may\n' + ' support "slice" objects as well. Negative index ' + 'support is also\n' + ' optional. If *key* is of an inappropriate type, ' + '"TypeError" may be\n' + ' raised; if *key* is a value outside the set of indexes ' + 'for the\n' + ' sequence (after any special interpretation of negative ' + 'values),\n' + ' "IndexError" should be raised. For *mapping* types, if ' + '*key* is\n' + ' missing (not in the container), "KeyError" should be ' + 'raised.\n' + '\n' + ' Note:\n' + '\n' + ' "for" loops expect that an "IndexError" will be ' + 'raised for\n' + ' illegal indexes to allow proper detection of the end ' + 'of the\n' + ' sequence.\n' + '\n' + ' Note:\n' + '\n' + ' When subscripting a *class*, the special class ' + 'method\n' + ' "__class_getitem__()" may be called instead of ' + '"__getitem__()".\n' + ' See __class_getitem__ versus __getitem__ for more ' + 'details.\n' + '\n' + 'object.__setitem__(self, key, value)\n' + '\n' + ' Called to implement assignment to "self[key]". Same ' + 'note as for\n' + ' "__getitem__()". This should only be implemented for ' + 'mappings if\n' + ' the objects support changes to the values for keys, or ' + 'if new keys\n' + ' can be added, or for sequences if elements can be ' + 'replaced. The\n' + ' same exceptions should be raised for improper *key* ' + 'values as for\n' + ' the "__getitem__()" method.\n' + '\n' + 'object.__delitem__(self, key)\n' + '\n' + ' Called to implement deletion of "self[key]". Same note ' + 'as for\n' + ' "__getitem__()". This should only be implemented for ' + 'mappings if\n' + ' the objects support removal of keys, or for sequences ' + 'if elements\n' + ' can be removed from the sequence. The same exceptions ' + 'should be\n' + ' raised for improper *key* values as for the ' + '"__getitem__()" method.\n' + '\n' + 'object.__missing__(self, key)\n' + '\n' + ' Called by "dict"."__getitem__()" to implement ' + '"self[key]" for dict\n' + ' subclasses when key is not in the dictionary.\n' + '\n' + 'object.__iter__(self)\n' + '\n' + ' This method is called when an *iterator* is required ' + 'for a\n' + ' container. This method should return a new iterator ' + 'object that can\n' + ' iterate over all the objects in the container. For ' + 'mappings, it\n' + ' should iterate over the keys of the container.\n' + '\n' + 'object.__reversed__(self)\n' + '\n' + ' Called (if present) by the "reversed()" built-in to ' + 'implement\n' + ' reverse iteration. It should return a new iterator ' + 'object that\n' + ' iterates over all the objects in the container in ' + 'reverse order.\n' + '\n' + ' If the "__reversed__()" method is not provided, the ' + '"reversed()"\n' + ' built-in will fall back to using the sequence protocol ' + '("__len__()"\n' + ' and "__getitem__()"). Objects that support the ' + 'sequence protocol\n' + ' should only provide "__reversed__()" if they can ' + 'provide an\n' + ' implementation that is more efficient than the one ' + 'provided by\n' + ' "reversed()".\n' + '\n' + 'The membership test operators ("in" and "not in") are ' + 'normally\n' + 'implemented as an iteration through a container. However, ' + 'container\n' + 'objects can supply the following special method with a ' + 'more efficient\n' + 'implementation, which also does not require the object be ' + 'iterable.\n' + '\n' + 'object.__contains__(self, item)\n' + '\n' + ' Called to implement membership test operators. Should ' + 'return true\n' + ' if *item* is in *self*, false otherwise. For mapping ' + 'objects, this\n' + ' should consider the keys of the mapping rather than the ' + 'values or\n' + ' the key-item pairs.\n' + '\n' + ' For objects that don’t define "__contains__()", the ' + 'membership test\n' + ' first tries iteration via "__iter__()", then the old ' + 'sequence\n' + ' iteration protocol via "__getitem__()", see this ' + 'section in the\n' + ' language reference.\n', + 'shifting': 'Shifting operations\n' + '*******************\n' + '\n' + 'The shifting operations have lower priority than the arithmetic\n' + 'operations:\n' + '\n' + ' shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr\n' + '\n' + 'These operators accept integers as arguments. They shift the ' + 'first\n' + 'argument to the left or right by the number of bits given by ' + 'the\n' + 'second argument.\n' + '\n' + 'This operation can be customized using the special ' + '"__lshift__()" and\n' + '"__rshift__()" methods.\n' + '\n' + 'A right shift by *n* bits is defined as floor division by ' + '"pow(2,n)".\n' + 'A left shift by *n* bits is defined as multiplication with ' + '"pow(2,n)".\n', + 'slicings': 'Slicings\n' + '********\n' + '\n' + 'A slicing selects a range of items in a sequence object (e.g., ' + 'a\n' + 'string, tuple or list). Slicings may be used as expressions or ' + 'as\n' + 'targets in assignment or "del" statements. The syntax for a ' + 'slicing:\n' + '\n' + ' slicing ::= primary "[" slice_list "]"\n' + ' slice_list ::= slice_item ("," slice_item)* [","]\n' + ' slice_item ::= expression | proper_slice\n' + ' proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" ' + '[stride] ]\n' + ' lower_bound ::= expression\n' + ' upper_bound ::= expression\n' + ' stride ::= expression\n' + '\n' + 'There is ambiguity in the formal syntax here: anything that ' + 'looks like\n' + 'an expression list also looks like a slice list, so any ' + 'subscription\n' + 'can be interpreted as a slicing. Rather than further ' + 'complicating the\n' + 'syntax, this is disambiguated by defining that in this case the\n' + 'interpretation as a subscription takes priority over the\n' + 'interpretation as a slicing (this is the case if the slice list\n' + 'contains no proper slice).\n' + '\n' + 'The semantics for a slicing are as follows. The primary is ' + 'indexed\n' + '(using the same "__getitem__()" method as normal subscription) ' + 'with a\n' + 'key that is constructed from the slice list, as follows. If the ' + 'slice\n' + 'list contains at least one comma, the key is a tuple containing ' + 'the\n' + 'conversion of the slice items; otherwise, the conversion of the ' + 'lone\n' + 'slice item is the key. The conversion of a slice item that is ' + 'an\n' + 'expression is that expression. The conversion of a proper slice ' + 'is a\n' + 'slice object (see section The standard type hierarchy) whose ' + '"start",\n' + '"stop" and "step" attributes are the values of the expressions ' + 'given\n' + 'as lower bound, upper bound and stride, respectively, ' + 'substituting\n' + '"None" for missing expressions.\n', + 'specialattrs': 'Special Attributes\n' + '******************\n' + '\n' + 'The implementation adds a few special read-only attributes ' + 'to several\n' + 'object types, where they are relevant. Some of these are ' + 'not reported\n' + 'by the "dir()" built-in function.\n' + '\n' + 'object.__dict__\n' + '\n' + ' A dictionary or other mapping object used to store an ' + 'object’s\n' + ' (writable) attributes.\n' + '\n' + 'instance.__class__\n' + '\n' + ' The class to which a class instance belongs.\n' + '\n' + 'class.__bases__\n' + '\n' + ' The tuple of base classes of a class object.\n' + '\n' + 'definition.__name__\n' + '\n' + ' The name of the class, function, method, descriptor, or ' + 'generator\n' + ' instance.\n' + '\n' + 'definition.__qualname__\n' + '\n' + ' The *qualified name* of the class, function, method, ' + 'descriptor, or\n' + ' generator instance.\n' + '\n' + ' New in version 3.3.\n' + '\n' + 'class.__mro__\n' + '\n' + ' This attribute is a tuple of classes that are considered ' + 'when\n' + ' looking for base classes during method resolution.\n' + '\n' + 'class.mro()\n' + '\n' + ' This method can be overridden by a metaclass to customize ' + 'the\n' + ' method resolution order for its instances. It is called ' + 'at class\n' + ' instantiation, and its result is stored in "__mro__".\n' + '\n' + 'class.__subclasses__()\n' + '\n' + ' Each class keeps a list of weak references to its ' + 'immediate\n' + ' subclasses. This method returns a list of all those ' + 'references\n' + ' still alive. The list is in definition order. Example:\n' + '\n' + ' >>> int.__subclasses__()\n' + " [, , , " + "]\n", + 'specialnames': 'Special method names\n' + '********************\n' + '\n' + 'A class can implement certain operations that are invoked by ' + 'special\n' + 'syntax (such as arithmetic operations or subscripting and ' + 'slicing) by\n' + 'defining methods with special names. This is Python’s ' + 'approach to\n' + '*operator overloading*, allowing classes to define their own ' + 'behavior\n' + 'with respect to language operators. For instance, if a ' + 'class defines\n' + 'a method named "__getitem__()", and "x" is an instance of ' + 'this class,\n' + 'then "x[i]" is roughly equivalent to "type(x).__getitem__(x, ' + 'i)".\n' + 'Except where mentioned, attempts to execute an operation ' + 'raise an\n' + 'exception when no appropriate method is defined (typically\n' + '"AttributeError" or "TypeError").\n' + '\n' + 'Setting a special method to "None" indicates that the ' + 'corresponding\n' + 'operation is not available. For example, if a class sets ' + '"__iter__()"\n' + 'to "None", the class is not iterable, so calling "iter()" on ' + 'its\n' + 'instances will raise a "TypeError" (without falling back to\n' + '"__getitem__()"). [2]\n' + '\n' + 'When implementing a class that emulates any built-in type, ' + 'it is\n' + 'important that the emulation only be implemented to the ' + 'degree that it\n' + 'makes sense for the object being modelled. For example, ' + 'some\n' + 'sequences may work well with retrieval of individual ' + 'elements, but\n' + 'extracting a slice may not make sense. (One example of this ' + 'is the\n' + '"NodeList" interface in the W3C’s Document Object Model.)\n' + '\n' + '\n' + 'Basic customization\n' + '===================\n' + '\n' + 'object.__new__(cls[, ...])\n' + '\n' + ' Called to create a new instance of class *cls*. ' + '"__new__()" is a\n' + ' static method (special-cased so you need not declare it ' + 'as such)\n' + ' that takes the class of which an instance was requested ' + 'as its\n' + ' first argument. The remaining arguments are those passed ' + 'to the\n' + ' object constructor expression (the call to the class). ' + 'The return\n' + ' value of "__new__()" should be the new object instance ' + '(usually an\n' + ' instance of *cls*).\n' + '\n' + ' Typical implementations create a new instance of the ' + 'class by\n' + ' invoking the superclass’s "__new__()" method using\n' + ' "super().__new__(cls[, ...])" with appropriate arguments ' + 'and then\n' + ' modifying the newly created instance as necessary before ' + 'returning\n' + ' it.\n' + '\n' + ' If "__new__()" is invoked during object construction and ' + 'it returns\n' + ' an instance of *cls*, then the new instance’s ' + '"__init__()" method\n' + ' will be invoked like "__init__(self[, ...])", where ' + '*self* is the\n' + ' new instance and the remaining arguments are the same as ' + 'were\n' + ' passed to the object constructor.\n' + '\n' + ' If "__new__()" does not return an instance of *cls*, then ' + 'the new\n' + ' instance’s "__init__()" method will not be invoked.\n' + '\n' + ' "__new__()" is intended mainly to allow subclasses of ' + 'immutable\n' + ' types (like int, str, or tuple) to customize instance ' + 'creation. It\n' + ' is also commonly overridden in custom metaclasses in ' + 'order to\n' + ' customize class creation.\n' + '\n' + 'object.__init__(self[, ...])\n' + '\n' + ' Called after the instance has been created (by ' + '"__new__()"), but\n' + ' before it is returned to the caller. The arguments are ' + 'those\n' + ' passed to the class constructor expression. If a base ' + 'class has an\n' + ' "__init__()" method, the derived class’s "__init__()" ' + 'method, if\n' + ' any, must explicitly call it to ensure proper ' + 'initialization of the\n' + ' base class part of the instance; for example:\n' + ' "super().__init__([args...])".\n' + '\n' + ' Because "__new__()" and "__init__()" work together in ' + 'constructing\n' + ' objects ("__new__()" to create it, and "__init__()" to ' + 'customize\n' + ' it), no non-"None" value may be returned by "__init__()"; ' + 'doing so\n' + ' will cause a "TypeError" to be raised at runtime.\n' + '\n' + 'object.__del__(self)\n' + '\n' + ' Called when the instance is about to be destroyed. This ' + 'is also\n' + ' called a finalizer or (improperly) a destructor. If a ' + 'base class\n' + ' has a "__del__()" method, the derived class’s "__del__()" ' + 'method,\n' + ' if any, must explicitly call it to ensure proper deletion ' + 'of the\n' + ' base class part of the instance.\n' + '\n' + ' It is possible (though not recommended!) for the ' + '"__del__()" method\n' + ' to postpone destruction of the instance by creating a new ' + 'reference\n' + ' to it. This is called object *resurrection*. It is\n' + ' implementation-dependent whether "__del__()" is called a ' + 'second\n' + ' time when a resurrected object is about to be destroyed; ' + 'the\n' + ' current *CPython* implementation only calls it once.\n' + '\n' + ' It is not guaranteed that "__del__()" methods are called ' + 'for\n' + ' objects that still exist when the interpreter exits.\n' + '\n' + ' Note:\n' + '\n' + ' "del x" doesn’t directly call "x.__del__()" — the ' + 'former\n' + ' decrements the reference count for "x" by one, and the ' + 'latter is\n' + ' only called when "x"’s reference count reaches zero.\n' + '\n' + ' **CPython implementation detail:** It is possible for a ' + 'reference\n' + ' cycle to prevent the reference count of an object from ' + 'going to\n' + ' zero. In this case, the cycle will be later detected and ' + 'deleted\n' + ' by the *cyclic garbage collector*. A common cause of ' + 'reference\n' + ' cycles is when an exception has been caught in a local ' + 'variable.\n' + ' The frame’s locals then reference the exception, which ' + 'references\n' + ' its own traceback, which references the locals of all ' + 'frames caught\n' + ' in the traceback.\n' + '\n' + ' See also: Documentation for the "gc" module.\n' + '\n' + ' Warning:\n' + '\n' + ' Due to the precarious circumstances under which ' + '"__del__()"\n' + ' methods are invoked, exceptions that occur during their ' + 'execution\n' + ' are ignored, and a warning is printed to "sys.stderr" ' + 'instead.\n' + ' In particular:\n' + '\n' + ' * "__del__()" can be invoked when arbitrary code is ' + 'being\n' + ' executed, including from any arbitrary thread. If ' + '"__del__()"\n' + ' needs to take a lock or invoke any other blocking ' + 'resource, it\n' + ' may deadlock as the resource may already be taken by ' + 'the code\n' + ' that gets interrupted to execute "__del__()".\n' + '\n' + ' * "__del__()" can be executed during interpreter ' + 'shutdown. As a\n' + ' consequence, the global variables it needs to access ' + '(including\n' + ' other modules) may already have been deleted or set ' + 'to "None".\n' + ' Python guarantees that globals whose name begins with ' + 'a single\n' + ' underscore are deleted from their module before other ' + 'globals\n' + ' are deleted; if no other references to such globals ' + 'exist, this\n' + ' may help in assuring that imported modules are still ' + 'available\n' + ' at the time when the "__del__()" method is called.\n' + '\n' + 'object.__repr__(self)\n' + '\n' + ' Called by the "repr()" built-in function to compute the ' + '“official”\n' + ' string representation of an object. If at all possible, ' + 'this\n' + ' should look like a valid Python expression that could be ' + 'used to\n' + ' recreate an object with the same value (given an ' + 'appropriate\n' + ' environment). If this is not possible, a string of the ' + 'form\n' + ' "<...some useful description...>" should be returned. The ' + 'return\n' + ' value must be a string object. If a class defines ' + '"__repr__()" but\n' + ' not "__str__()", then "__repr__()" is also used when an ' + '“informal”\n' + ' string representation of instances of that class is ' + 'required.\n' + '\n' + ' This is typically used for debugging, so it is important ' + 'that the\n' + ' representation is information-rich and unambiguous.\n' + '\n' + 'object.__str__(self)\n' + '\n' + ' Called by "str(object)" and the built-in functions ' + '"format()" and\n' + ' "print()" to compute the “informal” or nicely printable ' + 'string\n' + ' representation of an object. The return value must be a ' + 'string\n' + ' object.\n' + '\n' + ' This method differs from "object.__repr__()" in that ' + 'there is no\n' + ' expectation that "__str__()" return a valid Python ' + 'expression: a\n' + ' more convenient or concise representation can be used.\n' + '\n' + ' The default implementation defined by the built-in type ' + '"object"\n' + ' calls "object.__repr__()".\n' + '\n' + 'object.__bytes__(self)\n' + '\n' + ' Called by bytes to compute a byte-string representation ' + 'of an\n' + ' object. This should return a "bytes" object.\n' + '\n' + 'object.__format__(self, format_spec)\n' + '\n' + ' Called by the "format()" built-in function, and by ' + 'extension,\n' + ' evaluation of formatted string literals and the ' + '"str.format()"\n' + ' method, to produce a “formatted” string representation of ' + 'an\n' + ' object. The *format_spec* argument is a string that ' + 'contains a\n' + ' description of the formatting options desired. The ' + 'interpretation\n' + ' of the *format_spec* argument is up to the type ' + 'implementing\n' + ' "__format__()", however most classes will either ' + 'delegate\n' + ' formatting to one of the built-in types, or use a ' + 'similar\n' + ' formatting option syntax.\n' + '\n' + ' See Format Specification Mini-Language for a description ' + 'of the\n' + ' standard formatting syntax.\n' + '\n' + ' The return value must be a string object.\n' + '\n' + ' Changed in version 3.4: The __format__ method of "object" ' + 'itself\n' + ' raises a "TypeError" if passed any non-empty string.\n' + '\n' + ' Changed in version 3.7: "object.__format__(x, \'\')" is ' + 'now\n' + ' equivalent to "str(x)" rather than "format(str(x), ' + '\'\')".\n' + '\n' + 'object.__lt__(self, other)\n' + 'object.__le__(self, other)\n' + 'object.__eq__(self, other)\n' + 'object.__ne__(self, other)\n' + 'object.__gt__(self, other)\n' + 'object.__ge__(self, other)\n' + '\n' + ' These are the so-called “rich comparison” methods. The\n' + ' correspondence between operator symbols and method names ' + 'is as\n' + ' follows: "xy" calls\n' + ' "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n' + '\n' + ' A rich comparison method may return the singleton ' + '"NotImplemented"\n' + ' if it does not implement the operation for a given pair ' + 'of\n' + ' arguments. By convention, "False" and "True" are returned ' + 'for a\n' + ' successful comparison. However, these methods can return ' + 'any value,\n' + ' so if the comparison operator is used in a Boolean ' + 'context (e.g.,\n' + ' in the condition of an "if" statement), Python will call ' + '"bool()"\n' + ' on the value to determine if the result is true or ' + 'false.\n' + '\n' + ' By default, "object" implements "__eq__()" by using "is", ' + 'returning\n' + ' "NotImplemented" in the case of a false comparison: "True ' + 'if x is y\n' + ' else NotImplemented". For "__ne__()", by default it ' + 'delegates to\n' + ' "__eq__()" and inverts the result unless it is ' + '"NotImplemented".\n' + ' There are no other implied relationships among the ' + 'comparison\n' + ' operators or default implementations; for example, the ' + 'truth of\n' + ' "(x.__hash__".\n' + '\n' + ' If a class that does not override "__eq__()" wishes to ' + 'suppress\n' + ' hash support, it should include "__hash__ = None" in the ' + 'class\n' + ' definition. A class which defines its own "__hash__()" ' + 'that\n' + ' explicitly raises a "TypeError" would be incorrectly ' + 'identified as\n' + ' hashable by an "isinstance(obj, ' + 'collections.abc.Hashable)" call.\n' + '\n' + ' Note:\n' + '\n' + ' By default, the "__hash__()" values of str and bytes ' + 'objects are\n' + ' “salted” with an unpredictable random value. Although ' + 'they\n' + ' remain constant within an individual Python process, ' + 'they are not\n' + ' predictable between repeated invocations of Python.This ' + 'is\n' + ' intended to provide protection against a ' + 'denial-of-service caused\n' + ' by carefully chosen inputs that exploit the worst case\n' + ' performance of a dict insertion, *O*(*n*^2) ' + 'complexity. See\n' + ' http://ocert.org/advisories/ocert-2011-003.html for\n' + ' details.Changing hash values affects the iteration ' + 'order of sets.\n' + ' Python has never made guarantees about this ordering ' + '(and it\n' + ' typically varies between 32-bit and 64-bit builds).See ' + 'also\n' + ' "PYTHONHASHSEED".\n' + '\n' + ' Changed in version 3.3: Hash randomization is enabled by ' + 'default.\n' + '\n' + 'object.__bool__(self)\n' + '\n' + ' Called to implement truth value testing and the built-in ' + 'operation\n' + ' "bool()"; should return "False" or "True". When this ' + 'method is not\n' + ' defined, "__len__()" is called, if it is defined, and the ' + 'object is\n' + ' considered true if its result is nonzero. If a class ' + 'defines\n' + ' neither "__len__()" nor "__bool__()", all its instances ' + 'are\n' + ' considered true.\n' + '\n' + '\n' + 'Customizing attribute access\n' + '============================\n' + '\n' + 'The following methods can be defined to customize the ' + 'meaning of\n' + 'attribute access (use of, assignment to, or deletion of ' + '"x.name") for\n' + 'class instances.\n' + '\n' + 'object.__getattr__(self, name)\n' + '\n' + ' Called when the default attribute access fails with an\n' + ' "AttributeError" (either "__getattribute__()" raises an\n' + ' "AttributeError" because *name* is not an instance ' + 'attribute or an\n' + ' attribute in the class tree for "self"; or "__get__()" of ' + 'a *name*\n' + ' property raises "AttributeError"). This method should ' + 'either\n' + ' return the (computed) attribute value or raise an ' + '"AttributeError"\n' + ' exception.\n' + '\n' + ' Note that if the attribute is found through the normal ' + 'mechanism,\n' + ' "__getattr__()" is not called. (This is an intentional ' + 'asymmetry\n' + ' between "__getattr__()" and "__setattr__()".) This is ' + 'done both for\n' + ' efficiency reasons and because otherwise "__getattr__()" ' + 'would have\n' + ' no way to access other attributes of the instance. Note ' + 'that at\n' + ' least for instance variables, you can fake total control ' + 'by not\n' + ' inserting any values in the instance attribute dictionary ' + '(but\n' + ' instead inserting them in another object). See the\n' + ' "__getattribute__()" method below for a way to actually ' + 'get total\n' + ' control over attribute access.\n' + '\n' + 'object.__getattribute__(self, name)\n' + '\n' + ' Called unconditionally to implement attribute accesses ' + 'for\n' + ' instances of the class. If the class also defines ' + '"__getattr__()",\n' + ' the latter will not be called unless "__getattribute__()" ' + 'either\n' + ' calls it explicitly or raises an "AttributeError". This ' + 'method\n' + ' should return the (computed) attribute value or raise an\n' + ' "AttributeError" exception. In order to avoid infinite ' + 'recursion in\n' + ' this method, its implementation should always call the ' + 'base class\n' + ' method with the same name to access any attributes it ' + 'needs, for\n' + ' example, "object.__getattribute__(self, name)".\n' + '\n' + ' Note:\n' + '\n' + ' This method may still be bypassed when looking up ' + 'special methods\n' + ' as the result of implicit invocation via language ' + 'syntax or\n' + ' built-in functions. See Special method lookup.\n' + '\n' + ' For certain sensitive attribute accesses, raises an ' + 'auditing event\n' + ' "object.__getattr__" with arguments "obj" and "name".\n' + '\n' + 'object.__setattr__(self, name, value)\n' + '\n' + ' Called when an attribute assignment is attempted. This ' + 'is called\n' + ' instead of the normal mechanism (i.e. store the value in ' + 'the\n' + ' instance dictionary). *name* is the attribute name, ' + '*value* is the\n' + ' value to be assigned to it.\n' + '\n' + ' If "__setattr__()" wants to assign to an instance ' + 'attribute, it\n' + ' should call the base class method with the same name, for ' + 'example,\n' + ' "object.__setattr__(self, name, value)".\n' + '\n' + ' For certain sensitive attribute assignments, raises an ' + 'auditing\n' + ' event "object.__setattr__" with arguments "obj", "name", ' + '"value".\n' + '\n' + 'object.__delattr__(self, name)\n' + '\n' + ' Like "__setattr__()" but for attribute deletion instead ' + 'of\n' + ' assignment. This should only be implemented if "del ' + 'obj.name" is\n' + ' meaningful for the object.\n' + '\n' + ' For certain sensitive attribute deletions, raises an ' + 'auditing event\n' + ' "object.__delattr__" with arguments "obj" and "name".\n' + '\n' + 'object.__dir__(self)\n' + '\n' + ' Called when "dir()" is called on the object. An iterable ' + 'must be\n' + ' returned. "dir()" converts the returned iterable to a ' + 'list and\n' + ' sorts it.\n' + '\n' + '\n' + 'Customizing module attribute access\n' + '-----------------------------------\n' + '\n' + 'Special names "__getattr__" and "__dir__" can be also used ' + 'to\n' + 'customize access to module attributes. The "__getattr__" ' + 'function at\n' + 'the module level should accept one argument which is the ' + 'name of an\n' + 'attribute and return the computed value or raise an ' + '"AttributeError".\n' + 'If an attribute is not found on a module object through the ' + 'normal\n' + 'lookup, i.e. "object.__getattribute__()", then "__getattr__" ' + 'is\n' + 'searched in the module "__dict__" before raising an ' + '"AttributeError".\n' + 'If found, it is called with the attribute name and the ' + 'result is\n' + 'returned.\n' + '\n' + 'The "__dir__" function should accept no arguments, and ' + 'return an\n' + 'iterable of strings that represents the names accessible on ' + 'module. If\n' + 'present, this function overrides the standard "dir()" search ' + 'on a\n' + 'module.\n' + '\n' + 'For a more fine grained customization of the module behavior ' + '(setting\n' + 'attributes, properties, etc.), one can set the "__class__" ' + 'attribute\n' + 'of a module object to a subclass of "types.ModuleType". For ' + 'example:\n' + '\n' + ' import sys\n' + ' from types import ModuleType\n' + '\n' + ' class VerboseModule(ModuleType):\n' + ' def __repr__(self):\n' + " return f'Verbose {self.__name__}'\n" + '\n' + ' def __setattr__(self, attr, value):\n' + " print(f'Setting {attr}...')\n" + ' super().__setattr__(attr, value)\n' + '\n' + ' sys.modules[__name__].__class__ = VerboseModule\n' + '\n' + 'Note:\n' + '\n' + ' Defining module "__getattr__" and setting module ' + '"__class__" only\n' + ' affect lookups made using the attribute access syntax – ' + 'directly\n' + ' accessing the module globals (whether by code within the ' + 'module, or\n' + ' via a reference to the module’s globals dictionary) is ' + 'unaffected.\n' + '\n' + 'Changed in version 3.5: "__class__" module attribute is now ' + 'writable.\n' + '\n' + 'New in version 3.7: "__getattr__" and "__dir__" module ' + 'attributes.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 562** - Module __getattr__ and __dir__\n' + ' Describes the "__getattr__" and "__dir__" functions on ' + 'modules.\n' + '\n' + '\n' + 'Implementing Descriptors\n' + '------------------------\n' + '\n' + 'The following methods only apply when an instance of the ' + 'class\n' + 'containing the method (a so-called *descriptor* class) ' + 'appears in an\n' + '*owner* class (the descriptor must be in either the owner’s ' + 'class\n' + 'dictionary or in the class dictionary for one of its ' + 'parents). In the\n' + 'examples below, “the attribute” refers to the attribute ' + 'whose name is\n' + 'the key of the property in the owner class’ "__dict__".\n' + '\n' + 'object.__get__(self, instance, owner=None)\n' + '\n' + ' Called to get the attribute of the owner class (class ' + 'attribute\n' + ' access) or of an instance of that class (instance ' + 'attribute\n' + ' access). The optional *owner* argument is the owner ' + 'class, while\n' + ' *instance* is the instance that the attribute was ' + 'accessed through,\n' + ' or "None" when the attribute is accessed through the ' + '*owner*.\n' + '\n' + ' This method should return the computed attribute value or ' + 'raise an\n' + ' "AttributeError" exception.\n' + '\n' + ' **PEP 252** specifies that "__get__()" is callable with ' + 'one or two\n' + ' arguments. Python’s own built-in descriptors support ' + 'this\n' + ' specification; however, it is likely that some ' + 'third-party tools\n' + ' have descriptors that require both arguments. Python’s ' + 'own\n' + ' "__getattribute__()" implementation always passes in both ' + 'arguments\n' + ' whether they are required or not.\n' + '\n' + 'object.__set__(self, instance, value)\n' + '\n' + ' Called to set the attribute on an instance *instance* of ' + 'the owner\n' + ' class to a new value, *value*.\n' + '\n' + ' Note, adding "__set__()" or "__delete__()" changes the ' + 'kind of\n' + ' descriptor to a “data descriptor”. See Invoking ' + 'Descriptors for\n' + ' more details.\n' + '\n' + 'object.__delete__(self, instance)\n' + '\n' + ' Called to delete the attribute on an instance *instance* ' + 'of the\n' + ' owner class.\n' + '\n' + 'Instances of descriptors may also have the "__objclass__" ' + 'attribute\n' + 'present:\n' + '\n' + 'object.__objclass__\n' + '\n' + ' The attribute "__objclass__" is interpreted by the ' + '"inspect" module\n' + ' as specifying the class where this object was defined ' + '(setting this\n' + ' appropriately can assist in runtime introspection of ' + 'dynamic class\n' + ' attributes). For callables, it may indicate that an ' + 'instance of the\n' + ' given type (or a subclass) is expected or required as the ' + 'first\n' + ' positional argument (for example, CPython sets this ' + 'attribute for\n' + ' unbound methods that are implemented in C).\n' + '\n' + '\n' + 'Invoking Descriptors\n' + '--------------------\n' + '\n' + 'In general, a descriptor is an object attribute with ' + '“binding\n' + 'behavior”, one whose attribute access has been overridden by ' + 'methods\n' + 'in the descriptor protocol: "__get__()", "__set__()", and\n' + '"__delete__()". If any of those methods are defined for an ' + 'object, it\n' + 'is said to be a descriptor.\n' + '\n' + 'The default behavior for attribute access is to get, set, or ' + 'delete\n' + 'the attribute from an object’s dictionary. For instance, ' + '"a.x" has a\n' + 'lookup chain starting with "a.__dict__[\'x\']", then\n' + '"type(a).__dict__[\'x\']", and continuing through the base ' + 'classes of\n' + '"type(a)" excluding metaclasses.\n' + '\n' + 'However, if the looked-up value is an object defining one of ' + 'the\n' + 'descriptor methods, then Python may override the default ' + 'behavior and\n' + 'invoke the descriptor method instead. Where this occurs in ' + 'the\n' + 'precedence chain depends on which descriptor methods were ' + 'defined and\n' + 'how they were called.\n' + '\n' + 'The starting point for descriptor invocation is a binding, ' + '"a.x". How\n' + 'the arguments are assembled depends on "a":\n' + '\n' + 'Direct Call\n' + ' The simplest and least common call is when user code ' + 'directly\n' + ' invokes a descriptor method: "x.__get__(a)".\n' + '\n' + 'Instance Binding\n' + ' If binding to an object instance, "a.x" is transformed ' + 'into the\n' + ' call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n' + '\n' + 'Class Binding\n' + ' If binding to a class, "A.x" is transformed into the ' + 'call:\n' + ' "A.__dict__[\'x\'].__get__(None, A)".\n' + '\n' + 'Super Binding\n' + ' A dotted lookup such as "super(A, a).x" searches\n' + ' "a.__class__.__mro__" for a base class "B" following "A" ' + 'and then\n' + ' returns "B.__dict__[\'x\'].__get__(a, A)". If not a ' + 'descriptor, "x"\n' + ' is returned unchanged.\n' + '\n' + 'For instance bindings, the precedence of descriptor ' + 'invocation depends\n' + 'on which descriptor methods are defined. A descriptor can ' + 'define any\n' + 'combination of "__get__()", "__set__()" and "__delete__()". ' + 'If it\n' + 'does not define "__get__()", then accessing the attribute ' + 'will return\n' + 'the descriptor object itself unless there is a value in the ' + 'object’s\n' + 'instance dictionary. If the descriptor defines "__set__()" ' + 'and/or\n' + '"__delete__()", it is a data descriptor; if it defines ' + 'neither, it is\n' + 'a non-data descriptor. Normally, data descriptors define ' + 'both\n' + '"__get__()" and "__set__()", while non-data descriptors have ' + 'just the\n' + '"__get__()" method. Data descriptors with "__get__()" and ' + '"__set__()"\n' + '(and/or "__delete__()") defined always override a ' + 'redefinition in an\n' + 'instance dictionary. In contrast, non-data descriptors can ' + 'be\n' + 'overridden by instances.\n' + '\n' + 'Python methods (including those decorated with ' + '"@staticmethod" and\n' + '"@classmethod") are implemented as non-data descriptors. ' + 'Accordingly,\n' + 'instances can redefine and override methods. This allows ' + 'individual\n' + 'instances to acquire behaviors that differ from other ' + 'instances of the\n' + 'same class.\n' + '\n' + 'The "property()" function is implemented as a data ' + 'descriptor.\n' + 'Accordingly, instances cannot override the behavior of a ' + 'property.\n' + '\n' + '\n' + '__slots__\n' + '---------\n' + '\n' + '*__slots__* allow us to explicitly declare data members ' + '(like\n' + 'properties) and deny the creation of "__dict__" and ' + '*__weakref__*\n' + '(unless explicitly declared in *__slots__* or available in a ' + 'parent.)\n' + '\n' + 'The space saved over using "__dict__" can be significant. ' + 'Attribute\n' + 'lookup speed can be significantly improved as well.\n' + '\n' + 'object.__slots__\n' + '\n' + ' This class variable can be assigned a string, iterable, ' + 'or sequence\n' + ' of strings with variable names used by instances. ' + '*__slots__*\n' + ' reserves space for the declared variables and prevents ' + 'the\n' + ' automatic creation of "__dict__" and *__weakref__* for ' + 'each\n' + ' instance.\n' + '\n' + 'Notes on using *__slots__*:\n' + '\n' + '* When inheriting from a class without *__slots__*, the ' + '"__dict__" and\n' + ' *__weakref__* attribute of the instances will always be ' + 'accessible.\n' + '\n' + '* Without a "__dict__" variable, instances cannot be ' + 'assigned new\n' + ' variables not listed in the *__slots__* definition. ' + 'Attempts to\n' + ' assign to an unlisted variable name raises ' + '"AttributeError". If\n' + ' dynamic assignment of new variables is desired, then add\n' + ' "\'__dict__\'" to the sequence of strings in the ' + '*__slots__*\n' + ' declaration.\n' + '\n' + '* Without a *__weakref__* variable for each instance, ' + 'classes defining\n' + ' *__slots__* do not support "weak references" to its ' + 'instances. If\n' + ' weak reference support is needed, then add ' + '"\'__weakref__\'" to the\n' + ' sequence of strings in the *__slots__* declaration.\n' + '\n' + '* *__slots__* are implemented at the class level by ' + 'creating\n' + ' descriptors for each variable name. As a result, class ' + 'attributes\n' + ' cannot be used to set default values for instance ' + 'variables defined\n' + ' by *__slots__*; otherwise, the class attribute would ' + 'overwrite the\n' + ' descriptor assignment.\n' + '\n' + '* The action of a *__slots__* declaration is not limited to ' + 'the class\n' + ' where it is defined. *__slots__* declared in parents are ' + 'available\n' + ' in child classes. However, child subclasses will get a ' + '"__dict__"\n' + ' and *__weakref__* unless they also define *__slots__* ' + '(which should\n' + ' only contain names of any *additional* slots).\n' + '\n' + '* If a class defines a slot also defined in a base class, ' + 'the instance\n' + ' variable defined by the base class slot is inaccessible ' + '(except by\n' + ' retrieving its descriptor directly from the base class). ' + 'This\n' + ' renders the meaning of the program undefined. In the ' + 'future, a\n' + ' check may be added to prevent this.\n' + '\n' + '* "TypeError" will be raised if nonempty *__slots__* are ' + 'defined for a\n' + ' class derived from a ""variable-length" built-in type" ' + 'such as\n' + ' "int", "bytes", and "tuple".\n' + '\n' + '* Any non-string *iterable* may be assigned to *__slots__*.\n' + '\n' + '* If a "dictionary" is used to assign *__slots__*, the ' + 'dictionary keys\n' + ' will be used as the slot names. The values of the ' + 'dictionary can be\n' + ' used to provide per-attribute docstrings that will be ' + 'recognised by\n' + ' "inspect.getdoc()" and displayed in the output of ' + '"help()".\n' + '\n' + '* "__class__" assignment works only if both classes have the ' + 'same\n' + ' *__slots__*.\n' + '\n' + '* Multiple inheritance with multiple slotted parent classes ' + 'can be\n' + ' used, but only one parent is allowed to have attributes ' + 'created by\n' + ' slots (the other bases must have empty slot layouts) - ' + 'violations\n' + ' raise "TypeError".\n' + '\n' + '* If an *iterator* is used for *__slots__* then a ' + '*descriptor* is\n' + ' created for each of the iterator’s values. However, the ' + '*__slots__*\n' + ' attribute will be an empty iterator.\n' + '\n' + '\n' + 'Customizing class creation\n' + '==========================\n' + '\n' + 'Whenever a class inherits from another class, ' + '"__init_subclass__()" is\n' + 'called on the parent class. This way, it is possible to ' + 'write classes\n' + 'which change the behavior of subclasses. This is closely ' + 'related to\n' + 'class decorators, but where class decorators only affect the ' + 'specific\n' + 'class they’re applied to, "__init_subclass__" solely applies ' + 'to future\n' + 'subclasses of the class defining the method.\n' + '\n' + 'classmethod object.__init_subclass__(cls)\n' + '\n' + ' This method is called whenever the containing class is ' + 'subclassed.\n' + ' *cls* is then the new subclass. If defined as a normal ' + 'instance\n' + ' method, this method is implicitly converted to a class ' + 'method.\n' + '\n' + ' Keyword arguments which are given to a new class are ' + 'passed to the\n' + ' parent class’s "__init_subclass__". For compatibility ' + 'with other\n' + ' classes using "__init_subclass__", one should take out ' + 'the needed\n' + ' keyword arguments and pass the others over to the base ' + 'class, as\n' + ' in:\n' + '\n' + ' class Philosopher:\n' + ' def __init_subclass__(cls, /, default_name, ' + '**kwargs):\n' + ' super().__init_subclass__(**kwargs)\n' + ' cls.default_name = default_name\n' + '\n' + ' class AustralianPhilosopher(Philosopher, ' + 'default_name="Bruce"):\n' + ' pass\n' + '\n' + ' The default implementation "object.__init_subclass__" ' + 'does nothing,\n' + ' but raises an error if it is called with any arguments.\n' + '\n' + ' Note:\n' + '\n' + ' The metaclass hint "metaclass" is consumed by the rest ' + 'of the\n' + ' type machinery, and is never passed to ' + '"__init_subclass__"\n' + ' implementations. The actual metaclass (rather than the ' + 'explicit\n' + ' hint) can be accessed as "type(cls)".\n' + '\n' + ' New in version 3.6.\n' + '\n' + 'When a class is created, "type.__new__()" scans the class ' + 'variables\n' + 'and makes callbacks to those with a "__set_name__()" hook.\n' + '\n' + 'object.__set_name__(self, owner, name)\n' + '\n' + ' Automatically called at the time the owning class *owner* ' + 'is\n' + ' created. The object has been assigned to *name* in that ' + 'class:\n' + '\n' + ' class A:\n' + ' x = C() # Automatically calls: x.__set_name__(A, ' + "'x')\n" + '\n' + ' If the class variable is assigned after the class is ' + 'created,\n' + ' "__set_name__()" will not be called automatically. If ' + 'needed,\n' + ' "__set_name__()" can be called directly:\n' + '\n' + ' class A:\n' + ' pass\n' + '\n' + ' c = C()\n' + ' A.x = c # The hook is not called\n' + " c.__set_name__(A, 'x') # Manually invoke the hook\n" + '\n' + ' See Creating the class object for more details.\n' + '\n' + ' New in version 3.6.\n' + '\n' + '\n' + 'Metaclasses\n' + '-----------\n' + '\n' + 'By default, classes are constructed using "type()". The ' + 'class body is\n' + 'executed in a new namespace and the class name is bound ' + 'locally to the\n' + 'result of "type(name, bases, namespace)".\n' + '\n' + 'The class creation process can be customized by passing the\n' + '"metaclass" keyword argument in the class definition line, ' + 'or by\n' + 'inheriting from an existing class that included such an ' + 'argument. In\n' + 'the following example, both "MyClass" and "MySubclass" are ' + 'instances\n' + 'of "Meta":\n' + '\n' + ' class Meta(type):\n' + ' pass\n' + '\n' + ' class MyClass(metaclass=Meta):\n' + ' pass\n' + '\n' + ' class MySubclass(MyClass):\n' + ' pass\n' + '\n' + 'Any other keyword arguments that are specified in the class ' + 'definition\n' + 'are passed through to all metaclass operations described ' + 'below.\n' + '\n' + 'When a class definition is executed, the following steps ' + 'occur:\n' + '\n' + '* MRO entries are resolved;\n' + '\n' + '* the appropriate metaclass is determined;\n' + '\n' + '* the class namespace is prepared;\n' + '\n' + '* the class body is executed;\n' + '\n' + '* the class object is created.\n' + '\n' + '\n' + 'Resolving MRO entries\n' + '---------------------\n' + '\n' + 'object.__mro_entries__(self, bases)\n' + '\n' + ' If a base that appears in a class definition is not an ' + 'instance of\n' + ' "type", then an "__mro_entries__()" method is searched on ' + 'the base.\n' + ' If an "__mro_entries__()" method is found, the base is ' + 'substituted\n' + ' with the result of a call to "__mro_entries__()" when ' + 'creating the\n' + ' class. The method is called with the original bases tuple ' + 'passed to\n' + ' the *bases* parameter, and must return a tuple of classes ' + 'that will\n' + ' be used instead of the base. The returned tuple may be ' + 'empty: in\n' + ' these cases, the original base is ignored.\n' + '\n' + 'See also:\n' + '\n' + ' "types.resolve_bases()"\n' + ' Dynamically resolve bases that are not instances of ' + '"type".\n' + '\n' + ' **PEP 560**\n' + ' Core support for typing module and generic types.\n' + '\n' + '\n' + 'Determining the appropriate metaclass\n' + '-------------------------------------\n' + '\n' + 'The appropriate metaclass for a class definition is ' + 'determined as\n' + 'follows:\n' + '\n' + '* if no bases and no explicit metaclass are given, then ' + '"type()" is\n' + ' used;\n' + '\n' + '* if an explicit metaclass is given and it is *not* an ' + 'instance of\n' + ' "type()", then it is used directly as the metaclass;\n' + '\n' + '* if an instance of "type()" is given as the explicit ' + 'metaclass, or\n' + ' bases are defined, then the most derived metaclass is ' + 'used.\n' + '\n' + 'The most derived metaclass is selected from the explicitly ' + 'specified\n' + 'metaclass (if any) and the metaclasses (i.e. "type(cls)") of ' + 'all\n' + 'specified base classes. The most derived metaclass is one ' + 'which is a\n' + 'subtype of *all* of these candidate metaclasses. If none of ' + 'the\n' + 'candidate metaclasses meets that criterion, then the class ' + 'definition\n' + 'will fail with "TypeError".\n' + '\n' + '\n' + 'Preparing the class namespace\n' + '-----------------------------\n' + '\n' + 'Once the appropriate metaclass has been identified, then the ' + 'class\n' + 'namespace is prepared. If the metaclass has a "__prepare__" ' + 'attribute,\n' + 'it is called as "namespace = metaclass.__prepare__(name, ' + 'bases,\n' + '**kwds)" (where the additional keyword arguments, if any, ' + 'come from\n' + 'the class definition). The "__prepare__" method should be ' + 'implemented\n' + 'as a "classmethod". The namespace returned by "__prepare__" ' + 'is passed\n' + 'in to "__new__", but when the final class object is created ' + 'the\n' + 'namespace is copied into a new "dict".\n' + '\n' + 'If the metaclass has no "__prepare__" attribute, then the ' + 'class\n' + 'namespace is initialised as an empty ordered mapping.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3115** - Metaclasses in Python 3000\n' + ' Introduced the "__prepare__" namespace hook\n' + '\n' + '\n' + 'Executing the class body\n' + '------------------------\n' + '\n' + 'The class body is executed (approximately) as "exec(body, ' + 'globals(),\n' + 'namespace)". The key difference from a normal call to ' + '"exec()" is that\n' + 'lexical scoping allows the class body (including any ' + 'methods) to\n' + 'reference names from the current and outer scopes when the ' + 'class\n' + 'definition occurs inside a function.\n' + '\n' + 'However, even when the class definition occurs inside the ' + 'function,\n' + 'methods defined inside the class still cannot see names ' + 'defined at the\n' + 'class scope. Class variables must be accessed through the ' + 'first\n' + 'parameter of instance or class methods, or through the ' + 'implicit\n' + 'lexically scoped "__class__" reference described in the next ' + 'section.\n' + '\n' + '\n' + 'Creating the class object\n' + '-------------------------\n' + '\n' + 'Once the class namespace has been populated by executing the ' + 'class\n' + 'body, the class object is created by calling ' + '"metaclass(name, bases,\n' + 'namespace, **kwds)" (the additional keywords passed here are ' + 'the same\n' + 'as those passed to "__prepare__").\n' + '\n' + 'This class object is the one that will be referenced by the ' + 'zero-\n' + 'argument form of "super()". "__class__" is an implicit ' + 'closure\n' + 'reference created by the compiler if any methods in a class ' + 'body refer\n' + 'to either "__class__" or "super". This allows the zero ' + 'argument form\n' + 'of "super()" to correctly identify the class being defined ' + 'based on\n' + 'lexical scoping, while the class or instance that was used ' + 'to make the\n' + 'current call is identified based on the first argument ' + 'passed to the\n' + 'method.\n' + '\n' + '**CPython implementation detail:** In CPython 3.6 and later, ' + 'the\n' + '"__class__" cell is passed to the metaclass as a ' + '"__classcell__" entry\n' + 'in the class namespace. If present, this must be propagated ' + 'up to the\n' + '"type.__new__" call in order for the class to be ' + 'initialised\n' + 'correctly. Failing to do so will result in a "RuntimeError" ' + 'in Python\n' + '3.8.\n' + '\n' + 'When using the default metaclass "type", or any metaclass ' + 'that\n' + 'ultimately calls "type.__new__", the following additional\n' + 'customization steps are invoked after creating the class ' + 'object:\n' + '\n' + '1. The "type.__new__" method collects all of the attributes ' + 'in the\n' + ' class namespace that define a "__set_name__()" method;\n' + '\n' + '2. Those "__set_name__" methods are called with the class ' + 'being\n' + ' defined and the assigned name of that particular ' + 'attribute;\n' + '\n' + '3. The "__init_subclass__()" hook is called on the immediate ' + 'parent of\n' + ' the new class in its method resolution order.\n' + '\n' + 'After the class object is created, it is passed to the ' + 'class\n' + 'decorators included in the class definition (if any) and the ' + 'resulting\n' + 'object is bound in the local namespace as the defined ' + 'class.\n' + '\n' + 'When a new class is created by "type.__new__", the object ' + 'provided as\n' + 'the namespace parameter is copied to a new ordered mapping ' + 'and the\n' + 'original object is discarded. The new copy is wrapped in a ' + 'read-only\n' + 'proxy, which becomes the "__dict__" attribute of the class ' + 'object.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3135** - New super\n' + ' Describes the implicit "__class__" closure reference\n' + '\n' + '\n' + 'Uses for metaclasses\n' + '--------------------\n' + '\n' + 'The potential uses for metaclasses are boundless. Some ideas ' + 'that have\n' + 'been explored include enum, logging, interface checking, ' + 'automatic\n' + 'delegation, automatic property creation, proxies, ' + 'frameworks, and\n' + 'automatic resource locking/synchronization.\n' + '\n' + '\n' + 'Customizing instance and subclass checks\n' + '========================================\n' + '\n' + 'The following methods are used to override the default ' + 'behavior of the\n' + '"isinstance()" and "issubclass()" built-in functions.\n' + '\n' + 'In particular, the metaclass "abc.ABCMeta" implements these ' + 'methods in\n' + 'order to allow the addition of Abstract Base Classes (ABCs) ' + 'as\n' + '“virtual base classes” to any class or type (including ' + 'built-in\n' + 'types), including other ABCs.\n' + '\n' + 'class.__instancecheck__(self, instance)\n' + '\n' + ' Return true if *instance* should be considered a (direct ' + 'or\n' + ' indirect) instance of *class*. If defined, called to ' + 'implement\n' + ' "isinstance(instance, class)".\n' + '\n' + 'class.__subclasscheck__(self, subclass)\n' + '\n' + ' Return true if *subclass* should be considered a (direct ' + 'or\n' + ' indirect) subclass of *class*. If defined, called to ' + 'implement\n' + ' "issubclass(subclass, class)".\n' + '\n' + 'Note that these methods are looked up on the type ' + '(metaclass) of a\n' + 'class. They cannot be defined as class methods in the ' + 'actual class.\n' + 'This is consistent with the lookup of special methods that ' + 'are called\n' + 'on instances, only in this case the instance is itself a ' + 'class.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 3119** - Introducing Abstract Base Classes\n' + ' Includes the specification for customizing ' + '"isinstance()" and\n' + ' "issubclass()" behavior through "__instancecheck__()" ' + 'and\n' + ' "__subclasscheck__()", with motivation for this ' + 'functionality in\n' + ' the context of adding Abstract Base Classes (see the ' + '"abc"\n' + ' module) to the language.\n' + '\n' + '\n' + 'Emulating generic types\n' + '=======================\n' + '\n' + 'When using *type annotations*, it is often useful to ' + '*parameterize* a\n' + '*generic type* using Python’s square-brackets notation. For ' + 'example,\n' + 'the annotation "list[int]" might be used to signify a "list" ' + 'in which\n' + 'all the elements are of type "int".\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 484** - Type Hints\n' + ' Introducing Python’s framework for type annotations\n' + '\n' + ' Generic Alias Types\n' + ' Documentation for objects representing parameterized ' + 'generic\n' + ' classes\n' + '\n' + ' Generics, user-defined generics and "typing.Generic"\n' + ' Documentation on how to implement generic classes that ' + 'can be\n' + ' parameterized at runtime and understood by static ' + 'type-checkers.\n' + '\n' + 'A class can *generally* only be parameterized if it defines ' + 'the\n' + 'special class method "__class_getitem__()".\n' + '\n' + 'classmethod object.__class_getitem__(cls, key)\n' + '\n' + ' Return an object representing the specialization of a ' + 'generic class\n' + ' by type arguments found in *key*.\n' + '\n' + ' When defined on a class, "__class_getitem__()" is ' + 'automatically a\n' + ' class method. As such, there is no need for it to be ' + 'decorated with\n' + ' "@classmethod" when it is defined.\n' + '\n' + '\n' + 'The purpose of *__class_getitem__*\n' + '----------------------------------\n' + '\n' + 'The purpose of "__class_getitem__()" is to allow runtime\n' + 'parameterization of standard-library generic classes in ' + 'order to more\n' + 'easily apply *type hints* to these classes.\n' + '\n' + 'To implement custom generic classes that can be ' + 'parameterized at\n' + 'runtime and understood by static type-checkers, users should ' + 'either\n' + 'inherit from a standard library class that already ' + 'implements\n' + '"__class_getitem__()", or inherit from "typing.Generic", ' + 'which has its\n' + 'own implementation of "__class_getitem__()".\n' + '\n' + 'Custom implementations of "__class_getitem__()" on classes ' + 'defined\n' + 'outside of the standard library may not be understood by ' + 'third-party\n' + 'type-checkers such as mypy. Using "__class_getitem__()" on ' + 'any class\n' + 'for purposes other than type hinting is discouraged.\n' + '\n' + '\n' + '*__class_getitem__* versus *__getitem__*\n' + '----------------------------------------\n' + '\n' + 'Usually, the subscription of an object using square brackets ' + 'will call\n' + 'the "__getitem__()" instance method defined on the object’s ' + 'class.\n' + 'However, if the object being subscribed is itself a class, ' + 'the class\n' + 'method "__class_getitem__()" may be called instead.\n' + '"__class_getitem__()" should return a GenericAlias object if ' + 'it is\n' + 'properly defined.\n' + '\n' + 'Presented with the *expression* "obj[x]", the Python ' + 'interpreter\n' + 'follows something like the following process to decide ' + 'whether\n' + '"__getitem__()" or "__class_getitem__()" should be called:\n' + '\n' + ' from inspect import isclass\n' + '\n' + ' def subscribe(obj, x):\n' + ' """Return the result of the expression \'obj[x]\'"""\n' + '\n' + ' class_of_obj = type(obj)\n' + '\n' + ' # If the class of obj defines __getitem__,\n' + ' # call class_of_obj.__getitem__(obj, x)\n' + " if hasattr(class_of_obj, '__getitem__'):\n" + ' return class_of_obj.__getitem__(obj, x)\n' + '\n' + ' # Else, if obj is a class and defines ' + '__class_getitem__,\n' + ' # call obj.__class_getitem__(x)\n' + ' elif isclass(obj) and hasattr(obj, ' + "'__class_getitem__'):\n" + ' return obj.__class_getitem__(x)\n' + '\n' + ' # Else, raise an exception\n' + ' else:\n' + ' raise TypeError(\n' + ' f"\'{class_of_obj.__name__}\' object is not ' + 'subscriptable"\n' + ' )\n' + '\n' + 'In Python, all classes are themselves instances of other ' + 'classes. The\n' + 'class of a class is known as that class’s *metaclass*, and ' + 'most\n' + 'classes have the "type" class as their metaclass. "type" ' + 'does not\n' + 'define "__getitem__()", meaning that expressions such as ' + '"list[int]",\n' + '"dict[str, float]" and "tuple[str, bytes]" all result in\n' + '"__class_getitem__()" being called:\n' + '\n' + ' >>> # list has class "type" as its metaclass, like most ' + 'classes:\n' + ' >>> type(list)\n' + " \n" + ' >>> type(dict) == type(list) == type(tuple) == type(str) ' + '== type(bytes)\n' + ' True\n' + ' >>> # "list[int]" calls "list.__class_getitem__(int)"\n' + ' >>> list[int]\n' + ' list[int]\n' + ' >>> # list.__class_getitem__ returns a GenericAlias ' + 'object:\n' + ' >>> type(list[int])\n' + " \n" + '\n' + 'However, if a class has a custom metaclass that defines\n' + '"__getitem__()", subscribing the class may result in ' + 'different\n' + 'behaviour. An example of this can be found in the "enum" ' + 'module:\n' + '\n' + ' >>> from enum import Enum\n' + ' >>> class Menu(Enum):\n' + ' ... """A breakfast menu"""\n' + " ... SPAM = 'spam'\n" + " ... BACON = 'bacon'\n" + ' ...\n' + ' >>> # Enum classes have a custom metaclass:\n' + ' >>> type(Menu)\n' + " \n" + ' >>> # EnumMeta defines __getitem__,\n' + ' >>> # so __class_getitem__ is not called,\n' + ' >>> # and the result is not a GenericAlias object:\n' + " >>> Menu['SPAM']\n" + " \n" + " >>> type(Menu['SPAM'])\n" + " \n" + '\n' + 'See also:\n' + '\n' + ' **PEP 560** - Core Support for typing module and generic ' + 'types\n' + ' Introducing "__class_getitem__()", and outlining when ' + 'a\n' + ' subscription results in "__class_getitem__()" being ' + 'called\n' + ' instead of "__getitem__()"\n' + '\n' + '\n' + 'Emulating callable objects\n' + '==========================\n' + '\n' + 'object.__call__(self[, args...])\n' + '\n' + ' Called when the instance is “called” as a function; if ' + 'this method\n' + ' is defined, "x(arg1, arg2, ...)" roughly translates to\n' + ' "type(x).__call__(x, arg1, ...)".\n' + '\n' + '\n' + 'Emulating container types\n' + '=========================\n' + '\n' + 'The following methods can be defined to implement container ' + 'objects.\n' + 'Containers usually are *sequences* (such as "lists" or ' + '"tuples") or\n' + '*mappings* (like "dictionaries"), but can represent other ' + 'containers\n' + 'as well. The first set of methods is used either to emulate ' + 'a\n' + 'sequence or to emulate a mapping; the difference is that for ' + 'a\n' + 'sequence, the allowable keys should be the integers *k* for ' + 'which "0\n' + '<= k < N" where *N* is the length of the sequence, or ' + '"slice" objects,\n' + 'which define a range of items. It is also recommended that ' + 'mappings\n' + 'provide the methods "keys()", "values()", "items()", ' + '"get()",\n' + '"clear()", "setdefault()", "pop()", "popitem()", "copy()", ' + 'and\n' + '"update()" behaving similar to those for Python’s standard\n' + '"dictionary" objects. The "collections.abc" module provides ' + 'a\n' + '"MutableMapping" *abstract base class* to help create those ' + 'methods\n' + 'from a base set of "__getitem__()", "__setitem__()", ' + '"__delitem__()",\n' + 'and "keys()". Mutable sequences should provide methods ' + '"append()",\n' + '"count()", "index()", "extend()", "insert()", "pop()", ' + '"remove()",\n' + '"reverse()" and "sort()", like Python standard "list" ' + 'objects.\n' + 'Finally, sequence types should implement addition (meaning\n' + 'concatenation) and multiplication (meaning repetition) by ' + 'defining the\n' + 'methods "__add__()", "__radd__()", "__iadd__()", ' + '"__mul__()",\n' + '"__rmul__()" and "__imul__()" described below; they should ' + 'not define\n' + 'other numerical operators. It is recommended that both ' + 'mappings and\n' + 'sequences implement the "__contains__()" method to allow ' + 'efficient use\n' + 'of the "in" operator; for mappings, "in" should search the ' + 'mapping’s\n' + 'keys; for sequences, it should search through the values. ' + 'It is\n' + 'further recommended that both mappings and sequences ' + 'implement the\n' + '"__iter__()" method to allow efficient iteration through ' + 'the\n' + 'container; for mappings, "__iter__()" should iterate through ' + 'the\n' + 'object’s keys; for sequences, it should iterate through the ' + 'values.\n' + '\n' + 'object.__len__(self)\n' + '\n' + ' Called to implement the built-in function "len()". ' + 'Should return\n' + ' the length of the object, an integer ">=" 0. Also, an ' + 'object that\n' + ' doesn’t define a "__bool__()" method and whose ' + '"__len__()" method\n' + ' returns zero is considered to be false in a Boolean ' + 'context.\n' + '\n' + ' **CPython implementation detail:** In CPython, the length ' + 'is\n' + ' required to be at most "sys.maxsize". If the length is ' + 'larger than\n' + ' "sys.maxsize" some features (such as "len()") may raise\n' + ' "OverflowError". To prevent raising "OverflowError" by ' + 'truth value\n' + ' testing, an object must define a "__bool__()" method.\n' + '\n' + 'object.__length_hint__(self)\n' + '\n' + ' Called to implement "operator.length_hint()". Should ' + 'return an\n' + ' estimated length for the object (which may be greater or ' + 'less than\n' + ' the actual length). The length must be an integer ">=" 0. ' + 'The\n' + ' return value may also be "NotImplemented", which is ' + 'treated the\n' + ' same as if the "__length_hint__" method didn’t exist at ' + 'all. This\n' + ' method is purely an optimization and is never required ' + 'for\n' + ' correctness.\n' + '\n' + ' New in version 3.4.\n' + '\n' + 'Note:\n' + '\n' + ' Slicing is done exclusively with the following three ' + 'methods. A\n' + ' call like\n' + '\n' + ' a[1:2] = b\n' + '\n' + ' is translated to\n' + '\n' + ' a[slice(1, 2, None)] = b\n' + '\n' + ' and so forth. Missing slice items are always filled in ' + 'with "None".\n' + '\n' + 'object.__getitem__(self, key)\n' + '\n' + ' Called to implement evaluation of "self[key]". For ' + '*sequence*\n' + ' types, the accepted keys should be integers. Optionally, ' + 'they may\n' + ' support "slice" objects as well. Negative index support ' + 'is also\n' + ' optional. If *key* is of an inappropriate type, ' + '"TypeError" may be\n' + ' raised; if *key* is a value outside the set of indexes ' + 'for the\n' + ' sequence (after any special interpretation of negative ' + 'values),\n' + ' "IndexError" should be raised. For *mapping* types, if ' + '*key* is\n' + ' missing (not in the container), "KeyError" should be ' + 'raised.\n' + '\n' + ' Note:\n' + '\n' + ' "for" loops expect that an "IndexError" will be raised ' + 'for\n' + ' illegal indexes to allow proper detection of the end of ' + 'the\n' + ' sequence.\n' + '\n' + ' Note:\n' + '\n' + ' When subscripting a *class*, the special class method\n' + ' "__class_getitem__()" may be called instead of ' + '"__getitem__()".\n' + ' See __class_getitem__ versus __getitem__ for more ' + 'details.\n' + '\n' + 'object.__setitem__(self, key, value)\n' + '\n' + ' Called to implement assignment to "self[key]". Same note ' + 'as for\n' + ' "__getitem__()". This should only be implemented for ' + 'mappings if\n' + ' the objects support changes to the values for keys, or if ' + 'new keys\n' + ' can be added, or for sequences if elements can be ' + 'replaced. The\n' + ' same exceptions should be raised for improper *key* ' + 'values as for\n' + ' the "__getitem__()" method.\n' + '\n' + 'object.__delitem__(self, key)\n' + '\n' + ' Called to implement deletion of "self[key]". Same note ' + 'as for\n' + ' "__getitem__()". This should only be implemented for ' + 'mappings if\n' + ' the objects support removal of keys, or for sequences if ' + 'elements\n' + ' can be removed from the sequence. The same exceptions ' + 'should be\n' + ' raised for improper *key* values as for the ' + '"__getitem__()" method.\n' + '\n' + 'object.__missing__(self, key)\n' + '\n' + ' Called by "dict"."__getitem__()" to implement "self[key]" ' + 'for dict\n' + ' subclasses when key is not in the dictionary.\n' + '\n' + 'object.__iter__(self)\n' + '\n' + ' This method is called when an *iterator* is required for ' + 'a\n' + ' container. This method should return a new iterator ' + 'object that can\n' + ' iterate over all the objects in the container. For ' + 'mappings, it\n' + ' should iterate over the keys of the container.\n' + '\n' + 'object.__reversed__(self)\n' + '\n' + ' Called (if present) by the "reversed()" built-in to ' + 'implement\n' + ' reverse iteration. It should return a new iterator ' + 'object that\n' + ' iterates over all the objects in the container in reverse ' + 'order.\n' + '\n' + ' If the "__reversed__()" method is not provided, the ' + '"reversed()"\n' + ' built-in will fall back to using the sequence protocol ' + '("__len__()"\n' + ' and "__getitem__()"). Objects that support the sequence ' + 'protocol\n' + ' should only provide "__reversed__()" if they can provide ' + 'an\n' + ' implementation that is more efficient than the one ' + 'provided by\n' + ' "reversed()".\n' + '\n' + 'The membership test operators ("in" and "not in") are ' + 'normally\n' + 'implemented as an iteration through a container. However, ' + 'container\n' + 'objects can supply the following special method with a more ' + 'efficient\n' + 'implementation, which also does not require the object be ' + 'iterable.\n' + '\n' + 'object.__contains__(self, item)\n' + '\n' + ' Called to implement membership test operators. Should ' + 'return true\n' + ' if *item* is in *self*, false otherwise. For mapping ' + 'objects, this\n' + ' should consider the keys of the mapping rather than the ' + 'values or\n' + ' the key-item pairs.\n' + '\n' + ' For objects that don’t define "__contains__()", the ' + 'membership test\n' + ' first tries iteration via "__iter__()", then the old ' + 'sequence\n' + ' iteration protocol via "__getitem__()", see this section ' + 'in the\n' + ' language reference.\n' + '\n' + '\n' + 'Emulating numeric types\n' + '=======================\n' + '\n' + 'The following methods can be defined to emulate numeric ' + 'objects.\n' + 'Methods corresponding to operations that are not supported ' + 'by the\n' + 'particular kind of number implemented (e.g., bitwise ' + 'operations for\n' + 'non-integral numbers) should be left undefined.\n' + '\n' + 'object.__add__(self, other)\n' + 'object.__sub__(self, other)\n' + 'object.__mul__(self, other)\n' + 'object.__matmul__(self, other)\n' + 'object.__truediv__(self, other)\n' + 'object.__floordiv__(self, other)\n' + 'object.__mod__(self, other)\n' + 'object.__divmod__(self, other)\n' + 'object.__pow__(self, other[, modulo])\n' + 'object.__lshift__(self, other)\n' + 'object.__rshift__(self, other)\n' + 'object.__and__(self, other)\n' + 'object.__xor__(self, other)\n' + 'object.__or__(self, other)\n' + '\n' + ' These methods are called to implement the binary ' + 'arithmetic\n' + ' operations ("+", "-", "*", "@", "/", "//", "%", ' + '"divmod()",\n' + ' "pow()", "**", "<<", ">>", "&", "^", "|"). For instance, ' + 'to\n' + ' evaluate the expression "x + y", where *x* is an instance ' + 'of a\n' + ' class that has an "__add__()" method, "type(x).__add__(x, ' + 'y)" is\n' + ' called. The "__divmod__()" method should be the ' + 'equivalent to\n' + ' using "__floordiv__()" and "__mod__()"; it should not be ' + 'related to\n' + ' "__truediv__()". Note that "__pow__()" should be defined ' + 'to accept\n' + ' an optional third argument if the ternary version of the ' + 'built-in\n' + ' "pow()" function is to be supported.\n' + '\n' + ' If one of those methods does not support the operation ' + 'with the\n' + ' supplied arguments, it should return "NotImplemented".\n' + '\n' + 'object.__radd__(self, other)\n' + 'object.__rsub__(self, other)\n' + 'object.__rmul__(self, other)\n' + 'object.__rmatmul__(self, other)\n' + 'object.__rtruediv__(self, other)\n' + 'object.__rfloordiv__(self, other)\n' + 'object.__rmod__(self, other)\n' + 'object.__rdivmod__(self, other)\n' + 'object.__rpow__(self, other[, modulo])\n' + 'object.__rlshift__(self, other)\n' + 'object.__rrshift__(self, other)\n' + 'object.__rand__(self, other)\n' + 'object.__rxor__(self, other)\n' + 'object.__ror__(self, other)\n' + '\n' + ' These methods are called to implement the binary ' + 'arithmetic\n' + ' operations ("+", "-", "*", "@", "/", "//", "%", ' + '"divmod()",\n' + ' "pow()", "**", "<<", ">>", "&", "^", "|") with reflected ' + '(swapped)\n' + ' operands. These functions are only called if the left ' + 'operand does\n' + ' not support the corresponding operation [3] and the ' + 'operands are of\n' + ' different types. [4] For instance, to evaluate the ' + 'expression "x -\n' + ' y", where *y* is an instance of a class that has an ' + '"__rsub__()"\n' + ' method, "type(y).__rsub__(y, x)" is called if ' + '"type(x).__sub__(x,\n' + ' y)" returns "NotImplemented".\n' + '\n' + ' Note that ternary "pow()" will not try calling ' + '"__rpow__()" (the\n' + ' coercion rules would become too complicated).\n' + '\n' + ' Note:\n' + '\n' + ' If the right operand’s type is a subclass of the left ' + 'operand’s\n' + ' type and that subclass provides a different ' + 'implementation of the\n' + ' reflected method for the operation, this method will be ' + 'called\n' + ' before the left operand’s non-reflected method. This ' + 'behavior\n' + ' allows subclasses to override their ancestors’ ' + 'operations.\n' + '\n' + 'object.__iadd__(self, other)\n' + 'object.__isub__(self, other)\n' + 'object.__imul__(self, other)\n' + 'object.__imatmul__(self, other)\n' + 'object.__itruediv__(self, other)\n' + 'object.__ifloordiv__(self, other)\n' + 'object.__imod__(self, other)\n' + 'object.__ipow__(self, other[, modulo])\n' + 'object.__ilshift__(self, other)\n' + 'object.__irshift__(self, other)\n' + 'object.__iand__(self, other)\n' + 'object.__ixor__(self, other)\n' + 'object.__ior__(self, other)\n' + '\n' + ' These methods are called to implement the augmented ' + 'arithmetic\n' + ' assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", ' + '"**=",\n' + ' "<<=", ">>=", "&=", "^=", "|="). These methods should ' + 'attempt to\n' + ' do the operation in-place (modifying *self*) and return ' + 'the result\n' + ' (which could be, but does not have to be, *self*). If a ' + 'specific\n' + ' method is not defined, or if that method returns ' + '"NotImplemented",\n' + ' the augmented assignment falls back to the normal ' + 'methods. For\n' + ' instance, if *x* is an instance of a class with an ' + '"__iadd__()"\n' + ' method, "x += y" is equivalent to "x = x.__iadd__(y)" . ' + 'If\n' + ' "__iadd__()" does not exist, or if "x.__iadd__(y)" ' + 'returns\n' + ' "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are\n' + ' considered, as with the evaluation of "x + y". In ' + 'certain\n' + ' situations, augmented assignment can result in unexpected ' + 'errors\n' + ' (see Why does a_tuple[i] += [‘item’] raise an exception ' + 'when the\n' + ' addition works?), but this behavior is in fact part of ' + 'the data\n' + ' model.\n' + '\n' + 'object.__neg__(self)\n' + 'object.__pos__(self)\n' + 'object.__abs__(self)\n' + 'object.__invert__(self)\n' + '\n' + ' Called to implement the unary arithmetic operations ("-", ' + '"+",\n' + ' "abs()" and "~").\n' + '\n' + 'object.__complex__(self)\n' + 'object.__int__(self)\n' + 'object.__float__(self)\n' + '\n' + ' Called to implement the built-in functions "complex()", ' + '"int()" and\n' + ' "float()". Should return a value of the appropriate ' + 'type.\n' + '\n' + 'object.__index__(self)\n' + '\n' + ' Called to implement "operator.index()", and whenever ' + 'Python needs\n' + ' to losslessly convert the numeric object to an integer ' + 'object (such\n' + ' as in slicing, or in the built-in "bin()", "hex()" and ' + '"oct()"\n' + ' functions). Presence of this method indicates that the ' + 'numeric\n' + ' object is an integer type. Must return an integer.\n' + '\n' + ' If "__int__()", "__float__()" and "__complex__()" are not ' + 'defined\n' + ' then corresponding built-in functions "int()", "float()" ' + 'and\n' + ' "complex()" fall back to "__index__()".\n' + '\n' + 'object.__round__(self[, ndigits])\n' + 'object.__trunc__(self)\n' + 'object.__floor__(self)\n' + 'object.__ceil__(self)\n' + '\n' + ' Called to implement the built-in function "round()" and ' + '"math"\n' + ' functions "trunc()", "floor()" and "ceil()". Unless ' + '*ndigits* is\n' + ' passed to "__round__()" all these methods should return ' + 'the value\n' + ' of the object truncated to an "Integral" (typically an ' + '"int").\n' + '\n' + ' The built-in function "int()" falls back to "__trunc__()" ' + 'if\n' + ' neither "__int__()" nor "__index__()" is defined.\n' + '\n' + ' Changed in version 3.11: The delegation of "int()" to ' + '"__trunc__()"\n' + ' is deprecated.\n' + '\n' + '\n' + 'With Statement Context Managers\n' + '===============================\n' + '\n' + 'A *context manager* is an object that defines the runtime ' + 'context to\n' + 'be established when executing a "with" statement. The ' + 'context manager\n' + 'handles the entry into, and the exit from, the desired ' + 'runtime context\n' + 'for the execution of the block of code. Context managers ' + 'are normally\n' + 'invoked using the "with" statement (described in section The ' + 'with\n' + 'statement), but can also be used by directly invoking their ' + 'methods.\n' + '\n' + 'Typical uses of context managers include saving and ' + 'restoring various\n' + 'kinds of global state, locking and unlocking resources, ' + 'closing opened\n' + 'files, etc.\n' + '\n' + 'For more information on context managers, see Context ' + 'Manager Types.\n' + '\n' + 'object.__enter__(self)\n' + '\n' + ' Enter the runtime context related to this object. The ' + '"with"\n' + ' statement will bind this method’s return value to the ' + 'target(s)\n' + ' specified in the "as" clause of the statement, if any.\n' + '\n' + 'object.__exit__(self, exc_type, exc_value, traceback)\n' + '\n' + ' Exit the runtime context related to this object. The ' + 'parameters\n' + ' describe the exception that caused the context to be ' + 'exited. If the\n' + ' context was exited without an exception, all three ' + 'arguments will\n' + ' be "None".\n' + '\n' + ' If an exception is supplied, and the method wishes to ' + 'suppress the\n' + ' exception (i.e., prevent it from being propagated), it ' + 'should\n' + ' return a true value. Otherwise, the exception will be ' + 'processed\n' + ' normally upon exit from this method.\n' + '\n' + ' Note that "__exit__()" methods should not reraise the ' + 'passed-in\n' + ' exception; this is the caller’s responsibility.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 343** - The “with” statement\n' + ' The specification, background, and examples for the ' + 'Python "with"\n' + ' statement.\n' + '\n' + '\n' + 'Customizing positional arguments in class pattern matching\n' + '==========================================================\n' + '\n' + 'When using a class name in a pattern, positional arguments ' + 'in the\n' + 'pattern are not allowed by default, i.e. "case MyClass(x, ' + 'y)" is\n' + 'typically invalid without special support in "MyClass". To ' + 'be able to\n' + 'use that kind of pattern, the class needs to define a ' + '*__match_args__*\n' + 'attribute.\n' + '\n' + 'object.__match_args__\n' + '\n' + ' This class variable can be assigned a tuple of strings. ' + 'When this\n' + ' class is used in a class pattern with positional ' + 'arguments, each\n' + ' positional argument will be converted into a keyword ' + 'argument,\n' + ' using the corresponding value in *__match_args__* as the ' + 'keyword.\n' + ' The absence of this attribute is equivalent to setting it ' + 'to "()".\n' + '\n' + 'For example, if "MyClass.__match_args__" is "("left", ' + '"center",\n' + '"right")" that means that "case MyClass(x, y)" is equivalent ' + 'to "case\n' + 'MyClass(left=x, center=y)". Note that the number of ' + 'arguments in the\n' + 'pattern must be smaller than or equal to the number of ' + 'elements in\n' + '*__match_args__*; if it is larger, the pattern match attempt ' + 'will\n' + 'raise a "TypeError".\n' + '\n' + 'New in version 3.10.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 634** - Structural Pattern Matching\n' + ' The specification for the Python "match" statement.\n' + '\n' + '\n' + 'Special method lookup\n' + '=====================\n' + '\n' + 'For custom classes, implicit invocations of special methods ' + 'are only\n' + 'guaranteed to work correctly if defined on an object’s type, ' + 'not in\n' + 'the object’s instance dictionary. That behaviour is the ' + 'reason why\n' + 'the following code raises an exception:\n' + '\n' + ' >>> class C:\n' + ' ... pass\n' + ' ...\n' + ' >>> c = C()\n' + ' >>> c.__len__ = lambda: 5\n' + ' >>> len(c)\n' + ' Traceback (most recent call last):\n' + ' File "", line 1, in \n' + " TypeError: object of type 'C' has no len()\n" + '\n' + 'The rationale behind this behaviour lies with a number of ' + 'special\n' + 'methods such as "__hash__()" and "__repr__()" that are ' + 'implemented by\n' + 'all objects, including type objects. If the implicit lookup ' + 'of these\n' + 'methods used the conventional lookup process, they would ' + 'fail when\n' + 'invoked on the type object itself:\n' + '\n' + ' >>> 1 .__hash__() == hash(1)\n' + ' True\n' + ' >>> int.__hash__() == hash(int)\n' + ' Traceback (most recent call last):\n' + ' File "", line 1, in \n' + " TypeError: descriptor '__hash__' of 'int' object needs an " + 'argument\n' + '\n' + 'Incorrectly attempting to invoke an unbound method of a ' + 'class in this\n' + 'way is sometimes referred to as ‘metaclass confusion’, and ' + 'is avoided\n' + 'by bypassing the instance when looking up special methods:\n' + '\n' + ' >>> type(1).__hash__(1) == hash(1)\n' + ' True\n' + ' >>> type(int).__hash__(int) == hash(int)\n' + ' True\n' + '\n' + 'In addition to bypassing any instance attributes in the ' + 'interest of\n' + 'correctness, implicit special method lookup generally also ' + 'bypasses\n' + 'the "__getattribute__()" method even of the object’s ' + 'metaclass:\n' + '\n' + ' >>> class Meta(type):\n' + ' ... def __getattribute__(*args):\n' + ' ... print("Metaclass getattribute invoked")\n' + ' ... return type.__getattribute__(*args)\n' + ' ...\n' + ' >>> class C(object, metaclass=Meta):\n' + ' ... def __len__(self):\n' + ' ... return 10\n' + ' ... def __getattribute__(*args):\n' + ' ... print("Class getattribute invoked")\n' + ' ... return object.__getattribute__(*args)\n' + ' ...\n' + ' >>> c = C()\n' + ' >>> c.__len__() # Explicit lookup via ' + 'instance\n' + ' Class getattribute invoked\n' + ' 10\n' + ' >>> type(c).__len__(c) # Explicit lookup via ' + 'type\n' + ' Metaclass getattribute invoked\n' + ' 10\n' + ' >>> len(c) # Implicit lookup\n' + ' 10\n' + '\n' + 'Bypassing the "__getattribute__()" machinery in this fashion ' + 'provides\n' + 'significant scope for speed optimisations within the ' + 'interpreter, at\n' + 'the cost of some flexibility in the handling of special ' + 'methods (the\n' + 'special method *must* be set on the class object itself in ' + 'order to be\n' + 'consistently invoked by the interpreter).\n', + 'string-methods': 'String Methods\n' + '**************\n' + '\n' + 'Strings implement all of the common sequence operations, ' + 'along with\n' + 'the additional methods described below.\n' + '\n' + 'Strings also support two styles of string formatting, one ' + 'providing a\n' + 'large degree of flexibility and customization (see ' + '"str.format()",\n' + 'Format String Syntax and Custom String Formatting) and the ' + 'other based\n' + 'on C "printf" style formatting that handles a narrower ' + 'range of types\n' + 'and is slightly harder to use correctly, but is often ' + 'faster for the\n' + 'cases it can handle (printf-style String Formatting).\n' + '\n' + 'The Text Processing Services section of the standard ' + 'library covers a\n' + 'number of other modules that provide various text related ' + 'utilities\n' + '(including regular expression support in the "re" ' + 'module).\n' + '\n' + 'str.capitalize()\n' + '\n' + ' Return a copy of the string with its first character ' + 'capitalized\n' + ' and the rest lowercased.\n' + '\n' + ' Changed in version 3.8: The first character is now put ' + 'into\n' + ' titlecase rather than uppercase. This means that ' + 'characters like\n' + ' digraphs will only have their first letter capitalized, ' + 'instead of\n' + ' the full character.\n' + '\n' + 'str.casefold()\n' + '\n' + ' Return a casefolded copy of the string. Casefolded ' + 'strings may be\n' + ' used for caseless matching.\n' + '\n' + ' Casefolding is similar to lowercasing but more ' + 'aggressive because\n' + ' it is intended to remove all case distinctions in a ' + 'string. For\n' + ' example, the German lowercase letter "\'ß\'" is ' + 'equivalent to ""ss"".\n' + ' Since it is already lowercase, "lower()" would do ' + 'nothing to "\'ß\'";\n' + ' "casefold()" converts it to ""ss"".\n' + '\n' + ' The casefolding algorithm is described in section 3.13 ' + 'of the\n' + ' Unicode Standard.\n' + '\n' + ' New in version 3.3.\n' + '\n' + 'str.center(width[, fillchar])\n' + '\n' + ' Return centered in a string of length *width*. Padding ' + 'is done\n' + ' using the specified *fillchar* (default is an ASCII ' + 'space). The\n' + ' original string is returned if *width* is less than or ' + 'equal to\n' + ' "len(s)".\n' + '\n' + 'str.count(sub[, start[, end]])\n' + '\n' + ' Return the number of non-overlapping occurrences of ' + 'substring *sub*\n' + ' in the range [*start*, *end*]. Optional arguments ' + '*start* and\n' + ' *end* are interpreted as in slice notation.\n' + '\n' + ' If *sub* is empty, returns the number of empty strings ' + 'between\n' + ' characters which is the length of the string plus one.\n' + '\n' + "str.encode(encoding='utf-8', errors='strict')\n" + '\n' + ' Return the string encoded to "bytes".\n' + '\n' + ' *encoding* defaults to "\'utf-8\'"; see Standard ' + 'Encodings for\n' + ' possible values.\n' + '\n' + ' *errors* controls how encoding errors are handled. If ' + '"\'strict\'"\n' + ' (the default), a "UnicodeError" exception is raised. ' + 'Other possible\n' + ' values are "\'ignore\'", "\'replace\'", ' + '"\'xmlcharrefreplace\'",\n' + ' "\'backslashreplace\'" and any other name registered ' + 'via\n' + ' "codecs.register_error()". See Error Handlers for ' + 'details.\n' + '\n' + ' For performance reasons, the value of *errors* is not ' + 'checked for\n' + ' validity unless an encoding error actually occurs, ' + 'Python\n' + ' Development Mode is enabled or a debug build is used.\n' + '\n' + ' Changed in version 3.1: Added support for keyword ' + 'arguments.\n' + '\n' + ' Changed in version 3.9: The value of the *errors* ' + 'argument is now\n' + ' checked in Python Development Mode and in debug mode.\n' + '\n' + 'str.endswith(suffix[, start[, end]])\n' + '\n' + ' Return "True" if the string ends with the specified ' + '*suffix*,\n' + ' otherwise return "False". *suffix* can also be a tuple ' + 'of suffixes\n' + ' to look for. With optional *start*, test beginning at ' + 'that\n' + ' position. With optional *end*, stop comparing at that ' + 'position.\n' + '\n' + 'str.expandtabs(tabsize=8)\n' + '\n' + ' Return a copy of the string where all tab characters ' + 'are replaced\n' + ' by one or more spaces, depending on the current column ' + 'and the\n' + ' given tab size. Tab positions occur every *tabsize* ' + 'characters\n' + ' (default is 8, giving tab positions at columns 0, 8, 16 ' + 'and so on).\n' + ' To expand the string, the current column is set to zero ' + 'and the\n' + ' string is examined character by character. If the ' + 'character is a\n' + ' tab ("\\t"), one or more space characters are inserted ' + 'in the result\n' + ' until the current column is equal to the next tab ' + 'position. (The\n' + ' tab character itself is not copied.) If the character ' + 'is a newline\n' + ' ("\\n") or return ("\\r"), it is copied and the current ' + 'column is\n' + ' reset to zero. Any other character is copied unchanged ' + 'and the\n' + ' current column is incremented by one regardless of how ' + 'the\n' + ' character is represented when printed.\n' + '\n' + " >>> '01\\t012\\t0123\\t01234'.expandtabs()\n" + " '01 012 0123 01234'\n" + " >>> '01\\t012\\t0123\\t01234'.expandtabs(4)\n" + " '01 012 0123 01234'\n" + '\n' + 'str.find(sub[, start[, end]])\n' + '\n' + ' Return the lowest index in the string where substring ' + '*sub* is\n' + ' found within the slice "s[start:end]". Optional ' + 'arguments *start*\n' + ' and *end* are interpreted as in slice notation. Return ' + '"-1" if\n' + ' *sub* is not found.\n' + '\n' + ' Note:\n' + '\n' + ' The "find()" method should be used only if you need ' + 'to know the\n' + ' position of *sub*. To check if *sub* is a substring ' + 'or not, use\n' + ' the "in" operator:\n' + '\n' + " >>> 'Py' in 'Python'\n" + ' True\n' + '\n' + 'str.format(*args, **kwargs)\n' + '\n' + ' Perform a string formatting operation. The string on ' + 'which this\n' + ' method is called can contain literal text or ' + 'replacement fields\n' + ' delimited by braces "{}". Each replacement field ' + 'contains either\n' + ' the numeric index of a positional argument, or the name ' + 'of a\n' + ' keyword argument. Returns a copy of the string where ' + 'each\n' + ' replacement field is replaced with the string value of ' + 'the\n' + ' corresponding argument.\n' + '\n' + ' >>> "The sum of 1 + 2 is {0}".format(1+2)\n' + " 'The sum of 1 + 2 is 3'\n" + '\n' + ' See Format String Syntax for a description of the ' + 'various\n' + ' formatting options that can be specified in format ' + 'strings.\n' + '\n' + ' Note:\n' + '\n' + ' When formatting a number ("int", "float", "complex",\n' + ' "decimal.Decimal" and subclasses) with the "n" type ' + '(ex:\n' + ' "\'{:n}\'.format(1234)"), the function temporarily ' + 'sets the\n' + ' "LC_CTYPE" locale to the "LC_NUMERIC" locale to ' + 'decode\n' + ' "decimal_point" and "thousands_sep" fields of ' + '"localeconv()" if\n' + ' they are non-ASCII or longer than 1 byte, and the ' + '"LC_NUMERIC"\n' + ' locale is different than the "LC_CTYPE" locale. This ' + 'temporary\n' + ' change affects other threads.\n' + '\n' + ' Changed in version 3.7: When formatting a number with ' + 'the "n" type,\n' + ' the function sets temporarily the "LC_CTYPE" locale to ' + 'the\n' + ' "LC_NUMERIC" locale in some cases.\n' + '\n' + 'str.format_map(mapping)\n' + '\n' + ' Similar to "str.format(**mapping)", except that ' + '"mapping" is used\n' + ' directly and not copied to a "dict". This is useful if ' + 'for example\n' + ' "mapping" is a dict subclass:\n' + '\n' + ' >>> class Default(dict):\n' + ' ... def __missing__(self, key):\n' + ' ... return key\n' + ' ...\n' + " >>> '{name} was born in " + "{country}'.format_map(Default(name='Guido'))\n" + " 'Guido was born in country'\n" + '\n' + ' New in version 3.2.\n' + '\n' + 'str.index(sub[, start[, end]])\n' + '\n' + ' Like "find()", but raise "ValueError" when the ' + 'substring is not\n' + ' found.\n' + '\n' + 'str.isalnum()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'alphanumeric and\n' + ' there is at least one character, "False" otherwise. A ' + 'character\n' + ' "c" is alphanumeric if one of the following returns ' + '"True":\n' + ' "c.isalpha()", "c.isdecimal()", "c.isdigit()", or ' + '"c.isnumeric()".\n' + '\n' + 'str.isalpha()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'alphabetic and\n' + ' there is at least one character, "False" otherwise. ' + 'Alphabetic\n' + ' characters are those characters defined in the Unicode ' + 'character\n' + ' database as “Letter”, i.e., those with general category ' + 'property\n' + ' being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note ' + 'that this is\n' + ' different from the “Alphabetic” property defined in the ' + 'Unicode\n' + ' Standard.\n' + '\n' + 'str.isascii()\n' + '\n' + ' Return "True" if the string is empty or all characters ' + 'in the\n' + ' string are ASCII, "False" otherwise. ASCII characters ' + 'have code\n' + ' points in the range U+0000-U+007F.\n' + '\n' + ' New in version 3.7.\n' + '\n' + 'str.isdecimal()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'decimal\n' + ' characters and there is at least one character, "False" ' + 'otherwise.\n' + ' Decimal characters are those that can be used to form ' + 'numbers in\n' + ' base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. ' + 'Formally a decimal\n' + ' character is a character in the Unicode General ' + 'Category “Nd”.\n' + '\n' + 'str.isdigit()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'digits and there\n' + ' is at least one character, "False" otherwise. Digits ' + 'include\n' + ' decimal characters and digits that need special ' + 'handling, such as\n' + ' the compatibility superscript digits. This covers ' + 'digits which\n' + ' cannot be used to form numbers in base 10, like the ' + 'Kharosthi\n' + ' numbers. Formally, a digit is a character that has the ' + 'property\n' + ' value Numeric_Type=Digit or Numeric_Type=Decimal.\n' + '\n' + 'str.isidentifier()\n' + '\n' + ' Return "True" if the string is a valid identifier ' + 'according to the\n' + ' language definition, section Identifiers and keywords.\n' + '\n' + ' Call "keyword.iskeyword()" to test whether string "s" ' + 'is a reserved\n' + ' identifier, such as "def" and "class".\n' + '\n' + ' Example:\n' + '\n' + ' >>> from keyword import iskeyword\n' + '\n' + " >>> 'hello'.isidentifier(), iskeyword('hello')\n" + ' (True, False)\n' + " >>> 'def'.isidentifier(), iskeyword('def')\n" + ' (True, True)\n' + '\n' + 'str.islower()\n' + '\n' + ' Return "True" if all cased characters [4] in the string ' + 'are\n' + ' lowercase and there is at least one cased character, ' + '"False"\n' + ' otherwise.\n' + '\n' + 'str.isnumeric()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'numeric\n' + ' characters, and there is at least one character, ' + '"False" otherwise.\n' + ' Numeric characters include digit characters, and all ' + 'characters\n' + ' that have the Unicode numeric value property, e.g. ' + 'U+2155, VULGAR\n' + ' FRACTION ONE FIFTH. Formally, numeric characters are ' + 'those with\n' + ' the property value Numeric_Type=Digit, ' + 'Numeric_Type=Decimal or\n' + ' Numeric_Type=Numeric.\n' + '\n' + 'str.isprintable()\n' + '\n' + ' Return "True" if all characters in the string are ' + 'printable or the\n' + ' string is empty, "False" otherwise. Nonprintable ' + 'characters are\n' + ' those characters defined in the Unicode character ' + 'database as\n' + ' “Other” or “Separator”, excepting the ASCII space ' + '(0x20) which is\n' + ' considered printable. (Note that printable characters ' + 'in this\n' + ' context are those which should not be escaped when ' + '"repr()" is\n' + ' invoked on a string. It has no bearing on the handling ' + 'of strings\n' + ' written to "sys.stdout" or "sys.stderr".)\n' + '\n' + 'str.isspace()\n' + '\n' + ' Return "True" if there are only whitespace characters ' + 'in the string\n' + ' and there is at least one character, "False" ' + 'otherwise.\n' + '\n' + ' A character is *whitespace* if in the Unicode character ' + 'database\n' + ' (see "unicodedata"), either its general category is ' + '"Zs"\n' + ' (“Separator, space”), or its bidirectional class is one ' + 'of "WS",\n' + ' "B", or "S".\n' + '\n' + 'str.istitle()\n' + '\n' + ' Return "True" if the string is a titlecased string and ' + 'there is at\n' + ' least one character, for example uppercase characters ' + 'may only\n' + ' follow uncased characters and lowercase characters only ' + 'cased ones.\n' + ' Return "False" otherwise.\n' + '\n' + 'str.isupper()\n' + '\n' + ' Return "True" if all cased characters [4] in the string ' + 'are\n' + ' uppercase and there is at least one cased character, ' + '"False"\n' + ' otherwise.\n' + '\n' + " >>> 'BANANA'.isupper()\n" + ' True\n' + " >>> 'banana'.isupper()\n" + ' False\n' + " >>> 'baNana'.isupper()\n" + ' False\n' + " >>> ' '.isupper()\n" + ' False\n' + '\n' + 'str.join(iterable)\n' + '\n' + ' Return a string which is the concatenation of the ' + 'strings in\n' + ' *iterable*. A "TypeError" will be raised if there are ' + 'any non-\n' + ' string values in *iterable*, including "bytes" ' + 'objects. The\n' + ' separator between elements is the string providing this ' + 'method.\n' + '\n' + 'str.ljust(width[, fillchar])\n' + '\n' + ' Return the string left justified in a string of length ' + '*width*.\n' + ' Padding is done using the specified *fillchar* (default ' + 'is an ASCII\n' + ' space). The original string is returned if *width* is ' + 'less than or\n' + ' equal to "len(s)".\n' + '\n' + 'str.lower()\n' + '\n' + ' Return a copy of the string with all the cased ' + 'characters [4]\n' + ' converted to lowercase.\n' + '\n' + ' The lowercasing algorithm used is described in section ' + '3.13 of the\n' + ' Unicode Standard.\n' + '\n' + 'str.lstrip([chars])\n' + '\n' + ' Return a copy of the string with leading characters ' + 'removed. The\n' + ' *chars* argument is a string specifying the set of ' + 'characters to be\n' + ' removed. If omitted or "None", the *chars* argument ' + 'defaults to\n' + ' removing whitespace. The *chars* argument is not a ' + 'prefix; rather,\n' + ' all combinations of its values are stripped:\n' + '\n' + " >>> ' spacious '.lstrip()\n" + " 'spacious '\n" + " >>> 'www.example.com'.lstrip('cmowz.')\n" + " 'example.com'\n" + '\n' + ' See "str.removeprefix()" for a method that will remove ' + 'a single\n' + ' prefix string rather than all of a set of characters. ' + 'For example:\n' + '\n' + " >>> 'Arthur: three!'.lstrip('Arthur: ')\n" + " 'ee!'\n" + " >>> 'Arthur: three!'.removeprefix('Arthur: ')\n" + " 'three!'\n" + '\n' + 'static str.maketrans(x[, y[, z]])\n' + '\n' + ' This static method returns a translation table usable ' + 'for\n' + ' "str.translate()".\n' + '\n' + ' If there is only one argument, it must be a dictionary ' + 'mapping\n' + ' Unicode ordinals (integers) or characters (strings of ' + 'length 1) to\n' + ' Unicode ordinals, strings (of arbitrary lengths) or ' + '"None".\n' + ' Character keys will then be converted to ordinals.\n' + '\n' + ' If there are two arguments, they must be strings of ' + 'equal length,\n' + ' and in the resulting dictionary, each character in x ' + 'will be mapped\n' + ' to the character at the same position in y. If there ' + 'is a third\n' + ' argument, it must be a string, whose characters will be ' + 'mapped to\n' + ' "None" in the result.\n' + '\n' + 'str.partition(sep)\n' + '\n' + ' Split the string at the first occurrence of *sep*, and ' + 'return a\n' + ' 3-tuple containing the part before the separator, the ' + 'separator\n' + ' itself, and the part after the separator. If the ' + 'separator is not\n' + ' found, return a 3-tuple containing the string itself, ' + 'followed by\n' + ' two empty strings.\n' + '\n' + 'str.removeprefix(prefix, /)\n' + '\n' + ' If the string starts with the *prefix* string, return\n' + ' "string[len(prefix):]". Otherwise, return a copy of the ' + 'original\n' + ' string:\n' + '\n' + " >>> 'TestHook'.removeprefix('Test')\n" + " 'Hook'\n" + " >>> 'BaseTestCase'.removeprefix('Test')\n" + " 'BaseTestCase'\n" + '\n' + ' New in version 3.9.\n' + '\n' + 'str.removesuffix(suffix, /)\n' + '\n' + ' If the string ends with the *suffix* string and that ' + '*suffix* is\n' + ' not empty, return "string[:-len(suffix)]". Otherwise, ' + 'return a copy\n' + ' of the original string:\n' + '\n' + " >>> 'MiscTests'.removesuffix('Tests')\n" + " 'Misc'\n" + " >>> 'TmpDirMixin'.removesuffix('Tests')\n" + " 'TmpDirMixin'\n" + '\n' + ' New in version 3.9.\n' + '\n' + 'str.replace(old, new[, count])\n' + '\n' + ' Return a copy of the string with all occurrences of ' + 'substring *old*\n' + ' replaced by *new*. If the optional argument *count* is ' + 'given, only\n' + ' the first *count* occurrences are replaced.\n' + '\n' + 'str.rfind(sub[, start[, end]])\n' + '\n' + ' Return the highest index in the string where substring ' + '*sub* is\n' + ' found, such that *sub* is contained within ' + '"s[start:end]".\n' + ' Optional arguments *start* and *end* are interpreted as ' + 'in slice\n' + ' notation. Return "-1" on failure.\n' + '\n' + 'str.rindex(sub[, start[, end]])\n' + '\n' + ' Like "rfind()" but raises "ValueError" when the ' + 'substring *sub* is\n' + ' not found.\n' + '\n' + 'str.rjust(width[, fillchar])\n' + '\n' + ' Return the string right justified in a string of length ' + '*width*.\n' + ' Padding is done using the specified *fillchar* (default ' + 'is an ASCII\n' + ' space). The original string is returned if *width* is ' + 'less than or\n' + ' equal to "len(s)".\n' + '\n' + 'str.rpartition(sep)\n' + '\n' + ' Split the string at the last occurrence of *sep*, and ' + 'return a\n' + ' 3-tuple containing the part before the separator, the ' + 'separator\n' + ' itself, and the part after the separator. If the ' + 'separator is not\n' + ' found, return a 3-tuple containing two empty strings, ' + 'followed by\n' + ' the string itself.\n' + '\n' + 'str.rsplit(sep=None, maxsplit=-1)\n' + '\n' + ' Return a list of the words in the string, using *sep* ' + 'as the\n' + ' delimiter string. If *maxsplit* is given, at most ' + '*maxsplit* splits\n' + ' are done, the *rightmost* ones. If *sep* is not ' + 'specified or\n' + ' "None", any whitespace string is a separator. Except ' + 'for splitting\n' + ' from the right, "rsplit()" behaves like "split()" which ' + 'is\n' + ' described in detail below.\n' + '\n' + 'str.rstrip([chars])\n' + '\n' + ' Return a copy of the string with trailing characters ' + 'removed. The\n' + ' *chars* argument is a string specifying the set of ' + 'characters to be\n' + ' removed. If omitted or "None", the *chars* argument ' + 'defaults to\n' + ' removing whitespace. The *chars* argument is not a ' + 'suffix; rather,\n' + ' all combinations of its values are stripped:\n' + '\n' + " >>> ' spacious '.rstrip()\n" + " ' spacious'\n" + " >>> 'mississippi'.rstrip('ipz')\n" + " 'mississ'\n" + '\n' + ' See "str.removesuffix()" for a method that will remove ' + 'a single\n' + ' suffix string rather than all of a set of characters. ' + 'For example:\n' + '\n' + " >>> 'Monty Python'.rstrip(' Python')\n" + " 'M'\n" + " >>> 'Monty Python'.removesuffix(' Python')\n" + " 'Monty'\n" + '\n' + 'str.split(sep=None, maxsplit=-1)\n' + '\n' + ' Return a list of the words in the string, using *sep* ' + 'as the\n' + ' delimiter string. If *maxsplit* is given, at most ' + '*maxsplit*\n' + ' splits are done (thus, the list will have at most ' + '"maxsplit+1"\n' + ' elements). If *maxsplit* is not specified or "-1", ' + 'then there is\n' + ' no limit on the number of splits (all possible splits ' + 'are made).\n' + '\n' + ' If *sep* is given, consecutive delimiters are not ' + 'grouped together\n' + ' and are deemed to delimit empty strings (for example,\n' + ' "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', ' + '\'2\']"). The *sep* argument\n' + ' may consist of multiple characters (for example,\n' + ' "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', ' + '\'3\']"). Splitting an\n' + ' empty string with a specified separator returns ' + '"[\'\']".\n' + '\n' + ' For example:\n' + '\n' + " >>> '1,2,3'.split(',')\n" + " ['1', '2', '3']\n" + " >>> '1,2,3'.split(',', maxsplit=1)\n" + " ['1', '2,3']\n" + " >>> '1,2,,3,'.split(',')\n" + " ['1', '2', '', '3', '']\n" + '\n' + ' If *sep* is not specified or is "None", a different ' + 'splitting\n' + ' algorithm is applied: runs of consecutive whitespace ' + 'are regarded\n' + ' as a single separator, and the result will contain no ' + 'empty strings\n' + ' at the start or end if the string has leading or ' + 'trailing\n' + ' whitespace. Consequently, splitting an empty string or ' + 'a string\n' + ' consisting of just whitespace with a "None" separator ' + 'returns "[]".\n' + '\n' + ' For example:\n' + '\n' + " >>> '1 2 3'.split()\n" + " ['1', '2', '3']\n" + " >>> '1 2 3'.split(maxsplit=1)\n" + " ['1', '2 3']\n" + " >>> ' 1 2 3 '.split()\n" + " ['1', '2', '3']\n" + '\n' + 'str.splitlines(keepends=False)\n' + '\n' + ' Return a list of the lines in the string, breaking at ' + 'line\n' + ' boundaries. Line breaks are not included in the ' + 'resulting list\n' + ' unless *keepends* is given and true.\n' + '\n' + ' This method splits on the following line boundaries. ' + 'In\n' + ' particular, the boundaries are a superset of *universal ' + 'newlines*.\n' + '\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | Representation | ' + 'Description |\n' + ' ' + '|=========================|===============================|\n' + ' | "\\n" | Line ' + 'Feed |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\r" | Carriage ' + 'Return |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\r\\n" | Carriage Return + Line ' + 'Feed |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\v" or "\\x0b" | Line ' + 'Tabulation |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\f" or "\\x0c" | Form ' + 'Feed |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\x1c" | File ' + 'Separator |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\x1d" | Group ' + 'Separator |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\x1e" | Record ' + 'Separator |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\x85" | Next Line (C1 Control ' + 'Code) |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\u2028" | Line ' + 'Separator |\n' + ' ' + '+-------------------------+-------------------------------+\n' + ' | "\\u2029" | Paragraph ' + 'Separator |\n' + ' ' + '+-------------------------+-------------------------------+\n' + '\n' + ' Changed in version 3.2: "\\v" and "\\f" added to list ' + 'of line\n' + ' boundaries.\n' + '\n' + ' For example:\n' + '\n' + " >>> 'ab c\\n\\nde fg\\rkl\\r\\n'.splitlines()\n" + " ['ab c', '', 'de fg', 'kl']\n" + " >>> 'ab c\\n\\nde " + "fg\\rkl\\r\\n'.splitlines(keepends=True)\n" + " ['ab c\\n', '\\n', 'de fg\\r', 'kl\\r\\n']\n" + '\n' + ' Unlike "split()" when a delimiter string *sep* is ' + 'given, this\n' + ' method returns an empty list for the empty string, and ' + 'a terminal\n' + ' line break does not result in an extra line:\n' + '\n' + ' >>> "".splitlines()\n' + ' []\n' + ' >>> "One line\\n".splitlines()\n' + " ['One line']\n" + '\n' + ' For comparison, "split(\'\\n\')" gives:\n' + '\n' + " >>> ''.split('\\n')\n" + " ['']\n" + " >>> 'Two lines\\n'.split('\\n')\n" + " ['Two lines', '']\n" + '\n' + 'str.startswith(prefix[, start[, end]])\n' + '\n' + ' Return "True" if string starts with the *prefix*, ' + 'otherwise return\n' + ' "False". *prefix* can also be a tuple of prefixes to ' + 'look for.\n' + ' With optional *start*, test string beginning at that ' + 'position.\n' + ' With optional *end*, stop comparing string at that ' + 'position.\n' + '\n' + 'str.strip([chars])\n' + '\n' + ' Return a copy of the string with the leading and ' + 'trailing\n' + ' characters removed. The *chars* argument is a string ' + 'specifying the\n' + ' set of characters to be removed. If omitted or "None", ' + 'the *chars*\n' + ' argument defaults to removing whitespace. The *chars* ' + 'argument is\n' + ' not a prefix or suffix; rather, all combinations of its ' + 'values are\n' + ' stripped:\n' + '\n' + " >>> ' spacious '.strip()\n" + " 'spacious'\n" + " >>> 'www.example.com'.strip('cmowz.')\n" + " 'example'\n" + '\n' + ' The outermost leading and trailing *chars* argument ' + 'values are\n' + ' stripped from the string. Characters are removed from ' + 'the leading\n' + ' end until reaching a string character that is not ' + 'contained in the\n' + ' set of characters in *chars*. A similar action takes ' + 'place on the\n' + ' trailing end. For example:\n' + '\n' + " >>> comment_string = '#....... Section 3.2.1 Issue " + "#32 .......'\n" + " >>> comment_string.strip('.#! ')\n" + " 'Section 3.2.1 Issue #32'\n" + '\n' + 'str.swapcase()\n' + '\n' + ' Return a copy of the string with uppercase characters ' + 'converted to\n' + ' lowercase and vice versa. Note that it is not ' + 'necessarily true that\n' + ' "s.swapcase().swapcase() == s".\n' + '\n' + 'str.title()\n' + '\n' + ' Return a titlecased version of the string where words ' + 'start with an\n' + ' uppercase character and the remaining characters are ' + 'lowercase.\n' + '\n' + ' For example:\n' + '\n' + " >>> 'Hello world'.title()\n" + " 'Hello World'\n" + '\n' + ' The algorithm uses a simple language-independent ' + 'definition of a\n' + ' word as groups of consecutive letters. The definition ' + 'works in\n' + ' many contexts but it means that apostrophes in ' + 'contractions and\n' + ' possessives form word boundaries, which may not be the ' + 'desired\n' + ' result:\n' + '\n' + ' >>> "they\'re bill\'s friends from the UK".title()\n' + ' "They\'Re Bill\'S Friends From The Uk"\n' + '\n' + ' The "string.capwords()" function does not have this ' + 'problem, as it\n' + ' splits words on spaces only.\n' + '\n' + ' Alternatively, a workaround for apostrophes can be ' + 'constructed\n' + ' using regular expressions:\n' + '\n' + ' >>> import re\n' + ' >>> def titlecase(s):\n' + ' ... return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n' + ' ... lambda mo: ' + 'mo.group(0).capitalize(),\n' + ' ... s)\n' + ' ...\n' + ' >>> titlecase("they\'re bill\'s friends.")\n' + ' "They\'re Bill\'s Friends."\n' + '\n' + 'str.translate(table)\n' + '\n' + ' Return a copy of the string in which each character has ' + 'been mapped\n' + ' through the given translation table. The table must be ' + 'an object\n' + ' that implements indexing via "__getitem__()", typically ' + 'a *mapping*\n' + ' or *sequence*. When indexed by a Unicode ordinal (an ' + 'integer), the\n' + ' table object can do any of the following: return a ' + 'Unicode ordinal\n' + ' or a string, to map the character to one or more other ' + 'characters;\n' + ' return "None", to delete the character from the return ' + 'string; or\n' + ' raise a "LookupError" exception, to map the character ' + 'to itself.\n' + '\n' + ' You can use "str.maketrans()" to create a translation ' + 'map from\n' + ' character-to-character mappings in different formats.\n' + '\n' + ' See also the "codecs" module for a more flexible ' + 'approach to custom\n' + ' character mappings.\n' + '\n' + 'str.upper()\n' + '\n' + ' Return a copy of the string with all the cased ' + 'characters [4]\n' + ' converted to uppercase. Note that ' + '"s.upper().isupper()" might be\n' + ' "False" if "s" contains uncased characters or if the ' + 'Unicode\n' + ' category of the resulting character(s) is not “Lu” ' + '(Letter,\n' + ' uppercase), but e.g. “Lt” (Letter, titlecase).\n' + '\n' + ' The uppercasing algorithm used is described in section ' + '3.13 of the\n' + ' Unicode Standard.\n' + '\n' + 'str.zfill(width)\n' + '\n' + ' Return a copy of the string left filled with ASCII ' + '"\'0\'" digits to\n' + ' make a string of length *width*. A leading sign prefix\n' + ' ("\'+\'"/"\'-\'") is handled by inserting the padding ' + '*after* the sign\n' + ' character rather than before. The original string is ' + 'returned if\n' + ' *width* is less than or equal to "len(s)".\n' + '\n' + ' For example:\n' + '\n' + ' >>> "42".zfill(5)\n' + " '00042'\n" + ' >>> "-42".zfill(5)\n' + " '-0042'\n", + 'strings': 'String and Bytes literals\n' + '*************************\n' + '\n' + 'String literals are described by the following lexical ' + 'definitions:\n' + '\n' + ' stringliteral ::= [stringprefix](shortstring | longstring)\n' + ' stringprefix ::= "r" | "u" | "R" | "U" | "f" | "F"\n' + ' | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | ' + '"Rf" | "RF"\n' + ' shortstring ::= "\'" shortstringitem* "\'" | \'"\' ' + 'shortstringitem* \'"\'\n' + ' longstring ::= "\'\'\'" longstringitem* "\'\'\'" | ' + '\'"""\' longstringitem* \'"""\'\n' + ' shortstringitem ::= shortstringchar | stringescapeseq\n' + ' longstringitem ::= longstringchar | stringescapeseq\n' + ' shortstringchar ::= \n' + ' longstringchar ::= \n' + ' stringescapeseq ::= "\\" \n' + '\n' + ' bytesliteral ::= bytesprefix(shortbytes | longbytes)\n' + ' bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | ' + '"rb" | "rB" | "Rb" | "RB"\n' + ' shortbytes ::= "\'" shortbytesitem* "\'" | \'"\' ' + 'shortbytesitem* \'"\'\n' + ' longbytes ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' ' + 'longbytesitem* \'"""\'\n' + ' shortbytesitem ::= shortbyteschar | bytesescapeseq\n' + ' longbytesitem ::= longbyteschar | bytesescapeseq\n' + ' shortbyteschar ::= \n' + ' longbyteschar ::= \n' + ' bytesescapeseq ::= "\\" \n' + '\n' + 'One syntactic restriction not indicated by these productions is ' + 'that\n' + 'whitespace is not allowed between the "stringprefix" or ' + '"bytesprefix"\n' + 'and the rest of the literal. The source character set is defined ' + 'by\n' + 'the encoding declaration; it is UTF-8 if no encoding declaration ' + 'is\n' + 'given in the source file; see section Encoding declarations.\n' + '\n' + 'In plain English: Both types of literals can be enclosed in ' + 'matching\n' + 'single quotes ("\'") or double quotes ("""). They can also be ' + 'enclosed\n' + 'in matching groups of three single or double quotes (these are\n' + 'generally referred to as *triple-quoted strings*). The ' + 'backslash\n' + '("\\") character is used to escape characters that otherwise have ' + 'a\n' + 'special meaning, such as newline, backslash itself, or the quote\n' + 'character.\n' + '\n' + 'Bytes literals are always prefixed with "\'b\'" or "\'B\'"; they ' + 'produce\n' + 'an instance of the "bytes" type instead of the "str" type. They ' + 'may\n' + 'only contain ASCII characters; bytes with a numeric value of 128 ' + 'or\n' + 'greater must be expressed with escapes.\n' + '\n' + 'Both string and bytes literals may optionally be prefixed with a\n' + 'letter "\'r\'" or "\'R\'"; such strings are called *raw strings* ' + 'and treat\n' + 'backslashes as literal characters. As a result, in string ' + 'literals,\n' + '"\'\\U\'" and "\'\\u\'" escapes in raw strings are not treated ' + 'specially.\n' + 'Given that Python 2.x’s raw unicode literals behave differently ' + 'than\n' + 'Python 3.x’s the "\'ur\'" syntax is not supported.\n' + '\n' + 'New in version 3.3: The "\'rb\'" prefix of raw bytes literals has ' + 'been\n' + 'added as a synonym of "\'br\'".Support for the unicode legacy ' + 'literal\n' + '("u\'value\'") was reintroduced to simplify the maintenance of ' + 'dual\n' + 'Python 2.x and 3.x codebases. See **PEP 414** for more ' + 'information.\n' + '\n' + 'A string literal with "\'f\'" or "\'F\'" in its prefix is a ' + '*formatted\n' + 'string literal*; see f-strings. The "\'f\'" may be combined with ' + '"\'r\'",\n' + 'but not with "\'b\'" or "\'u\'", therefore raw formatted strings ' + 'are\n' + 'possible, but formatted bytes literals are not.\n' + '\n' + 'In triple-quoted literals, unescaped newlines and quotes are ' + 'allowed\n' + '(and are retained), except that three unescaped quotes in a row\n' + 'terminate the literal. (A “quote” is the character used to open ' + 'the\n' + 'literal, i.e. either "\'" or """.)\n' + '\n' + '\n' + 'Escape sequences\n' + '================\n' + '\n' + 'Unless an "\'r\'" or "\'R\'" prefix is present, escape sequences ' + 'in string\n' + 'and bytes literals are interpreted according to rules similar to ' + 'those\n' + 'used by Standard C. The recognized escape sequences are:\n' + '\n' + '+---------------------------+-----------------------------------+---------+\n' + '| Escape Sequence | Meaning | ' + 'Notes |\n' + '|===========================|===================================|=========|\n' + '| "\\" | Backslash and newline ignored ' + '| (1) |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\\\" | Backslash ' + '("\\") | |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\\'" | Single quote ' + '("\'") | |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\"" | Double quote (""") ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\a" | ASCII Bell (BEL) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\b" | ASCII Backspace (BS) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\f" | ASCII Formfeed (FF) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\n" | ASCII Linefeed (LF) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\r" | ASCII Carriage Return (CR) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\t" | ASCII Horizontal Tab (TAB) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\v" | ASCII Vertical Tab (VT) ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\*ooo*" | Character with octal value *ooo* ' + '| (2,4) |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\x*hh*" | Character with hex value *hh* ' + '| (3,4) |\n' + '+---------------------------+-----------------------------------+---------+\n' + '\n' + 'Escape sequences only recognized in string literals are:\n' + '\n' + '+---------------------------+-----------------------------------+---------+\n' + '| Escape Sequence | Meaning | ' + 'Notes |\n' + '|===========================|===================================|=========|\n' + '| "\\N{*name*}" | Character named *name* in the ' + '| (5) |\n' + '| | Unicode database ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\u*xxxx*" | Character with 16-bit hex value ' + '| (6) |\n' + '| | *xxxx* ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '| "\\U*xxxxxxxx*" | Character with 32-bit hex value ' + '| (7) |\n' + '| | *xxxxxxxx* ' + '| |\n' + '+---------------------------+-----------------------------------+---------+\n' + '\n' + 'Notes:\n' + '\n' + '1. A backslash can be added at the end of a line to ignore the\n' + ' newline:\n' + '\n' + " >>> 'This string will not include \\\n" + " ... backslashes or newline characters.'\n" + " 'This string will not include backslashes or newline " + "characters.'\n" + '\n' + ' The same result can be achieved using triple-quoted strings, ' + 'or\n' + ' parentheses and string literal concatenation.\n' + '\n' + '2. As in Standard C, up to three octal digits are accepted.\n' + '\n' + ' Changed in version 3.11: Octal escapes with value larger than\n' + ' "0o377" produce a "DeprecationWarning". In a future Python ' + 'version\n' + ' they will be a "SyntaxWarning" and eventually a ' + '"SyntaxError".\n' + '\n' + '3. Unlike in Standard C, exactly two hex digits are required.\n' + '\n' + '4. In a bytes literal, hexadecimal and octal escapes denote the ' + 'byte\n' + ' with the given value. In a string literal, these escapes ' + 'denote a\n' + ' Unicode character with the given value.\n' + '\n' + '5. Changed in version 3.3: Support for name aliases [1] has been\n' + ' added.\n' + '\n' + '6. Exactly four hex digits are required.\n' + '\n' + '7. Any Unicode character can be encoded this way. Exactly eight ' + 'hex\n' + ' digits are required.\n' + '\n' + 'Unlike Standard C, all unrecognized escape sequences are left in ' + 'the\n' + 'string unchanged, i.e., *the backslash is left in the result*. ' + '(This\n' + 'behavior is useful when debugging: if an escape sequence is ' + 'mistyped,\n' + 'the resulting output is more easily recognized as broken.) It is ' + 'also\n' + 'important to note that the escape sequences only recognized in ' + 'string\n' + 'literals fall into the category of unrecognized escapes for ' + 'bytes\n' + 'literals.\n' + '\n' + 'Changed in version 3.6: Unrecognized escape sequences produce a\n' + '"DeprecationWarning". In a future Python version they will be a\n' + '"SyntaxWarning" and eventually a "SyntaxError".\n' + '\n' + 'Even in a raw literal, quotes can be escaped with a backslash, ' + 'but the\n' + 'backslash remains in the result; for example, "r"\\""" is a ' + 'valid\n' + 'string literal consisting of two characters: a backslash and a ' + 'double\n' + 'quote; "r"\\"" is not a valid string literal (even a raw string ' + 'cannot\n' + 'end in an odd number of backslashes). Specifically, *a raw ' + 'literal\n' + 'cannot end in a single backslash* (since the backslash would ' + 'escape\n' + 'the following quote character). Note also that a single ' + 'backslash\n' + 'followed by a newline is interpreted as those two characters as ' + 'part\n' + 'of the literal, *not* as a line continuation.\n', + 'subscriptions': 'Subscriptions\n' + '*************\n' + '\n' + 'The subscription of an instance of a container class will ' + 'generally\n' + 'select an element from the container. The subscription of a ' + '*generic\n' + 'class* will generally return a GenericAlias object.\n' + '\n' + ' subscription ::= primary "[" expression_list "]"\n' + '\n' + 'When an object is subscripted, the interpreter will ' + 'evaluate the\n' + 'primary and the expression list.\n' + '\n' + 'The primary must evaluate to an object that supports ' + 'subscription. An\n' + 'object may support subscription through defining one or ' + 'both of\n' + '"__getitem__()" and "__class_getitem__()". When the primary ' + 'is\n' + 'subscripted, the evaluated result of the expression list ' + 'will be\n' + 'passed to one of these methods. For more details on when\n' + '"__class_getitem__" is called instead of "__getitem__", ' + 'see\n' + '__class_getitem__ versus __getitem__.\n' + '\n' + 'If the expression list contains at least one comma, it will ' + 'evaluate\n' + 'to a "tuple" containing the items of the expression list. ' + 'Otherwise,\n' + 'the expression list will evaluate to the value of the ' + 'list’s sole\n' + 'member.\n' + '\n' + 'For built-in objects, there are two types of objects that ' + 'support\n' + 'subscription via "__getitem__()":\n' + '\n' + '1. Mappings. If the primary is a *mapping*, the expression ' + 'list must\n' + ' evaluate to an object whose value is one of the keys of ' + 'the\n' + ' mapping, and the subscription selects the value in the ' + 'mapping that\n' + ' corresponds to that key. An example of a builtin mapping ' + 'class is\n' + ' the "dict" class.\n' + '\n' + '2. Sequences. If the primary is a *sequence*, the ' + 'expression list must\n' + ' evaluate to an "int" or a "slice" (as discussed in the ' + 'following\n' + ' section). Examples of builtin sequence classes include ' + 'the "str",\n' + ' "list" and "tuple" classes.\n' + '\n' + 'The formal syntax makes no special provision for negative ' + 'indices in\n' + '*sequences*. However, built-in sequences all provide a ' + '"__getitem__()"\n' + 'method that interprets negative indices by adding the ' + 'length of the\n' + 'sequence to the index so that, for example, "x[-1]" selects ' + 'the last\n' + 'item of "x". The resulting value must be a nonnegative ' + 'integer less\n' + 'than the number of items in the sequence, and the ' + 'subscription selects\n' + 'the item whose index is that value (counting from zero). ' + 'Since the\n' + 'support for negative indices and slicing occurs in the ' + 'object’s\n' + '"__getitem__()" method, subclasses overriding this method ' + 'will need to\n' + 'explicitly add that support.\n' + '\n' + 'A "string" is a special kind of sequence whose items are ' + '*characters*.\n' + 'A character is not a separate data type but a string of ' + 'exactly one\n' + 'character.\n', + 'truth': 'Truth Value Testing\n' + '*******************\n' + '\n' + 'Any object can be tested for truth value, for use in an "if" or\n' + '"while" condition or as operand of the Boolean operations below.\n' + '\n' + 'By default, an object is considered true unless its class defines\n' + 'either a "__bool__()" method that returns "False" or a "__len__()"\n' + 'method that returns zero, when called with the object. [1] Here ' + 'are\n' + 'most of the built-in objects considered false:\n' + '\n' + '* constants defined to be false: "None" and "False"\n' + '\n' + '* zero of any numeric type: "0", "0.0", "0j", "Decimal(0)",\n' + ' "Fraction(0, 1)"\n' + '\n' + '* empty sequences and collections: "\'\'", "()", "[]", "{}", ' + '"set()",\n' + ' "range(0)"\n' + '\n' + 'Operations and built-in functions that have a Boolean result ' + 'always\n' + 'return "0" or "False" for false and "1" or "True" for true, unless\n' + 'otherwise stated. (Important exception: the Boolean operations ' + '"or"\n' + 'and "and" always return one of their operands.)\n', + 'try': 'The "try" statement\n' + '*******************\n' + '\n' + 'The "try" statement specifies exception handlers and/or cleanup code\n' + 'for a group of statements:\n' + '\n' + ' try_stmt ::= try1_stmt | try2_stmt | try3_stmt\n' + ' try1_stmt ::= "try" ":" suite\n' + ' ("except" [expression ["as" identifier]] ":" ' + 'suite)+\n' + ' ["else" ":" suite]\n' + ' ["finally" ":" suite]\n' + ' try2_stmt ::= "try" ":" suite\n' + ' ("except" "*" expression ["as" identifier] ":" ' + 'suite)+\n' + ' ["else" ":" suite]\n' + ' ["finally" ":" suite]\n' + ' try3_stmt ::= "try" ":" suite\n' + ' "finally" ":" suite\n' + '\n' + 'Additional information on exceptions can be found in section\n' + 'Exceptions, and information on using the "raise" statement to ' + 'generate\n' + 'exceptions may be found in section The raise statement.\n' + '\n' + '\n' + '"except" clause\n' + '===============\n' + '\n' + 'The "except" clause(s) specify one or more exception handlers. When ' + 'no\n' + 'exception occurs in the "try" clause, no exception handler is\n' + 'executed. When an exception occurs in the "try" suite, a search for ' + 'an\n' + 'exception handler is started. This search inspects the "except"\n' + 'clauses in turn until one is found that matches the exception. An\n' + 'expression-less "except" clause, if present, must be last; it ' + 'matches\n' + 'any exception. For an "except" clause with an expression, that\n' + 'expression is evaluated, and the clause matches the exception if the\n' + 'resulting object is “compatible” with the exception. An object is\n' + 'compatible with an exception if the object is the class or a *non-\n' + 'virtual base class* of the exception object, or a tuple containing ' + 'an\n' + 'item that is the class or a non-virtual base class of the exception\n' + 'object.\n' + '\n' + 'If no "except" clause matches the exception, the search for an\n' + 'exception handler continues in the surrounding code and on the\n' + 'invocation stack. [1]\n' + '\n' + 'If the evaluation of an expression in the header of an "except" ' + 'clause\n' + 'raises an exception, the original search for a handler is canceled ' + 'and\n' + 'a search starts for the new exception in the surrounding code and on\n' + 'the call stack (it is treated as if the entire "try" statement ' + 'raised\n' + 'the exception).\n' + '\n' + 'When a matching "except" clause is found, the exception is assigned ' + 'to\n' + 'the target specified after the "as" keyword in that "except" clause,\n' + 'if present, and the "except" clause’s suite is executed. All ' + '"except"\n' + 'clauses must have an executable block. When the end of this block is\n' + 'reached, execution continues normally after the entire "try"\n' + 'statement. (This means that if two nested handlers exist for the ' + 'same\n' + 'exception, and the exception occurs in the "try" clause of the inner\n' + 'handler, the outer handler will not handle the exception.)\n' + '\n' + 'When an exception has been assigned using "as target", it is cleared\n' + 'at the end of the "except" clause. This is as if\n' + '\n' + ' except E as N:\n' + ' foo\n' + '\n' + 'was translated to\n' + '\n' + ' except E as N:\n' + ' try:\n' + ' foo\n' + ' finally:\n' + ' del N\n' + '\n' + 'This means the exception must be assigned to a different name to be\n' + 'able to refer to it after the "except" clause. Exceptions are ' + 'cleared\n' + 'because with the traceback attached to them, they form a reference\n' + 'cycle with the stack frame, keeping all locals in that frame alive\n' + 'until the next garbage collection occurs.\n' + '\n' + 'Before an "except" clause’s suite is executed, the exception is ' + 'stored\n' + 'in the "sys" module, where it can be accessed from within the body ' + 'of\n' + 'the "except" clause by calling "sys.exception()". When leaving an\n' + 'exception handler, the exception stored in the "sys" module is reset\n' + 'to its previous value:\n' + '\n' + ' >>> print(sys.exception())\n' + ' None\n' + ' >>> try:\n' + ' ... raise TypeError\n' + ' ... except:\n' + ' ... print(repr(sys.exception()))\n' + ' ... try:\n' + ' ... raise ValueError\n' + ' ... except:\n' + ' ... print(repr(sys.exception()))\n' + ' ... print(repr(sys.exception()))\n' + ' ...\n' + ' TypeError()\n' + ' ValueError()\n' + ' TypeError()\n' + ' >>> print(sys.exception())\n' + ' None\n' + '\n' + '\n' + '"except*" clause\n' + '================\n' + '\n' + 'The "except*" clause(s) are used for handling "ExceptionGroup"s. The\n' + 'exception type for matching is interpreted as in the case of ' + '"except",\n' + 'but in the case of exception groups we can have partial matches when\n' + 'the type matches some of the exceptions in the group. This means ' + 'that\n' + 'multiple "except*" clauses can execute, each handling part of the\n' + 'exception group. Each clause executes at most once and handles an\n' + 'exception group of all matching exceptions. Each exception in the\n' + 'group is handled by at most one "except*" clause, the first that\n' + 'matches it.\n' + '\n' + ' >>> try:\n' + ' ... raise ExceptionGroup("eg",\n' + ' ... [ValueError(1), TypeError(2), OSError(3), ' + 'OSError(4)])\n' + ' ... except* TypeError as e:\n' + " ... print(f'caught {type(e)} with nested {e.exceptions}')\n" + ' ... except* OSError as e:\n' + " ... print(f'caught {type(e)} with nested {e.exceptions}')\n" + ' ...\n' + " caught with nested (TypeError(2),)\n" + " caught with nested (OSError(3), " + 'OSError(4))\n' + ' + Exception Group Traceback (most recent call last):\n' + ' | File "", line 2, in \n' + ' | ExceptionGroup: eg\n' + ' +-+---------------- 1 ----------------\n' + ' | ValueError: 1\n' + ' +------------------------------------\n' + '\n' + 'Any remaining exceptions that were not handled by any "except*" ' + 'clause\n' + 'are re-raised at the end, combined into an exception group along ' + 'with\n' + 'all exceptions that were raised from within "except*" clauses.\n' + '\n' + 'From version 3.11.4, when the entire "ExceptionGroup" is handled and\n' + 'only one exception is raised from an "except*" clause, this ' + 'exception\n' + 'is no longer wrapped to form a new "ExceptionGroup".\n' + '\n' + 'If the raised exception is not an exception group and its type ' + 'matches\n' + 'one of the "except*" clauses, it is caught and wrapped by an ' + 'exception\n' + 'group with an empty message string.\n' + '\n' + ' >>> try:\n' + ' ... raise BlockingIOError\n' + ' ... except* BlockingIOError as e:\n' + ' ... print(repr(e))\n' + ' ...\n' + " ExceptionGroup('', (BlockingIOError()))\n" + '\n' + 'An "except*" clause must have a matching type, and this type cannot ' + 'be\n' + 'a subclass of "BaseExceptionGroup". It is not possible to mix ' + '"except"\n' + 'and "except*" in the same "try". "break", "continue" and "return"\n' + 'cannot appear in an "except*" clause.\n' + '\n' + '\n' + '"else" clause\n' + '=============\n' + '\n' + 'The optional "else" clause is executed if the control flow leaves ' + 'the\n' + '"try" suite, no exception was raised, and no "return", "continue", ' + 'or\n' + '"break" statement was executed. Exceptions in the "else" clause are\n' + 'not handled by the preceding "except" clauses.\n' + '\n' + '\n' + '"finally" clause\n' + '================\n' + '\n' + 'If "finally" is present, it specifies a ‘cleanup’ handler. The ' + '"try"\n' + 'clause is executed, including any "except" and "else" clauses. If ' + 'an\n' + 'exception occurs in any of the clauses and is not handled, the\n' + 'exception is temporarily saved. The "finally" clause is executed. ' + 'If\n' + 'there is a saved exception it is re-raised at the end of the ' + '"finally"\n' + 'clause. If the "finally" clause raises another exception, the saved\n' + 'exception is set as the context of the new exception. If the ' + '"finally"\n' + 'clause executes a "return", "break" or "continue" statement, the ' + 'saved\n' + 'exception is discarded:\n' + '\n' + ' >>> def f():\n' + ' ... try:\n' + ' ... 1/0\n' + ' ... finally:\n' + ' ... return 42\n' + ' ...\n' + ' >>> f()\n' + ' 42\n' + '\n' + 'The exception information is not available to the program during\n' + 'execution of the "finally" clause.\n' + '\n' + 'When a "return", "break" or "continue" statement is executed in the\n' + '"try" suite of a "try"…"finally" statement, the "finally" clause is\n' + 'also executed ‘on the way out.’\n' + '\n' + 'The return value of a function is determined by the last "return"\n' + 'statement executed. Since the "finally" clause always executes, a\n' + '"return" statement executed in the "finally" clause will always be ' + 'the\n' + 'last one executed:\n' + '\n' + ' >>> def foo():\n' + ' ... try:\n' + " ... return 'try'\n" + ' ... finally:\n' + " ... return 'finally'\n" + ' ...\n' + ' >>> foo()\n' + " 'finally'\n" + '\n' + 'Changed in version 3.8: Prior to Python 3.8, a "continue" statement\n' + 'was illegal in the "finally" clause due to a problem with the\n' + 'implementation.\n', + 'types': 'The standard type hierarchy\n' + '***************************\n' + '\n' + 'Below is a list of the types that are built into Python. ' + 'Extension\n' + 'modules (written in C, Java, or other languages, depending on the\n' + 'implementation) can define additional types. Future versions of\n' + 'Python may add types to the type hierarchy (e.g., rational ' + 'numbers,\n' + 'efficiently stored arrays of integers, etc.), although such ' + 'additions\n' + 'will often be provided via the standard library instead.\n' + '\n' + 'Some of the type descriptions below contain a paragraph listing\n' + '‘special attributes.’ These are attributes that provide access to ' + 'the\n' + 'implementation and are not intended for general use. Their ' + 'definition\n' + 'may change in the future.\n' + '\n' + '\n' + 'None\n' + '====\n' + '\n' + 'This type has a single value. There is a single object with this\n' + 'value. This object is accessed through the built-in name "None". It ' + 'is\n' + 'used to signify the absence of a value in many situations, e.g., it ' + 'is\n' + 'returned from functions that don’t explicitly return anything. Its\n' + 'truth value is false.\n' + '\n' + '\n' + 'NotImplemented\n' + '==============\n' + '\n' + 'This type has a single value. There is a single object with this\n' + 'value. This object is accessed through the built-in name\n' + '"NotImplemented". Numeric methods and rich comparison methods ' + 'should\n' + 'return this value if they do not implement the operation for the\n' + 'operands provided. (The interpreter will then try the reflected\n' + 'operation, or some other fallback, depending on the operator.) It\n' + 'should not be evaluated in a boolean context.\n' + '\n' + 'See Implementing the arithmetic operations for more details.\n' + '\n' + 'Changed in version 3.9: Evaluating "NotImplemented" in a boolean\n' + 'context is deprecated. While it currently evaluates as true, it ' + 'will\n' + 'emit a "DeprecationWarning". It will raise a "TypeError" in a ' + 'future\n' + 'version of Python.\n' + '\n' + '\n' + 'Ellipsis\n' + '========\n' + '\n' + 'This type has a single value. There is a single object with this\n' + 'value. This object is accessed through the literal "..." or the ' + 'built-\n' + 'in name "Ellipsis". Its truth value is true.\n' + '\n' + '\n' + '"numbers.Number"\n' + '================\n' + '\n' + 'These are created by numeric literals and returned as results by\n' + 'arithmetic operators and arithmetic built-in functions. Numeric\n' + 'objects are immutable; once created their value never changes. ' + 'Python\n' + 'numbers are of course strongly related to mathematical numbers, ' + 'but\n' + 'subject to the limitations of numerical representation in ' + 'computers.\n' + '\n' + 'The string representations of the numeric classes, computed by\n' + '"__repr__()" and "__str__()", have the following properties:\n' + '\n' + '* They are valid numeric literals which, when passed to their ' + 'class\n' + ' constructor, produce an object having the value of the original\n' + ' numeric.\n' + '\n' + '* The representation is in base 10, when possible.\n' + '\n' + '* Leading zeros, possibly excepting a single zero before a decimal\n' + ' point, are not shown.\n' + '\n' + '* Trailing zeros, possibly excepting a single zero after a decimal\n' + ' point, are not shown.\n' + '\n' + '* A sign is shown only when the number is negative.\n' + '\n' + 'Python distinguishes between integers, floating point numbers, and\n' + 'complex numbers:\n' + '\n' + '\n' + '"numbers.Integral"\n' + '------------------\n' + '\n' + 'These represent elements from the mathematical set of integers\n' + '(positive and negative).\n' + '\n' + 'Note:\n' + '\n' + ' The rules for integer representation are intended to give the ' + 'most\n' + ' meaningful interpretation of shift and mask operations involving\n' + ' negative integers.\n' + '\n' + 'There are two types of integers:\n' + '\n' + 'Integers ("int")\n' + ' These represent numbers in an unlimited range, subject to ' + 'available\n' + ' (virtual) memory only. For the purpose of shift and mask\n' + ' operations, a binary representation is assumed, and negative\n' + ' numbers are represented in a variant of 2’s complement which ' + 'gives\n' + ' the illusion of an infinite string of sign bits extending to ' + 'the\n' + ' left.\n' + '\n' + 'Booleans ("bool")\n' + ' These represent the truth values False and True. The two ' + 'objects\n' + ' representing the values "False" and "True" are the only Boolean\n' + ' objects. The Boolean type is a subtype of the integer type, and\n' + ' Boolean values behave like the values 0 and 1, respectively, in\n' + ' almost all contexts, the exception being that when converted to ' + 'a\n' + ' string, the strings ""False"" or ""True"" are returned,\n' + ' respectively.\n' + '\n' + '\n' + '"numbers.Real" ("float")\n' + '------------------------\n' + '\n' + 'These represent machine-level double precision floating point ' + 'numbers.\n' + 'You are at the mercy of the underlying machine architecture (and C ' + 'or\n' + 'Java implementation) for the accepted range and handling of ' + 'overflow.\n' + 'Python does not support single-precision floating point numbers; ' + 'the\n' + 'savings in processor and memory usage that are usually the reason ' + 'for\n' + 'using these are dwarfed by the overhead of using objects in Python, ' + 'so\n' + 'there is no reason to complicate the language with two kinds of\n' + 'floating point numbers.\n' + '\n' + '\n' + '"numbers.Complex" ("complex")\n' + '-----------------------------\n' + '\n' + 'These represent complex numbers as a pair of machine-level double\n' + 'precision floating point numbers. The same caveats apply as for\n' + 'floating point numbers. The real and imaginary parts of a complex\n' + 'number "z" can be retrieved through the read-only attributes ' + '"z.real"\n' + 'and "z.imag".\n' + '\n' + '\n' + 'Sequences\n' + '=========\n' + '\n' + 'These represent finite ordered sets indexed by non-negative ' + 'numbers.\n' + 'The built-in function "len()" returns the number of items of a\n' + 'sequence. When the length of a sequence is *n*, the index set ' + 'contains\n' + 'the numbers 0, 1, …, *n*-1. Item *i* of sequence *a* is selected ' + 'by\n' + '"a[i]". Some sequences, including built-in sequences, interpret\n' + 'negative subscripts by adding the sequence length. For example,\n' + '"a[-2]" equals "a[n-2]", the second to last item of sequence a ' + 'with\n' + 'length "n".\n' + '\n' + 'Sequences also support slicing: "a[i:j]" selects all items with ' + 'index\n' + '*k* such that *i* "<=" *k* "<" *j*. When used as an expression, a\n' + 'slice is a sequence of the same type. The comment above about ' + 'negative\n' + 'indexes also applies to negative slice positions.\n' + '\n' + 'Some sequences also support “extended slicing” with a third “step”\n' + 'parameter: "a[i:j:k]" selects all items of *a* with index *x* where ' + '"x\n' + '= i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.\n' + '\n' + 'Sequences are distinguished according to their mutability:\n' + '\n' + '\n' + 'Immutable sequences\n' + '-------------------\n' + '\n' + 'An object of an immutable sequence type cannot change once it is\n' + 'created. (If the object contains references to other objects, ' + 'these\n' + 'other objects may be mutable and may be changed; however, the\n' + 'collection of objects directly referenced by an immutable object\n' + 'cannot change.)\n' + '\n' + 'The following types are immutable sequences:\n' + '\n' + 'Strings\n' + ' A string is a sequence of values that represent Unicode code\n' + ' points. All the code points in the range "U+0000 - U+10FFFF" can ' + 'be\n' + ' represented in a string. Python doesn’t have a char type; ' + 'instead,\n' + ' every code point in the string is represented as a string ' + 'object\n' + ' with length "1". The built-in function "ord()" converts a code\n' + ' point from its string form to an integer in the range "0 - ' + '10FFFF";\n' + ' "chr()" converts an integer in the range "0 - 10FFFF" to the\n' + ' corresponding length "1" string object. "str.encode()" can be ' + 'used\n' + ' to convert a "str" to "bytes" using the given text encoding, ' + 'and\n' + ' "bytes.decode()" can be used to achieve the opposite.\n' + '\n' + 'Tuples\n' + ' The items of a tuple are arbitrary Python objects. Tuples of two ' + 'or\n' + ' more items are formed by comma-separated lists of expressions. ' + 'A\n' + ' tuple of one item (a ‘singleton’) can be formed by affixing a ' + 'comma\n' + ' to an expression (an expression by itself does not create a ' + 'tuple,\n' + ' since parentheses must be usable for grouping of expressions). ' + 'An\n' + ' empty tuple can be formed by an empty pair of parentheses.\n' + '\n' + 'Bytes\n' + ' A bytes object is an immutable array. The items are 8-bit ' + 'bytes,\n' + ' represented by integers in the range 0 <= x < 256. Bytes ' + 'literals\n' + ' (like "b\'abc\'") and the built-in "bytes()" constructor can be ' + 'used\n' + ' to create bytes objects. Also, bytes objects can be decoded to\n' + ' strings via the "decode()" method.\n' + '\n' + '\n' + 'Mutable sequences\n' + '-----------------\n' + '\n' + 'Mutable sequences can be changed after they are created. The\n' + 'subscription and slicing notations can be used as the target of\n' + 'assignment and "del" (delete) statements.\n' + '\n' + 'Note:\n' + '\n' + ' The "collections" and "array" module provide additional examples ' + 'of\n' + ' mutable sequence types.\n' + '\n' + 'There are currently two intrinsic mutable sequence types:\n' + '\n' + 'Lists\n' + ' The items of a list are arbitrary Python objects. Lists are ' + 'formed\n' + ' by placing a comma-separated list of expressions in square\n' + ' brackets. (Note that there are no special cases needed to form\n' + ' lists of length 0 or 1.)\n' + '\n' + 'Byte Arrays\n' + ' A bytearray object is a mutable array. They are created by the\n' + ' built-in "bytearray()" constructor. Aside from being mutable ' + '(and\n' + ' hence unhashable), byte arrays otherwise provide the same ' + 'interface\n' + ' and functionality as immutable "bytes" objects.\n' + '\n' + '\n' + 'Set types\n' + '=========\n' + '\n' + 'These represent unordered, finite sets of unique, immutable ' + 'objects.\n' + 'As such, they cannot be indexed by any subscript. However, they can ' + 'be\n' + 'iterated over, and the built-in function "len()" returns the number ' + 'of\n' + 'items in a set. Common uses for sets are fast membership testing,\n' + 'removing duplicates from a sequence, and computing mathematical\n' + 'operations such as intersection, union, difference, and symmetric\n' + 'difference.\n' + '\n' + 'For set elements, the same immutability rules apply as for ' + 'dictionary\n' + 'keys. Note that numeric types obey the normal rules for numeric\n' + 'comparison: if two numbers compare equal (e.g., "1" and "1.0"), ' + 'only\n' + 'one of them can be contained in a set.\n' + '\n' + 'There are currently two intrinsic set types:\n' + '\n' + 'Sets\n' + ' These represent a mutable set. They are created by the built-in\n' + ' "set()" constructor and can be modified afterwards by several\n' + ' methods, such as "add()".\n' + '\n' + 'Frozen sets\n' + ' These represent an immutable set. They are created by the ' + 'built-in\n' + ' "frozenset()" constructor. As a frozenset is immutable and\n' + ' *hashable*, it can be used again as an element of another set, ' + 'or\n' + ' as a dictionary key.\n' + '\n' + '\n' + 'Mappings\n' + '========\n' + '\n' + 'These represent finite sets of objects indexed by arbitrary index\n' + 'sets. The subscript notation "a[k]" selects the item indexed by ' + '"k"\n' + 'from the mapping "a"; this can be used in expressions and as the\n' + 'target of assignments or "del" statements. The built-in function\n' + '"len()" returns the number of items in a mapping.\n' + '\n' + 'There is currently a single intrinsic mapping type:\n' + '\n' + '\n' + 'Dictionaries\n' + '------------\n' + '\n' + 'These represent finite sets of objects indexed by nearly arbitrary\n' + 'values. The only types of values not acceptable as keys are ' + 'values\n' + 'containing lists or dictionaries or other mutable types that are\n' + 'compared by value rather than by object identity, the reason being\n' + 'that the efficient implementation of dictionaries requires a key’s\n' + 'hash value to remain constant. Numeric types used for keys obey ' + 'the\n' + 'normal rules for numeric comparison: if two numbers compare equal\n' + '(e.g., "1" and "1.0") then they can be used interchangeably to ' + 'index\n' + 'the same dictionary entry.\n' + '\n' + 'Dictionaries preserve insertion order, meaning that keys will be\n' + 'produced in the same order they were added sequentially over the\n' + 'dictionary. Replacing an existing key does not change the order,\n' + 'however removing a key and re-inserting it will add it to the end\n' + 'instead of keeping its old place.\n' + '\n' + 'Dictionaries are mutable; they can be created by the "{...}" ' + 'notation\n' + '(see section Dictionary displays).\n' + '\n' + 'The extension modules "dbm.ndbm" and "dbm.gnu" provide additional\n' + 'examples of mapping types, as does the "collections" module.\n' + '\n' + 'Changed in version 3.7: Dictionaries did not preserve insertion ' + 'order\n' + 'in versions of Python before 3.6. In CPython 3.6, insertion order ' + 'was\n' + 'preserved, but it was considered an implementation detail at that ' + 'time\n' + 'rather than a language guarantee.\n' + '\n' + '\n' + 'Callable types\n' + '==============\n' + '\n' + 'These are the types to which the function call operation (see ' + 'section\n' + 'Calls) can be applied:\n' + '\n' + '\n' + 'User-defined functions\n' + '----------------------\n' + '\n' + 'A user-defined function object is created by a function definition\n' + '(see section Function definitions). It should be called with an\n' + 'argument list containing the same number of items as the ' + 'function’s\n' + 'formal parameter list.\n' + '\n' + '\n' + 'Special read-only attributes\n' + '~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| Attribute | ' + 'Meaning |\n' + '|====================================================|====================================================|\n' + '| function.__globals__ | A reference ' + 'to the "dictionary" that holds the |\n' + '| | function’s ' + 'global variables – the global namespace |\n' + '| | of the ' + 'module in which the function was defined. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__closure__ | "None" or a ' + '"tuple" of cells that contain bindings |\n' + '| | for the ' + 'function’s free variables. A cell object |\n' + '| | has the ' + 'attribute "cell_contents". This can be |\n' + '| | used to get ' + 'the value of the cell, as well as set |\n' + '| | the ' + 'value. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + '\n' + 'Special writable attributes\n' + '~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + 'Most of these attributes check the type of the assigned value:\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| Attribute | ' + 'Meaning |\n' + '|====================================================|====================================================|\n' + '| function.__doc__ | The ' + 'function’s documentation string, or "None" if |\n' + '| | unavailable. ' + 'Not inherited by subclasses. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__name__ | The ' + 'function’s name. See also: "__name__ |\n' + '| | ' + 'attributes". |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__qualname__ | The ' + 'function’s *qualified name*. See also: |\n' + '| | ' + '"__qualname__ attributes". New in version 3.3. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__module__ | The name of ' + 'the module the function was defined |\n' + '| | in, or ' + '"None" if unavailable. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__defaults__ | A "tuple" ' + 'containing default *parameter* values |\n' + '| | for those ' + 'parameters that have defaults, or "None" |\n' + '| | if no ' + 'parameters have a default value. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__code__ | The code ' + 'object representing the compiled function |\n' + '| | ' + 'body. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__dict__ | The ' + 'namespace supporting arbitrary function |\n' + '| | attributes. ' + 'See also: "__dict__ attributes". |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__annotations__ | A ' + '"dictionary" containing annotations of |\n' + '| | ' + '*parameters*. The keys of the dictionary are the |\n' + '| | parameter ' + 'names, and "\'return\'" for the return |\n' + '| | annotation, ' + 'if provided. See also: Annotations |\n' + '| | Best ' + 'Practices. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| function.__kwdefaults__ | A ' + '"dictionary" containing defaults for keyword- |\n' + '| | only ' + '*parameters*. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + 'Function objects also support getting and setting arbitrary\n' + 'attributes, which can be used, for example, to attach metadata to\n' + 'functions. Regular attribute dot-notation is used to get and set ' + 'such\n' + 'attributes.\n' + '\n' + '**CPython implementation detail:** CPython’s current ' + 'implementation\n' + 'only supports function attributes on user-defined functions. ' + 'Function\n' + 'attributes on built-in functions may be supported in the future.\n' + '\n' + 'Additional information about a function’s definition can be ' + 'retrieved\n' + 'from its code object (accessible via the "__code__" attribute).\n' + '\n' + '\n' + 'Instance methods\n' + '----------------\n' + '\n' + 'An instance method object combines a class, a class instance and ' + 'any\n' + 'callable object (normally a user-defined function).\n' + '\n' + 'Special read-only attributes:\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| method.__self__ | Refers to ' + 'the class instance object to which the |\n' + '| | method is ' + 'bound |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| method.__func__ | Refers to ' + 'the original function object |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| method.__doc__ | The method’s ' + 'documentation (same as |\n' + '| | ' + '"method.__func__.__doc__"). A "string" if the |\n' + '| | original ' + 'function had a docstring, else "None". |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| method.__name__ | The name of ' + 'the method (same as |\n' + '| | ' + '"method.__func__.__name__") |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| method.__module__ | The name of ' + 'the module the method was defined in, |\n' + '| | or "None" if ' + 'unavailable. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + 'Methods also support accessing (but not setting) the arbitrary\n' + 'function attributes on the underlying function object.\n' + '\n' + 'User-defined method objects may be created when getting an ' + 'attribute\n' + 'of a class (perhaps via an instance of that class), if that ' + 'attribute\n' + 'is a user-defined function object or a "classmethod" object.\n' + '\n' + 'When an instance method object is created by retrieving a ' + 'user-defined\n' + 'function object from a class via one of its instances, its ' + '"__self__"\n' + 'attribute is the instance, and the method object is said to be\n' + '*bound*. The new method’s "__func__" attribute is the original\n' + 'function object.\n' + '\n' + 'When an instance method object is created by retrieving a\n' + '"classmethod" object from a class or instance, its "__self__"\n' + 'attribute is the class itself, and its "__func__" attribute is the\n' + 'function object underlying the class method.\n' + '\n' + 'When an instance method object is called, the underlying function\n' + '("__func__") is called, inserting the class instance ("__self__") ' + 'in\n' + 'front of the argument list. For instance, when "C" is a class ' + 'which\n' + 'contains a definition for a function "f()", and "x" is an instance ' + 'of\n' + '"C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".\n' + '\n' + 'When an instance method object is derived from a "classmethod" ' + 'object,\n' + 'the “class instance” stored in "__self__" will actually be the ' + 'class\n' + 'itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent ' + 'to\n' + 'calling "f(C,1)" where "f" is the underlying function.\n' + '\n' + 'Note that the transformation from function object to instance ' + 'method\n' + 'object happens each time the attribute is retrieved from the ' + 'instance.\n' + 'In some cases, a fruitful optimization is to assign the attribute ' + 'to a\n' + 'local variable and call that local variable. Also notice that this\n' + 'transformation only happens for user-defined functions; other ' + 'callable\n' + 'objects (and all non-callable objects) are retrieved without\n' + 'transformation. It is also important to note that user-defined\n' + 'functions which are attributes of a class instance are not ' + 'converted\n' + 'to bound methods; this *only* happens when the function is an\n' + 'attribute of the class.\n' + '\n' + '\n' + 'Generator functions\n' + '-------------------\n' + '\n' + 'A function or method which uses the "yield" statement (see section ' + 'The\n' + 'yield statement) is called a *generator function*. Such a ' + 'function,\n' + 'when called, always returns an *iterator* object which can be used ' + 'to\n' + 'execute the body of the function: calling the iterator’s\n' + '"iterator.__next__()" method will cause the function to execute ' + 'until\n' + 'it provides a value using the "yield" statement. When the ' + 'function\n' + 'executes a "return" statement or falls off the end, a ' + '"StopIteration"\n' + 'exception is raised and the iterator will have reached the end of ' + 'the\n' + 'set of values to be returned.\n' + '\n' + '\n' + 'Coroutine functions\n' + '-------------------\n' + '\n' + 'A function or method which is defined using "async def" is called ' + 'a\n' + '*coroutine function*. Such a function, when called, returns a\n' + '*coroutine* object. It may contain "await" expressions, as well ' + 'as\n' + '"async with" and "async for" statements. See also the Coroutine\n' + 'Objects section.\n' + '\n' + '\n' + 'Asynchronous generator functions\n' + '--------------------------------\n' + '\n' + 'A function or method which is defined using "async def" and which ' + 'uses\n' + 'the "yield" statement is called a *asynchronous generator ' + 'function*.\n' + 'Such a function, when called, returns an *asynchronous iterator*\n' + 'object which can be used in an "async for" statement to execute ' + 'the\n' + 'body of the function.\n' + '\n' + 'Calling the asynchronous iterator’s "aiterator.__anext__" method ' + 'will\n' + 'return an *awaitable* which when awaited will execute until it\n' + 'provides a value using the "yield" expression. When the function\n' + 'executes an empty "return" statement or falls off the end, a\n' + '"StopAsyncIteration" exception is raised and the asynchronous ' + 'iterator\n' + 'will have reached the end of the set of values to be yielded.\n' + '\n' + '\n' + 'Built-in functions\n' + '------------------\n' + '\n' + 'A built-in function object is a wrapper around a C function. ' + 'Examples\n' + 'of built-in functions are "len()" and "math.sin()" ("math" is a\n' + 'standard built-in module). The number and type of the arguments ' + 'are\n' + 'determined by the C function. Special read-only attributes:\n' + '\n' + '* "__doc__" is the function’s documentation string, or "None" if\n' + ' unavailable. See "function.__doc__".\n' + '\n' + '* "__name__" is the function’s name. See "function.__name__".\n' + '\n' + '* "__self__" is set to "None" (but see the next item).\n' + '\n' + '* "__module__" is the name of the module the function was defined ' + 'in\n' + ' or "None" if unavailable. See "function.__module__".\n' + '\n' + '\n' + 'Built-in methods\n' + '----------------\n' + '\n' + 'This is really a different disguise of a built-in function, this ' + 'time\n' + 'containing an object passed to the C function as an implicit extra\n' + 'argument. An example of a built-in method is "alist.append()",\n' + 'assuming *alist* is a list object. In this case, the special ' + 'read-only\n' + 'attribute "__self__" is set to the object denoted by *alist*. (The\n' + 'attribute has the same semantics as it does with "other instance\n' + 'methods".)\n' + '\n' + '\n' + 'Classes\n' + '-------\n' + '\n' + 'Classes are callable. These objects normally act as factories for ' + 'new\n' + 'instances of themselves, but variations are possible for class ' + 'types\n' + 'that override "__new__()". The arguments of the call are passed ' + 'to\n' + '"__new__()" and, in the typical case, to "__init__()" to ' + 'initialize\n' + 'the new instance.\n' + '\n' + '\n' + 'Class Instances\n' + '---------------\n' + '\n' + 'Instances of arbitrary classes can be made callable by defining a\n' + '"__call__()" method in their class.\n' + '\n' + '\n' + 'Modules\n' + '=======\n' + '\n' + 'Modules are a basic organizational unit of Python code, and are\n' + 'created by the import system as invoked either by the "import"\n' + 'statement, or by calling functions such as ' + '"importlib.import_module()"\n' + 'and built-in "__import__()". A module object has a namespace\n' + 'implemented by a "dictionary" object (this is the dictionary\n' + 'referenced by the "__globals__" attribute of functions defined in ' + 'the\n' + 'module). Attribute references are translated to lookups in this\n' + 'dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A ' + 'module\n' + 'object does not contain the code object used to initialize the ' + 'module\n' + '(since it isn’t needed once the initialization is done).\n' + '\n' + 'Attribute assignment updates the module’s namespace dictionary, ' + 'e.g.,\n' + '"m.x = 1" is equivalent to "m.__dict__["x"] = 1".\n' + '\n' + 'Predefined (writable) attributes:\n' + '\n' + ' "__name__"\n' + ' The module’s name.\n' + '\n' + ' "__doc__"\n' + ' The module’s documentation string, or "None" if unavailable.\n' + '\n' + ' "__file__"\n' + ' The pathname of the file from which the module was loaded, if ' + 'it\n' + ' was loaded from a file. The "__file__" attribute may be ' + 'missing\n' + ' for certain types of modules, such as C modules that are\n' + ' statically linked into the interpreter. For extension ' + 'modules\n' + ' loaded dynamically from a shared library, it’s the pathname ' + 'of\n' + ' the shared library file.\n' + '\n' + ' "__annotations__"\n' + ' A dictionary containing *variable annotations* collected ' + 'during\n' + ' module body execution. For best practices on working with\n' + ' "__annotations__", please see Annotations Best Practices.\n' + '\n' + 'Special read-only attribute: "__dict__" is the module’s namespace ' + 'as a\n' + 'dictionary object.\n' + '\n' + '**CPython implementation detail:** Because of the way CPython ' + 'clears\n' + 'module dictionaries, the module dictionary will be cleared when ' + 'the\n' + 'module falls out of scope even if the dictionary still has live\n' + 'references. To avoid this, copy the dictionary or keep the module\n' + 'around while using its dictionary directly.\n' + '\n' + '\n' + 'Custom classes\n' + '==============\n' + '\n' + 'Custom class types are typically created by class definitions (see\n' + 'section Class definitions). A class has a namespace implemented by ' + 'a\n' + 'dictionary object. Class attribute references are translated to\n' + 'lookups in this dictionary, e.g., "C.x" is translated to\n' + '"C.__dict__["x"]" (although there are a number of hooks which ' + 'allow\n' + 'for other means of locating attributes). When the attribute name ' + 'is\n' + 'not found there, the attribute search continues in the base ' + 'classes.\n' + 'This search of the base classes uses the C3 method resolution ' + 'order\n' + 'which behaves correctly even in the presence of ‘diamond’ ' + 'inheritance\n' + 'structures where there are multiple inheritance paths leading back ' + 'to\n' + 'a common ancestor. Additional details on the C3 MRO used by Python ' + 'can\n' + 'be found in the documentation accompanying the 2.3 release at\n' + 'https://www.python.org/download/releases/2.3/mro/.\n' + '\n' + 'When a class attribute reference (for class "C", say) would yield ' + 'a\n' + 'class method object, it is transformed into an instance method ' + 'object\n' + 'whose "__self__" attribute is "C". When it would yield a\n' + '"staticmethod" object, it is transformed into the object wrapped ' + 'by\n' + 'the static method object. See section Implementing Descriptors for\n' + 'another way in which attributes retrieved from a class may differ ' + 'from\n' + 'those actually contained in its "__dict__".\n' + '\n' + 'Class attribute assignments update the class’s dictionary, never ' + 'the\n' + 'dictionary of a base class.\n' + '\n' + 'A class object can be called (see above) to yield a class instance\n' + '(see below).\n' + '\n' + 'Special attributes:\n' + '\n' + ' "__name__"\n' + ' The class name.\n' + '\n' + ' "__module__"\n' + ' The name of the module in which the class was defined.\n' + '\n' + ' "__dict__"\n' + ' The dictionary containing the class’s namespace.\n' + '\n' + ' "__bases__"\n' + ' A tuple containing the base classes, in the order of their\n' + ' occurrence in the base class list.\n' + '\n' + ' "__doc__"\n' + ' The class’s documentation string, or "None" if undefined.\n' + '\n' + ' "__annotations__"\n' + ' A dictionary containing *variable annotations* collected ' + 'during\n' + ' class body execution. For best practices on working with\n' + ' "__annotations__", please see Annotations Best Practices.\n' + '\n' + '\n' + 'Class instances\n' + '===============\n' + '\n' + 'A class instance is created by calling a class object (see above). ' + 'A\n' + 'class instance has a namespace implemented as a dictionary which ' + 'is\n' + 'the first place in which attribute references are searched. When ' + 'an\n' + 'attribute is not found there, and the instance’s class has an\n' + 'attribute by that name, the search continues with the class\n' + 'attributes. If a class attribute is found that is a user-defined\n' + 'function object, it is transformed into an instance method object\n' + 'whose "__self__" attribute is the instance. Static method and ' + 'class\n' + 'method objects are also transformed; see above under “Classes”. ' + 'See\n' + 'section Implementing Descriptors for another way in which ' + 'attributes\n' + 'of a class retrieved via its instances may differ from the objects\n' + 'actually stored in the class’s "__dict__". If no class attribute ' + 'is\n' + 'found, and the object’s class has a "__getattr__()" method, that ' + 'is\n' + 'called to satisfy the lookup.\n' + '\n' + 'Attribute assignments and deletions update the instance’s ' + 'dictionary,\n' + 'never a class’s dictionary. If the class has a "__setattr__()" or\n' + '"__delattr__()" method, this is called instead of updating the\n' + 'instance dictionary directly.\n' + '\n' + 'Class instances can pretend to be numbers, sequences, or mappings ' + 'if\n' + 'they have methods with certain special names. See section Special\n' + 'method names.\n' + '\n' + 'Special attributes: "__dict__" is the attribute dictionary;\n' + '"__class__" is the instance’s class.\n' + '\n' + '\n' + 'I/O objects (also known as file objects)\n' + '========================================\n' + '\n' + 'A *file object* represents an open file. Various shortcuts are\n' + 'available to create file objects: the "open()" built-in function, ' + 'and\n' + 'also "os.popen()", "os.fdopen()", and the "makefile()" method of\n' + 'socket objects (and perhaps by other functions or methods provided ' + 'by\n' + 'extension modules).\n' + '\n' + 'The objects "sys.stdin", "sys.stdout" and "sys.stderr" are ' + 'initialized\n' + 'to file objects corresponding to the interpreter’s standard input,\n' + 'output and error streams; they are all open in text mode and ' + 'therefore\n' + 'follow the interface defined by the "io.TextIOBase" abstract ' + 'class.\n' + '\n' + '\n' + 'Internal types\n' + '==============\n' + '\n' + 'A few types used internally by the interpreter are exposed to the\n' + 'user. Their definitions may change with future versions of the\n' + 'interpreter, but they are mentioned here for completeness.\n' + '\n' + '\n' + 'Code objects\n' + '------------\n' + '\n' + 'Code objects represent *byte-compiled* executable Python code, or\n' + '*bytecode*. The difference between a code object and a function ' + 'object\n' + 'is that the function object contains an explicit reference to the\n' + 'function’s globals (the module in which it was defined), while a ' + 'code\n' + 'object contains no context; also the default argument values are\n' + 'stored in the function object, not in the code object (because ' + 'they\n' + 'represent values calculated at run-time). Unlike function ' + 'objects,\n' + 'code objects are immutable and contain no references (directly or\n' + 'indirectly) to mutable objects.\n' + '\n' + '\n' + 'Special read-only attributes\n' + '~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_name | The function ' + 'name |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_qualname | The fully ' + 'qualified function name New in version |\n' + '| | ' + '3.11. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_argcount | The total ' + 'number of positional *parameters* |\n' + '| | (including ' + 'positional-only parameters and |\n' + '| | parameters ' + 'with default values) that the function |\n' + '| | ' + 'has |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_posonlyargcount | The number ' + 'of positional-only *parameters* |\n' + '| | (including ' + 'arguments with default values) that the |\n' + '| | function ' + 'has |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_kwonlyargcount | The number ' + 'of keyword-only *parameters* (including |\n' + '| | arguments ' + 'with default values) that the function |\n' + '| | ' + 'has |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_nlocals | The number ' + 'of local variables used by the function |\n' + '| | (including ' + 'parameters) |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_varnames | A "tuple" ' + 'containing the names of the local |\n' + '| | variables in ' + 'the function (starting with the |\n' + '| | parameter ' + 'names) |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_cellvars | A "tuple" ' + 'containing the names of local variables |\n' + '| | that are ' + 'referenced by nested functions inside the |\n' + '| | ' + 'function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_freevars | A "tuple" ' + 'containing the names of free variables |\n' + '| | in the ' + 'function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_code | A string ' + 'representing the sequence of *bytecode* |\n' + '| | instructions ' + 'in the function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_consts | A "tuple" ' + 'containing the literals used by the |\n' + '| | *bytecode* ' + 'in the function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_names | A "tuple" ' + 'containing the names used by the |\n' + '| | *bytecode* ' + 'in the function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_filename | The name of ' + 'the file from which the code was |\n' + '| | ' + 'compiled |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_firstlineno | The line ' + 'number of the first line of the function |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_lnotab | A string ' + 'encoding the mapping from *bytecode* |\n' + '| | offsets to ' + 'line numbers. For details, see the |\n' + '| | source code ' + 'of the interpreter. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_stacksize | The required ' + 'stack size of the code object |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| codeobject.co_flags | An "integer" ' + 'encoding a number of flags for the |\n' + '| | ' + 'interpreter. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + 'The following flag bits are defined for "co_flags": bit "0x04" is ' + 'set\n' + 'if the function uses the "*arguments" syntax to accept an ' + 'arbitrary\n' + 'number of positional arguments; bit "0x08" is set if the function ' + 'uses\n' + 'the "**keywords" syntax to accept arbitrary keyword arguments; bit\n' + '"0x20" is set if the function is a generator. See Code Objects Bit\n' + 'Flags for details on the semantics of each flags that might be\n' + 'present.\n' + '\n' + 'Future feature declarations ("from __future__ import division") ' + 'also\n' + 'use bits in "co_flags" to indicate whether a code object was ' + 'compiled\n' + 'with a particular feature enabled: bit "0x2000" is set if the ' + 'function\n' + 'was compiled with future division enabled; bits "0x10" and ' + '"0x1000"\n' + 'were used in earlier versions of Python.\n' + '\n' + 'Other bits in "co_flags" are reserved for internal use.\n' + '\n' + 'If a code object represents a function, the first item in ' + '"co_consts"\n' + 'is the documentation string of the function, or "None" if ' + 'undefined.\n' + '\n' + '\n' + 'Methods on code objects\n' + '~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + 'codeobject.co_positions()\n' + '\n' + ' Returns an iterable over the source code positions of each\n' + ' *bytecode* instruction in the code object.\n' + '\n' + ' The iterator returns "tuple"s containing the "(start_line,\n' + ' end_line, start_column, end_column)". The *i-th* tuple ' + 'corresponds\n' + ' to the position of the source code that compiled to the *i-th* ' + 'code\n' + ' unit. Column information is 0-indexed utf-8 byte offsets on the\n' + ' given source line.\n' + '\n' + ' This positional information can be missing. A non-exhaustive ' + 'lists\n' + ' of cases where this may happen:\n' + '\n' + ' * Running the interpreter with "-X" "no_debug_ranges".\n' + '\n' + ' * Loading a pyc file compiled while using "-X" ' + '"no_debug_ranges".\n' + '\n' + ' * Position tuples corresponding to artificial instructions.\n' + '\n' + ' * Line and column numbers that can’t be represented due to\n' + ' implementation specific limitations.\n' + '\n' + ' When this occurs, some or all of the tuple elements can be ' + '"None".\n' + '\n' + ' New in version 3.11.\n' + '\n' + ' Note:\n' + '\n' + ' This feature requires storing column positions in code ' + 'objects\n' + ' which may result in a small increase of disk usage of ' + 'compiled\n' + ' Python files or interpreter memory usage. To avoid storing ' + 'the\n' + ' extra information and/or deactivate printing the extra ' + 'traceback\n' + ' information, the "-X" "no_debug_ranges" command line flag or ' + 'the\n' + ' "PYTHONNODEBUGRANGES" environment variable can be used.\n' + '\n' + 'codeobject.co_lines()\n' + '\n' + ' Returns an iterator that yields information about successive ' + 'ranges\n' + ' of *bytecode*s. Each item yielded is a "(start, end, lineno)"\n' + ' "tuple":\n' + '\n' + ' * "start" (an "int") represents the offset (inclusive) of the ' + 'start\n' + ' of the *bytecode* range\n' + '\n' + ' * "end" (an "int") represents the offset (exclusive) of the end ' + 'of\n' + ' the *bytecode* range\n' + '\n' + ' * "lineno" is an "int" representing the line number of the\n' + ' *bytecode* range, or "None" if the bytecodes in the given ' + 'range\n' + ' have no line number\n' + '\n' + ' The items yielded will have the following properties:\n' + '\n' + ' * The first range yielded will have a "start" of 0.\n' + '\n' + ' * The "(start, end)" ranges will be non-decreasing and ' + 'consecutive.\n' + ' That is, for any pair of "tuple"s, the "start" of the second ' + 'will\n' + ' be equal to the "end" of the first.\n' + '\n' + ' * No range will be backwards: "end >= start" for all triples.\n' + '\n' + ' * The last "tuple" yielded will have "end" equal to the size of ' + 'the\n' + ' *bytecode*.\n' + '\n' + ' Zero-width ranges, where "start == end", are allowed. ' + 'Zero-width\n' + ' ranges are used for lines that are present in the source code, ' + 'but\n' + ' have been eliminated by the *bytecode* compiler.\n' + '\n' + ' New in version 3.10.\n' + '\n' + ' See also:\n' + '\n' + ' **PEP 626** - Precise line numbers for debugging and other ' + 'tools.\n' + ' The PEP that introduced the "co_lines()" method.\n' + '\n' + 'codeobject.replace(**kwargs)\n' + '\n' + ' Return a copy of the code object with new values for the ' + 'specified\n' + ' fields.\n' + '\n' + ' New in version 3.8.\n' + '\n' + '\n' + 'Frame objects\n' + '-------------\n' + '\n' + 'Frame objects represent execution frames. They may occur in ' + 'traceback\n' + 'objects, and are also passed to registered trace functions.\n' + '\n' + '\n' + 'Special read-only attributes\n' + '~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_back | Points to ' + 'the previous stack frame (towards the |\n' + '| | caller), or ' + '"None" if this is the bottom stack |\n' + '| | ' + 'frame |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_code | The code ' + 'object being executed in this frame. |\n' + '| | Accessing ' + 'this attribute raises an auditing event |\n' + '| | ' + '"object.__getattr__" with arguments "obj" and |\n' + '| | ' + '""f_code"". |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_locals | The ' + 'dictionary used by the frame to look up local |\n' + '| | ' + 'variables |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_globals | The ' + 'dictionary used by the frame to look up global |\n' + '| | ' + 'variables |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_builtins | The ' + 'dictionary used by the frame to look up built- |\n' + '| | in ' + '(intrinsic) names |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_lasti | The “precise ' + 'instruction” of the frame object |\n' + '| | (this is an ' + 'index into the *bytecode* string of |\n' + '| | the code ' + 'object) |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + '\n' + 'Special writable attributes\n' + '~~~~~~~~~~~~~~~~~~~~~~~~~~~\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_trace | If not ' + '"None", this is a function called for |\n' + '| | various ' + 'events during code execution (this is used |\n' + '| | by ' + 'debuggers). Normally an event is triggered for |\n' + '| | each new ' + 'source line (see "f_trace_lines"). |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_trace_lines | Set this ' + 'attribute to "False" to disable |\n' + '| | triggering a ' + 'tracing event for each source line. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_trace_opcodes | Set this ' + 'attribute to "True" to allow per-opcode |\n' + '| | events to be ' + 'requested. Note that this may lead to |\n' + '| | undefined ' + 'interpreter behaviour if exceptions |\n' + '| | raised by ' + 'the trace function escape to the |\n' + '| | function ' + 'being traced. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| frame.f_lineno | The current ' + 'line number of the frame – writing to |\n' + '| | this from ' + 'within a trace function jumps to the |\n' + '| | given line ' + '(only for the bottom-most frame). A |\n' + '| | debugger can ' + 'implement a Jump command (aka Set |\n' + '| | Next ' + 'Statement) by writing to this attribute. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + '\n' + 'Frame object methods\n' + '~~~~~~~~~~~~~~~~~~~~\n' + '\n' + 'Frame objects support one method:\n' + '\n' + 'frame.clear()\n' + '\n' + ' This method clears all references to local variables held by ' + 'the\n' + ' frame. Also, if the frame belonged to a *generator*, the ' + 'generator\n' + ' is finalized. This helps break reference cycles involving ' + 'frame\n' + ' objects (for example when catching an exception and storing its\n' + ' traceback for later use).\n' + '\n' + ' "RuntimeError" is raised if the frame is currently executing.\n' + '\n' + ' New in version 3.4.\n' + '\n' + '\n' + 'Traceback objects\n' + '-----------------\n' + '\n' + 'Traceback objects represent the stack trace of an exception. A\n' + 'traceback object is implicitly created when an exception occurs, ' + 'and\n' + 'may also be explicitly created by calling "types.TracebackType".\n' + '\n' + 'Changed in version 3.7: Traceback objects can now be explicitly\n' + 'instantiated from Python code.\n' + '\n' + 'For implicitly created tracebacks, when the search for an ' + 'exception\n' + 'handler unwinds the execution stack, at each unwound level a ' + 'traceback\n' + 'object is inserted in front of the current traceback. When an\n' + 'exception handler is entered, the stack trace is made available to ' + 'the\n' + 'program. (See section The try statement.) It is accessible as the\n' + 'third item of the tuple returned by "sys.exc_info()", and as the\n' + '"__traceback__" attribute of the caught exception.\n' + '\n' + 'When the program contains no suitable handler, the stack trace is\n' + 'written (nicely formatted) to the standard error stream; if the\n' + 'interpreter is interactive, it is also made available to the user ' + 'as\n' + '"sys.last_traceback".\n' + '\n' + 'For explicitly created tracebacks, it is up to the creator of the\n' + 'traceback to determine how the "tb_next" attributes should be ' + 'linked\n' + 'to form a full stack trace.\n' + '\n' + 'Special read-only attributes:\n' + '\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| traceback.tb_frame | Points to ' + 'the execution frame of the current |\n' + '| | level. ' + 'Accessing this attribute raises an |\n' + '| | auditing ' + 'event "object.__getattr__" with arguments |\n' + '| | "obj" and ' + '""tb_frame"". |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| traceback.tb_lineno | Gives the ' + 'line number where the exception occurred |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '| traceback.tb_lasti | Indicates ' + 'the “precise instruction”. |\n' + '+----------------------------------------------------+----------------------------------------------------+\n' + '\n' + 'The line number and last instruction in the traceback may differ ' + 'from\n' + 'the line number of its frame object if the exception occurred in a\n' + '"try" statement with no matching except clause or with a "finally"\n' + 'clause.\n' + '\n' + 'traceback.tb_next\n' + '\n' + ' The special writable attribute "tb_next" is the next level in ' + 'the\n' + ' stack trace (towards the frame where the exception occurred), ' + 'or\n' + ' "None" if there is no next level.\n' + '\n' + ' Changed in version 3.7: This attribute is now writable\n' + '\n' + '\n' + 'Slice objects\n' + '-------------\n' + '\n' + 'Slice objects are used to represent slices for "__getitem__()"\n' + 'methods. They are also created by the built-in "slice()" ' + 'function.\n' + '\n' + 'Special read-only attributes: "start" is the lower bound; "stop" ' + 'is\n' + 'the upper bound; "step" is the step value; each is "None" if ' + 'omitted.\n' + 'These attributes can have any type.\n' + '\n' + 'Slice objects support one method:\n' + '\n' + 'slice.indices(self, length)\n' + '\n' + ' This method takes a single integer argument *length* and ' + 'computes\n' + ' information about the slice that the slice object would describe ' + 'if\n' + ' applied to a sequence of *length* items. It returns a tuple of\n' + ' three integers; respectively these are the *start* and *stop*\n' + ' indices and the *step* or stride length of the slice. Missing ' + 'or\n' + ' out-of-bounds indices are handled in a manner consistent with\n' + ' regular slices.\n' + '\n' + '\n' + 'Static method objects\n' + '---------------------\n' + '\n' + 'Static method objects provide a way of defeating the transformation ' + 'of\n' + 'function objects to method objects described above. A static ' + 'method\n' + 'object is a wrapper around any other object, usually a ' + 'user-defined\n' + 'method object. When a static method object is retrieved from a ' + 'class\n' + 'or a class instance, the object actually returned is the wrapped\n' + 'object, which is not subject to any further transformation. Static\n' + 'method objects are also callable. Static method objects are created ' + 'by\n' + 'the built-in "staticmethod()" constructor.\n' + '\n' + '\n' + 'Class method objects\n' + '--------------------\n' + '\n' + 'A class method object, like a static method object, is a wrapper\n' + 'around another object that alters the way in which that object is\n' + 'retrieved from classes and class instances. The behaviour of class\n' + 'method objects upon such retrieval is described above, under ' + '“instance\n' + 'methods”. Class method objects are created by the built-in\n' + '"classmethod()" constructor.\n', + 'typesfunctions': 'Functions\n' + '*********\n' + '\n' + 'Function objects are created by function definitions. The ' + 'only\n' + 'operation on a function object is to call it: ' + '"func(argument-list)".\n' + '\n' + 'There are really two flavors of function objects: built-in ' + 'functions\n' + 'and user-defined functions. Both support the same ' + 'operation (to call\n' + 'the function), but the implementation is different, hence ' + 'the\n' + 'different object types.\n' + '\n' + 'See Function definitions for more information.\n', + 'typesmapping': 'Mapping Types — "dict"\n' + '**********************\n' + '\n' + 'A *mapping* object maps *hashable* values to arbitrary ' + 'objects.\n' + 'Mappings are mutable objects. There is currently only one ' + 'standard\n' + 'mapping type, the *dictionary*. (For other containers see ' + 'the built-\n' + 'in "list", "set", and "tuple" classes, and the "collections" ' + 'module.)\n' + '\n' + 'A dictionary’s keys are *almost* arbitrary values. Values ' + 'that are\n' + 'not *hashable*, that is, values containing lists, ' + 'dictionaries or\n' + 'other mutable types (that are compared by value rather than ' + 'by object\n' + 'identity) may not be used as keys. Values that compare equal ' + '(such as\n' + '"1", "1.0", and "True") can be used interchangeably to index ' + 'the same\n' + 'dictionary entry.\n' + '\n' + 'class dict(**kwargs)\n' + 'class dict(mapping, **kwargs)\n' + 'class dict(iterable, **kwargs)\n' + '\n' + ' Return a new dictionary initialized from an optional ' + 'positional\n' + ' argument and a possibly empty set of keyword arguments.\n' + '\n' + ' Dictionaries can be created by several means:\n' + '\n' + ' * Use a comma-separated list of "key: value" pairs within ' + 'braces:\n' + ' "{\'jack\': 4098, \'sjoerd\': 4127}" or "{4098: ' + "'jack', 4127:\n" + ' \'sjoerd\'}"\n' + '\n' + ' * Use a dict comprehension: "{}", "{x: x ** 2 for x in ' + 'range(10)}"\n' + '\n' + ' * Use the type constructor: "dict()", "dict([(\'foo\', ' + "100), ('bar',\n" + ' 200)])", "dict(foo=100, bar=200)"\n' + '\n' + ' If no positional argument is given, an empty dictionary ' + 'is created.\n' + ' If a positional argument is given and it is a mapping ' + 'object, a\n' + ' dictionary is created with the same key-value pairs as ' + 'the mapping\n' + ' object. Otherwise, the positional argument must be an ' + '*iterable*\n' + ' object. Each item in the iterable must itself be an ' + 'iterable with\n' + ' exactly two objects. The first object of each item ' + 'becomes a key\n' + ' in the new dictionary, and the second object the ' + 'corresponding\n' + ' value. If a key occurs more than once, the last value ' + 'for that key\n' + ' becomes the corresponding value in the new dictionary.\n' + '\n' + ' If keyword arguments are given, the keyword arguments and ' + 'their\n' + ' values are added to the dictionary created from the ' + 'positional\n' + ' argument. If a key being added is already present, the ' + 'value from\n' + ' the keyword argument replaces the value from the ' + 'positional\n' + ' argument.\n' + '\n' + ' To illustrate, the following examples all return a ' + 'dictionary equal\n' + ' to "{"one": 1, "two": 2, "three": 3}":\n' + '\n' + ' >>> a = dict(one=1, two=2, three=3)\n' + " >>> b = {'one': 1, 'two': 2, 'three': 3}\n" + " >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n" + " >>> d = dict([('two', 2), ('one', 1), ('three', 3)])\n" + " >>> e = dict({'three': 3, 'one': 1, 'two': 2})\n" + " >>> f = dict({'one': 1, 'three': 3}, two=2)\n" + ' >>> a == b == c == d == e == f\n' + ' True\n' + '\n' + ' Providing keyword arguments as in the first example only ' + 'works for\n' + ' keys that are valid Python identifiers. Otherwise, any ' + 'valid keys\n' + ' can be used.\n' + '\n' + ' These are the operations that dictionaries support (and ' + 'therefore,\n' + ' custom mapping types should support too):\n' + '\n' + ' list(d)\n' + '\n' + ' Return a list of all the keys used in the dictionary ' + '*d*.\n' + '\n' + ' len(d)\n' + '\n' + ' Return the number of items in the dictionary *d*.\n' + '\n' + ' d[key]\n' + '\n' + ' Return the item of *d* with key *key*. Raises a ' + '"KeyError" if\n' + ' *key* is not in the map.\n' + '\n' + ' If a subclass of dict defines a method "__missing__()" ' + 'and *key*\n' + ' is not present, the "d[key]" operation calls that ' + 'method with\n' + ' the key *key* as argument. The "d[key]" operation ' + 'then returns\n' + ' or raises whatever is returned or raised by the\n' + ' "__missing__(key)" call. No other operations or ' + 'methods invoke\n' + ' "__missing__()". If "__missing__()" is not defined, ' + '"KeyError"\n' + ' is raised. "__missing__()" must be a method; it cannot ' + 'be an\n' + ' instance variable:\n' + '\n' + ' >>> class Counter(dict):\n' + ' ... def __missing__(self, key):\n' + ' ... return 0\n' + ' >>> c = Counter()\n' + " >>> c['red']\n" + ' 0\n' + " >>> c['red'] += 1\n" + " >>> c['red']\n" + ' 1\n' + '\n' + ' The example above shows part of the implementation of\n' + ' "collections.Counter". A different "__missing__" ' + 'method is used\n' + ' by "collections.defaultdict".\n' + '\n' + ' d[key] = value\n' + '\n' + ' Set "d[key]" to *value*.\n' + '\n' + ' del d[key]\n' + '\n' + ' Remove "d[key]" from *d*. Raises a "KeyError" if ' + '*key* is not\n' + ' in the map.\n' + '\n' + ' key in d\n' + '\n' + ' Return "True" if *d* has a key *key*, else "False".\n' + '\n' + ' key not in d\n' + '\n' + ' Equivalent to "not key in d".\n' + '\n' + ' iter(d)\n' + '\n' + ' Return an iterator over the keys of the dictionary. ' + 'This is a\n' + ' shortcut for "iter(d.keys())".\n' + '\n' + ' clear()\n' + '\n' + ' Remove all items from the dictionary.\n' + '\n' + ' copy()\n' + '\n' + ' Return a shallow copy of the dictionary.\n' + '\n' + ' classmethod fromkeys(iterable[, value])\n' + '\n' + ' Create a new dictionary with keys from *iterable* and ' + 'values set\n' + ' to *value*.\n' + '\n' + ' "fromkeys()" is a class method that returns a new ' + 'dictionary.\n' + ' *value* defaults to "None". All of the values refer ' + 'to just a\n' + ' single instance, so it generally doesn’t make sense ' + 'for *value*\n' + ' to be a mutable object such as an empty list. To get ' + 'distinct\n' + ' values, use a dict comprehension instead.\n' + '\n' + ' get(key[, default])\n' + '\n' + ' Return the value for *key* if *key* is in the ' + 'dictionary, else\n' + ' *default*. If *default* is not given, it defaults to ' + '"None", so\n' + ' that this method never raises a "KeyError".\n' + '\n' + ' items()\n' + '\n' + ' Return a new view of the dictionary’s items ("(key, ' + 'value)"\n' + ' pairs). See the documentation of view objects.\n' + '\n' + ' keys()\n' + '\n' + ' Return a new view of the dictionary’s keys. See the\n' + ' documentation of view objects.\n' + '\n' + ' pop(key[, default])\n' + '\n' + ' If *key* is in the dictionary, remove it and return ' + 'its value,\n' + ' else return *default*. If *default* is not given and ' + '*key* is\n' + ' not in the dictionary, a "KeyError" is raised.\n' + '\n' + ' popitem()\n' + '\n' + ' Remove and return a "(key, value)" pair from the ' + 'dictionary.\n' + ' Pairs are returned in LIFO (last-in, first-out) ' + 'order.\n' + '\n' + ' "popitem()" is useful to destructively iterate over a\n' + ' dictionary, as often used in set algorithms. If the ' + 'dictionary\n' + ' is empty, calling "popitem()" raises a "KeyError".\n' + '\n' + ' Changed in version 3.7: LIFO order is now guaranteed. ' + 'In prior\n' + ' versions, "popitem()" would return an arbitrary ' + 'key/value pair.\n' + '\n' + ' reversed(d)\n' + '\n' + ' Return a reverse iterator over the keys of the ' + 'dictionary. This\n' + ' is a shortcut for "reversed(d.keys())".\n' + '\n' + ' New in version 3.8.\n' + '\n' + ' setdefault(key[, default])\n' + '\n' + ' If *key* is in the dictionary, return its value. If ' + 'not, insert\n' + ' *key* with a value of *default* and return *default*. ' + '*default*\n' + ' defaults to "None".\n' + '\n' + ' update([other])\n' + '\n' + ' Update the dictionary with the key/value pairs from ' + '*other*,\n' + ' overwriting existing keys. Return "None".\n' + '\n' + ' "update()" accepts either another dictionary object or ' + 'an\n' + ' iterable of key/value pairs (as tuples or other ' + 'iterables of\n' + ' length two). If keyword arguments are specified, the ' + 'dictionary\n' + ' is then updated with those key/value pairs: ' + '"d.update(red=1,\n' + ' blue=2)".\n' + '\n' + ' values()\n' + '\n' + ' Return a new view of the dictionary’s values. See ' + 'the\n' + ' documentation of view objects.\n' + '\n' + ' An equality comparison between one "dict.values()" ' + 'view and\n' + ' another will always return "False". This also applies ' + 'when\n' + ' comparing "dict.values()" to itself:\n' + '\n' + " >>> d = {'a': 1}\n" + ' >>> d.values() == d.values()\n' + ' False\n' + '\n' + ' d | other\n' + '\n' + ' Create a new dictionary with the merged keys and ' + 'values of *d*\n' + ' and *other*, which must both be dictionaries. The ' + 'values of\n' + ' *other* take priority when *d* and *other* share ' + 'keys.\n' + '\n' + ' New in version 3.9.\n' + '\n' + ' d |= other\n' + '\n' + ' Update the dictionary *d* with keys and values from ' + '*other*,\n' + ' which may be either a *mapping* or an *iterable* of ' + 'key/value\n' + ' pairs. The values of *other* take priority when *d* ' + 'and *other*\n' + ' share keys.\n' + '\n' + ' New in version 3.9.\n' + '\n' + ' Dictionaries compare equal if and only if they have the ' + 'same "(key,\n' + ' value)" pairs (regardless of ordering). Order comparisons ' + '(‘<’,\n' + ' ‘<=’, ‘>=’, ‘>’) raise "TypeError".\n' + '\n' + ' Dictionaries preserve insertion order. Note that ' + 'updating a key\n' + ' does not affect the order. Keys added after deletion are ' + 'inserted\n' + ' at the end.\n' + '\n' + ' >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}\n' + ' >>> d\n' + " {'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" + ' >>> list(d)\n' + " ['one', 'two', 'three', 'four']\n" + ' >>> list(d.values())\n' + ' [1, 2, 3, 4]\n' + ' >>> d["one"] = 42\n' + ' >>> d\n' + " {'one': 42, 'two': 2, 'three': 3, 'four': 4}\n" + ' >>> del d["two"]\n' + ' >>> d["two"] = None\n' + ' >>> d\n' + " {'one': 42, 'three': 3, 'four': 4, 'two': None}\n" + '\n' + ' Changed in version 3.7: Dictionary order is guaranteed to ' + 'be\n' + ' insertion order. This behavior was an implementation ' + 'detail of\n' + ' CPython from 3.6.\n' + '\n' + ' Dictionaries and dictionary views are reversible.\n' + '\n' + ' >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}\n' + ' >>> d\n' + " {'one': 1, 'two': 2, 'three': 3, 'four': 4}\n" + ' >>> list(reversed(d))\n' + " ['four', 'three', 'two', 'one']\n" + ' >>> list(reversed(d.values()))\n' + ' [4, 3, 2, 1]\n' + ' >>> list(reversed(d.items()))\n' + " [('four', 4), ('three', 3), ('two', 2), ('one', 1)]\n" + '\n' + ' Changed in version 3.8: Dictionaries are now reversible.\n' + '\n' + 'See also:\n' + '\n' + ' "types.MappingProxyType" can be used to create a read-only ' + 'view of a\n' + ' "dict".\n' + '\n' + '\n' + 'Dictionary view objects\n' + '=======================\n' + '\n' + 'The objects returned by "dict.keys()", "dict.values()" and\n' + '"dict.items()" are *view objects*. They provide a dynamic ' + 'view on the\n' + 'dictionary’s entries, which means that when the dictionary ' + 'changes,\n' + 'the view reflects these changes.\n' + '\n' + 'Dictionary views can be iterated over to yield their ' + 'respective data,\n' + 'and support membership tests:\n' + '\n' + 'len(dictview)\n' + '\n' + ' Return the number of entries in the dictionary.\n' + '\n' + 'iter(dictview)\n' + '\n' + ' Return an iterator over the keys, values or items ' + '(represented as\n' + ' tuples of "(key, value)") in the dictionary.\n' + '\n' + ' Keys and values are iterated over in insertion order. ' + 'This allows\n' + ' the creation of "(value, key)" pairs using "zip()": ' + '"pairs =\n' + ' zip(d.values(), d.keys())". Another way to create the ' + 'same list is\n' + ' "pairs = [(v, k) for (k, v) in d.items()]".\n' + '\n' + ' Iterating views while adding or deleting entries in the ' + 'dictionary\n' + ' may raise a "RuntimeError" or fail to iterate over all ' + 'entries.\n' + '\n' + ' Changed in version 3.7: Dictionary order is guaranteed to ' + 'be\n' + ' insertion order.\n' + '\n' + 'x in dictview\n' + '\n' + ' Return "True" if *x* is in the underlying dictionary’s ' + 'keys, values\n' + ' or items (in the latter case, *x* should be a "(key, ' + 'value)"\n' + ' tuple).\n' + '\n' + 'reversed(dictview)\n' + '\n' + ' Return a reverse iterator over the keys, values or items ' + 'of the\n' + ' dictionary. The view will be iterated in reverse order of ' + 'the\n' + ' insertion.\n' + '\n' + ' Changed in version 3.8: Dictionary views are now ' + 'reversible.\n' + '\n' + 'dictview.mapping\n' + '\n' + ' Return a "types.MappingProxyType" that wraps the ' + 'original\n' + ' dictionary to which the view refers.\n' + '\n' + ' New in version 3.10.\n' + '\n' + 'Keys views are set-like since their entries are unique and ' + '*hashable*.\n' + 'If all values are hashable, so that "(key, value)" pairs are ' + 'unique\n' + 'and hashable, then the items view is also set-like. (Values ' + 'views are\n' + 'not treated as set-like since the entries are generally not ' + 'unique.)\n' + 'For set-like views, all of the operations defined for the ' + 'abstract\n' + 'base class "collections.abc.Set" are available (for example, ' + '"==",\n' + '"<", or "^").\n' + '\n' + 'An example of dictionary view usage:\n' + '\n' + " >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, " + "'spam': 500}\n" + ' >>> keys = dishes.keys()\n' + ' >>> values = dishes.values()\n' + '\n' + ' >>> # iteration\n' + ' >>> n = 0\n' + ' >>> for val in values:\n' + ' ... n += val\n' + ' >>> print(n)\n' + ' 504\n' + '\n' + ' >>> # keys and values are iterated over in the same order ' + '(insertion order)\n' + ' >>> list(keys)\n' + " ['eggs', 'sausage', 'bacon', 'spam']\n" + ' >>> list(values)\n' + ' [2, 1, 1, 500]\n' + '\n' + ' >>> # view objects are dynamic and reflect dict changes\n' + " >>> del dishes['eggs']\n" + " >>> del dishes['sausage']\n" + ' >>> list(keys)\n' + " ['bacon', 'spam']\n" + '\n' + ' >>> # set operations\n' + " >>> keys & {'eggs', 'bacon', 'salad'}\n" + " {'bacon'}\n" + " >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', " + "'bacon', 'spam'}\n" + ' True\n' + " >>> keys | ['juice', 'juice', 'juice'] == {'bacon', " + "'spam', 'juice'}\n" + ' True\n' + '\n' + ' >>> # get back a read-only proxy for the original ' + 'dictionary\n' + ' >>> values.mapping\n' + " mappingproxy({'bacon': 1, 'spam': 500})\n" + " >>> values.mapping['spam']\n" + ' 500\n', + 'typesmethods': 'Methods\n' + '*******\n' + '\n' + 'Methods are functions that are called using the attribute ' + 'notation.\n' + 'There are two flavors: built-in methods (such as "append()" ' + 'on lists)\n' + 'and class instance method. Built-in methods are described ' + 'with the\n' + 'types that support them.\n' + '\n' + 'If you access a method (a function defined in a class ' + 'namespace)\n' + 'through an instance, you get a special object: a *bound ' + 'method* (also\n' + 'called instance method) object. When called, it will add the ' + '"self"\n' + 'argument to the argument list. Bound methods have two ' + 'special read-\n' + 'only attributes: "m.__self__" is the object on which the ' + 'method\n' + 'operates, and "m.__func__" is the function implementing the ' + 'method.\n' + 'Calling "m(arg-1, arg-2, ..., arg-n)" is completely ' + 'equivalent to\n' + 'calling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".\n' + '\n' + 'Like function objects, bound method objects support getting ' + 'arbitrary\n' + 'attributes. However, since method attributes are actually ' + 'stored on\n' + 'the underlying function object ("method.__func__"), setting ' + 'method\n' + 'attributes on bound methods is disallowed. Attempting to ' + 'set an\n' + 'attribute on a method results in an "AttributeError" being ' + 'raised. In\n' + 'order to set a method attribute, you need to explicitly set ' + 'it on the\n' + 'underlying function object:\n' + '\n' + ' >>> class C:\n' + ' ... def method(self):\n' + ' ... pass\n' + ' ...\n' + ' >>> c = C()\n' + " >>> c.method.whoami = 'my name is method' # can't set on " + 'the method\n' + ' Traceback (most recent call last):\n' + ' File "", line 1, in \n' + " AttributeError: 'method' object has no attribute " + "'whoami'\n" + " >>> c.method.__func__.whoami = 'my name is method'\n" + ' >>> c.method.whoami\n' + " 'my name is method'\n" + '\n' + 'See Instance methods for more information.\n', + 'typesmodules': 'Modules\n' + '*******\n' + '\n' + 'The only special operation on a module is attribute access: ' + '"m.name",\n' + 'where *m* is a module and *name* accesses a name defined in ' + '*m*’s\n' + 'symbol table. Module attributes can be assigned to. (Note ' + 'that the\n' + '"import" statement is not, strictly speaking, an operation ' + 'on a module\n' + 'object; "import foo" does not require a module object named ' + '*foo* to\n' + 'exist, rather it requires an (external) *definition* for a ' + 'module\n' + 'named *foo* somewhere.)\n' + '\n' + 'A special attribute of every module is "__dict__". This is ' + 'the\n' + 'dictionary containing the module’s symbol table. Modifying ' + 'this\n' + 'dictionary will actually change the module’s symbol table, ' + 'but direct\n' + 'assignment to the "__dict__" attribute is not possible (you ' + 'can write\n' + '"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but ' + 'you can’t\n' + 'write "m.__dict__ = {}"). Modifying "__dict__" directly is ' + 'not\n' + 'recommended.\n' + '\n' + 'Modules built into the interpreter are written like this: ' + '"". If loaded from a file, they are ' + 'written as\n' + '"".\n', + 'typesseq': 'Sequence Types — "list", "tuple", "range"\n' + '*****************************************\n' + '\n' + 'There are three basic sequence types: lists, tuples, and range\n' + 'objects. Additional sequence types tailored for processing of ' + 'binary\n' + 'data and text strings are described in dedicated sections.\n' + '\n' + '\n' + 'Common Sequence Operations\n' + '==========================\n' + '\n' + 'The operations in the following table are supported by most ' + 'sequence\n' + 'types, both mutable and immutable. The ' + '"collections.abc.Sequence" ABC\n' + 'is provided to make it easier to correctly implement these ' + 'operations\n' + 'on custom sequence types.\n' + '\n' + 'This table lists the sequence operations sorted in ascending ' + 'priority.\n' + 'In the table, *s* and *t* are sequences of the same type, *n*, ' + '*i*,\n' + '*j* and *k* are integers and *x* is an arbitrary object that ' + 'meets any\n' + 'type and value restrictions imposed by *s*.\n' + '\n' + 'The "in" and "not in" operations have the same priorities as ' + 'the\n' + 'comparison operations. The "+" (concatenation) and "*" ' + '(repetition)\n' + 'operations have the same priority as the corresponding numeric\n' + 'operations. [3]\n' + '\n' + '+----------------------------+----------------------------------+------------+\n' + '| Operation | Result ' + '| Notes |\n' + '|============================|==================================|============|\n' + '| "x in s" | "True" if an item of *s* is ' + '| (1) |\n' + '| | equal to *x*, else "False" ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "x not in s" | "False" if an item of *s* is ' + '| (1) |\n' + '| | equal to *x*, else "True" ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s + t" | the concatenation of *s* and *t* ' + '| (6)(7) |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s * n" or "n * s" | equivalent to adding *s* to ' + '| (2)(7) |\n' + '| | itself *n* times ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s[i]" | *i*th item of *s*, origin 0 ' + '| (3) |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s[i:j]" | slice of *s* from *i* to *j* ' + '| (3)(4) |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s[i:j:k]" | slice of *s* from *i* to *j* ' + '| (3)(5) |\n' + '| | with step *k* ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "len(s)" | length of *s* ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "min(s)" | smallest item of *s* ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "max(s)" | largest item of *s* ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s.index(x[, i[, j]])" | index of the first occurrence of ' + '| (8) |\n' + '| | *x* in *s* (at or after index ' + '| |\n' + '| | *i* and before index *j*) ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '| "s.count(x)" | total number of occurrences of ' + '| |\n' + '| | *x* in *s* ' + '| |\n' + '+----------------------------+----------------------------------+------------+\n' + '\n' + 'Sequences of the same type also support comparisons. In ' + 'particular,\n' + 'tuples and lists are compared lexicographically by comparing\n' + 'corresponding elements. This means that to compare equal, every\n' + 'element must compare equal and the two sequences must be of the ' + 'same\n' + 'type and have the same length. (For full details see ' + 'Comparisons in\n' + 'the language reference.)\n' + '\n' + 'Forward and reversed iterators over mutable sequences access ' + 'values\n' + 'using an index. That index will continue to march forward (or\n' + 'backward) even if the underlying sequence is mutated. The ' + 'iterator\n' + 'terminates only when an "IndexError" or a "StopIteration" is\n' + 'encountered (or when the index drops below zero).\n' + '\n' + 'Notes:\n' + '\n' + '1. While the "in" and "not in" operations are used only for ' + 'simple\n' + ' containment testing in the general case, some specialised ' + 'sequences\n' + ' (such as "str", "bytes" and "bytearray") also use them for\n' + ' subsequence testing:\n' + '\n' + ' >>> "gg" in "eggs"\n' + ' True\n' + '\n' + '2. Values of *n* less than "0" are treated as "0" (which yields ' + 'an\n' + ' empty sequence of the same type as *s*). Note that items in ' + 'the\n' + ' sequence *s* are not copied; they are referenced multiple ' + 'times.\n' + ' This often haunts new Python programmers; consider:\n' + '\n' + ' >>> lists = [[]] * 3\n' + ' >>> lists\n' + ' [[], [], []]\n' + ' >>> lists[0].append(3)\n' + ' >>> lists\n' + ' [[3], [3], [3]]\n' + '\n' + ' What has happened is that "[[]]" is a one-element list ' + 'containing\n' + ' an empty list, so all three elements of "[[]] * 3" are ' + 'references\n' + ' to this single empty list. Modifying any of the elements of\n' + ' "lists" modifies this single list. You can create a list of\n' + ' different lists this way:\n' + '\n' + ' >>> lists = [[] for i in range(3)]\n' + ' >>> lists[0].append(3)\n' + ' >>> lists[1].append(5)\n' + ' >>> lists[2].append(7)\n' + ' >>> lists\n' + ' [[3], [5], [7]]\n' + '\n' + ' Further explanation is available in the FAQ entry How do I ' + 'create a\n' + ' multidimensional list?.\n' + '\n' + '3. If *i* or *j* is negative, the index is relative to the end ' + 'of\n' + ' sequence *s*: "len(s) + i" or "len(s) + j" is substituted. ' + 'But\n' + ' note that "-0" is still "0".\n' + '\n' + '4. The slice of *s* from *i* to *j* is defined as the sequence ' + 'of\n' + ' items with index *k* such that "i <= k < j". If *i* or *j* ' + 'is\n' + ' greater than "len(s)", use "len(s)". If *i* is omitted or ' + '"None",\n' + ' use "0". If *j* is omitted or "None", use "len(s)". If *i* ' + 'is\n' + ' greater than or equal to *j*, the slice is empty.\n' + '\n' + '5. The slice of *s* from *i* to *j* with step *k* is defined as ' + 'the\n' + ' sequence of items with index "x = i + n*k" such that "0 <= n ' + '<\n' + ' (j-i)/k". In other words, the indices are "i", "i+k", ' + '"i+2*k",\n' + ' "i+3*k" and so on, stopping when *j* is reached (but never\n' + ' including *j*). When *k* is positive, *i* and *j* are ' + 'reduced to\n' + ' "len(s)" if they are greater. When *k* is negative, *i* and ' + '*j* are\n' + ' reduced to "len(s) - 1" if they are greater. If *i* or *j* ' + 'are\n' + ' omitted or "None", they become “end” values (which end ' + 'depends on\n' + ' the sign of *k*). Note, *k* cannot be zero. If *k* is ' + '"None", it\n' + ' is treated like "1".\n' + '\n' + '6. Concatenating immutable sequences always results in a new ' + 'object.\n' + ' This means that building up a sequence by repeated ' + 'concatenation\n' + ' will have a quadratic runtime cost in the total sequence ' + 'length.\n' + ' To get a linear runtime cost, you must switch to one of the\n' + ' alternatives below:\n' + '\n' + ' * if concatenating "str" objects, you can build a list and ' + 'use\n' + ' "str.join()" at the end or else write to an "io.StringIO"\n' + ' instance and retrieve its value when complete\n' + '\n' + ' * if concatenating "bytes" objects, you can similarly use\n' + ' "bytes.join()" or "io.BytesIO", or you can do in-place\n' + ' concatenation with a "bytearray" object. "bytearray" ' + 'objects are\n' + ' mutable and have an efficient overallocation mechanism\n' + '\n' + ' * if concatenating "tuple" objects, extend a "list" instead\n' + '\n' + ' * for other types, investigate the relevant class ' + 'documentation\n' + '\n' + '7. Some sequence types (such as "range") only support item ' + 'sequences\n' + ' that follow specific patterns, and hence don’t support ' + 'sequence\n' + ' concatenation or repetition.\n' + '\n' + '8. "index" raises "ValueError" when *x* is not found in *s*. Not ' + 'all\n' + ' implementations support passing the additional arguments *i* ' + 'and\n' + ' *j*. These arguments allow efficient searching of subsections ' + 'of\n' + ' the sequence. Passing the extra arguments is roughly ' + 'equivalent to\n' + ' using "s[i:j].index(x)", only without copying any data and ' + 'with the\n' + ' returned index being relative to the start of the sequence ' + 'rather\n' + ' than the start of the slice.\n' + '\n' + '\n' + 'Immutable Sequence Types\n' + '========================\n' + '\n' + 'The only operation that immutable sequence types generally ' + 'implement\n' + 'that is not also implemented by mutable sequence types is ' + 'support for\n' + 'the "hash()" built-in.\n' + '\n' + 'This support allows immutable sequences, such as "tuple" ' + 'instances, to\n' + 'be used as "dict" keys and stored in "set" and "frozenset" ' + 'instances.\n' + '\n' + 'Attempting to hash an immutable sequence that contains ' + 'unhashable\n' + 'values will result in "TypeError".\n' + '\n' + '\n' + 'Mutable Sequence Types\n' + '======================\n' + '\n' + 'The operations in the following table are defined on mutable ' + 'sequence\n' + 'types. The "collections.abc.MutableSequence" ABC is provided to ' + 'make\n' + 'it easier to correctly implement these operations on custom ' + 'sequence\n' + 'types.\n' + '\n' + 'In the table *s* is an instance of a mutable sequence type, *t* ' + 'is any\n' + 'iterable object and *x* is an arbitrary object that meets any ' + 'type and\n' + 'value restrictions imposed by *s* (for example, "bytearray" ' + 'only\n' + 'accepts integers that meet the value restriction "0 <= x <= ' + '255").\n' + '\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| Operation | ' + 'Result | Notes |\n' + '|================================|==================================|=======================|\n' + '| "s[i] = x" | item *i* of *s* is replaced ' + 'by | |\n' + '| | ' + '*x* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s[i:j] = t" | slice of *s* from *i* to *j* ' + 'is | |\n' + '| | replaced by the contents of ' + 'the | |\n' + '| | iterable ' + '*t* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "del s[i:j]" | same as "s[i:j] = ' + '[]" | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s[i:j:k] = t" | the elements of "s[i:j:k]" ' + 'are | (1) |\n' + '| | replaced by those of ' + '*t* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "del s[i:j:k]" | removes the elements ' + 'of | |\n' + '| | "s[i:j:k]" from the ' + 'list | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.append(x)" | appends *x* to the end of ' + 'the | |\n' + '| | sequence (same ' + 'as | |\n' + '| | "s[len(s):len(s)] = ' + '[x]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.clear()" | removes all items from *s* ' + '(same | (5) |\n' + '| | as "del ' + 's[:]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.copy()" | creates a shallow copy of ' + '*s* | (5) |\n' + '| | (same as ' + '"s[:]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.extend(t)" or "s += t" | extends *s* with the contents ' + 'of | |\n' + '| | *t* (for the most part the ' + 'same | |\n' + '| | as "s[len(s):len(s)] = ' + 't") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s *= n" | updates *s* with its ' + 'contents | (6) |\n' + '| | repeated *n* ' + 'times | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.insert(i, x)" | inserts *x* into *s* at ' + 'the | |\n' + '| | index given by *i* (same ' + 'as | |\n' + '| | "s[i:i] = ' + '[x]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.pop()" or "s.pop(i)" | retrieves the item at *i* ' + 'and | (2) |\n' + '| | also removes it from ' + '*s* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.remove(x)" | remove the first item from ' + '*s* | (3) |\n' + '| | where "s[i]" is equal to ' + '*x* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.reverse()" | reverses the items of *s* ' + 'in | (4) |\n' + '| | ' + 'place | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '\n' + 'Notes:\n' + '\n' + '1. *t* must have the same length as the slice it is replacing.\n' + '\n' + '2. The optional argument *i* defaults to "-1", so that by ' + 'default the\n' + ' last item is removed and returned.\n' + '\n' + '3. "remove()" raises "ValueError" when *x* is not found in *s*.\n' + '\n' + '4. The "reverse()" method modifies the sequence in place for ' + 'economy\n' + ' of space when reversing a large sequence. To remind users ' + 'that it\n' + ' operates by side effect, it does not return the reversed ' + 'sequence.\n' + '\n' + '5. "clear()" and "copy()" are included for consistency with the\n' + ' interfaces of mutable containers that don’t support slicing\n' + ' operations (such as "dict" and "set"). "copy()" is not part ' + 'of the\n' + ' "collections.abc.MutableSequence" ABC, but most concrete ' + 'mutable\n' + ' sequence classes provide it.\n' + '\n' + ' New in version 3.3: "clear()" and "copy()" methods.\n' + '\n' + '6. The value *n* is an integer, or an object implementing\n' + ' "__index__()". Zero and negative values of *n* clear the ' + 'sequence.\n' + ' Items in the sequence are not copied; they are referenced ' + 'multiple\n' + ' times, as explained for "s * n" under Common Sequence ' + 'Operations.\n' + '\n' + '\n' + 'Lists\n' + '=====\n' + '\n' + 'Lists are mutable sequences, typically used to store collections ' + 'of\n' + 'homogeneous items (where the precise degree of similarity will ' + 'vary by\n' + 'application).\n' + '\n' + 'class list([iterable])\n' + '\n' + ' Lists may be constructed in several ways:\n' + '\n' + ' * Using a pair of square brackets to denote the empty list: ' + '"[]"\n' + '\n' + ' * Using square brackets, separating items with commas: "[a]", ' + '"[a,\n' + ' b, c]"\n' + '\n' + ' * Using a list comprehension: "[x for x in iterable]"\n' + '\n' + ' * Using the type constructor: "list()" or "list(iterable)"\n' + '\n' + ' The constructor builds a list whose items are the same and in ' + 'the\n' + ' same order as *iterable*’s items. *iterable* may be either ' + 'a\n' + ' sequence, a container that supports iteration, or an ' + 'iterator\n' + ' object. If *iterable* is already a list, a copy is made and\n' + ' returned, similar to "iterable[:]". For example, ' + '"list(\'abc\')"\n' + ' returns "[\'a\', \'b\', \'c\']" and "list( (1, 2, 3) )" ' + 'returns "[1, 2,\n' + ' 3]". If no argument is given, the constructor creates a new ' + 'empty\n' + ' list, "[]".\n' + '\n' + ' Many other operations also produce lists, including the ' + '"sorted()"\n' + ' built-in.\n' + '\n' + ' Lists implement all of the common and mutable sequence ' + 'operations.\n' + ' Lists also provide the following additional method:\n' + '\n' + ' sort(*, key=None, reverse=False)\n' + '\n' + ' This method sorts the list in place, using only "<" ' + 'comparisons\n' + ' between items. Exceptions are not suppressed - if any ' + 'comparison\n' + ' operations fail, the entire sort operation will fail (and ' + 'the\n' + ' list will likely be left in a partially modified state).\n' + '\n' + ' "sort()" accepts two arguments that can only be passed by\n' + ' keyword (keyword-only arguments):\n' + '\n' + ' *key* specifies a function of one argument that is used ' + 'to\n' + ' extract a comparison key from each list element (for ' + 'example,\n' + ' "key=str.lower"). The key corresponding to each item in ' + 'the list\n' + ' is calculated once and then used for the entire sorting ' + 'process.\n' + ' The default value of "None" means that list items are ' + 'sorted\n' + ' directly without calculating a separate key value.\n' + '\n' + ' The "functools.cmp_to_key()" utility is available to ' + 'convert a\n' + ' 2.x style *cmp* function to a *key* function.\n' + '\n' + ' *reverse* is a boolean value. If set to "True", then the ' + 'list\n' + ' elements are sorted as if each comparison were reversed.\n' + '\n' + ' This method modifies the sequence in place for economy of ' + 'space\n' + ' when sorting a large sequence. To remind users that it ' + 'operates\n' + ' by side effect, it does not return the sorted sequence ' + '(use\n' + ' "sorted()" to explicitly request a new sorted list ' + 'instance).\n' + '\n' + ' The "sort()" method is guaranteed to be stable. A sort ' + 'is\n' + ' stable if it guarantees not to change the relative order ' + 'of\n' + ' elements that compare equal — this is helpful for sorting ' + 'in\n' + ' multiple passes (for example, sort by department, then by ' + 'salary\n' + ' grade).\n' + '\n' + ' For sorting examples and a brief sorting tutorial, see ' + 'Sorting\n' + ' HOW TO.\n' + '\n' + ' **CPython implementation detail:** While a list is being ' + 'sorted,\n' + ' the effect of attempting to mutate, or even inspect, the ' + 'list is\n' + ' undefined. The C implementation of Python makes the list ' + 'appear\n' + ' empty for the duration, and raises "ValueError" if it can ' + 'detect\n' + ' that the list has been mutated during a sort.\n' + '\n' + '\n' + 'Tuples\n' + '======\n' + '\n' + 'Tuples are immutable sequences, typically used to store ' + 'collections of\n' + 'heterogeneous data (such as the 2-tuples produced by the ' + '"enumerate()"\n' + 'built-in). Tuples are also used for cases where an immutable ' + 'sequence\n' + 'of homogeneous data is needed (such as allowing storage in a ' + '"set" or\n' + '"dict" instance).\n' + '\n' + 'class tuple([iterable])\n' + '\n' + ' Tuples may be constructed in a number of ways:\n' + '\n' + ' * Using a pair of parentheses to denote the empty tuple: ' + '"()"\n' + '\n' + ' * Using a trailing comma for a singleton tuple: "a," or ' + '"(a,)"\n' + '\n' + ' * Separating items with commas: "a, b, c" or "(a, b, c)"\n' + '\n' + ' * Using the "tuple()" built-in: "tuple()" or ' + '"tuple(iterable)"\n' + '\n' + ' The constructor builds a tuple whose items are the same and ' + 'in the\n' + ' same order as *iterable*’s items. *iterable* may be either ' + 'a\n' + ' sequence, a container that supports iteration, or an ' + 'iterator\n' + ' object. If *iterable* is already a tuple, it is returned\n' + ' unchanged. For example, "tuple(\'abc\')" returns "(\'a\', ' + '\'b\', \'c\')"\n' + ' and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument ' + 'is\n' + ' given, the constructor creates a new empty tuple, "()".\n' + '\n' + ' Note that it is actually the comma which makes a tuple, not ' + 'the\n' + ' parentheses. The parentheses are optional, except in the ' + 'empty\n' + ' tuple case, or when they are needed to avoid syntactic ' + 'ambiguity.\n' + ' For example, "f(a, b, c)" is a function call with three ' + 'arguments,\n' + ' while "f((a, b, c))" is a function call with a 3-tuple as the ' + 'sole\n' + ' argument.\n' + '\n' + ' Tuples implement all of the common sequence operations.\n' + '\n' + 'For heterogeneous collections of data where access by name is ' + 'clearer\n' + 'than access by index, "collections.namedtuple()" may be a more\n' + 'appropriate choice than a simple tuple object.\n' + '\n' + '\n' + 'Ranges\n' + '======\n' + '\n' + 'The "range" type represents an immutable sequence of numbers and ' + 'is\n' + 'commonly used for looping a specific number of times in "for" ' + 'loops.\n' + '\n' + 'class range(stop)\n' + 'class range(start, stop[, step])\n' + '\n' + ' The arguments to the range constructor must be integers ' + '(either\n' + ' built-in "int" or any object that implements the ' + '"__index__()"\n' + ' special method). If the *step* argument is omitted, it ' + 'defaults to\n' + ' "1". If the *start* argument is omitted, it defaults to "0". ' + 'If\n' + ' *step* is zero, "ValueError" is raised.\n' + '\n' + ' For a positive *step*, the contents of a range "r" are ' + 'determined\n' + ' by the formula "r[i] = start + step*i" where "i >= 0" and ' + '"r[i] <\n' + ' stop".\n' + '\n' + ' For a negative *step*, the contents of the range are still\n' + ' determined by the formula "r[i] = start + step*i", but the\n' + ' constraints are "i >= 0" and "r[i] > stop".\n' + '\n' + ' A range object will be empty if "r[0]" does not meet the ' + 'value\n' + ' constraint. Ranges do support negative indices, but these ' + 'are\n' + ' interpreted as indexing from the end of the sequence ' + 'determined by\n' + ' the positive indices.\n' + '\n' + ' Ranges containing absolute values larger than "sys.maxsize" ' + 'are\n' + ' permitted but some features (such as "len()") may raise\n' + ' "OverflowError".\n' + '\n' + ' Range examples:\n' + '\n' + ' >>> list(range(10))\n' + ' [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n' + ' >>> list(range(1, 11))\n' + ' [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n' + ' >>> list(range(0, 30, 5))\n' + ' [0, 5, 10, 15, 20, 25]\n' + ' >>> list(range(0, 10, 3))\n' + ' [0, 3, 6, 9]\n' + ' >>> list(range(0, -10, -1))\n' + ' [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n' + ' >>> list(range(0))\n' + ' []\n' + ' >>> list(range(1, 0))\n' + ' []\n' + '\n' + ' Ranges implement all of the common sequence operations ' + 'except\n' + ' concatenation and repetition (due to the fact that range ' + 'objects\n' + ' can only represent sequences that follow a strict pattern ' + 'and\n' + ' repetition and concatenation will usually violate that ' + 'pattern).\n' + '\n' + ' start\n' + '\n' + ' The value of the *start* parameter (or "0" if the ' + 'parameter was\n' + ' not supplied)\n' + '\n' + ' stop\n' + '\n' + ' The value of the *stop* parameter\n' + '\n' + ' step\n' + '\n' + ' The value of the *step* parameter (or "1" if the parameter ' + 'was\n' + ' not supplied)\n' + '\n' + 'The advantage of the "range" type over a regular "list" or ' + '"tuple" is\n' + 'that a "range" object will always take the same (small) amount ' + 'of\n' + 'memory, no matter the size of the range it represents (as it ' + 'only\n' + 'stores the "start", "stop" and "step" values, calculating ' + 'individual\n' + 'items and subranges as needed).\n' + '\n' + 'Range objects implement the "collections.abc.Sequence" ABC, and\n' + 'provide features such as containment tests, element index ' + 'lookup,\n' + 'slicing and support for negative indices (see Sequence Types — ' + 'list,\n' + 'tuple, range):\n' + '\n' + '>>> r = range(0, 20, 2)\n' + '>>> r\n' + 'range(0, 20, 2)\n' + '>>> 11 in r\n' + 'False\n' + '>>> 10 in r\n' + 'True\n' + '>>> r.index(10)\n' + '5\n' + '>>> r[5]\n' + '10\n' + '>>> r[:5]\n' + 'range(0, 10, 2)\n' + '>>> r[-1]\n' + '18\n' + '\n' + 'Testing range objects for equality with "==" and "!=" compares ' + 'them as\n' + 'sequences. That is, two range objects are considered equal if ' + 'they\n' + 'represent the same sequence of values. (Note that two range ' + 'objects\n' + 'that compare equal might have different "start", "stop" and ' + '"step"\n' + 'attributes, for example "range(0) == range(2, 1, 3)" or ' + '"range(0, 3,\n' + '2) == range(0, 4, 2)".)\n' + '\n' + 'Changed in version 3.2: Implement the Sequence ABC. Support ' + 'slicing\n' + 'and negative indices. Test "int" objects for membership in ' + 'constant\n' + 'time instead of iterating through all items.\n' + '\n' + 'Changed in version 3.3: Define ‘==’ and ‘!=’ to compare range ' + 'objects\n' + 'based on the sequence of values they define (instead of ' + 'comparing\n' + 'based on object identity).Added the "start", "stop" and "step"\n' + 'attributes.\n' + '\n' + 'See also:\n' + '\n' + ' * The linspace recipe shows how to implement a lazy version of ' + 'range\n' + ' suitable for floating point applications.\n', + 'typesseq-mutable': 'Mutable Sequence Types\n' + '**********************\n' + '\n' + 'The operations in the following table are defined on ' + 'mutable sequence\n' + 'types. The "collections.abc.MutableSequence" ABC is ' + 'provided to make\n' + 'it easier to correctly implement these operations on ' + 'custom sequence\n' + 'types.\n' + '\n' + 'In the table *s* is an instance of a mutable sequence ' + 'type, *t* is any\n' + 'iterable object and *x* is an arbitrary object that ' + 'meets any type and\n' + 'value restrictions imposed by *s* (for example, ' + '"bytearray" only\n' + 'accepts integers that meet the value restriction "0 <= x ' + '<= 255").\n' + '\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| Operation | ' + 'Result | Notes ' + '|\n' + '|================================|==================================|=======================|\n' + '| "s[i] = x" | item *i* of *s* is ' + 'replaced by | |\n' + '| | ' + '*x* | ' + '|\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s[i:j] = t" | slice of *s* from *i* ' + 'to *j* is | |\n' + '| | replaced by the ' + 'contents of the | |\n' + '| | iterable ' + '*t* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "del s[i:j]" | same as "s[i:j] = ' + '[]" | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s[i:j:k] = t" | the elements of ' + '"s[i:j:k]" are | (1) |\n' + '| | replaced by those of ' + '*t* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "del s[i:j:k]" | removes the elements ' + 'of | |\n' + '| | "s[i:j:k]" from the ' + 'list | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.append(x)" | appends *x* to the ' + 'end of the | |\n' + '| | sequence (same ' + 'as | |\n' + '| | "s[len(s):len(s)] = ' + '[x]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.clear()" | removes all items ' + 'from *s* (same | (5) |\n' + '| | as "del ' + 's[:]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.copy()" | creates a shallow ' + 'copy of *s* | (5) |\n' + '| | (same as ' + '"s[:]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.extend(t)" or "s += t" | extends *s* with the ' + 'contents of | |\n' + '| | *t* (for the most ' + 'part the same | |\n' + '| | as "s[len(s):len(s)] ' + '= t") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s *= n" | updates *s* with its ' + 'contents | (6) |\n' + '| | repeated *n* ' + 'times | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.insert(i, x)" | inserts *x* into *s* ' + 'at the | |\n' + '| | index given by *i* ' + '(same as | |\n' + '| | "s[i:i] = ' + '[x]") | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.pop()" or "s.pop(i)" | retrieves the item at ' + '*i* and | (2) |\n' + '| | also removes it from ' + '*s* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.remove(x)" | remove the first item ' + 'from *s* | (3) |\n' + '| | where "s[i]" is equal ' + 'to *x* | |\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '| "s.reverse()" | reverses the items of ' + '*s* in | (4) |\n' + '| | ' + 'place | ' + '|\n' + '+--------------------------------+----------------------------------+-----------------------+\n' + '\n' + 'Notes:\n' + '\n' + '1. *t* must have the same length as the slice it is ' + 'replacing.\n' + '\n' + '2. The optional argument *i* defaults to "-1", so that ' + 'by default the\n' + ' last item is removed and returned.\n' + '\n' + '3. "remove()" raises "ValueError" when *x* is not found ' + 'in *s*.\n' + '\n' + '4. The "reverse()" method modifies the sequence in place ' + 'for economy\n' + ' of space when reversing a large sequence. To remind ' + 'users that it\n' + ' operates by side effect, it does not return the ' + 'reversed sequence.\n' + '\n' + '5. "clear()" and "copy()" are included for consistency ' + 'with the\n' + ' interfaces of mutable containers that don’t support ' + 'slicing\n' + ' operations (such as "dict" and "set"). "copy()" is ' + 'not part of the\n' + ' "collections.abc.MutableSequence" ABC, but most ' + 'concrete mutable\n' + ' sequence classes provide it.\n' + '\n' + ' New in version 3.3: "clear()" and "copy()" methods.\n' + '\n' + '6. The value *n* is an integer, or an object ' + 'implementing\n' + ' "__index__()". Zero and negative values of *n* clear ' + 'the sequence.\n' + ' Items in the sequence are not copied; they are ' + 'referenced multiple\n' + ' times, as explained for "s * n" under Common Sequence ' + 'Operations.\n', + 'unary': 'Unary arithmetic and bitwise operations\n' + '***************************************\n' + '\n' + 'All unary arithmetic and bitwise operations have the same ' + 'priority:\n' + '\n' + ' u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n' + '\n' + 'The unary "-" (minus) operator yields the negation of its numeric\n' + 'argument; the operation can be overridden with the "__neg__()" ' + 'special\n' + 'method.\n' + '\n' + 'The unary "+" (plus) operator yields its numeric argument ' + 'unchanged;\n' + 'the operation can be overridden with the "__pos__()" special ' + 'method.\n' + '\n' + 'The unary "~" (invert) operator yields the bitwise inversion of ' + 'its\n' + 'integer argument. The bitwise inversion of "x" is defined as\n' + '"-(x+1)". It only applies to integral numbers or to custom ' + 'objects\n' + 'that override the "__invert__()" special method.\n' + '\n' + 'In all three cases, if the argument does not have the proper type, ' + 'a\n' + '"TypeError" exception is raised.\n', + 'while': 'The "while" statement\n' + '*********************\n' + '\n' + 'The "while" statement is used for repeated execution as long as an\n' + 'expression is true:\n' + '\n' + ' while_stmt ::= "while" assignment_expression ":" suite\n' + ' ["else" ":" suite]\n' + '\n' + 'This repeatedly tests the expression and, if it is true, executes ' + 'the\n' + 'first suite; if the expression is false (which may be the first ' + 'time\n' + 'it is tested) the suite of the "else" clause, if present, is ' + 'executed\n' + 'and the loop terminates.\n' + '\n' + 'A "break" statement executed in the first suite terminates the ' + 'loop\n' + 'without executing the "else" clause’s suite. A "continue" ' + 'statement\n' + 'executed in the first suite skips the rest of the suite and goes ' + 'back\n' + 'to testing the expression.\n', + 'with': 'The "with" statement\n' + '********************\n' + '\n' + 'The "with" statement is used to wrap the execution of a block with\n' + 'methods defined by a context manager (see section With Statement\n' + 'Context Managers). This allows common "try"…"except"…"finally" ' + 'usage\n' + 'patterns to be encapsulated for convenient reuse.\n' + '\n' + ' with_stmt ::= "with" ( "(" with_stmt_contents ","? ")" | ' + 'with_stmt_contents ) ":" suite\n' + ' with_stmt_contents ::= with_item ("," with_item)*\n' + ' with_item ::= expression ["as" target]\n' + '\n' + 'The execution of the "with" statement with one “item” proceeds as\n' + 'follows:\n' + '\n' + '1. The context expression (the expression given in the "with_item") ' + 'is\n' + ' evaluated to obtain a context manager.\n' + '\n' + '2. The context manager’s "__enter__()" is loaded for later use.\n' + '\n' + '3. The context manager’s "__exit__()" is loaded for later use.\n' + '\n' + '4. The context manager’s "__enter__()" method is invoked.\n' + '\n' + '5. If a target was included in the "with" statement, the return ' + 'value\n' + ' from "__enter__()" is assigned to it.\n' + '\n' + ' Note:\n' + '\n' + ' The "with" statement guarantees that if the "__enter__()" ' + 'method\n' + ' returns without an error, then "__exit__()" will always be\n' + ' called. Thus, if an error occurs during the assignment to the\n' + ' target list, it will be treated the same as an error occurring\n' + ' within the suite would be. See step 7 below.\n' + '\n' + '6. The suite is executed.\n' + '\n' + '7. The context manager’s "__exit__()" method is invoked. If an\n' + ' exception caused the suite to be exited, its type, value, and\n' + ' traceback are passed as arguments to "__exit__()". Otherwise, ' + 'three\n' + ' "None" arguments are supplied.\n' + '\n' + ' If the suite was exited due to an exception, and the return ' + 'value\n' + ' from the "__exit__()" method was false, the exception is ' + 'reraised.\n' + ' If the return value was true, the exception is suppressed, and\n' + ' execution continues with the statement following the "with"\n' + ' statement.\n' + '\n' + ' If the suite was exited for any reason other than an exception, ' + 'the\n' + ' return value from "__exit__()" is ignored, and execution ' + 'proceeds\n' + ' at the normal location for the kind of exit that was taken.\n' + '\n' + 'The following code:\n' + '\n' + ' with EXPRESSION as TARGET:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' manager = (EXPRESSION)\n' + ' enter = type(manager).__enter__\n' + ' exit = type(manager).__exit__\n' + ' value = enter(manager)\n' + ' hit_except = False\n' + '\n' + ' try:\n' + ' TARGET = value\n' + ' SUITE\n' + ' except:\n' + ' hit_except = True\n' + ' if not exit(manager, *sys.exc_info()):\n' + ' raise\n' + ' finally:\n' + ' if not hit_except:\n' + ' exit(manager, None, None, None)\n' + '\n' + 'With more than one item, the context managers are processed as if\n' + 'multiple "with" statements were nested:\n' + '\n' + ' with A() as a, B() as b:\n' + ' SUITE\n' + '\n' + 'is semantically equivalent to:\n' + '\n' + ' with A() as a:\n' + ' with B() as b:\n' + ' SUITE\n' + '\n' + 'You can also write multi-item context managers in multiple lines if\n' + 'the items are surrounded by parentheses. For example:\n' + '\n' + ' with (\n' + ' A() as a,\n' + ' B() as b,\n' + ' ):\n' + ' SUITE\n' + '\n' + 'Changed in version 3.1: Support for multiple context expressions.\n' + '\n' + 'Changed in version 3.10: Support for using grouping parentheses to\n' + 'break the statement in multiple lines.\n' + '\n' + 'See also:\n' + '\n' + ' **PEP 343** - The “with” statement\n' + ' The specification, background, and examples for the Python ' + '"with"\n' + ' statement.\n', + 'yield': 'The "yield" statement\n' + '*********************\n' + '\n' + ' yield_stmt ::= yield_expression\n' + '\n' + 'A "yield" statement is semantically equivalent to a yield ' + 'expression.\n' + 'The yield statement can be used to omit the parentheses that would\n' + 'otherwise be required in the equivalent yield expression ' + 'statement.\n' + 'For example, the yield statements\n' + '\n' + ' yield \n' + ' yield from \n' + '\n' + 'are equivalent to the yield expression statements\n' + '\n' + ' (yield )\n' + ' (yield from )\n' + '\n' + 'Yield expressions and statements are only used when defining a\n' + '*generator* function, and are only used in the body of the ' + 'generator\n' + 'function. Using yield in a function definition is sufficient to ' + 'cause\n' + 'that definition to create a generator function instead of a normal\n' + 'function.\n' + '\n' + 'For full details of "yield" semantics, refer to the Yield ' + 'expressions\n' + 'section.\n'} diff --git a/shared/package-files/bc/bc45e83b06d348d5bd8f9f4d8cc7ff84d5ce0fb3c383b031ffa058b92dea551e/SmallVector.h b/shared/package-files/bc/bc45e83b06d348d5bd8f9f4d8cc7ff84d5ce0fb3c383b031ffa058b92dea551e/SmallVector.h new file mode 100644 index 0000000000000000000000000000000000000000..0b5282c9b9e641261021ea36590a99a9ead7609d --- /dev/null +++ b/shared/package-files/bc/bc45e83b06d348d5bd8f9f4d8cc7ff84d5ce0fb3c383b031ffa058b92dea551e/SmallVector.h @@ -0,0 +1,1467 @@ +//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the SmallVector class. +// +//===----------------------------------------------------------------------===// + +// ATen: modified from llvm::SmallVector. +// used std::is_trivially_{copy,move}_constructible +// replaced iterator_range constructor with inline Container&& constructor +// replaced LLVM_NODISCARD, LLVM_LIKELY, and LLVM_UNLIKELY with c10 equivalents +// removed LLVM_GSL_OWNER +// added SmallVector::at +// added operator<< for std::ostream +// added C10_API to export SmallVectorBase + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace c10 { + +/// This is all the stuff common to all SmallVectors. +/// +/// The template parameter specifies the type which should be used to hold the +/// Size and Capacity of the SmallVector, so it can be adjusted. +/// Using 32 bit size is desirable to shrink the size of the SmallVector. +/// Using 64 bit size is desirable for cases like SmallVector, where a +/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for +/// buffering bitcode output - which can exceed 4GB. +template +class C10_API SmallVectorBase { + protected: + void* BeginX; + Size_T Size = 0, Capacity; + + /// The maximum value of the Size_T used. + static constexpr size_t SizeTypeMax() { + return std::numeric_limits::max(); + } + + SmallVectorBase(void* FirstEl, size_t TotalCapacity) + : BeginX(FirstEl), Capacity(TotalCapacity) {} + + /// This is a helper for \a grow() that's out of line to reduce code + /// duplication. This function will report a fatal error if it can't grow at + /// least to \p MinSize. + void* mallocForGrow(size_t MinSize, size_t TSize, size_t& NewCapacity); + + /// This is an implementation of the grow() method which only works + /// on POD-like data types and is out of line to reduce code duplication. + /// This function will report a fatal error if it cannot increase capacity. + void grow_pod(const void* FirstEl, size_t MinSize, size_t TSize); + + public: + SmallVectorBase() = delete; + size_t size() const { + return Size; + } + size_t capacity() const { + return Capacity; + } + + [[nodiscard]] bool empty() const { + return !Size; + } + + /// Set the array size to \p N, which the current array must have enough + /// capacity for. + /// + /// This does not construct or destroy any elements in the vector. + /// + /// Clients can use this in conjunction with capacity() to write past the end + /// of the buffer when they know that more elements are available, and only + /// update the size later. This avoids the cost of value initializing elements + /// which will only be overwritten. + void set_size(size_t N) { + assert(N <= capacity()); + Size = N; + } +}; + +template +using SmallVectorSizeType = + std::conditional_t= 8, uint64_t, uint32_t>; + +/// Figure out the offset of the first element. +template +struct SmallVectorAlignmentAndSize { + // NOLINTNEXTLINE(*c-arrays*) + alignas(SmallVectorBase>) char Base[sizeof( + SmallVectorBase>)]; + // NOLINTNEXTLINE(*c-arrays*) + alignas(T) char FirstEl[sizeof(T)]; +}; + +/// This is the part of SmallVectorTemplateBase which does not depend on whether +/// the type T is a POD. The extra dummy template argument is used by ArrayRef +/// to avoid unnecessarily requiring T to be complete. +template +class SmallVectorTemplateCommon + : public SmallVectorBase> { + using Base = SmallVectorBase>; + + /// Find the address of the first element. For this pointer math to be valid + /// with small-size of 0 for T with lots of alignment, it's important that + /// SmallVectorStorage is properly-aligned even for small-size of 0. + void* getFirstEl() const { + return const_cast(reinterpret_cast( + reinterpret_cast(this) + + offsetof(SmallVectorAlignmentAndSize, FirstEl))); + } + // Space after 'FirstEl' is clobbered, do not add any instance vars after it. + + protected: + SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {} + + void grow_pod(size_t MinSize, size_t TSize) { + Base::grow_pod(getFirstEl(), MinSize, TSize); + } + + /// Return true if this is a smallvector which has not had dynamic + /// memory allocated for it. + bool isSmall() const { + return this->BeginX == getFirstEl(); + } + + /// Put this vector in a state of being small. + void resetToSmall() { + this->BeginX = getFirstEl(); + this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect. + } + + /// Return true if V is an internal reference to the given range. + bool isReferenceToRange(const void* V, const void* First, const void* Last) + const { + // Use std::less to avoid UB. + std::less<> LessThan; + return !LessThan(V, First) && LessThan(V, Last); + } + + /// Return true if V is an internal reference to this vector. + bool isReferenceToStorage(const void* V) const { + return isReferenceToRange(V, this->begin(), this->end()); + } + + /// Return true if First and Last form a valid (possibly empty) range in this + /// vector's storage. + bool isRangeInStorage(const void* First, const void* Last) const { + // Use std::less to avoid UB. + std::less<> LessThan; + return !LessThan(First, this->begin()) && !LessThan(Last, First) && + !LessThan(this->end(), Last); + } + + /// Return true unless Elt will be invalidated by resizing the vector to + /// NewSize. + bool isSafeToReferenceAfterResize(const void* Elt, size_t NewSize) { + // Past the end. + if (C10_LIKELY(!isReferenceToStorage(Elt))) + return true; + + // Return false if Elt will be destroyed by shrinking. + if (NewSize <= this->size()) + return Elt < this->begin() + NewSize; + + // Return false if we need to grow. + return NewSize <= this->capacity(); + } + + /// Check whether Elt will be invalidated by resizing the vector to NewSize. + void assertSafeToReferenceAfterResize(const void* Elt, size_t NewSize) { + (void)Elt; // Suppress unused variable warning + (void)NewSize; // Suppress unused variable warning + assert( + isSafeToReferenceAfterResize(Elt, NewSize) && + "Attempting to reference an element of the vector in an operation " + "that invalidates it"); + } + + /// Check whether Elt will be invalidated by increasing the size of the + /// vector by N. + void assertSafeToAdd(const void* Elt, size_t N = 1) { + this->assertSafeToReferenceAfterResize(Elt, this->size() + N); + } + + /// Check whether any part of the range will be invalidated by clearing. + void assertSafeToReferenceAfterClear(const T* From, const T* To) { + if (From == To) + return; + this->assertSafeToReferenceAfterResize(From, 0); + this->assertSafeToReferenceAfterResize(To - 1, 0); + } + template < + class ItTy, + std::enable_if_t, T*>, bool> = + false> + void assertSafeToReferenceAfterClear(ItTy, ItTy) {} + + /// Check whether any part of the range will be invalidated by growing. + void assertSafeToAddRange(const T* From, const T* To) { + if (From == To) + return; + this->assertSafeToAdd(From, To - From); + this->assertSafeToAdd(To - 1, To - From); + } + template < + class ItTy, + std::enable_if_t, T*>, bool> = + false> + void assertSafeToAddRange(ItTy, ItTy) {} + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + template + static const T* reserveForParamAndGetAddressImpl( + U* This, + const T& Elt, + size_t N) { + size_t NewSize = This->size() + N; + if (C10_LIKELY(NewSize <= This->capacity())) + return &Elt; + + bool ReferencesStorage = false; + int64_t Index = -1; + if constexpr (!U::TakesParamByValue) { + if (C10_UNLIKELY(This->isReferenceToStorage(&Elt))) { + ReferencesStorage = true; + Index = &Elt - This->begin(); + } + } + This->grow(NewSize); + return ReferencesStorage ? This->begin() + Index : &Elt; + } + + public: + using size_type = size_t; + using difference_type = ptrdiff_t; + using value_type = T; + using iterator = T*; + using const_iterator = const T*; + + using const_reverse_iterator = std::reverse_iterator; + using reverse_iterator = std::reverse_iterator; + + using reference = T&; + using const_reference = const T&; + using pointer = T*; + using const_pointer = const T*; + + using Base::capacity; + using Base::empty; + using Base::size; + + // forward iterator creation methods. + iterator begin() { + return (iterator)this->BeginX; + } + const_iterator begin() const { + return (const_iterator)this->BeginX; + } + iterator end() { + return begin() + size(); + } + const_iterator end() const { + return begin() + size(); + } + + // reverse iterator creation methods. + reverse_iterator rbegin() { + return reverse_iterator(end()); + } + const_reverse_iterator rbegin() const { + return const_reverse_iterator(end()); + } + reverse_iterator rend() { + return reverse_iterator(begin()); + } + const_reverse_iterator rend() const { + return const_reverse_iterator(begin()); + } + + size_type size_in_bytes() const { + return size() * sizeof(T); + } + constexpr size_type max_size() const { + return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T)); + } + + size_t capacity_in_bytes() const { + return capacity() * sizeof(T); + } + + /// Return a pointer to the vector's buffer, even if empty(). + pointer data() { + return pointer(begin()); + } + /// Return a pointer to the vector's buffer, even if empty(). + const_pointer data() const { + return const_pointer(begin()); + } + + // SmallVector::at is NOT from LLVM. + reference at(size_type idx) { + assert(idx < size()); + return begin()[idx]; + } + const_reference at(size_type idx) const { + assert(idx < size()); + return begin()[idx]; + } + reference operator[](size_type idx) { + assert(idx < size()); + return begin()[idx]; + } + const_reference operator[](size_type idx) const { + assert(idx < size()); + return begin()[idx]; + } + + reference front() { + assert(!empty()); + return begin()[0]; + } + const_reference front() const { + assert(!empty()); + return begin()[0]; + } + + reference back() { + assert(!empty()); + return end()[-1]; + } + const_reference back() const { + assert(!empty()); + return end()[-1]; + } +}; + +/// SmallVectorTemplateBase - This is where we put +/// method implementations that are designed to work with non-trivial T's. +/// +/// We approximate is_trivially_copyable with trivial move/copy construction and +/// trivial destruction. While the standard doesn't specify that you're allowed +/// copy these types with memcpy, there is no way for the type to observe this. +/// This catches the important case of std::pair, which is not +/// trivially assignable. +/// +/// XXX: if build fails here fall back to C10_IS_TRIVIALLY_COPYABLE and make a +/// note +template < + typename T, + bool = (std::is_trivially_copy_constructible_v)&&( + std::is_trivially_move_constructible_v< + T>)&&std::is_trivially_destructible_v> +class SmallVectorTemplateBase : public SmallVectorTemplateCommon { + friend class SmallVectorTemplateCommon; + + protected: + static constexpr bool TakesParamByValue = false; + using ValueParamT = const T&; + + SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} + + static void destroy_range(T* S, T* E) { + while (S != E) { + --E; + E->~T(); + } + } + + /// Move the range [I, E) into the uninitialized memory starting with "Dest", + /// constructing elements as needed. + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) { + std::uninitialized_copy( + std::make_move_iterator(I), std::make_move_iterator(E), Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory starting with "Dest", + /// constructing elements as needed. + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + std::uninitialized_copy(I, E, Dest); + } + + /// Grow the allocated memory (without initializing new elements), doubling + /// the size of the allocated memory. Guarantees space for at least one more + /// element, or MinSize more elements if specified. + void grow(size_t MinSize = 0); + + /// Create a new allocation big enough for \p MinSize and pass back its size + /// in \p NewCapacity. This is the first section of \a grow(). + T* mallocForGrow(size_t MinSize, size_t& NewCapacity) { + return static_cast( + SmallVectorBase>::mallocForGrow( + MinSize, sizeof(T), NewCapacity)); + } + + /// Move existing elements over to the new allocation \p NewElts, the middle + /// section of \a grow(). + void moveElementsForGrow(T* NewElts); + + /// Transfer ownership of the allocation, finishing up \a grow(). + void takeAllocationForGrow(T* NewElts, size_t NewCapacity); + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + const T* reserveForParamAndGetAddress(const T& Elt, size_t N = 1) { + return this->reserveForParamAndGetAddressImpl(this, Elt, N); + } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + T* reserveForParamAndGetAddress(T& Elt, size_t N = 1) { + return const_cast(this->reserveForParamAndGetAddressImpl(this, Elt, N)); + } + + static T&& forward_value_param(T&& V) { + return std::move(V); + } + static const T& forward_value_param(const T& V) { + return V; + } + + void growAndAssign(size_t NumElts, const T& Elt) { + // Grow manually in case Elt is an internal reference. + size_t NewCapacity = 0; + T* NewElts = mallocForGrow(NumElts, NewCapacity); + std::uninitialized_fill_n(NewElts, NumElts, Elt); + this->destroy_range(this->begin(), this->end()); + takeAllocationForGrow(NewElts, NewCapacity); + this->set_size(NumElts); + } + + template + T& growAndEmplaceBack(ArgTypes&&... Args) { + // Grow manually in case one of Args is an internal reference. + size_t NewCapacity = 0; + T* NewElts = mallocForGrow(0, NewCapacity); + ::new ((void*)(NewElts + this->size())) T(std::forward(Args)...); + moveElementsForGrow(NewElts); + takeAllocationForGrow(NewElts, NewCapacity); + this->set_size(this->size() + 1); + return this->back(); + } + + public: + void push_back(const T& Elt) { + const T* EltPtr = reserveForParamAndGetAddress(Elt); + ::new ((void*)this->end()) T(*EltPtr); + this->set_size(this->size() + 1); + } + + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + void push_back(T&& Elt) { + T* EltPtr = reserveForParamAndGetAddress(Elt); + ::new ((void*)this->end()) T(::std::move(*EltPtr)); + this->set_size(this->size() + 1); + } + + void pop_back() { + this->set_size(this->size() - 1); + this->end()->~T(); + } +}; + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void SmallVectorTemplateBase::grow(size_t MinSize) { + size_t NewCapacity = 0; + T* NewElts = mallocForGrow(MinSize, NewCapacity); + moveElementsForGrow(NewElts); + takeAllocationForGrow(NewElts, NewCapacity); +} + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void SmallVectorTemplateBase::moveElementsForGrow( + T* NewElts) { + // Move the elements over. + this->uninitialized_move(this->begin(), this->end(), NewElts); + + // Destroy the original elements. + destroy_range(this->begin(), this->end()); +} + +// Define this out-of-line to dissuade the C++ compiler from inlining it. +template +void SmallVectorTemplateBase::takeAllocationForGrow( + T* NewElts, + size_t NewCapacity) { + // If this wasn't grown from the inline copy, deallocate the old space. + if (!this->isSmall()) + free(this->begin()); + + this->BeginX = NewElts; + this->Capacity = NewCapacity; +} + +/// SmallVectorTemplateBase - This is where we put +/// method implementations that are designed to work with trivially copyable +/// T's. This allows using memcpy in place of copy/move construction and +/// skipping destruction. +template +class SmallVectorTemplateBase : public SmallVectorTemplateCommon { + friend class SmallVectorTemplateCommon; + + protected: + /// True if it's cheap enough to take parameters by value. Doing so avoids + /// overhead related to mitigations for reference invalidation. + static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void*); + + /// Either const T& or T, depending on whether it's cheap enough to take + /// parameters by value. + using ValueParamT = std::conditional_t; + + SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} + + // No need to do a destroy loop for POD's. + static void destroy_range(T*, T*) {} + + /// Move the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) { + // Just do a copy. + uninitialized_copy(I, E, Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + // Arbitrary iterator types; just use the basic implementation. + std::uninitialized_copy(I, E, Dest); + } + + /// Copy the range [I, E) onto the uninitialized memory + /// starting with "Dest", constructing elements into it as needed. + template + static void uninitialized_copy( + T1* I, + T1* E, + T2* Dest, + std::enable_if_t, T2>>* = + nullptr) { + // Use memcpy for PODs iterated by pointers (which includes SmallVector + // iterators): std::uninitialized_copy optimizes to memmove, but we can + // use memcpy here. Note that I and E are iterators and thus might be + // invalid for memcpy if they are equal. + if (I != E) + memcpy(reinterpret_cast(Dest), I, (E - I) * sizeof(T)); + } + + /// Double the size of the allocated memory, guaranteeing space for at + /// least one more element or MinSize if specified. + void grow(size_t MinSize = 0) { + this->grow_pod(MinSize, sizeof(T)); + } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + const T* reserveForParamAndGetAddress(const T& Elt, size_t N = 1) { + return this->reserveForParamAndGetAddressImpl(this, Elt, N); + } + + /// Reserve enough space to add one element, and return the updated element + /// pointer in case it was a reference to the storage. + T* reserveForParamAndGetAddress(T& Elt, size_t N = 1) { + return const_cast(this->reserveForParamAndGetAddressImpl(this, Elt, N)); + } + + /// Copy \p V or return a reference, depending on \a ValueParamT. + static ValueParamT forward_value_param(ValueParamT V) { + return V; + } + + void growAndAssign(size_t NumElts, T Elt) { + // Elt has been copied in case it's an internal reference, side-stepping + // reference invalidation problems without losing the realloc optimization. + this->set_size(0); + this->grow(NumElts); + std::uninitialized_fill_n(this->begin(), NumElts, Elt); + this->set_size(NumElts); + } + + template + T& growAndEmplaceBack(ArgTypes&&... Args) { + // Use push_back with a copy in case Args has an internal reference, + // side-stepping reference invalidation problems without losing the realloc + // optimization. + push_back(T(std::forward(Args)...)); + return this->back(); + } + + public: + void push_back(ValueParamT Elt) { + const T* EltPtr = reserveForParamAndGetAddress(Elt); + memcpy(reinterpret_cast(this->end()), EltPtr, sizeof(T)); + this->set_size(this->size() + 1); + } + + void pop_back() { + this->set_size(this->size() - 1); + } +}; + +/// This class consists of common code factored out of the SmallVector class to +/// reduce code duplication based on the SmallVector 'N' template parameter. +template +class SmallVectorImpl : public SmallVectorTemplateBase { + using SuperClass = SmallVectorTemplateBase; + + public: + using iterator = typename SuperClass::iterator; + using const_iterator = typename SuperClass::const_iterator; + using reference = typename SuperClass::reference; + using size_type = typename SuperClass::size_type; + + protected: + using SmallVectorTemplateBase::TakesParamByValue; + using ValueParamT = typename SuperClass::ValueParamT; + + // Default ctor - Initialize to empty. + explicit SmallVectorImpl(unsigned N) : SmallVectorTemplateBase(N) {} + + public: + SmallVectorImpl(const SmallVectorImpl&) = delete; + + ~SmallVectorImpl() { + // Subclass has already destructed this vector's elements. + // If this wasn't grown from the inline copy, deallocate the old space. + if (!this->isSmall()) + free(this->begin()); + } + + void clear() { + this->destroy_range(this->begin(), this->end()); + this->Size = 0; + } + + private: + template + void resizeImpl(size_type N) { + if (N < this->size()) { + this->pop_back_n(this->size() - N); + } else if (N > this->size()) { + this->reserve(N); + for (auto I = this->end(), E = this->begin() + N; I != E; ++I) + if (ForOverwrite) + new (&*I) T; + else + new (&*I) T(); + this->set_size(N); + } + } + + public: + void resize(size_type N) { + resizeImpl(N); + } + + /// Like resize, but \ref T is POD, the new values won't be initialized. + void resize_for_overwrite(size_type N) { + resizeImpl(N); + } + + void resize(size_type N, ValueParamT NV) { + if (N == this->size()) + return; + + if (N < this->size()) { + this->pop_back_n(this->size() - N); + return; + } + + // N > this->size(). Defer to append. + this->append(N - this->size(), NV); + } + + void reserve(size_type N) { + if (this->capacity() < N) + this->grow(N); + } + + void pop_back_n(size_type NumItems) { + assert(this->size() >= NumItems); + this->destroy_range(this->end() - NumItems, this->end()); + this->set_size(this->size() - NumItems); + } + + [[nodiscard]] T pop_back_val() { + T Result = ::std::move(this->back()); + this->pop_back(); + return Result; + } + + void swap(SmallVectorImpl& RHS) noexcept; + + /// Add the specified range to the end of the SmallVector. + template < + typename in_iter, + typename = std::enable_if_t::iterator_category, + std::input_iterator_tag>>> + void append(in_iter in_start, in_iter in_end) { + this->assertSafeToAddRange(in_start, in_end); + size_type NumInputs = std::distance(in_start, in_end); + this->reserve(this->size() + NumInputs); + this->uninitialized_copy(in_start, in_end, this->end()); + this->set_size(this->size() + NumInputs); + } + + /// Append \p NumInputs copies of \p Elt to the end. + void append(size_type NumInputs, ValueParamT Elt) { + const T* EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs); + std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr); + this->set_size(this->size() + NumInputs); + } + + void append(std::initializer_list IL) { + append(IL.begin(), IL.end()); + } + + void append(const SmallVectorImpl& RHS) { + append(RHS.begin(), RHS.end()); + } + + void assign(size_type NumElts, ValueParamT Elt) { + // Note that Elt could be an internal reference. + if (NumElts > this->capacity()) { + this->growAndAssign(NumElts, Elt); + return; + } + + // Assign over existing elements. + std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt); + if (NumElts > this->size()) + std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt); + else if (NumElts < this->size()) + this->destroy_range(this->begin() + NumElts, this->end()); + this->set_size(NumElts); + } + + // FIXME: Consider assigning over existing elements, rather than clearing & + // re-initializing them - for all assign(...) variants. + + template < + typename in_iter, + typename = std::enable_if_t::iterator_category, + std::input_iterator_tag>>> + void assign(in_iter in_start, in_iter in_end) { + this->assertSafeToReferenceAfterClear(in_start, in_end); + clear(); + append(in_start, in_end); + } + + void assign(std::initializer_list IL) { + clear(); + append(IL); + } + + void assign(const SmallVectorImpl& RHS) { + assign(RHS.begin(), RHS.end()); + } + + iterator erase(iterator I) { + assert( + this->isReferenceToStorage(I) && "Iterator to erase is out of bounds."); + + iterator N = I; + // Shift all elts down one. + std::move(I + 1, this->end(), I); + // Drop the last elt. + this->pop_back(); + return (N); + } + + iterator erase(iterator S, iterator E) { + assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds."); + + iterator N = S; + // Shift all elts down. + iterator I = std::move(E, this->end(), S); + // Drop the last elts. + this->destroy_range(I, this->end()); + this->set_size(I - this->begin()); + return (N); + } + + private: + template + iterator insert_one_impl(iterator I, ArgType&& Elt) { + // Callers ensure that ArgType is derived from T. + static_assert( + std::is_same>, T>:: + value, + "ArgType must be derived from T!"); + + if (I == this->end()) { // Important special case for empty vector. + this->push_back(::std::forward(Elt)); + return this->end() - 1; + } + + assert( + this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Grow if necessary. + size_t Index = I - this->begin(); + std::remove_reference_t* EltPtr = + this->reserveForParamAndGetAddress(Elt); + I = this->begin() + Index; + + ::new ((void*)this->end()) T(::std::move(this->back())); + // Push everything else over. + std::move_backward(I, this->end() - 1, this->end()); + this->set_size(this->size() + 1); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + static_assert( + !TakesParamByValue || std::is_same_v, + "ArgType must be 'T' when taking by value!"); + if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end())) + ++EltPtr; + + *I = ::std::forward(*EltPtr); + return I; + } + + public: + iterator insert(iterator I, T&& Elt) { + return insert_one_impl(I, this->forward_value_param(std::move(Elt))); + } + + iterator insert(iterator I, const T& Elt) { + return insert_one_impl(I, this->forward_value_param(Elt)); + } + + iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) { + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + if (I == this->end()) { // Important special case for empty vector. + append(NumToInsert, Elt); + return this->begin() + InsertElt; + } + + assert( + this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Ensure there is enough space, and get the (maybe updated) address of + // Elt. + const T* EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert); + + // Uninvalidate the iterator. + I = this->begin() + InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end() - I) >= NumToInsert) { + T* OldEnd = this->end(); + append( + std::move_iterator(this->end() - NumToInsert), + std::move_iterator(this->end())); + + // Copy the existing elements that get replaced. + std::move_backward(I, OldEnd - NumToInsert, OldEnd); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) + EltPtr += NumToInsert; + + std::fill_n(I, NumToInsert, *EltPtr); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Move over the elements that we're about to overwrite. + T* OldEnd = this->end(); + this->set_size(this->size() + NumToInsert); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); + + // If we just moved the element we're inserting, be sure to update + // the reference (never happens if TakesParamByValue). + if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end()) + EltPtr += NumToInsert; + + // Replace the overwritten part. + std::fill_n(I, NumOverwritten, *EltPtr); + + // Insert the non-overwritten middle part. + std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr); + return I; + } + + template < + typename ItTy, + typename = std::enable_if_t::iterator_category, + std::input_iterator_tag>>> + iterator insert(iterator I, ItTy From, ItTy To) { + // Convert iterator to elt# to avoid invalidating iterator when we reserve() + size_t InsertElt = I - this->begin(); + + if (I == this->end()) { // Important special case for empty vector. + append(From, To); + return this->begin() + InsertElt; + } + + assert( + this->isReferenceToStorage(I) && + "Insertion iterator is out of bounds."); + + // Check that the reserve that follows doesn't invalidate the iterators. + this->assertSafeToAddRange(From, To); + + size_t NumToInsert = std::distance(From, To); + + // Ensure there is enough space. + reserve(this->size() + NumToInsert); + + // Uninvalidate the iterator. + I = this->begin() + InsertElt; + + // If there are more elements between the insertion point and the end of the + // range than there are being inserted, we can use a simple approach to + // insertion. Since we already reserved space, we know that this won't + // reallocate the vector. + if (size_t(this->end() - I) >= NumToInsert) { + T* OldEnd = this->end(); + append( + std::move_iterator(this->end() - NumToInsert), + std::move_iterator(this->end())); + + // Copy the existing elements that get replaced. + std::move_backward(I, OldEnd - NumToInsert, OldEnd); + + std::copy(From, To, I); + return I; + } + + // Otherwise, we're inserting more elements than exist already, and we're + // not inserting at the end. + + // Move over the elements that we're about to overwrite. + T* OldEnd = this->end(); + this->set_size(this->size() + NumToInsert); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); + + // Replace the overwritten part. + for (T* J = I; NumOverwritten > 0; --NumOverwritten) { + *J = *From; + ++J; + ++From; + } + + // Insert the non-overwritten middle part. + this->uninitialized_copy(From, To, OldEnd); + return I; + } + + void insert(iterator I, std::initializer_list IL) { + insert(I, IL.begin(), IL.end()); + } + + template + reference emplace_back(ArgTypes&&... Args) { + if (C10_UNLIKELY(this->size() >= this->capacity())) + return this->growAndEmplaceBack(std::forward(Args)...); + + ::new ((void*)this->end()) T(std::forward(Args)...); + this->set_size(this->size() + 1); + return this->back(); + } + + SmallVectorImpl& operator=(const SmallVectorImpl& RHS); + + SmallVectorImpl& operator=(SmallVectorImpl&& RHS) noexcept( + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v); + + bool operator==(const SmallVectorImpl& RHS) const { + if (this->size() != RHS.size()) + return false; + return std::equal(this->begin(), this->end(), RHS.begin()); + } + bool operator!=(const SmallVectorImpl& RHS) const { + return !(*this == RHS); + } + + bool operator<(const SmallVectorImpl& RHS) const { + return std::lexicographical_compare( + this->begin(), this->end(), RHS.begin(), RHS.end()); + } +}; + +template +void SmallVectorImpl::swap(SmallVectorImpl& RHS) noexcept { + if (this == &RHS) + return; + + // We can only avoid copying elements if neither vector is small. + if (!this->isSmall() && !RHS.isSmall()) { + std::swap(this->BeginX, RHS.BeginX); + std::swap(this->Size, RHS.Size); + std::swap(this->Capacity, RHS.Capacity); + return; + } + this->reserve(RHS.size()); + RHS.reserve(this->size()); + + // Swap the shared elements. + size_t NumShared = this->size(); + if (NumShared > RHS.size()) + NumShared = RHS.size(); + for (size_type i = 0; i != NumShared; ++i) + std::swap((*this)[i], RHS[i]); + + // Copy over the extra elts. + if (this->size() > RHS.size()) { + size_t EltDiff = this->size() - RHS.size(); + this->uninitialized_copy(this->begin() + NumShared, this->end(), RHS.end()); + RHS.set_size(RHS.size() + EltDiff); + this->destroy_range(this->begin() + NumShared, this->end()); + this->set_size(NumShared); + } else if (RHS.size() > this->size()) { + size_t EltDiff = RHS.size() - this->size(); + this->uninitialized_copy(RHS.begin() + NumShared, RHS.end(), this->end()); + this->set_size(this->size() + EltDiff); + this->destroy_range(RHS.begin() + NumShared, RHS.end()); + RHS.set_size(NumShared); + } +} + +template +SmallVectorImpl& SmallVectorImpl::operator=( + const SmallVectorImpl& RHS) { + // Avoid self-assignment. + if (this == &RHS) + return *this; + + // If we already have sufficient space, assign the common elements, then + // destroy any excess. + size_t RHSSize = RHS.size(); + size_t CurSize = this->size(); + if (CurSize >= RHSSize) { + // Assign common elements. + iterator NewEnd; + if (RHSSize) + NewEnd = std::copy(RHS.begin(), RHS.begin() + RHSSize, this->begin()); + else + NewEnd = this->begin(); + + // Destroy excess elements. + this->destroy_range(NewEnd, this->end()); + + // Trim. + this->set_size(RHSSize); + return *this; + } + + // If we have to grow to have enough elements, destroy the current elements. + // This allows us to avoid copying them during the grow. + // FIXME: don't do this if they're efficiently moveable. + if (this->capacity() < RHSSize) { + // Destroy current elements. + this->clear(); + CurSize = 0; + this->grow(RHSSize); + } else if (CurSize) { + // Otherwise, use assignment for the already-constructed elements. + std::copy(RHS.begin(), RHS.begin() + CurSize, this->begin()); + } + + // Copy construct the new elements in place. + this->uninitialized_copy( + RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); + + // Set end. + this->set_size(RHSSize); + return *this; +} + +template +SmallVectorImpl& SmallVectorImpl:: +operator=(SmallVectorImpl&& RHS) noexcept( + std::is_nothrow_move_constructible_v && + std::is_nothrow_destructible_v) { + // Avoid self-assignment. + if (this == &RHS) + return *this; + + // If the RHS isn't small, clear this vector and then steal its buffer. + if (!RHS.isSmall()) { + this->destroy_range(this->begin(), this->end()); + if (!this->isSmall()) + free(this->begin()); + this->BeginX = RHS.BeginX; + this->Size = RHS.Size; + this->Capacity = RHS.Capacity; + RHS.resetToSmall(); + return *this; + } + + // If we already have sufficient space, assign the common elements, then + // destroy any excess. + size_t RHSSize = RHS.size(); + size_t CurSize = this->size(); + if (CurSize >= RHSSize) { + // Assign common elements. + iterator NewEnd = this->begin(); + if (RHSSize) + NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd); + + // Destroy excess elements and trim the bounds. + this->destroy_range(NewEnd, this->end()); + this->set_size(RHSSize); + + // Clear the RHS. + RHS.clear(); + + return *this; + } + + // If we have to grow to have enough elements, destroy the current elements. + // This allows us to avoid copying them during the grow. + // FIXME: this may not actually make any sense if we can efficiently move + // elements. + if (this->capacity() < RHSSize) { + // Destroy current elements. + this->clear(); + CurSize = 0; + this->grow(RHSSize); + } else if (CurSize) { + // Otherwise, use assignment for the already-constructed elements. + std::move(RHS.begin(), RHS.begin() + CurSize, this->begin()); + } + + // Move-construct the new elements in place. + this->uninitialized_move( + RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); + + // Set end. + this->set_size(RHSSize); + + RHS.clear(); + return *this; +} + +/// Storage for the SmallVector elements. This is specialized for the N=0 case +/// to avoid allocating unnecessary storage. +template +struct SmallVectorStorage { + alignas(T) char InlineElts[N * sizeof(T)]; +}; + +/// We need the storage to be properly aligned even for small-size of 0 so that +/// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is +/// well-defined. +template +struct alignas(T) SmallVectorStorage {}; + +/// Forward declaration of SmallVector so that +/// calculateSmallVectorDefaultInlinedElements can reference +/// `sizeof(SmallVector)`. +template +class /* LLVM_GSL_OWNER */ SmallVector; + +/// Helper class for calculating the default number of inline elements for +/// `SmallVector`. +/// +/// This should be migrated to a constexpr function when our minimum +/// compiler support is enough for multi-statement constexpr functions. +template +struct CalculateSmallVectorDefaultInlinedElements { + // Parameter controlling the default number of inlined elements + // for `SmallVector`. + // + // The default number of inlined elements ensures that + // 1. There is at least one inlined element. + // 2. `sizeof(SmallVector) <= kPreferredSmallVectorSizeof` unless + // it contradicts 1. + static constexpr size_t kPreferredSmallVectorSizeof = 64; + + // static_assert that sizeof(T) is not "too big". + // + // Because our policy guarantees at least one inlined element, it is possible + // for an arbitrarily large inlined element to allocate an arbitrarily large + // amount of inline storage. We generally consider it an antipattern for a + // SmallVector to allocate an excessive amount of inline storage, so we want + // to call attention to these cases and make sure that users are making an + // intentional decision if they request a lot of inline storage. + // + // We want this assertion to trigger in pathological cases, but otherwise + // not be too easy to hit. To accomplish that, the cutoff is actually somewhat + // larger than kPreferredSmallVectorSizeof (otherwise, + // `SmallVector>` would be one easy way to trip it, and that + // pattern seems useful in practice). + // + // One wrinkle is that this assertion is in theory non-portable, since + // sizeof(T) is in general platform-dependent. However, we don't expect this + // to be much of an issue, because most LLVM development happens on 64-bit + // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for + // 32-bit hosts, dodging the issue. The reverse situation, where development + // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a + // 64-bit host, is expected to be very rare. + static_assert( + sizeof(T) <= 256, + "You are trying to use a default number of inlined elements for " + "`SmallVector` but `sizeof(T)` is really big! Please use an " + "explicit number of inlined elements with `SmallVector` to make " + "sure you really want that much inline storage."); + + // Discount the size of the header itself when calculating the maximum inline + // bytes. + static constexpr size_t PreferredInlineBytes = + kPreferredSmallVectorSizeof - sizeof(SmallVector); + static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T); + static constexpr size_t value = + NumElementsThatFit == 0 ? 1 : NumElementsThatFit; +}; + +/// This is a 'vector' (really, a variable-sized array), optimized +/// for the case when the array is small. It contains some number of elements +/// in-place, which allows it to avoid heap allocation when the actual number of +/// elements is below that threshold. This allows normal "small" cases to be +/// fast without losing generality for large inputs. +/// +/// \note +/// In the absence of a well-motivated choice for the number of inlined +/// elements \p N, it is recommended to use \c SmallVector (that is, +/// omitting the \p N). This will choose a default number of inlined elements +/// reasonable for allocation on the stack (for example, trying to keep \c +/// sizeof(SmallVector) around 64 bytes). +/// +/// \warning This does not attempt to be exception safe. +/// +/// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h +template < + typename T, + unsigned N = CalculateSmallVectorDefaultInlinedElements::value> +class /* LLVM_GSL_OWNER */ SmallVector : public SmallVectorImpl, + SmallVectorStorage { + public: + SmallVector() : SmallVectorImpl(N) {} + + ~SmallVector() { + // Destroy the constructed elements in the vector. + this->destroy_range(this->begin(), this->end()); + } + + explicit SmallVector(size_t Size, const T& Value = T()) + : SmallVectorImpl(N) { + this->assign(Size, Value); + } + + template < + typename ItTy, + typename = std::enable_if_t::iterator_category, + std::input_iterator_tag>>> + SmallVector(ItTy S, ItTy E) : SmallVectorImpl(N) { + this->append(S, E); + } + + // note: The enable_if restricts Container to types that have a .begin() and + // .end() that return valid input iterators. + template < + typename Container, + std::enable_if_t< + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .begin())>::iterator_category, + std::input_iterator_tag> && + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .end())>::iterator_category, + std::input_iterator_tag>, + int> = 0> + explicit SmallVector(Container&& c) : SmallVectorImpl(N) { + this->append(c.begin(), c.end()); + } + + SmallVector(std::initializer_list IL) : SmallVectorImpl(N) { + this->assign(IL); + } + + SmallVector(const SmallVector& RHS) : SmallVectorImpl(N) { + if (!RHS.empty()) + SmallVectorImpl::operator=(RHS); + } + + SmallVector& operator=(const SmallVector& RHS) { + SmallVectorImpl::operator=(RHS); + return *this; + } + + SmallVector(SmallVector&& RHS) noexcept( + std::is_nothrow_move_assignable_v>) + : SmallVectorImpl(N) { + if (!RHS.empty()) + SmallVectorImpl::operator=(::std::move(RHS)); + } + + // note: The enable_if restricts Container to types that have a .begin() and + // .end() that return valid input iterators. + template < + typename Container, + std::enable_if_t< + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .begin())>::iterator_category, + std::input_iterator_tag> && + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .end())>::iterator_category, + std::input_iterator_tag>, + int> = 0> + SmallVector& operator=(const Container& RHS) { + this->assign(RHS.begin(), RHS.end()); + return *this; + } + + SmallVector(SmallVectorImpl&& RHS) noexcept( + std::is_nothrow_move_assignable_v>) + : SmallVectorImpl(N) { + if (!RHS.empty()) + SmallVectorImpl::operator=(::std::move(RHS)); + } + + SmallVector& operator=(SmallVector&& RHS) noexcept( + std::is_nothrow_move_assignable_v>) { + SmallVectorImpl::operator=(::std::move(RHS)); + return *this; + } + + SmallVector& operator=(SmallVectorImpl&& RHS) noexcept( + std::is_nothrow_move_constructible_v>) { + SmallVectorImpl::operator=(::std::move(RHS)); + return *this; + } + + // note: The enable_if restricts Container to types that have a .begin() and + // .end() that return valid input iterators. + template < + typename Container, + std::enable_if_t< + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .begin())>::iterator_category, + std::input_iterator_tag> && + std::is_convertible_v< + typename std::iterator_traits< + decltype(std::declval() + .end())>::iterator_category, + std::input_iterator_tag>, + int> = 0> + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + SmallVector& operator=(Container&& C) { + this->assign(C.begin(), C.end()); + return *this; + } + + SmallVector& operator=(std::initializer_list IL) { + this->assign(IL); + return *this; + } +}; + +template +inline size_t capacity_in_bytes(const SmallVector& X) { + return X.capacity_in_bytes(); +} + +template +std::ostream& operator<<(std::ostream& out, const SmallVector& list) { + int i = 0; + out << "["; + for (auto e : list) { + if (i++ > 0) + out << ", "; + out << e; + } + out << "]"; + return out; +} + +template +using ValueTypeFromRangeType = std::remove_const_t< + std::remove_reference_t()))>>; + +/// Given a range of type R, iterate the entire range and return a +/// SmallVector with elements of the vector. This is useful, for example, +/// when you want to iterate a range and then sort the results. +template +// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) +SmallVector, Size> to_vector(R&& Range) { + return {std::begin(Range), std::end(Range)}; +} +template +SmallVector< + ValueTypeFromRangeType, + CalculateSmallVectorDefaultInlinedElements< + ValueTypeFromRangeType>::value> +// NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) +to_vector(R&& Range) { + return {std::begin(Range), std::end(Range)}; +} + +} // end namespace c10 + +namespace std { + +/// Implement std::swap in terms of SmallVector swap. +template +inline void swap( + c10::SmallVectorImpl& LHS, + c10::SmallVectorImpl& RHS) noexcept { + LHS.swap(RHS); +} + +/// Implement std::swap in terms of SmallVector swap. +template +inline void swap( + c10::SmallVector& LHS, + c10::SmallVector& RHS) noexcept { + LHS.swap(RHS); +} + +} // end namespace std diff --git a/shared/package-files/bc/bc467ad060b98c120b45f0e5b8e3914e7d17e954e85574274c0439541773f880/_native_multi_head_attention_ops.h b/shared/package-files/bc/bc467ad060b98c120b45f0e5b8e3914e7d17e954e85574274c0439541773f880/_native_multi_head_attention_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c308986c2e291e2e8afbe7465900a90a72c7a0ce --- /dev/null +++ b/shared/package-files/bc/bc467ad060b98c120b45f0e5b8e3914e7d17e954e85574274c0439541773f880/_native_multi_head_attention_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _native_multi_head_attention { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const ::std::optional &, bool, bool, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_multi_head_attention"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_native_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None) -> (Tensor, Tensor)"; + static ::std::tuple call(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask, bool need_weights, bool average_attn_weights, ::std::optional mask_type); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask, bool need_weights, bool average_attn_weights, ::std::optional mask_type); +}; + +struct TORCH_API _native_multi_head_attention_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const ::std::optional &, bool, bool, ::std::optional, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_native_multi_head_attention"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_native_multi_head_attention.out(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))"; + static ::std::tuple call(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask, bool need_weights, bool average_attn_weights, ::std::optional mask_type, at::Tensor & out0, at::Tensor & out1); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask, bool need_weights, bool average_attn_weights, ::std::optional mask_type, at::Tensor & out0, at::Tensor & out1); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/bc/bc482d0681e929a43461f4770b39df648cb9fcd650a8adf86cc96f6b4afe8573/parse_bytecode.h b/shared/package-files/bc/bc482d0681e929a43461f4770b39df648cb9fcd650a8adf86cc96f6b4afe8573/parse_bytecode.h new file mode 100644 index 0000000000000000000000000000000000000000..cfc473682054747e81732950706b0aae83f9a812 --- /dev/null +++ b/shared/package-files/bc/bc482d0681e929a43461f4770b39df648cb9fcd650a8adf86cc96f6b4afe8573/parse_bytecode.h @@ -0,0 +1,21 @@ +#pragma once +#include + +namespace torch::jit::mobile { +using c10::IValue; +TORCH_API void parseInstructions( + const std::string& function_name, + c10::ivalue::TupleElements&& ins_list, + c10::ivalue::TupleElements& debug_handles_m_tuple, + mobile::Function* function); +TORCH_API void parseConstants( + const c10::ivalue::TupleElements& consts_list, + mobile::Function* function); +TORCH_API void parseTypes( + const c10::ivalue::TupleElements& types_list, + mobile::Function* function); +TORCH_API void parseRegisterSize(size_t rsize, mobile::Function* function); +TORCH_API void applyUpgrader( + mobile::Function* function, + uint64_t operator_version); +} // namespace torch::jit::mobile diff --git a/shared/package-files/bc/bc4e5e17f0a65364449fe3e6e166d9ea0157b4526d1a275f4d558815e1e45331/_native_multi_head_attention.h b/shared/package-files/bc/bc4e5e17f0a65364449fe3e6e166d9ea0157b4526d1a275f4d558815e1e45331/_native_multi_head_attention.h new file mode 100644 index 0000000000000000000000000000000000000000..6683c7e93a075b83040ac309b14509c6e4b25648 --- /dev/null +++ b/shared/package-files/bc/bc4e5e17f0a65364449fe3e6e166d9ea0157b4526d1a275f4d558815e1e45331/_native_multi_head_attention.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_native_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None) -> (Tensor, Tensor) +inline ::std::tuple _native_multi_head_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, ::std::optional mask_type=::std::nullopt) { + return at::_ops::_native_multi_head_attention::call(query, key, value, embed_dim, num_head, qkv_weight, qkv_bias, proj_weight, proj_bias, mask, need_weights, average_attn_weights, mask_type); +} + +// aten::_native_multi_head_attention.out(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple _native_multi_head_attention_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask={}, bool need_weights=true, bool average_attn_weights=true, ::std::optional mask_type=::std::nullopt) { + return at::_ops::_native_multi_head_attention_out::call(query, key, value, embed_dim, num_head, qkv_weight, qkv_bias, proj_weight, proj_bias, mask, need_weights, average_attn_weights, mask_type, out0, out1); +} +// aten::_native_multi_head_attention.out(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple _native_multi_head_attention_outf(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, int64_t embed_dim, int64_t num_head, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, const ::std::optional & mask, bool need_weights, bool average_attn_weights, ::std::optional mask_type, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::_native_multi_head_attention_out::call(query, key, value, embed_dim, num_head, qkv_weight, qkv_bias, proj_weight, proj_bias, mask, need_weights, average_attn_weights, mask_type, out0, out1); +} + +} diff --git a/shared/package-files/bc/bc4f95e04f1da6a4a393b76af246a00f4efe9e1450286bdc60c85cfdd1389ea8/bpacking_neon.h b/shared/package-files/bc/bc4f95e04f1da6a4a393b76af246a00f4efe9e1450286bdc60c85cfdd1389ea8/bpacking_neon.h new file mode 100644 index 0000000000000000000000000000000000000000..9d02cd568acbc9661f763259e1d4ed134f609e4d --- /dev/null +++ b/shared/package-files/bc/bc4f95e04f1da6a4a393b76af246a00f4efe9e1450286bdc60c85cfdd1389ea8/bpacking_neon.h @@ -0,0 +1,28 @@ +// 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. + +#pragma once + +#include + +namespace arrow { +namespace internal { + +int unpack32_neon(const uint32_t* in, uint32_t* out, int batch_size, int num_bits); + +} // namespace internal +} // namespace arrow diff --git a/shared/package-files/bc/bc54d3b283cb313ceb641b860fe3810d84550a386af5afeedcb9b84776c4651d/_foreach_tanh_ops.h b/shared/package-files/bc/bc54d3b283cb313ceb641b860fe3810d84550a386af5afeedcb9b84776c4651d/_foreach_tanh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d2026296acdee7f3dc0e8890456272877e8abfd6 --- /dev/null +++ b/shared/package-files/bc/bc54d3b283cb313ceb641b860fe3810d84550a386af5afeedcb9b84776c4651d/_foreach_tanh_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _foreach_tanh { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_tanh"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_tanh(Tensor[] self) -> Tensor[]"; + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_tanh_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_tanh_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "_foreach_tanh_(Tensor(a!)[] self) -> ()"; + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_tanh_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::_foreach_tanh"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "_foreach_tanh.out(Tensor[] self, *, Tensor(a!)[] out) -> ()"; + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/bc/bc559dd2b01b373929ef342697b1a4c102f10259d96351c3961e9364de5097b8/runner.py b/shared/package-files/bc/bc559dd2b01b373929ef342697b1a4c102f10259d96351c3961e9364de5097b8/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..cb452c7adefb73078086a5071775b7129962bd27 --- /dev/null +++ b/shared/package-files/bc/bc559dd2b01b373929ef342697b1a4c102f10259d96351c3961e9364de5097b8/runner.py @@ -0,0 +1,263 @@ +"""Running tests""" + +import sys +import time +import warnings + +from . import result +from .case import _SubTest +from .signals import registerResult + +__unittest = True + + +class _WritelnDecorator(object): + """Used to decorate file-like objects with a handy 'writeln' method""" + def __init__(self,stream): + self.stream = stream + + def __getattr__(self, attr): + if attr in ('stream', '__getstate__'): + raise AttributeError(attr) + return getattr(self.stream,attr) + + def writeln(self, arg=None): + if arg: + self.write(arg) + self.write('\n') # text-mode streams translate to \r\n if needed + + +class TextTestResult(result.TestResult): + """A test result class that can print formatted text results to a stream. + + Used by TextTestRunner. + """ + separator1 = '=' * 70 + separator2 = '-' * 70 + + def __init__(self, stream, descriptions, verbosity): + super(TextTestResult, self).__init__(stream, descriptions, verbosity) + self.stream = stream + self.showAll = verbosity > 1 + self.dots = verbosity == 1 + self.descriptions = descriptions + self._newline = True + + def getDescription(self, test): + doc_first_line = test.shortDescription() + if self.descriptions and doc_first_line: + return '\n'.join((str(test), doc_first_line)) + else: + return str(test) + + def startTest(self, test): + super(TextTestResult, self).startTest(test) + if self.showAll: + self.stream.write(self.getDescription(test)) + self.stream.write(" ... ") + self.stream.flush() + self._newline = False + + def _write_status(self, test, status): + is_subtest = isinstance(test, _SubTest) + if is_subtest or self._newline: + if not self._newline: + self.stream.writeln() + if is_subtest: + self.stream.write(" ") + self.stream.write(self.getDescription(test)) + self.stream.write(" ... ") + self.stream.writeln(status) + self.stream.flush() + self._newline = True + + def addSubTest(self, test, subtest, err): + if err is not None: + if self.showAll: + if issubclass(err[0], subtest.failureException): + self._write_status(subtest, "FAIL") + else: + self._write_status(subtest, "ERROR") + elif self.dots: + if issubclass(err[0], subtest.failureException): + self.stream.write('F') + else: + self.stream.write('E') + self.stream.flush() + super(TextTestResult, self).addSubTest(test, subtest, err) + + def addSuccess(self, test): + super(TextTestResult, self).addSuccess(test) + if self.showAll: + self._write_status(test, "ok") + elif self.dots: + self.stream.write('.') + self.stream.flush() + + def addError(self, test, err): + super(TextTestResult, self).addError(test, err) + if self.showAll: + self._write_status(test, "ERROR") + elif self.dots: + self.stream.write('E') + self.stream.flush() + + def addFailure(self, test, err): + super(TextTestResult, self).addFailure(test, err) + if self.showAll: + self._write_status(test, "FAIL") + elif self.dots: + self.stream.write('F') + self.stream.flush() + + def addSkip(self, test, reason): + super(TextTestResult, self).addSkip(test, reason) + if self.showAll: + self._write_status(test, "skipped {0!r}".format(reason)) + elif self.dots: + self.stream.write("s") + self.stream.flush() + + def addExpectedFailure(self, test, err): + super(TextTestResult, self).addExpectedFailure(test, err) + if self.showAll: + self.stream.writeln("expected failure") + self.stream.flush() + elif self.dots: + self.stream.write("x") + self.stream.flush() + + def addUnexpectedSuccess(self, test): + super(TextTestResult, self).addUnexpectedSuccess(test) + if self.showAll: + self.stream.writeln("unexpected success") + self.stream.flush() + elif self.dots: + self.stream.write("u") + self.stream.flush() + + def printErrors(self): + if self.dots or self.showAll: + self.stream.writeln() + self.stream.flush() + self.printErrorList('ERROR', self.errors) + self.printErrorList('FAIL', self.failures) + unexpectedSuccesses = getattr(self, 'unexpectedSuccesses', ()) + if unexpectedSuccesses: + self.stream.writeln(self.separator1) + for test in unexpectedSuccesses: + self.stream.writeln(f"UNEXPECTED SUCCESS: {self.getDescription(test)}") + self.stream.flush() + + def printErrorList(self, flavour, errors): + for test, err in errors: + self.stream.writeln(self.separator1) + self.stream.writeln("%s: %s" % (flavour,self.getDescription(test))) + self.stream.writeln(self.separator2) + self.stream.writeln("%s" % err) + self.stream.flush() + + +class TextTestRunner(object): + """A test runner class that displays results in textual form. + + It prints out the names of tests as they are run, errors as they + occur, and a summary of the results at the end of the test run. + """ + resultclass = TextTestResult + + def __init__(self, stream=None, descriptions=True, verbosity=1, + failfast=False, buffer=False, resultclass=None, warnings=None, + *, tb_locals=False): + """Construct a TextTestRunner. + + Subclasses should accept **kwargs to ensure compatibility as the + interface changes. + """ + if stream is None: + stream = sys.stderr + self.stream = _WritelnDecorator(stream) + self.descriptions = descriptions + self.verbosity = verbosity + self.failfast = failfast + self.buffer = buffer + self.tb_locals = tb_locals + self.warnings = warnings + if resultclass is not None: + self.resultclass = resultclass + + def _makeResult(self): + return self.resultclass(self.stream, self.descriptions, self.verbosity) + + def run(self, test): + "Run the given test case or test suite." + result = self._makeResult() + registerResult(result) + result.failfast = self.failfast + result.buffer = self.buffer + result.tb_locals = self.tb_locals + with warnings.catch_warnings(): + if self.warnings: + # if self.warnings is set, use it to filter all the warnings + warnings.simplefilter(self.warnings) + # if the filter is 'default' or 'always', special-case the + # warnings from the deprecated unittest methods to show them + # no more than once per module, because they can be fairly + # noisy. The -Wd and -Wa flags can be used to bypass this + # only when self.warnings is None. + if self.warnings in ['default', 'always']: + warnings.filterwarnings('module', + category=DeprecationWarning, + message=r'Please use assert\w+ instead.') + startTime = time.perf_counter() + startTestRun = getattr(result, 'startTestRun', None) + if startTestRun is not None: + startTestRun() + try: + test(result) + finally: + stopTestRun = getattr(result, 'stopTestRun', None) + if stopTestRun is not None: + stopTestRun() + stopTime = time.perf_counter() + timeTaken = stopTime - startTime + result.printErrors() + if hasattr(result, 'separator2'): + self.stream.writeln(result.separator2) + run = result.testsRun + self.stream.writeln("Ran %d test%s in %.3fs" % + (run, run != 1 and "s" or "", timeTaken)) + self.stream.writeln() + + expectedFails = unexpectedSuccesses = skipped = 0 + try: + results = map(len, (result.expectedFailures, + result.unexpectedSuccesses, + result.skipped)) + except AttributeError: + pass + else: + expectedFails, unexpectedSuccesses, skipped = results + + infos = [] + if not result.wasSuccessful(): + self.stream.write("FAILED") + failed, errored = len(result.failures), len(result.errors) + if failed: + infos.append("failures=%d" % failed) + if errored: + infos.append("errors=%d" % errored) + else: + self.stream.write("OK") + if skipped: + infos.append("skipped=%d" % skipped) + if expectedFails: + infos.append("expected failures=%d" % expectedFails) + if unexpectedSuccesses: + infos.append("unexpected successes=%d" % unexpectedSuccesses) + if infos: + self.stream.writeln(" (%s)" % (", ".join(infos),)) + else: + self.stream.write("\n") + self.stream.flush() + return result diff --git a/shared/package-files/bc/bc562d11ce6270b09d4ba6bf23b7492803691529a8c047a101d80a5eb6315fad/__init__.py b/shared/package-files/bc/bc562d11ce6270b09d4ba6bf23b7492803691529a8c047a101d80a5eb6315fad/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bad8c49350f56e5e58235570799a8d0968296d --- /dev/null +++ b/shared/package-files/bc/bc562d11ce6270b09d4ba6bf23b7492803691529a8c047a101d80a5eb6315fad/__init__.py @@ -0,0 +1,162 @@ +# mypy: allow-untyped-defs +import torch + +# The quantized modules use `torch.nn` and `torch.ao.nn.quantizable` +# packages. However, the `quantizable` package uses "lazy imports" +# to avoid circular dependency. +# Hence we need to include it here to make sure it is resolved before +# they are used in the modules. +import torch.ao.nn.quantizable +from torch.nn.modules.pooling import MaxPool2d + +from .activation import ( + ELU, + Hardswish, + LeakyReLU, + MultiheadAttention, + PReLU, + ReLU6, + Sigmoid, + Softmax, +) +from .batchnorm import BatchNorm2d, BatchNorm3d +from .conv import ( + Conv1d, + Conv2d, + Conv3d, + ConvTranspose1d, + ConvTranspose2d, + ConvTranspose3d, +) +from .dropout import Dropout +from .embedding_ops import Embedding, EmbeddingBag +from .functional_modules import FloatFunctional, FXFloatFunctional, QFunctional +from .linear import Linear +from .normalization import ( + GroupNorm, + InstanceNorm1d, + InstanceNorm2d, + InstanceNorm3d, + LayerNorm, +) +from .rnn import LSTM + + +__all__ = [ + "BatchNorm2d", + "BatchNorm3d", + "Conv1d", + "Conv2d", + "Conv3d", + "ConvTranspose1d", + "ConvTranspose2d", + "ConvTranspose3d", + "DeQuantize", + "ELU", + "Embedding", + "EmbeddingBag", + "GroupNorm", + "Hardswish", + "InstanceNorm1d", + "InstanceNorm2d", + "InstanceNorm3d", + "LayerNorm", + "LeakyReLU", + "Linear", + "LSTM", + "MultiheadAttention", + "Quantize", + "ReLU6", + "Sigmoid", + "Softmax", + "Dropout", + "PReLU", + # Wrapper modules + "FloatFunctional", + "FXFloatFunctional", + "QFunctional", +] + + +class Quantize(torch.nn.Module): + r"""Quantizes an incoming tensor + + Args: + `scale`: scale of the output Quantized Tensor + `zero_point`: zero_point of output Quantized Tensor + `dtype`: data type of output Quantized Tensor + `factory_kwargs`: Dictionary of kwargs used for configuring initialization + of internal buffers. Currently, `device` and `dtype` are supported. + Example: `factory_kwargs={'device': 'cuda', 'dtype': torch.float64}` + will initialize internal buffers as type `torch.float64` on the current CUDA device. + Note that `dtype` only applies to floating-point buffers. + + Examples:: + >>> t = torch.tensor([[1., -1.], [1., -1.]]) + >>> scale, zero_point, dtype = 1.0, 2, torch.qint8 + >>> qm = Quantize(scale, zero_point, dtype) + >>> # xdoctest: +SKIP + >>> qt = qm(t) + >>> print(qt) + tensor([[ 1., -1.], + [ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2) + """ + + scale: torch.Tensor + zero_point: torch.Tensor + + def __init__(self, scale, zero_point, dtype, factory_kwargs=None): + factory_kwargs = torch.nn.factory_kwargs(factory_kwargs) + super().__init__() + self.register_buffer("scale", torch.tensor([scale], **factory_kwargs)) + self.register_buffer( + "zero_point", + torch.tensor( + [zero_point], + dtype=torch.long, + **{k: v for k, v in factory_kwargs.items() if k != "dtype"}, + ), + ) + self.dtype = dtype + + def forward(self, X): + return torch.quantize_per_tensor( + X, float(self.scale), int(self.zero_point), self.dtype + ) + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + assert hasattr(mod, "activation_post_process") + scale, zero_point = mod.activation_post_process.calculate_qparams() + return Quantize( + scale.float().item(), + zero_point.long().item(), + mod.activation_post_process.dtype, + ) + + def extra_repr(self): + return f"scale={self.scale}, zero_point={self.zero_point}, dtype={self.dtype}" + + +class DeQuantize(torch.nn.Module): + r"""Dequantizes an incoming tensor + + Examples:: + >>> input = torch.tensor([[1., -1.], [1., -1.]]) + >>> scale, zero_point, dtype = 1.0, 2, torch.qint8 + >>> qm = Quantize(scale, zero_point, dtype) + >>> # xdoctest: +SKIP + >>> quantized_input = qm(input) + >>> dqm = DeQuantize() + >>> dequantized = dqm(quantized_input) + >>> print(dequantized) + tensor([[ 1., -1.], + [ 1., -1.]], dtype=torch.float32) + """ + + def forward(self, Xq): + return Xq.dequantize() + + @staticmethod + def from_float(mod, use_precomputed_fake_quant=False): + return DeQuantize() diff --git a/shared/package-files/bc/bc5f36cc500fdde416b9ca066d21dfd7245319274ffa69302de5e9a7bf56926f/__init__.cpython-311.pyc b/shared/package-files/bc/bc5f36cc500fdde416b9ca066d21dfd7245319274ffa69302de5e9a7bf56926f/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7faa388ae075d4d507b8db1351512f6020ab80be Binary files /dev/null and b/shared/package-files/bc/bc5f36cc500fdde416b9ca066d21dfd7245319274ffa69302de5e9a7bf56926f/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc6106a77d53932ccbbeddabd5055eb0eec1ccb1e1cbe3c97aae855cee0ed49e/_unflatten.cpython-311.pyc b/shared/package-files/bc/bc6106a77d53932ccbbeddabd5055eb0eec1ccb1e1cbe3c97aae855cee0ed49e/_unflatten.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b280d1a8a81a0cde521a0bf6774fa0c26d017904 Binary files /dev/null and b/shared/package-files/bc/bc6106a77d53932ccbbeddabd5055eb0eec1ccb1e1cbe3c97aae855cee0ed49e/_unflatten.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc67ee3837fc2ae6b029e8a6ca675b5a2430798716aa8227ad649b983853fc6a/use_rules.cpython-311.pyc b/shared/package-files/bc/bc67ee3837fc2ae6b029e8a6ca675b5a2430798716aa8227ad649b983853fc6a/use_rules.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df7188462917ece731868809f0cd13f93535ff2c Binary files /dev/null and b/shared/package-files/bc/bc67ee3837fc2ae6b029e8a6ca675b5a2430798716aa8227ad649b983853fc6a/use_rules.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc6ae88e7a66506d79b75674576196f2d0c89901d2bd85f152c5a0e78597d474/mem_file.h b/shared/package-files/bc/bc6ae88e7a66506d79b75674576196f2d0c89901d2bd85f152c5a0e78597d474/mem_file.h new file mode 100644 index 0000000000000000000000000000000000000000..099678bf8afe82348af43dd158b26313c4ff402a --- /dev/null +++ b/shared/package-files/bc/bc6ae88e7a66506d79b75674576196f2d0c89901d2bd85f152c5a0e78597d474/mem_file.h @@ -0,0 +1,159 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::unwind { + +struct Section { + char* data = nullptr; + size_t size = 0; + const char* string(size_t offset) { + return lexer(offset).readCString(); + } + CheckedLexer lexer(size_t offset) { + return CheckedLexer(data + offset, data, data + size); + } +}; + +/// Memory maps a file into the address space read-only, and manages the +/// lifetime of the mapping. Here are a few use cases: +/// 1. Used in the loader to read in initial image, and to inspect +// ELF files for dependencies before callling dlopen. +/// +/// 2. Used in unity to load the elf file. +struct MemFile { + explicit MemFile(const char* filename_) + : fd_(open(filename_, O_RDONLY)), name_(filename_) { + UNWIND_CHECK( + fd_ != -1, + "failed to open {}: {}", + filename_, + c10::utils::str_error(errno)); + struct stat s {}; + if (-1 == fstat(fd_, &s)) { + close(fd_); // destructors don't run during exceptions + UNWIND_CHECK( + false, + "failed to stat {}: {}", + filename_, + c10::utils::str_error(errno)); + } + n_bytes_ = s.st_size; + UNWIND_CHECK( + n_bytes_ > sizeof(Elf64_Ehdr), "empty shared library: {}", filename_); + mem_ = (char*)mmap(nullptr, n_bytes_, PROT_READ, MAP_SHARED, fd_, 0); + if (MAP_FAILED == mem_) { + close(fd_); + UNWIND_CHECK( + false, + "failed to mmap {}: {}", + filename_, + c10::utils::str_error(errno)); + } + ehdr_ = (Elf64_Ehdr*)mem_; +#define ELF_CHECK(cond) UNWIND_CHECK(cond, "not an ELF file: {}", filename_) + ELF_CHECK(ehdr_->e_ident[EI_MAG0] == ELFMAG0); + ELF_CHECK(ehdr_->e_ident[EI_MAG1] == ELFMAG1); + ELF_CHECK(ehdr_->e_ident[EI_MAG2] == ELFMAG2); + ELF_CHECK(ehdr_->e_ident[EI_MAG3] == ELFMAG3); + ELF_CHECK(ehdr_->e_ident[EI_CLASS] == ELFCLASS64); + ELF_CHECK(ehdr_->e_ident[EI_VERSION] == EV_CURRENT); + ELF_CHECK(ehdr_->e_version == EV_CURRENT); + ELF_CHECK(ehdr_->e_machine == EM_X86_64); +#undef ELF_CHECK + UNWIND_CHECK( + ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum <= n_bytes_, + "invalid section header table {} {} {}", + ehdr_->e_shoff + sizeof(Elf64_Shdr) * ehdr_->e_shnum, + n_bytes_, + ehdr_->e_shnum); + shdr_ = (Elf64_Shdr*)(mem_ + ehdr_->e_shoff); + UNWIND_CHECK( + ehdr_->e_shstrndx < ehdr_->e_shnum, "invalid strtab section offset"); + auto& strtab_hdr = shdr_[ehdr_->e_shstrndx]; + strtab_ = getSection(strtab_hdr); + } + + MemFile(const MemFile&) = delete; + MemFile(MemFile&&) = delete; + MemFile& operator=(const MemFile&) = delete; + MemFile& operator=(MemFile&&) = delete; + [[nodiscard]] const char* data() const { + return (const char*)mem_; + } + + /// Returns whether or not the file descriptor + /// of the underlying file is valid. + int valid() { + return fcntl(fd_, F_GETFD) != -1 || errno != EBADF; + } + + ~MemFile() { + if (mem_) { + munmap((void*)mem_, n_bytes_); + } + if (fd_ >= 0) { + close(fd_); + } + } + + /// Returns the size of the underlying file defined by the `MemFile` + size_t size() { + return n_bytes_; + } + [[nodiscard]] int fd() const { + return fd_; + } + + Section getSection(const Elf64_Shdr& shdr) { + UNWIND_CHECK(shdr.sh_offset + shdr.sh_size <= n_bytes_, "invalid section"); + return Section{mem_ + shdr.sh_offset, shdr.sh_size}; + } + + Section getSection(const char* name, bool optional) { + for (int i = 0; i < ehdr_->e_shnum; i++) { + if (strcmp(strtab_.string(shdr_[i].sh_name), name) == 0) { + return getSection(shdr_[i]); + } + } + UNWIND_CHECK(optional, "{} has no section {}", name_, name); + return Section{nullptr, 0}; + } + + Section strtab() { + return strtab_; + } + + private: + template + T* load(size_t offset) { + UNWIND_CHECK(offset < n_bytes_, "out of range"); + return (T*)(mem_ + offset); + } + int fd_; + char* mem_{nullptr}; + size_t n_bytes_{0}; + std::string name_; + Elf64_Ehdr* ehdr_; + Elf64_Shdr* shdr_; + Section strtab_ = {nullptr, 0}; +}; + +} // namespace torch::unwind diff --git a/shared/package-files/bc/bc6d98cd94459ad3b6ea5cb75cde38383647655054f065b897176f7635d2d8bc/__init__.py b/shared/package-files/bc/bc6d98cd94459ad3b6ea5cb75cde38383647655054f065b897176f7635d2d8bc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2858f8621d006b2a773251914189f76b0e41c8 --- /dev/null +++ b/shared/package-files/bc/bc6d98cd94459ad3b6ea5cb75cde38383647655054f065b897176f7635d2d8bc/__init__.py @@ -0,0 +1,1089 @@ +import os +import re +import abc +import csv +import sys +import email +import pathlib +import zipfile +import operator +import textwrap +import warnings +import functools +import itertools +import posixpath +import collections + +from . import _adapters, _meta +from ._collections import FreezableDefaultDict, Pair +from ._functools import method_cache, pass_none +from ._itertools import always_iterable, unique_everseen +from ._meta import PackageMetadata, SimplePath + +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import List, Mapping, Optional, Union + + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'distribution', + 'distributions', + 'entry_points', + 'files', + 'metadata', + 'packages_distributions', + 'requires', + 'version', +] + + +class PackageNotFoundError(ModuleNotFoundError): + """The package was not found.""" + + def __str__(self): + return f"No package metadata was found for {self.name}" + + @property + def name(self): + (name,) = self.args + return name + + +class Sectioned: + """ + A simple entry point config parser for performance + + >>> for item in Sectioned.read(Sectioned._sample): + ... print(item) + Pair(name='sec1', value='# comments ignored') + Pair(name='sec1', value='a = 1') + Pair(name='sec1', value='b = 2') + Pair(name='sec2', value='a = 2') + + >>> res = Sectioned.section_pairs(Sectioned._sample) + >>> item = next(res) + >>> item.name + 'sec1' + >>> item.value + Pair(name='a', value='1') + >>> item = next(res) + >>> item.value + Pair(name='b', value='2') + >>> item = next(res) + >>> item.name + 'sec2' + >>> item.value + Pair(name='a', value='2') + >>> list(res) + [] + """ + + _sample = textwrap.dedent( + """ + [sec1] + # comments ignored + a = 1 + b = 2 + + [sec2] + a = 2 + """ + ).lstrip() + + @classmethod + def section_pairs(cls, text): + return ( + section._replace(value=Pair.parse(section.value)) + for section in cls.read(text, filter_=cls.valid) + if section.name is not None + ) + + @staticmethod + def read(text, filter_=None): + lines = filter(filter_, map(str.strip, text.splitlines())) + name = None + for value in lines: + section_match = value.startswith('[') and value.endswith(']') + if section_match: + name = value.strip('[]') + continue + yield Pair(name, value) + + @staticmethod + def valid(line): + return line and not line.startswith('#') + + +class DeprecatedTuple: + """ + Provide subscript item access for backward compatibility. + + >>> recwarn = getfixture('recwarn') + >>> ep = EntryPoint(name='name', value='value', group='group') + >>> ep[:] + ('name', 'value', 'group') + >>> ep[0] + 'name' + >>> len(recwarn) + 1 + """ + + _warn = functools.partial( + warnings.warn, + "EntryPoint tuple interface is deprecated. Access members by name.", + DeprecationWarning, + stacklevel=2, + ) + + def __getitem__(self, item): + self._warn() + return self._key()[item] + + +class EntryPoint(DeprecatedTuple): + """An entry point as defined by Python packaging conventions. + + See `the packaging docs on entry points + `_ + for more information. + + >>> ep = EntryPoint( + ... name=None, group=None, value='package.module:attr [extra1, extra2]') + >>> ep.module + 'package.module' + >>> ep.attr + 'attr' + >>> ep.extras + ['extra1', 'extra2'] + """ + + pattern = re.compile( + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+)\s*)?' + r'((?P\[.*\])\s*)?$' + ) + """ + A regular expression describing the syntax for an entry point, + which might look like: + + - module + - package.module + - package.module:attribute + - package.module:object.attribute + - package.module:attr [extra1, extra2] + + Other combinations are possible as well. + + The expression is lenient about whitespace around the ':', + following the attr, and following any extras. + """ + + name: str + value: str + group: str + + dist: Optional['Distribution'] = None + + def __init__(self, name, value, group): + vars(self).update(name=name, value=value, group=group) + + def load(self): + """Load the entry point from its definition. If only a module + is indicated by the value, return that module. Otherwise, + return the named object. + """ + match = self.pattern.match(self.value) + module = import_module(match.group('module')) + attrs = filter(None, (match.group('attr') or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self): + match = self.pattern.match(self.value) + return match.group('module') + + @property + def attr(self): + match = self.pattern.match(self.value) + return match.group('attr') + + @property + def extras(self): + match = self.pattern.match(self.value) + return re.findall(r'\w+', match.group('extras') or '') + + def _for(self, dist): + vars(self).update(dist=dist) + return self + + def __iter__(self): + """ + Supply iter so one may construct dicts of EntryPoints by name. + """ + msg = ( + "Construction of dict of EntryPoints is deprecated in " + "favor of EntryPoints." + ) + warnings.warn(msg, DeprecationWarning) + return iter((self.name, self)) + + def matches(self, **params): + """ + EntryPoint matches the given parameters. + + >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') + >>> ep.matches(group='foo') + True + >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]') + True + >>> ep.matches(group='foo', name='other') + False + >>> ep.matches() + True + >>> ep.matches(extras=['extra1', 'extra2']) + True + >>> ep.matches(module='bing') + True + >>> ep.matches(attr='bong') + True + """ + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + def _key(self): + return self.name, self.value, self.group + + def __lt__(self, other): + return self._key() < other._key() + + def __eq__(self, other): + return self._key() == other._key() + + def __setattr__(self, name, value): + raise AttributeError("EntryPoint objects are immutable.") + + def __repr__(self): + return ( + f'EntryPoint(name={self.name!r}, value={self.value!r}, ' + f'group={self.group!r})' + ) + + def __hash__(self): + return hash(self._key()) + + +class DeprecatedList(list): + """ + Allow an otherwise immutable object to implement mutability + for compatibility. + + >>> recwarn = getfixture('recwarn') + >>> dl = DeprecatedList(range(3)) + >>> dl[0] = 1 + >>> dl.append(3) + >>> del dl[3] + >>> dl.reverse() + >>> dl.sort() + >>> dl.extend([4]) + >>> dl.pop(-1) + 4 + >>> dl.remove(1) + >>> dl += [5] + >>> dl + [6] + [1, 2, 5, 6] + >>> dl + (6,) + [1, 2, 5, 6] + >>> dl.insert(0, 0) + >>> dl + [0, 1, 2, 5] + >>> dl == [0, 1, 2, 5] + True + >>> dl == (0, 1, 2, 5) + True + >>> len(recwarn) + 1 + """ + + __slots__ = () + + _warn = functools.partial( + warnings.warn, + "EntryPoints list interface is deprecated. Cast to list if needed.", + DeprecationWarning, + stacklevel=2, + ) + + def _wrap_deprecated_method(method_name: str): # type: ignore + def wrapped(self, *args, **kwargs): + self._warn() + return getattr(super(), method_name)(*args, **kwargs) + + return method_name, wrapped + + locals().update( + map( + _wrap_deprecated_method, + '__setitem__ __delitem__ append reverse extend pop remove ' + '__iadd__ insert sort'.split(), + ) + ) + + def __add__(self, other): + if not isinstance(other, tuple): + self._warn() + other = tuple(other) + return self.__class__(tuple(self) + other) + + def __eq__(self, other): + if not isinstance(other, tuple): + self._warn() + other = tuple(other) + + return tuple(self).__eq__(other) + + +class EntryPoints(DeprecatedList): + """ + An immutable collection of selectable EntryPoint objects. + """ + + __slots__ = () + + def __getitem__(self, name): # -> EntryPoint: + """ + Get the EntryPoint in self matching name. + """ + if isinstance(name, int): + warnings.warn( + "Accessing entry points by index is deprecated. " + "Cast to tuple if needed.", + DeprecationWarning, + stacklevel=2, + ) + return super().__getitem__(name) + try: + return next(iter(self.select(name=name))) + except StopIteration: + raise KeyError(name) + + def select(self, **params): + """ + Select entry points from self that match the + given parameters (typically group and/or name). + """ + return EntryPoints(ep for ep in self if ep.matches(**params)) + + @property + def names(self): + """ + Return the set of all names of all entry points. + """ + return {ep.name for ep in self} + + @property + def groups(self): + """ + Return the set of all groups of all entry points. + + For coverage while SelectableGroups is present. + >>> EntryPoints().groups + set() + """ + return {ep.group for ep in self} + + @classmethod + def _from_text_for(cls, text, dist): + return cls(ep._for(dist) for ep in cls._from_text(text)) + + @staticmethod + def _from_text(text): + return ( + EntryPoint(name=item.value.name, value=item.value.value, group=item.name) + for item in Sectioned.section_pairs(text or '') + ) + + +class Deprecated: + """ + Compatibility add-in for mapping to indicate that + mapping behavior is deprecated. + + >>> recwarn = getfixture('recwarn') + >>> class DeprecatedDict(Deprecated, dict): pass + >>> dd = DeprecatedDict(foo='bar') + >>> dd.get('baz', None) + >>> dd['foo'] + 'bar' + >>> list(dd) + ['foo'] + >>> list(dd.keys()) + ['foo'] + >>> 'foo' in dd + True + >>> list(dd.values()) + ['bar'] + >>> len(recwarn) + 1 + """ + + _warn = functools.partial( + warnings.warn, + "SelectableGroups dict interface is deprecated. Use select.", + DeprecationWarning, + stacklevel=2, + ) + + def __getitem__(self, name): + self._warn() + return super().__getitem__(name) + + def get(self, name, default=None): + self._warn() + return super().get(name, default) + + def __iter__(self): + self._warn() + return super().__iter__() + + def __contains__(self, *args): + self._warn() + return super().__contains__(*args) + + def keys(self): + self._warn() + return super().keys() + + def values(self): + self._warn() + return super().values() + + +class SelectableGroups(Deprecated, dict): + """ + A backward- and forward-compatible result from + entry_points that fully implements the dict interface. + """ + + @classmethod + def load(cls, eps): + by_group = operator.attrgetter('group') + ordered = sorted(eps, key=by_group) + grouped = itertools.groupby(ordered, by_group) + return cls((group, EntryPoints(eps)) for group, eps in grouped) + + @property + def _all(self): + """ + Reconstruct a list of all entrypoints from the groups. + """ + groups = super(Deprecated, self).values() + return EntryPoints(itertools.chain.from_iterable(groups)) + + @property + def groups(self): + return self._all.groups + + @property + def names(self): + """ + for coverage: + >>> SelectableGroups().names + set() + """ + return self._all.names + + def select(self, **params): + if not params: + return self + return self._all.select(**params) + + +class PackagePath(pathlib.PurePosixPath): + """A reference to a path in a package""" + + def read_text(self, encoding='utf-8'): + with self.locate().open(encoding=encoding) as stream: + return stream.read() + + def read_binary(self): + with self.locate().open('rb') as stream: + return stream.read() + + def locate(self): + """Return a path-like object for this path""" + return self.dist.locate_file(self) + + +class FileHash: + def __init__(self, spec): + self.mode, _, self.value = spec.partition('=') + + def __repr__(self): + return f'' + + +class Distribution: + """A Python distribution package.""" + + @abc.abstractmethod + def read_text(self, filename): + """Attempt to load metadata file given by the name. + + :param filename: The name of the file in the distribution info. + :return: The text if found, otherwise None. + """ + + @abc.abstractmethod + def locate_file(self, path): + """ + Given a path to a file in this distribution, return a path + to it. + """ + + @classmethod + def from_name(cls, name: str): + """Return the Distribution for the given package name. + + :param name: The name of the distribution package to search for. + :return: The Distribution instance (or subclass thereof) for the named + package, if found. + :raises PackageNotFoundError: When the named package's distribution + metadata cannot be found. + :raises ValueError: When an invalid value is supplied for name. + """ + if not name: + raise ValueError("A distribution name is required.") + try: + return next(cls.discover(name=name)) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover(cls, **kwargs): + """Return an iterable of Distribution objects for all packages. + + Pass a ``context`` or pass keyword arguments for constructing + a context. + + :context: A ``DistributionFinder.Context`` object. + :return: Iterable of Distribution objects for all packages. + """ + context = kwargs.pop('context', None) + if context and kwargs: + raise ValueError("cannot accept context and kwargs") + context = context or DistributionFinder.Context(**kwargs) + return itertools.chain.from_iterable( + resolver(context) for resolver in cls._discover_resolvers() + ) + + @staticmethod + def at(path): + """Return a Distribution for the indicated metadata path + + :param path: a string or path-like object + :return: a concrete Distribution instance for the path + """ + return PathDistribution(pathlib.Path(path)) + + @staticmethod + def _discover_resolvers(): + """Search the meta_path for resolvers.""" + declared = ( + getattr(finder, 'find_distributions', None) for finder in sys.meta_path + ) + return filter(None, declared) + + @property + def metadata(self) -> _meta.PackageMetadata: + """Return the parsed metadata for this Distribution. + + The returned object will have keys that name the various bits of + metadata. See PEP 566 for details. + """ + text = ( + self.read_text('METADATA') + or self.read_text('PKG-INFO') + # This last clause is here to support old egg-info files. Its + # effect is to just end up using the PathDistribution's self._path + # (which points to the egg-info file) attribute unchanged. + or self.read_text('') + ) + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self): + """Return the 'Name' metadata for the distribution package.""" + return self.metadata['Name'] + + @property + def _normalized_name(self): + """Return a normalized version of the name.""" + return Prepared.normalize(self.name) + + @property + def version(self): + """Return the 'Version' metadata for the distribution package.""" + return self.metadata['Version'] + + @property + def entry_points(self): + return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) + + @property + def files(self): + """Files in this distribution. + + :return: List of PackagePath for this distribution or None + + Result is `None` if the metadata file that enumerates files + (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is + missing. + Result may be empty if the metadata exists but is empty. + """ + + def make_file(name, hash=None, size_str=None): + result = PackagePath(name) + result.hash = FileHash(hash) if hash else None + result.size = int(size_str) if size_str else None + result.dist = self + return result + + @pass_none + def make_files(lines): + return list(starmap(make_file, csv.reader(lines))) + + return make_files(self._read_files_distinfo() or self._read_files_egginfo()) + + def _read_files_distinfo(self): + """ + Read the lines of RECORD + """ + text = self.read_text('RECORD') + return text and text.splitlines() + + def _read_files_egginfo(self): + """ + SOURCES.txt might contain literal commas, so wrap each line + in quotes. + """ + text = self.read_text('SOURCES.txt') + return text and map('"{}"'.format, text.splitlines()) + + @property + def requires(self): + """Generated requirements specified for this Distribution""" + reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() + return reqs and list(reqs) + + def _read_dist_info_reqs(self): + return self.metadata.get_all('Requires-Dist') + + def _read_egg_info_reqs(self): + source = self.read_text('requires.txt') + return pass_none(self._deps_from_requires_text)(source) + + @classmethod + def _deps_from_requires_text(cls, source): + return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) + + @staticmethod + def _convert_egg_info_reqs_to_simple_reqs(sections): + """ + Historically, setuptools would solicit and store 'extra' + requirements, including those with environment markers, + in separate sections. More modern tools expect each + dependency to be defined separately, with any relevant + extras and environment markers attached directly to that + requirement. This method converts the former to the + latter. See _test_deps_from_requires_text for an example. + """ + + def make_condition(name): + return name and f'extra == "{name}"' + + def quoted_marker(section): + section = section or '' + extra, sep, markers = section.partition(':') + if extra and markers: + markers = f'({markers})' + conditions = list(filter(None, [markers, make_condition(extra)])) + return '; ' + ' and '.join(conditions) if conditions else '' + + def url_req_space(req): + """ + PEP 508 requires a space between the url_spec and the quoted_marker. + Ref python/importlib_metadata#357. + """ + # '@' is uniquely indicative of a url_req. + return ' ' * ('@' in req) + + for section in sections: + space = url_req_space(section.value) + yield section.value + space + quoted_marker(section.name) + + +class DistributionFinder(MetaPathFinder): + """ + A MetaPathFinder capable of discovering installed distributions. + """ + + class Context: + """ + Keyword arguments presented by the caller to + ``distributions()`` or ``Distribution.discover()`` + to narrow the scope of a search for distributions + in all DistributionFinders. + + Each DistributionFinder may expect any parameters + and should attempt to honor the canonical + parameters defined below when appropriate. + """ + + name = None + """ + Specific name for which a distribution finder should match. + A name of ``None`` matches all distributions. + """ + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + @property + def path(self): + """ + The sequence of directory path that a distribution finder + should search. + + Typically refers to Python installed package paths such as + "site-packages" directories and defaults to ``sys.path``. + """ + return vars(self).get('path', sys.path) + + @abc.abstractmethod + def find_distributions(self, context=Context()): + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching the ``context``, + a DistributionFinder.Context instance. + """ + + +class FastPath: + """ + Micro-optimized class for searching a path for + children. + + >>> FastPath('').children() + ['...'] + """ + + @functools.lru_cache() # type: ignore + def __new__(cls, root): + return super().__new__(cls) + + def __init__(self, root): + self.root = root + + def joinpath(self, child): + return pathlib.Path(self.root, child) + + def children(self): + with suppress(Exception): + return os.listdir(self.root or '.') + with suppress(Exception): + return self.zip_children() + return [] + + def zip_children(self): + zip_path = zipfile.Path(self.root) + names = zip_path.root.namelist() + self.joinpath = zip_path.joinpath + + return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) + + def search(self, name): + return self.lookup(self.mtime).search(name) + + @property + def mtime(self): + with suppress(OSError): + return os.stat(self.root).st_mtime + self.lookup.cache_clear() + + @method_cache + def lookup(self, mtime): + return Lookup(self) + + +class Lookup: + def __init__(self, path: FastPath): + base = os.path.basename(path.root).lower() + base_is_egg = base.endswith(".egg") + self.infos = FreezableDefaultDict(list) + self.eggs = FreezableDefaultDict(list) + + for child in path.children(): + low = child.lower() + if low.endswith((".dist-info", ".egg-info")): + # rpartition is faster than splitext and suitable for this purpose. + name = low.rpartition(".")[0].partition("-")[0] + normalized = Prepared.normalize(name) + self.infos[normalized].append(path.joinpath(child)) + elif base_is_egg and low == "egg-info": + name = base.rpartition(".")[0].partition("-")[0] + legacy_normalized = Prepared.legacy_normalize(name) + self.eggs[legacy_normalized].append(path.joinpath(child)) + + self.infos.freeze() + self.eggs.freeze() + + def search(self, prepared): + infos = ( + self.infos[prepared.normalized] + if prepared + else itertools.chain.from_iterable(self.infos.values()) + ) + eggs = ( + self.eggs[prepared.legacy_normalized] + if prepared + else itertools.chain.from_iterable(self.eggs.values()) + ) + return itertools.chain(infos, eggs) + + +class Prepared: + """ + A prepared search for metadata on a possibly-named package. + """ + + normalized = None + legacy_normalized = None + + def __init__(self, name): + self.name = name + if name is None: + return + self.normalized = self.normalize(name) + self.legacy_normalized = self.legacy_normalize(name) + + @staticmethod + def normalize(name): + """ + PEP 503 normalization plus dashes as underscores. + """ + return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') + + @staticmethod + def legacy_normalize(name): + """ + Normalize the package name as found in the convention in + older packaging tools versions and specs. + """ + return name.lower().replace('-', '_') + + def __bool__(self): + return bool(self.name) + + +class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context=DistributionFinder.Context()): + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + found = cls._search_paths(context.name, context.path) + return map(PathDistribution, found) + + @classmethod + def _search_paths(cls, name, paths): + """Find metadata directories in paths heuristically.""" + prepared = Prepared(name) + return itertools.chain.from_iterable( + path.search(prepared) for path in map(FastPath, paths) + ) + + @classmethod + def invalidate_caches(cls): + FastPath.__new__.cache_clear() + + +class PathDistribution(Distribution): + def __init__(self, path: SimplePath): + """Construct a distribution. + + :param path: SimplePath indicating the metadata directory. + """ + self._path = path + + def read_text(self, filename): + with suppress( + FileNotFoundError, + IsADirectoryError, + KeyError, + NotADirectoryError, + PermissionError, + ): + return self._path.joinpath(filename).read_text(encoding='utf-8') + + read_text.__doc__ = Distribution.read_text.__doc__ + + def locate_file(self, path): + return self._path.parent / path + + @property + def _normalized_name(self): + """ + Performance optimization: where possible, resolve the + normalized name from the file system path. + """ + stem = os.path.basename(str(self._path)) + return ( + pass_none(Prepared.normalize)(self._name_from_stem(stem)) + or super()._normalized_name + ) + + @staticmethod + def _name_from_stem(stem): + """ + >>> PathDistribution._name_from_stem('foo-3.0.egg-info') + 'foo' + >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info') + 'CherryPy' + >>> PathDistribution._name_from_stem('face.egg-info') + 'face' + >>> PathDistribution._name_from_stem('foo.bar') + """ + filename, ext = os.path.splitext(stem) + if ext not in ('.dist-info', '.egg-info'): + return + name, sep, rest = filename.partition('-') + return name + + +def distribution(distribution_name): + """Get the ``Distribution`` instance for the named package. + + :param distribution_name: The name of the distribution package as a string. + :return: A ``Distribution`` instance (or subclass thereof). + """ + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs): + """Get all ``Distribution`` instances in the current environment. + + :return: An iterable of ``Distribution`` instances. + """ + return Distribution.discover(**kwargs) + + +def metadata(distribution_name) -> _meta.PackageMetadata: + """Get the metadata for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: A PackageMetadata containing the parsed metadata. + """ + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name): + """Get the version string for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: The version string for the package as defined in the package's + "Version" metadata key. + """ + return distribution(distribution_name).version + + +_unique = functools.partial( + unique_everseen, + key=operator.attrgetter('_normalized_name'), +) +""" +Wrapper for ``distributions`` to return unique distributions by name. +""" + + +def entry_points(**params) -> Union[EntryPoints, SelectableGroups]: + """Return EntryPoint objects for all installed packages. + + Pass selection parameters (group or name) to filter the + result to entry points matching those properties (see + EntryPoints.select()). + + For compatibility, returns ``SelectableGroups`` object unless + selection parameters are supplied. In the future, this function + will return ``EntryPoints`` instead of ``SelectableGroups`` + even when no selection parameters are supplied. + + For maximum future compatibility, pass selection parameters + or invoke ``.select`` with parameters on the result. + + :return: EntryPoints or SelectableGroups for all installed packages. + """ + eps = itertools.chain.from_iterable( + dist.entry_points for dist in _unique(distributions()) + ) + return SelectableGroups.load(eps).select(**params) + + +def files(distribution_name): + """Return a list of files for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: List of files composing the distribution. + """ + return distribution(distribution_name).files + + +def requires(distribution_name): + """ + Return a list of requirements for the named package. + + :return: An iterator of requirements, suitable for + packaging.requirement.Requirement. + """ + return distribution(distribution_name).requires + + +def packages_distributions() -> Mapping[str, List[str]]: + """ + Return a mapping of top-level packages to their + distributions. + + >>> import collections.abc + >>> pkgs = packages_distributions() + >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) + True + """ + pkg_to_dist = collections.defaultdict(list) + for dist in distributions(): + for pkg in _top_level_declared(dist) or _top_level_inferred(dist): + pkg_to_dist[pkg].append(dist.metadata['Name']) + return dict(pkg_to_dist) + + +def _top_level_declared(dist): + return (dist.read_text('top_level.txt') or '').split() + + +def _top_level_inferred(dist): + return { + f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name + for f in always_iterable(dist.files) + if f.suffix == ".py" + } diff --git a/shared/package-files/bc/bc7361065702534d28dc043ba87d51c908eca72de2b54a899dbc5e36857ee780/log_softmax_native.h b/shared/package-files/bc/bc7361065702534d28dc043ba87d51c908eca72de2b54a899dbc5e36857ee780/log_softmax_native.h new file mode 100644 index 0000000000000000000000000000000000000000..d2bde848e0961f97436f9ee00c98df7fe261396f --- /dev/null +++ b/shared/package-files/bc/bc7361065702534d28dc043ba87d51c908eca72de2b54a899dbc5e36857ee780/log_softmax_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor log_softmax(const at::Tensor & self, int64_t dim, ::std::optional dtype=::std::nullopt); +TORCH_API at::Tensor & log_softmax_out(const at::Tensor & self, int64_t dim, ::std::optional dtype, at::Tensor & out); +TORCH_API at::Tensor log_softmax(const at::Tensor & self, at::Dimname dim, ::std::optional dtype=::std::nullopt); +} // namespace native +} // namespace at diff --git a/shared/package-files/bc/bc7767f4fd66e452a5fa74bc8772064ed27c55be5903b515079067404c7da64b/RECORD b/shared/package-files/bc/bc7767f4fd66e452a5fa74bc8772064ed27c55be5903b515079067404c7da64b/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8d989531a3e7e4206a5c646aa863132908a1c29d --- /dev/null +++ b/shared/package-files/bc/bc7767f4fd66e452a5fa74bc8772064ed27c55be5903b515079067404c7da64b/RECORD @@ -0,0 +1,406 @@ +../../../bin/proton,sha256=5e-7JmdH1RxHhHEQZreiaYNDqy2uHL-006r2yEYSaYM,230 +../../../bin/proton-viewer,sha256=7ZOtPJyR4aZGH86Q70wjbWLt8R_CSWQ7L-FGGStIIWU,230 +triton-3.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +triton-3.3.1.dist-info/METADATA,sha256=NNHcv0lI2GtpHg3IA6Gqnp2ISvjqEoE5Q3GAmwqOI00,1533 +triton-3.3.1.dist-info/RECORD,, +triton-3.3.1.dist-info/WHEEL,sha256=3daP3VhxT_uXQ4g9qxjrsHJLh9a9x1Dc522TvcSo1E0,152 +triton-3.3.1.dist-info/entry_points.txt,sha256=SAiHYj5xxm1U5d8569PbMXmtWkKGNtiyy7LeTlUHalM,99 +triton-3.3.1.dist-info/top_level.txt,sha256=cb7PAiQF749BL4w71j16XEG846XyQGTOq__k_M-qtP8,270 +triton/_C/libproton.so,sha256=YQ2aSG5tf2FqQSY0it_ZEMnoFBqnOhI9AqZxtTETdtI,11667976 +triton/_C/libtriton.so,sha256=4V1kTuLD_av5TrX7DgmkDPz-woK_7k_f4WBKRAIFKlQ,323494904 +triton/__init__.py,sha256=3SQQyt-oywQBYQfubass3Nuj08o8RqPqmli6IPYthww,1392 +triton/__pycache__/__init__.cpython-311.pyc,, +triton/__pycache__/_internal_testing.cpython-311.pyc,, +triton/__pycache__/_utils.cpython-311.pyc,, +triton/__pycache__/errors.cpython-311.pyc,, +triton/__pycache__/testing.cpython-311.pyc,, +triton/_internal_testing.py,sha256=OBY28huiEWItqGgiukgZzHLLaSbS8yj9kdhn_u562Yg,5904 +triton/_utils.py,sha256=5RiCLwW14w0Q3mdZ-9yz-VO5KiSexNj9xeDt4gaNsvE,1014 +triton/backends/__init__.py,sha256=opAo_vgEMt3tLO_bYFrYGksnIu0qohbmyuu_s3-rNAs,1595 +triton/backends/__pycache__/__init__.cpython-311.pyc,, +triton/backends/__pycache__/compiler.cpython-311.pyc,, +triton/backends/__pycache__/driver.cpython-311.pyc,, +triton/backends/amd/__pycache__/compiler.cpython-311.pyc,, +triton/backends/amd/__pycache__/driver.cpython-311.pyc,, +triton/backends/amd/compiler.py,sha256=27jurEV7tH5J6BHtOXrdPJyCMYIPHo5G4Op_O66gv4E,19135 +triton/backends/amd/driver.c,sha256=obiiiPndny5NyhUcJ8iyrVHrXU1ruLpLGd_LgaKQEbU,8459 +triton/backends/amd/driver.py,sha256=tYhxrqlI76ibEl4ZnwIcvsYoXWlNSew3sC08Rk9Fy5o,20376 +triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h,sha256=_2myGIdBTE0plFbGKOSx8HUqGZd0UBHo-YvKe2xkpbU,11708 +triton/backends/amd/include/hip/amd_detail/amd_device_functions.h,sha256=1TwUYh4RJhoiz850vLNicO1fFxFHR-vC-16ttDGDGGw,31367 +triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h,sha256=KfiNN5FjV6mqSAOam6VJDu9tI7l8uaRUrQ5EMiP5Ymw,50830 +triton/backends/amd/include/hip/amd_detail/amd_hip_bf16.h,sha256=AWsz68vSfi9PnCsIIMOQkCStRLbEat7f6om9_J2Ahj4,61352 +triton/backends/amd/include/hip/amd_detail/amd_hip_bfloat16.h,sha256=cFJlQEELGau_9geACeuiiFHyuAWCD6-VuSqcTnqajX0,9484 +triton/backends/amd/include/hip/amd_detail/amd_hip_common.h,sha256=dzkuIzuklqTRaNJjKLqfFEm6Fh4tK_FkTjYHFsZkmCI,1370 +triton/backends/amd/include/hip/amd_detail/amd_hip_complex.h,sha256=SEygl8X_MCXDVXxNIBm5Ds0eWwa-ojVXUUW48SIgsX8,5855 +triton/backends/amd/include/hip/amd_detail/amd_hip_cooperative_groups.h,sha256=t8rqzpZS--LGLI1D-pNBNCp7TCKGS0H136ps6m6VOlI,31861 +triton/backends/amd/include/hip/amd_detail/amd_hip_fp16.h,sha256=86Nw97iaiC4QV5xBv8d3Bwc4FioMh5DQuCHj3sh_Yrw,57854 +triton/backends/amd/include/hip/amd_detail/amd_hip_fp8.h,sha256=wc1l471D-BBroLMoV1uEsPXTp-zQjSpq-jF8bqeNZX8,53765 +triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h,sha256=djlpeoEOqtX0gVVRgqqakQZkwNzLudnK_ixbShizU7M,3861 +triton/backends/amd/include/hip/amd_detail/amd_hip_math_constants.h,sha256=u1fIaf-AiWF70ZA1zxVkUIbRqoJLu5lrfYbgt_usySk,5890 +triton/backends/amd/include/hip/amd_detail/amd_hip_runtime.h,sha256=ZvDsQ0AiZnJ178NuAsA7AuHrySXbN3aFs5Z9m2tsIDg,13954 +triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h,sha256=fc4mtHBkWmiSRh8m-dxIxvu9zsweLTwEgohkntYcgJw,9997 +triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h,sha256=w9nJ1S32GRl_ejDiGacteM6Zf84iovIifAzWX8Bze0Q,24202 +triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h,sha256=qPdmRJnzlgtjVshkafoHxdHoMLkoYS9U-ZD-TjLznr0,57088 +triton/backends/amd/include/hip/amd_detail/amd_math_functions.h,sha256=46wiaEMStCczEsHtccgHlATfw_0O5j6Z8rlFkC7bmUA,3171 +triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h,sha256=rsQuylNqmNhLb7PZjBz7WbruD_6YIXtOptY2BNJDxVU,11062 +triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h,sha256=-uJy_hBwSxRA9gzGp4UEZ3co8D_UHVNoMr_Rvx19qik,20042 +triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h,sha256=2B25tjpJ_KJGijRBaEy_a2_4HLt_TXQ6eJ57zRNoPOw,11706 +triton/backends/amd/include/hip/amd_detail/concepts.hpp,sha256=7EOkpr2w2-jclUQ115yxtFCkBWJ7btUzhBOe-mR0N0M,1252 +triton/backends/amd/include/hip/amd_detail/device_library_decls.h,sha256=4clSpgf898UVjfZFVnDkcYi75A27crPsuFtLcs1s4KU,7457 +triton/backends/amd/include/hip/amd_detail/functional_grid_launch.hpp,sha256=u7hRB9kQXX575a5C7cV3gKow55DSBUCwO0dTjIswlag,8129 +triton/backends/amd/include/hip/amd_detail/grid_launch.h,sha256=tNS7CQw9gy-z930CElH3n6c5iMvpsQ_WFZK024mNzEo,1830 +triton/backends/amd/include/hip/amd_detail/grid_launch.hpp,sha256=EuAlM3olyrArebqwW5eSxo4gfjvWCGOAGAuLLmFttgw,1370 +triton/backends/amd/include/hip/amd_detail/grid_launch_GGL.hpp,sha256=KpQAuyy1Dyt45WcPaR_x-Ex-onPGEHA01DBbla7TT-k,1219 +triton/backends/amd/include/hip/amd_detail/helpers.hpp,sha256=hi2pW1mXQnbIwvmwWt_nG6A38sqLOd-QP5S9sETTs60,5707 +triton/backends/amd/include/hip/amd_detail/hip_api_trace.hpp,sha256=UMsCaqurHFSRNiHpwjaA8DExAldhh4y0UP_KOxLa25Y,101025 +triton/backends/amd/include/hip/amd_detail/hip_assert.h,sha256=fNsG23KISuY-k5JFoX-5hZ7qGQScisXuHcdEwYlXOqw,3978 +triton/backends/amd/include/hip/amd_detail/hip_cooperative_groups_helper.h,sha256=tQ_XIvGKhvrj1h7gY-IVLmKvIPhsQa0YsBflxdhUHP8,7957 +triton/backends/amd/include/hip/amd_detail/hip_fp16_gcc.h,sha256=BtFsKmTptN4TOHocEicfNbBl2JCdZWKm_bd5mc5OzYY,6660 +triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h,sha256=63tKWMPdW56qWlH_HbCaF_isVXufm514ol_SxL4YjTQ,5134 +triton/backends/amd/include/hip/amd_detail/hip_ldg.h,sha256=KAEZb9H4z4DDrkaloMOeWzahiDfI2V6c68vWT3jb5fU,3652 +triton/backends/amd/include/hip/amd_detail/hip_prof_str.h,sha256=Xb0M9ztYHRqRLjKFBumbAR2rjbUnoZulweCZKTU8ejU,648748 +triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h,sha256=eZUI5cscYKb9xC9IqnaY53Jgy1dQjkERwQaw034Bt5g,2758 +triton/backends/amd/include/hip/amd_detail/host_defines.h,sha256=ZyCvaPsp4vcFiEEIt2BhapfYVvWoVI_Q2P9rZHlFmCY,7197 +triton/backends/amd/include/hip/amd_detail/hsa_helpers.hpp,sha256=Os-sJQOFI_0Abh8Ql05s0Rtfruk4NsSMfg7BtugxMgg,3232 +triton/backends/amd/include/hip/amd_detail/macro_based_grid_launch.hpp,sha256=6ocsArNa9_R6D6XCuNy8Zq23KG-j2uYsjqNCtnMrJws,67925 +triton/backends/amd/include/hip/amd_detail/math_fwd.h,sha256=nup5YhceJnngoLJCESI8qX08dNpbZci0i78WKu-wfdI,17000 +triton/backends/amd/include/hip/amd_detail/ockl_image.h,sha256=LzRPGMb515_iIAIIcbb2uQB-bTvT4xOjY51VdARD7lc,10538 +triton/backends/amd/include/hip/amd_detail/program_state.hpp,sha256=8QE9OmB8OKTy7rBr3EYEizJI2s-_1tgXpgU7zCA2Ky0,3154 +triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h,sha256=Ex1lF2gBWJxtC3yP9pXRSFywMp3gbEmyl0Sw8iL91yM,17787 +triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h,sha256=KkW5o5gMpoVMTRwzfXHA7-kZ9ynI8OaIw6jJ1EB1s98,18447 +triton/backends/amd/include/hip/channel_descriptor.h,sha256=gTYe7SzIg-m3ThOQY2vr5Rh6-uWvUP_d37v8F4T2Q14,1773 +triton/backends/amd/include/hip/device_functions.h,sha256=vkybrdk6wyZP-T1I5PRjtfcMqGYXDeBpB5jhYj358GU,1589 +triton/backends/amd/include/hip/driver_types.h,sha256=m1HI80HC80qkTeco2Jd07woL_jTy48lz9JiDCV_8zsg,18985 +triton/backends/amd/include/hip/hip_bf16.h,sha256=lLw6K5ltb6AqSuINYTq8flxxsDkBP8Y2zbqmUjBcG9c,1571 +triton/backends/amd/include/hip/hip_bfloat16.h,sha256=Nqoy9VjfjglVx2_NJcp8hyT1sJUukXRWj8XMlidv1yA,1755 +triton/backends/amd/include/hip/hip_common.h,sha256=q5aPhG3DHW0iUJ7ayS5lfM_ZnZQNbMmLmfdHlOwbPdA,3450 +triton/backends/amd/include/hip/hip_complex.h,sha256=TmdzQP5oVPfhBVARJYcR5eyv9HInmKMFuFoQ_1ECk_I,1594 +triton/backends/amd/include/hip/hip_cooperative_groups.h,sha256=gMLvaYQ3b-f1vcoMtEwtkN0hO5__zNfP5p5oBKmv_SE,1878 +triton/backends/amd/include/hip/hip_deprecated.h,sha256=gFLuCuKn7R_xCfum_i_Q-vi3Lg8NWHKphKZKze8DwEo,6340 +triton/backends/amd/include/hip/hip_ext.h,sha256=mlzOesF-X62g9AnWdA4MP99GRu_VtwMbffOJFloLtRc,8609 +triton/backends/amd/include/hip/hip_fp16.h,sha256=vKJh-zgDWUW7NyXxtv2ho6aVLXX8BIPfzCigEQ5d6I4,1523 +triton/backends/amd/include/hip/hip_fp8.h,sha256=C4qn0im7Uhvp226VmL_QbF2b45Hhss2eokdSbqWkBcs,1433 +triton/backends/amd/include/hip/hip_gl_interop.h,sha256=-GwkSFMBneM8akFE7pqlhi0k-Ft2uz5674wGoiaU43Q,1438 +triton/backends/amd/include/hip/hip_hcc.h,sha256=RYrArDlnTEP89xKbzIpW17_bsBY5moCitq00PL-4oWI,1307 +triton/backends/amd/include/hip/hip_math_constants.h,sha256=8bSfve5E7cDuvNAUkFUeQwSLg3iJJHuqhuD4FmHNxEM,1588 +triton/backends/amd/include/hip/hip_profile.h,sha256=sjsNuduu5Jd6s7sJndZvZLlE0RZ0wN1rTVwv5nR7If0,1304 +triton/backends/amd/include/hip/hip_runtime.h,sha256=uy90l8Nep6xNUzeGcHMoDv84BT3hMpieTV-5ijkpL5A,3058 +triton/backends/amd/include/hip/hip_runtime_api.h,sha256=H9vPaMQ7VBkEtkxI5RyJ9UOXCmKzbPF70pcAsYNbP_A,402475 +triton/backends/amd/include/hip/hip_texture_types.h,sha256=AhkvjG4cDjf_ZFLg5SsSTfBnXG614PBK1XVPa7irZbk,1237 +triton/backends/amd/include/hip/hip_vector_types.h,sha256=6FcBMBkP3ZN1Enalpa9hV0VopxdBJvbUCuaxISgzbTY,1630 +triton/backends/amd/include/hip/hip_version.h,sha256=3MuxlZXlLLrhLllRr-1yrIZyv7l_zknuZrT8bDDtm3g,407 +triton/backends/amd/include/hip/hiprtc.h,sha256=dBxesFd3NCvG-NQ99s61i4fUQXfoHNmYhdF6CtE9QHQ,15904 +triton/backends/amd/include/hip/library_types.h,sha256=tPOJTQedPH5qC9meawLgKpnbFrQC2WKlfo6s0rhKoZc,2370 +triton/backends/amd/include/hip/math_functions.h,sha256=frzdJ4veBG8n9ALO4EmRrdOiDguR6FP6ygLnvOnVVSM,1815 +triton/backends/amd/include/hip/surface_types.h,sha256=uQHjITphDM7k4pnuEoDEupMUxBobzvhJpSy0unpegh4,1959 +triton/backends/amd/include/hip/texture_types.h,sha256=CtmdykZfDikhnrVfdJk3w2VK5X3Af_6rEKzU-VgLu24,6687 +triton/backends/amd/include/hsa/Brig.h,sha256=5H-btCHq40qgjjpwVAoRWf3E0ccf-J6UCPEcKx_hGKw,32705 +triton/backends/amd/include/hsa/amd_hsa_common.h,sha256=q_zN0eq-dwR7FnQ84PcpV3yZyvjHsouIAjJgKltGoX8,3912 +triton/backends/amd/include/hsa/amd_hsa_elf.h,sha256=lBT57uuPT6ra01HQtM1O3RhVKW3n41AjESDSi6KVN7w,17306 +triton/backends/amd/include/hsa/amd_hsa_kernel_code.h,sha256=C55F8a480QsW16-iwN9TIT3cKnGh6GoeoEaEv3aVh4g,12659 +triton/backends/amd/include/hsa/amd_hsa_queue.h,sha256=ZJ-k5wY30heLmQnGB0VUz36XCiVHRmspg5FRNMGIk_U,4766 +triton/backends/amd/include/hsa/amd_hsa_signal.h,sha256=FDegZnWQC04GtnqHjXOBsB-AoVSaqdhNY6Mwbua5FGA,2947 +triton/backends/amd/include/hsa/hsa.h,sha256=KyOkPu9bhpsaDCJFqlnis9oPDAdN6l2ujQSepL86jjs,191193 +triton/backends/amd/include/hsa/hsa_amd_tool.h,sha256=pyZSyIVl-UA5AOhte78jvn4V3hCd0dxJAIv7KeADsPs,2843 +triton/backends/amd/include/hsa/hsa_api_trace.h,sha256=GRBMFBWlv2dYJIT8BAWa1y_q-veLIgEVa1uIm-eM-Yw,29602 +triton/backends/amd/include/hsa/hsa_api_trace_version.h,sha256=yU2aATDJyhnCZF-FmgeF2wnp-EvPLE7n5zSuw8CNAqc,3248 +triton/backends/amd/include/hsa/hsa_ext_amd.h,sha256=J7wvz4df2HGFTMsfw36qs53Qfy2z5Reb5ak5wQSk6pc,118088 +triton/backends/amd/include/hsa/hsa_ext_finalize.h,sha256=sv0AZbDM-B1wIdQ3cHTMlpUtNacQN2PkOgX90IZol_o,20227 +triton/backends/amd/include/hsa/hsa_ext_image.h,sha256=t5YJm_aw9EePCeFL1hoIfQ8ubIjBte-ptfReq6Ts-8Y,54232 +triton/backends/amd/include/hsa/hsa_ven_amd_aqlprofile.h,sha256=IR_vo3kSqcTs-gnRdpXW3JE1RHQ71FBi4S81G8GtpZ4,19823 +triton/backends/amd/include/hsa/hsa_ven_amd_loader.h,sha256=c6cxPAzAox7u6IbFzEkQZfCuRl-Kr39WhY2_w23X1R4,26146 +triton/backends/amd/include/hsa/hsa_ven_amd_pc_sampling.h,sha256=1jQvi96s94-GjOGktmvpqjVRsTGANugOsV6XmgMfivk,18767 +triton/backends/amd/include/roctracer/ext/prof_protocol.h,sha256=6FAcvVD-dNM7uulFs2B-aTxw5xOAWGy6evdD4yUaebA,3849 +triton/backends/amd/include/roctracer/hip_ostream_ops.h,sha256=Si6RFHPn0QtMpSBboKFyfkrcOMYhTiom5oUnDEqRnP0,188184 +triton/backends/amd/include/roctracer/hsa_ostream_ops.h,sha256=jSHN5Ltd_EJtecE59xJS4wL_CuLuNkbO3QMqDgMpunk,69906 +triton/backends/amd/include/roctracer/hsa_prof_str.h,sha256=f0pO8T0JBnG_stZ_Bgawx-5_B2BNS7s9ogvEldA0UFo,124187 +triton/backends/amd/include/roctracer/roctracer.h,sha256=B8sHz2DMNprP7EqNWIGwVLY1KQMpxmhfVy4UoR8dzzY,23849 +triton/backends/amd/include/roctracer/roctracer_ext.h,sha256=vLaZ8peAxSy0cwrdEalKnUApkKspfa04iw1Mr_Zcio0,2940 +triton/backends/amd/include/roctracer/roctracer_hcc.h,sha256=NlF3R8JQ9oX9lGpm0b2n-EWJ0r3y9sP9wbwnoucaCuY,1303 +triton/backends/amd/include/roctracer/roctracer_hip.h,sha256=RCzYuNw1vLR7xK4rb06TtM9TU546UYKHJ83IMHmZEm8,1432 +triton/backends/amd/include/roctracer/roctracer_hsa.h,sha256=M8APM64XNAWSslxQisM-pcmKoUQaUdTMaKvSACyt0Ag,4108 +triton/backends/amd/include/roctracer/roctracer_plugin.h,sha256=8GGE1zDbdPCVJtbmwOCYq7X0mwFjfWRtzDYKLD4cKys,4786 +triton/backends/amd/include/roctracer/roctracer_roctx.h,sha256=gBjBk5vb0l3PbBSQ7V9iFtaM_RzkIDJEW1A_PXBihBM,2014 +triton/backends/amd/include/roctracer/roctx.h,sha256=RhJXUXRhSJ5LRE_1gm7E6-bjEMrfcFBLDLuf3UxAIh8,6717 +triton/backends/amd/lib/asanrtl.bc,sha256=1xv2RlU3WvbdsghHlmhwiHewGM2B5dKts5bERM6S89o,24508 +triton/backends/amd/lib/ockl.bc,sha256=wQKCzkKukIHbu0lyjKUYlhndc7S27xto6L54J0Bn-C0,246124 +triton/backends/amd/lib/ocml.bc,sha256=UPNTXW0gCXUNB-c6orSYwb-mz9_mjUc7zny_vfFza44,205964 +triton/backends/compiler.py,sha256=ymaG0kpveAuESbQ9QZ0RyXjr0Aq4el_G5XGYogJ2gNA,3588 +triton/backends/driver.py,sha256=AN60upJlPgia0JwvZ8vIVgLITNPuI0fdz8zMIIHPpF4,1450 +triton/backends/nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/backends/nvidia/__pycache__/__init__.cpython-311.pyc,, +triton/backends/nvidia/__pycache__/compiler.cpython-311.pyc,, +triton/backends/nvidia/__pycache__/driver.cpython-311.pyc,, +triton/backends/nvidia/bin/cuobjdump,sha256=rR0PBpn0ZgNBbrWOe5_fmik-lfkxLJ33_W_aVqbDDUE,569008 +triton/backends/nvidia/bin/nvdisasm,sha256=EIC8kJowIHYf9MeKm3vZtJN725wJeHCcvlI4HeYSofI,5894744 +triton/backends/nvidia/bin/ptxas,sha256=UDKqXtwKmWD7QJ3xwURFw4XHhnjGNC66W8Q20ePTUgs,30309984 +triton/backends/nvidia/bin/ptxas-blackwell,sha256=S9mOj2epi5IcG-1yyHPz3A_FvCQaia9LJTucL2UXOAw,31887568 +triton/backends/nvidia/compiler.py,sha256=eJld1AxOVJZPYs3G1H5m9tnfi1Wxcq1-uZI18nmZyEA,19427 +triton/backends/nvidia/driver.c,sha256=a1EQkPp1bnC6AbMyAOYUmeIWzU-z_w52N_yJ1JhMJR4,17277 +triton/backends/nvidia/driver.py,sha256=98Juj_2vjNJJHeBCF9MoJ7Gk-Fn3-T6lbiZZDJ9eBxo,19911 +triton/backends/nvidia/include/Openacc/cupti_openacc.h,sha256=Z0OM5e_hbd3cxdXyn3SCHqBBQawLg4QORnlm57Cr2-M,3513 +triton/backends/nvidia/include/Openmp/cupti_openmp.h,sha256=E1WNmeb_7HaUSmBegtUNe4IV1i7pXeNxgzIlyKn1zrM,3491 +triton/backends/nvidia/include/Openmp/omp-tools.h,sha256=AmuC_xPC7VPu3B-W4PmXuCNufFawhY8PjNXePaQFAOg,37403 +triton/backends/nvidia/include/builtin_types.h,sha256=JxT9Vf2q2snxTBOL9ACzNmYzTWACO2VOVUu1KdFt7_g,3150 +triton/backends/nvidia/include/channel_descriptor.h,sha256=oZIDO1kdexPb9jltUx1AsXAFknvRWAAr1456925Pqig,21846 +triton/backends/nvidia/include/common_functions.h,sha256=22LTZRVcPZzEH6MJda7nNMCvMgIjSTe0OKR7sEQj6kc,3410 +triton/backends/nvidia/include/cooperative_groups.h,sha256=y2cFxa6e-saEFA9aW22ZuTwi0wud7eEHq7XN3v30LT0,60684 +triton/backends/nvidia/include/cooperative_groups/details/async.h,sha256=xsEHCZP3nuEY3l2p8SU2d1226XiXumUvDP_Gyh8PdVY,19122 +triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h,sha256=pBQgFY7i64V87XNATg1UEIQHVNYOItQtHjS5B4yn8pc,4257 +triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h,sha256=DfZv5d5W0XJv-tZVhgrIdjLjs6aCx_u0oy1lDIpjo1Q,7314 +triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h,sha256=v-ZUb4UgGKJk6NR2WCWHD3x_42y-togI1urFn70Gi-g,3964 +triton/backends/nvidia/include/cooperative_groups/details/functional.h,sha256=2BV8i8Bidz0kgxuYkJCAbwFxOIZRyzHgG-c_rVKhRzc,8905 +triton/backends/nvidia/include/cooperative_groups/details/helpers.h,sha256=K9jvxnXc5-6Fum1KG4EQKJJrVZ4BhHOSAJbZR4uDL0c,26476 +triton/backends/nvidia/include/cooperative_groups/details/info.h,sha256=FOrp3Ltt4PcbK2fAM5UX9jssFZtj_LqVShzLFcKiSaY,12465 +triton/backends/nvidia/include/cooperative_groups/details/invoke.h,sha256=Osq3K-tZuXHVCMQJ708PjPo-BwMhjhjApO4b0TYLFJg,8616 +triton/backends/nvidia/include/cooperative_groups/details/memory.h,sha256=hES3SfgXIBsj2MFrC_M5COXlOirSBuuhPMAJnWoI92w,5606 +triton/backends/nvidia/include/cooperative_groups/details/partitioning.h,sha256=AQz-TheqX3onqX2RmIUipzYUVB273zhLlHJw_kX9D2U,7153 +triton/backends/nvidia/include/cooperative_groups/details/reduce.h,sha256=MjqMDwT0TyWZk4JWcF3WHw8xtwMqyizA4C3zy7f8ee0,23296 +triton/backends/nvidia/include/cooperative_groups/details/scan.h,sha256=-Ttwb2AfEEY_tsmqJjR2dojkPpoRx387SoqxgvfdBtQ,17166 +triton/backends/nvidia/include/cooperative_groups/details/sync.h,sha256=Ed4K9QrPZi43ddSqZwv1X8NG_CTsXUowSQndoUv82LU,10795 +triton/backends/nvidia/include/cooperative_groups/memcpy_async.h,sha256=erOIHuObdfxRhBWfrXE3wsZF4B2GUuqwzQrsPwKPpbg,2960 +triton/backends/nvidia/include/cooperative_groups/reduce.h,sha256=B0hgDkqM-6ueqTTgb3b34A0RH4vGz8mBf5e2jT1dJ1o,2949 +triton/backends/nvidia/include/cooperative_groups/scan.h,sha256=2EU6T5cWNwftm2B7FicV31PojoI61yo5fHXGRYkGk40,2940 +triton/backends/nvidia/include/crt/common_functions.h,sha256=-U44f4yUGmwDPwd7Q_3Cz5if05xHGPSlAzz5zMylLSQ,13559 +triton/backends/nvidia/include/crt/cudacc_ext.h,sha256=KW6n0ImOZKS0VqVmBHWTXtHI816hh88YeEgUg2aYdVU,3224 +triton/backends/nvidia/include/crt/device_double_functions.h,sha256=A1vB3g0qwnNEfcpT1d9RiGDaxqPXXgYr-Vxe2oMHyxY,39938 +triton/backends/nvidia/include/crt/device_double_functions.hpp,sha256=YYIbqYhb5Qmf8c4YfcC_jytg4FRwcXPjv3TFTwhb24E,8568 +triton/backends/nvidia/include/crt/device_fp128_functions.h,sha256=3iCKrdmPp1NIjrlGR47dCZOgV9X6MmdfmjugrF6DEts,51047 +triton/backends/nvidia/include/crt/device_functions.h,sha256=T4INuRBIlLmd3JEA8H6B5XHVANGV6j8gwyUTj5h_F18,137919 +triton/backends/nvidia/include/crt/device_functions.hpp,sha256=OVHiqBjday_aUFnDKJxTeI0VDZI8ZA6JIdUKeAKR4pA,37991 +triton/backends/nvidia/include/crt/func_macro.h,sha256=EOpDlaM917bh9cwBiFBPF689DCMBw5hFarxLxFt-i74,1755 +triton/backends/nvidia/include/crt/host_config.h,sha256=1eki3w5xuY00gIkdYbmSfZO2SoI8giZWYSTRIL2uFs0,12169 +triton/backends/nvidia/include/crt/host_defines.h,sha256=fDU_0cQdtIvEdM0zZFKY0OboMANEMgHLblifPalPGLk,10102 +triton/backends/nvidia/include/crt/host_runtime.h,sha256=lOpmkxFZVkEp8dcMAGEZRITsh-19o9jy39kdSNLc3Ng,10284 +triton/backends/nvidia/include/crt/math_functions.h,sha256=LyGJ0XUthi6WEi-YVITInha9A6SFoB4fEUUU9zii7U8,238284 +triton/backends/nvidia/include/crt/math_functions.hpp,sha256=u-CGbd0R2FZWdKG-6bdmGSor9KT_wnmISj63lPQKASM,100207 +triton/backends/nvidia/include/crt/mma.h,sha256=BooWALDWATvZupJaL7-GFQRQYOotNe_Fy11I5NGh2FA,62695 +triton/backends/nvidia/include/crt/mma.hpp,sha256=spo0LX71tUCipxK517Bssj0nc-ZHf8oMWzvHoYYB_6I,66599 +triton/backends/nvidia/include/crt/nvfunctional,sha256=FDM0zqWO6bl9jpJKz9U8CMbjt6iTKh18tQalxAvRsag,16900 +triton/backends/nvidia/include/crt/sm_100_rt.h,sha256=3cBiCU11OcjGYpr85edCN1q4m2z91FaGhBtuO0is4To,8987 +triton/backends/nvidia/include/crt/sm_100_rt.hpp,sha256=vbI2CNCY08dDI7zXwp6BNceZKl0ceXG1lveq4w-VNao,6855 +triton/backends/nvidia/include/crt/sm_70_rt.h,sha256=Kf830xymA-zmF7LsunFHLSNyhhT5UiJMocgoHBQeNns,6837 +triton/backends/nvidia/include/crt/sm_70_rt.hpp,sha256=3a_rU-Y0MSB4htBDFY4PCQ_jXiWFTe7WT1ZyhMuCJOA,7837 +triton/backends/nvidia/include/crt/sm_80_rt.h,sha256=MdJHWCRzLM__nDDf1go61rDsl9ydOW3oi6SZBfjUyc8,7743 +triton/backends/nvidia/include/crt/sm_80_rt.hpp,sha256=o-rJu-jpehCeyABGgv-8dYRB7oJTCwuNdvSCq0VURdE,6705 +triton/backends/nvidia/include/crt/sm_90_rt.h,sha256=an47m0XFBaJ3pUX9MlE4-nktP1jb3eJUXhQ3ntZtzc8,11445 +triton/backends/nvidia/include/crt/sm_90_rt.hpp,sha256=YuqVygGV6rgtWtx1J9cPpEI3BXKQBII-Ez6oZFP3wrE,9228 +triton/backends/nvidia/include/crt/storage_class.h,sha256=dzcOZ16pLaN8ejqHaXw4iHbBJ6fXWxfaU-sj2QjYzzg,4791 +triton/backends/nvidia/include/cuComplex.h,sha256=WpcgpaiPhU_o9sTPMcNTEZuyXDIc8x3sz4dUWSztL2g,12186 +triton/backends/nvidia/include/cuda.h,sha256=RWjMnnoyHkdwfNZAOYDyGsLi5VFwUA0OCj9U_rA6mss,1156988 +triton/backends/nvidia/include/cudaEGL.h,sha256=iruZU9xSGAcJ29OEX4K_Uo1o4NGP9hggv2fiOZOfDQo,39955 +triton/backends/nvidia/include/cudaEGLTypedefs.h,sha256=xF_FAN1Kar9oyHJ3cCU7jztTpxX8WylpiuYyYpGGHek,5645 +triton/backends/nvidia/include/cudaGL.h,sha256=gMT1HPGa-siuji0gAsKYr4X45Lc29HKglC_ttNSGyUM,22501 +triton/backends/nvidia/include/cudaGLTypedefs.h,sha256=dClpQI-LuXgF9rPSBsj7OkIg8g_fXDjT0hLZS8TGpOg,6576 +triton/backends/nvidia/include/cudaProfilerTypedefs.h,sha256=F2aWLIKv_AhNbxNOaZVcRsxIh0kuscnV8UMWWxkBAlY,3297 +triton/backends/nvidia/include/cudaTypedefs.h,sha256=SKfAvTOj19zxsiLGKhoxXPiopKqoe5hjj5iXkR2_v6E,115169 +triton/backends/nvidia/include/cudaVDPAU.h,sha256=Np7Nc2Wjaz--hkpbhW6f9aapr-NbcPDAgkot0sJerco,12694 +triton/backends/nvidia/include/cudaVDPAUTypedefs.h,sha256=wz8nyOUdwM9mH9JO3QZW-A9dyxt-IufSX7nggSXpCNs,4144 +triton/backends/nvidia/include/cuda_awbarrier.h,sha256=3ZH-ZlXODhSiwSY9rqSni_EQwi25QMHP6Tm-zOdxBwE,9340 +triton/backends/nvidia/include/cuda_awbarrier_helpers.h,sha256=OCskCts5bCKl_RKBe9M74zKSIsVpePn44S_aJp1tFXE,12489 +triton/backends/nvidia/include/cuda_awbarrier_primitives.h,sha256=n5__E1jYYDhlgH-f3u8MQjtz57UZ7v5VshhMye1eicM,4699 +triton/backends/nvidia/include/cuda_bf16.h,sha256=TVoq2IrbF5g67wUF7W7SoGA0l8ecEDu6gskoMB6hIxA,204512 +triton/backends/nvidia/include/cuda_bf16.hpp,sha256=OukWXoN6bgRlC-p8CFbhUN0G0uAJb_zos1mCPagscnI,136544 +triton/backends/nvidia/include/cuda_device_runtime_api.h,sha256=54l66QbwerX0wPKoJC2y7qCdGP8nv1_GgdmMV8A0x4k,46986 +triton/backends/nvidia/include/cuda_egl_interop.h,sha256=awWBBEYvUFM7AURNp2mND8H7_5kGQLRswRveXYBy-3s,37509 +triton/backends/nvidia/include/cuda_fp16.h,sha256=jrFgCo4uM9QFcr_-cAGif2BGp0lJ2ANT_gLPiLJWPdo,206851 +triton/backends/nvidia/include/cuda_fp16.hpp,sha256=o1ITDmuN67N8YUGUcvTpV3IdpS-6wwlm65M_H-8LYKs,120927 +triton/backends/nvidia/include/cuda_fp4.h,sha256=pTEQf5rLfiaU_UMXgnnsS13NH5H9FtHgdeiNuW_NkHY,13823 +triton/backends/nvidia/include/cuda_fp4.hpp,sha256=YYaUu-YRgYdj9xYu4ZDh_uPVffxkDlEr0CD_bhlF8BE,35423 +triton/backends/nvidia/include/cuda_fp6.h,sha256=6xh0E4SNmjmJZD3H5_HoZe08bQ0loUE8y3cbO19-Ad4,13963 +triton/backends/nvidia/include/cuda_fp6.hpp,sha256=qa838buZeLP32xBVqbo71uFSW5RnBWx9qp5D-SR_xc0,56455 +triton/backends/nvidia/include/cuda_fp8.h,sha256=QSTMRb9l7I9mnvT1_8KXNqLO48wWaWEgG97bDjEh1ic,18072 +triton/backends/nvidia/include/cuda_fp8.hpp,sha256=6AABZPfPlK-jmQyMdbTEE0PZTlULjuLOrsQ0Z_cubBw,97230 +triton/backends/nvidia/include/cuda_gl_interop.h,sha256=VQEswFeOBF6JN6Q0pdlkvc5WT7bD1FnTfKewvANulCc,19150 +triton/backends/nvidia/include/cuda_occupancy.h,sha256=0HavrMIWXGxIujaq72iX31-73Zprx0WBYdiln3ZNP2w,71302 +triton/backends/nvidia/include/cuda_pipeline.h,sha256=0enXG49wN4JajlQi3ahbp2ei_ufTY_Mznic7zfWmKHM,8130 +triton/backends/nvidia/include/cuda_pipeline_helpers.h,sha256=bo1L7e6vCuM-K3Il8K1z4wJUja5DyXQKdo_hSWUME-E,13852 +triton/backends/nvidia/include/cuda_pipeline_primitives.h,sha256=FnJJtuV6rHr6LgL56XDwilcSbFr6W1Hj6mf1AJaMI20,8675 +triton/backends/nvidia/include/cuda_runtime.h,sha256=GqqE7SrECGrN-Qg5Dk90LSjs-xvKlHZpRLlpH7LUehM,98570 +triton/backends/nvidia/include/cuda_runtime_api.h,sha256=EWhSESFT_vV5eYZpTBEu4EvgNtE9rhmHP503XnIGHIs,655943 +triton/backends/nvidia/include/cuda_stdint.h,sha256=XbFOk9CtJjKqk7PpYNqbSVsDxAsVM8avA4rWpPi0BjQ,4093 +triton/backends/nvidia/include/cuda_surface_types.h,sha256=Mw5Lo4b8Q-f9mogOvATGyHhu9d2t2K6XOxuqtZrSh3A,3688 +triton/backends/nvidia/include/cuda_texture_types.h,sha256=ITbX-JNnP7Rm-JSgNVdJ9pq6k8FVor8RbnruDsKq6sk,3688 +triton/backends/nvidia/include/cuda_vdpau_interop.h,sha256=bXQanWc2IFXZAKWNGl2xAz9nLvFmQpWyGrsDvfeS9FA,7727 +triton/backends/nvidia/include/cudart_platform.h,sha256=YN6sKhB0b9w5tGX1IYL7ulJVPrWAiX9A44qLv4EtW5Q,2717 +triton/backends/nvidia/include/cupti.h,sha256=JkVyAGTIMYzwm62dfVqas3nMcILhgP_Wdz6fh4_NED0,4697 +triton/backends/nvidia/include/cupti_activity.h,sha256=kkYnS-1nKWTh2EZOKZ3iUugmBwvOZFiK3HwznfPWxc4,229736 +triton/backends/nvidia/include/cupti_activity_deprecated.h,sha256=B0p4zbll2vUn1j0ImTG6QIbpp6Hiw8y-X021Zmf7flE,137602 +triton/backends/nvidia/include/cupti_callbacks.h,sha256=aZ-SE0YMFfT9R-Uh5MHboPg0ypHMjeSSAJw3zdP7OCs,29689 +triton/backends/nvidia/include/cupti_checkpoint.h,sha256=rTz8JoWxqESBXyZWUhZJGm4xeYcx4OJOtJ7Ld13T_b0,5264 +triton/backends/nvidia/include/cupti_common.h,sha256=85m74bxUgXp3tEaPQpezeazmpsNMw41PsjNSYmQdT20,3514 +triton/backends/nvidia/include/cupti_driver_cbid.h,sha256=mkBNPYkLfcExhQZFDo0iYHlaHJWGD2vOMdtzaV-lEUk,77280 +triton/backends/nvidia/include/cupti_events.h,sha256=81wcvFvvHj8RmECbbEp5FfgjJIQDoC_81FhvqznFupY,51923 +triton/backends/nvidia/include/cupti_metrics.h,sha256=zmfZxq5VkUJp6Tj7oXEkP9oycRNw1zB9VNhoQlbhiN4,32175 +triton/backends/nvidia/include/cupti_nvtx_cbid.h,sha256=_azPtR1g4qivvX7qbvHRUg0RHCWF7iEOJyHMN9qZe9E,5912 +triton/backends/nvidia/include/cupti_pcsampling.h,sha256=ycJHT36DmPIaVzHsB3xxjXkhFyEfMCJOl3LbCsHFgyA,32144 +triton/backends/nvidia/include/cupti_pcsampling_util.h,sha256=lx8CaNXowJe5Zvc06LE-u_Zry_jODs1mM6j9Q5WIX9E,12430 +triton/backends/nvidia/include/cupti_pmsampling.h,sha256=U95hKOwIkZSbGNVP11QSmMawB8qdJsljY_tUJY4vedc,20440 +triton/backends/nvidia/include/cupti_profiler_host.h,sha256=MkkfXlKBRrRL4NfaPFiuE4D4z_gpmxiBWWTBixyyMTk,22155 +triton/backends/nvidia/include/cupti_profiler_target.h,sha256=MdLutIefwdMTI7wsce0LO3NuCm3FRgFR3GxAkqadMs4,32294 +triton/backends/nvidia/include/cupti_range_profiler.h,sha256=ue5bUA-3xCwAtQGyDe5O1d5rAmRbVbcrXKfITd4xM1I,18779 +triton/backends/nvidia/include/cupti_result.h,sha256=xQqBsZRoicBSWdk1lZAE_WeZj88MLH6ClTo58oshx-8,13114 +triton/backends/nvidia/include/cupti_runtime_cbid.h,sha256=BZJnzsvf2RjRlHKEhPjCk0CdjLI9_L-nClTwe4v9NUc,48372 +triton/backends/nvidia/include/cupti_sass_metrics.h,sha256=3RW9snJuFQdOhrEn3wDJOru05q0V_zssWrqD7tvVJKw,19674 +triton/backends/nvidia/include/cupti_target.h,sha256=x4Vz1Upb6m9ixmVpmGaKQldDWYQI3OZ-ocEXGzNK0EE,1263 +triton/backends/nvidia/include/cupti_version.h,sha256=KFXmjB4o-iZGvO8la9Sf9Urg4q4srmEimnxbPCyd2N8,4506 +triton/backends/nvidia/include/device_atomic_functions.h,sha256=OR2jNSfSKzaFri74zh4Vtz5M0z9UDBU3rKeC1rYaVQs,9500 +triton/backends/nvidia/include/device_atomic_functions.hpp,sha256=0e7MOiNNUnnloXpB_r9WT5YOws5cxgzQQAzRCYvgaFA,10486 +triton/backends/nvidia/include/device_double_functions.h,sha256=KUxId5Z1fx8SWfLRTxPD7RB-zN7zslzb4n7JaJLfL3I,3452 +triton/backends/nvidia/include/device_functions.h,sha256=bWSrhTYE9NQlss7xMSMEVusvto9j2fgUDXWVH2W_cOA,3410 +triton/backends/nvidia/include/device_launch_parameters.h,sha256=H1_CC-vvAaS26ys4XsTFkMgTxUTciAjdjswjizkisvQ,3846 +triton/backends/nvidia/include/device_types.h,sha256=2LFxoZBJPoA5V0H1EbKTEaXDi3GDJPtzOPdRHDaucIQ,3588 +triton/backends/nvidia/include/driver_functions.h,sha256=cN3IjRAz2Mj2Pj35SyxJIkZNDDusnJqaqzBdMzpQKbA,4625 +triton/backends/nvidia/include/driver_types.h,sha256=mMNbiIwg5E3k7Sk685YCSvnKYmfQ3bxWv3bkEgzOtNU,200083 +triton/backends/nvidia/include/fatbinary_section.h,sha256=NnuUfy358yGJx4enq0pBnetjv17UWa-nOlgYToUitrw,1809 +triton/backends/nvidia/include/generated_cudaGL_meta.h,sha256=dfd2QuaRdEjbStOKvaQLi1Md_qrpRQh8PfyZznJ8bWY,3115 +triton/backends/nvidia/include/generated_cudaVDPAU_meta.h,sha256=fAedsoQxaU3hIAApAWDOKsa9kgcuQw4tdyf8klLm-3k,1453 +triton/backends/nvidia/include/generated_cuda_gl_interop_meta.h,sha256=LXOqvQCej0sCgAT1LUKKYZ466EFxN4hIwf9oIhXOLF0,2250 +triton/backends/nvidia/include/generated_cuda_meta.h,sha256=DDdgfW84GVtsGbr7daNJchmmZDS_xfvDHvFCm3I1OEc,98664 +triton/backends/nvidia/include/generated_cuda_runtime_api_meta.h,sha256=CuziaDwO2Mh33paCLGKqi73PQfYNmzp38wYrhAK-fng,72208 +triton/backends/nvidia/include/generated_cuda_vdpau_interop_meta.h,sha256=8OLqWN26aEYpTWUXtbHJvA5GYhVv3ybYVOTW7yK37z8,1367 +triton/backends/nvidia/include/generated_cudart_removed_meta.h,sha256=X3I5WXmhtsJNNlgY7coJ5vg4t11G5FRR6Xo7MboIeck,5172 +triton/backends/nvidia/include/generated_nvtx_meta.h,sha256=YHb_RD8g3s4m8PJn7Z0wnxvUHarl7BOAX5ADr-BL3HI,7513 +triton/backends/nvidia/include/host_config.h,sha256=BscH_GazAZbbotddVzL5RmafbQ-QjRx8f-I1O01IBW8,3380 +triton/backends/nvidia/include/host_defines.h,sha256=bBQwQF5C1N1c2qpLV56g1c-weu9Ysgz-gIf2Kn3uz_A,3386 +triton/backends/nvidia/include/library_types.h,sha256=i-GFcw92wvcixs2bQjOj4I_q26HYY_VY4DpDvHWQCjY,5156 +triton/backends/nvidia/include/math_constants.h,sha256=cV6hAyQe8X7f7MBtaKjjIJq3BycOUDp6I5cizJX5HLw,7608 +triton/backends/nvidia/include/math_functions.h,sha256=5XcC6j-fJKttvhwc4hZNoLHNw808a2ZYIOtZ7ry7yd0,3398 +triton/backends/nvidia/include/mma.h,sha256=IY_VenxuEncwGq92MhrWUb-Xswh0ekAXLy9Rbxhxa2Y,2932 +triton/backends/nvidia/include/nvPTXCompiler.h,sha256=lF1ssKlrjsNWCsp0UdhbB6GyOgFCDO1q0ZBDzOswlj0,14471 +triton/backends/nvidia/include/nvfunctional,sha256=IkFoCi_Q4OhP9nEuBI-5jWwFlR_PfG05hJH7lSMsfWc,2975 +triton/backends/nvidia/include/nvperf_common.h,sha256=ykeTJ5I6c0z8KqMQh13hlJaMaHiqqVUB60oGXOCu7Bg,17255 +triton/backends/nvidia/include/nvperf_cuda_host.h,sha256=gC0JWoUdTyAOJs8y4uoJIhie9Xq4yF4HzoumLsYNVzU,7562 +triton/backends/nvidia/include/nvperf_host.h,sha256=wCB4mR8aIHWiqT1TsxztQgWBRh_yiq5ABFm8sb3_jwg,49197 +triton/backends/nvidia/include/nvperf_target.h,sha256=jRqQtuNLTrCzPDdyeANkTrPEijSCTjLy2A1qjKu0SdM,23607 +triton/backends/nvidia/include/sm_20_atomic_functions.h,sha256=x4ycINVq__l9B4SQPD-I48jQbKxxdBmgp8Vf2GO0Qfg,4478 +triton/backends/nvidia/include/sm_20_atomic_functions.hpp,sha256=1l5NLM8DhDbqYZ_E51LoqElQJXObkbwo57d3r-4uEbE,4107 +triton/backends/nvidia/include/sm_20_intrinsics.h,sha256=axeDr7y6nT1V6LzrSWNSaHUwXgiNjPbXn1T6Uh7hlNM,57702 +triton/backends/nvidia/include/sm_20_intrinsics.hpp,sha256=mJTejRhw1prNiP_ax1OPbkYlhEqBqO4nVI3DRDXIzpo,8392 +triton/backends/nvidia/include/sm_30_intrinsics.h,sha256=b6W8Vxp9vD9OCJI6lZuGyZYXEdQ3Ei8PTAloHNkwCcQ,16978 +triton/backends/nvidia/include/sm_30_intrinsics.hpp,sha256=yX0ebd265tJ-BDhvluP2BhadPuWXpRZPI2eeQFFt5ys,24567 +triton/backends/nvidia/include/sm_32_atomic_functions.h,sha256=HGnZgQHACE2AAb6zabGUURc53IsVZelc2BSJqvs9OgY,5703 +triton/backends/nvidia/include/sm_32_atomic_functions.hpp,sha256=CQTTvOEYp-s5hqAgLvAon11vLYDrDp8cTHdel-XRzBQ,6592 +triton/backends/nvidia/include/sm_32_intrinsics.h,sha256=Xdkogdsjy1vh8u3eGu0i5xTmHxBGAjj6_vVGR-spdOE,33539 +triton/backends/nvidia/include/sm_32_intrinsics.hpp,sha256=Gl8aSLDLcit4W3pKQS19GsDG8RYcwD65HwYB_CeZe8M,70616 +triton/backends/nvidia/include/sm_35_atomic_functions.h,sha256=a3XoEsKRCEOf0Q_5Y__rMfmC4pScv4VkUggVgVJVn44,2909 +triton/backends/nvidia/include/sm_35_intrinsics.h,sha256=0mS5-LCgvZiTvL7-MG_4YwI-zWGvM-s4xyRuMkunMC8,2664 +triton/backends/nvidia/include/sm_60_atomic_functions.h,sha256=_anfNaJsvQpDEorYeUKIkbizYkwrinBcG_ZCiECtLqI,13178 +triton/backends/nvidia/include/sm_60_atomic_functions.hpp,sha256=cgIKddDn2B3QzYlzeBILAP1IRys74QCCxsH0QqaVGls,22903 +triton/backends/nvidia/include/sm_61_intrinsics.h,sha256=h_MBL1UUDxQX_qOddSImzqyFjcrhhm_63G97pGDyreU,10902 +triton/backends/nvidia/include/sm_61_intrinsics.hpp,sha256=N-nQvcBsPMT2Umy5zR69c9K1q366W-Jqe7NpoLTqTmg,6787 +triton/backends/nvidia/include/surface_functions.h,sha256=b1O82SAvEgWWxA9uZTWQcGimzZUoem2QbAET3wh3fZc,6782 +triton/backends/nvidia/include/surface_indirect_functions.h,sha256=vy9QuFVV-ezZP-x2RT9RLp2qIUgdngACOCmalSfVFPA,10877 +triton/backends/nvidia/include/surface_types.h,sha256=XkFXD1nHbeSMgajR-UJE9uQ7TByzJnjdnUL4-yGiufk,4530 +triton/backends/nvidia/include/texture_fetch_functions.h,sha256=KLCmUxf5aY5_UalX8tSFB6e4TrjA8hyUPxLOkMFltAo,12468 +triton/backends/nvidia/include/texture_indirect_functions.h,sha256=lH_y3Ni-hq4RZ0_PMFbBM0th5-OmTn3TtqtpkHHhA8w,21163 +triton/backends/nvidia/include/texture_types.h,sha256=73ntVyg8r8fzKy5VIk6yuvC45GDeWepaLIqIk-M3Ri8,6360 +triton/backends/nvidia/include/vector_functions.h,sha256=WypGkL-IDbGOlay7g_G0p3HO7OLGRE0Do__JtiFoWxY,8003 +triton/backends/nvidia/include/vector_functions.hpp,sha256=afXhNSd3LFTZo96EPtesTLfvxd4nTmLVzgkj967rTRg,10060 +triton/backends/nvidia/include/vector_types.h,sha256=6CJ4yt3KD7zQVfm1NhrgqNYYEDEIZWwaivlFx12nhNg,13396 +triton/backends/nvidia/lib/cupti/libcheckpoint.so,sha256=BrqCvQkje5NM8W2iFy7VlDxYLKo1x5tSz8_rD_cfclA,1644872 +triton/backends/nvidia/lib/cupti/libcupti.so,sha256=6xqU1E-HM2nivcSuN5W-2_WFUtqthBV1uMcoH2k6iX4,7595792 +triton/backends/nvidia/lib/cupti/libcupti.so.12,sha256=6xqU1E-HM2nivcSuN5W-2_WFUtqthBV1uMcoH2k6iX4,7595792 +triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.0,sha256=6xqU1E-HM2nivcSuN5W-2_WFUtqthBV1uMcoH2k6iX4,7595792 +triton/backends/nvidia/lib/cupti/libcupti_static.a,sha256=64kffz04ExWSL4eI50o3EYpm9qR05haERukg49iFK-c,43549906 +triton/backends/nvidia/lib/cupti/libnvperf_host.so,sha256=YgaebMUU86lxdUQfcrnL0K4Ty06nxcpBPoqy9PcqNoc,25821840 +triton/backends/nvidia/lib/cupti/libnvperf_host_static.a,sha256=bJcgpYwzLMOLpfXE5ZPFP9avulOiAeu_Gx69P6ZIX34,33466138 +triton/backends/nvidia/lib/cupti/libnvperf_target.so,sha256=FzX7GLg8IsF-vF1XNA_pj6rtf2TATB2u1bN44eSwwR4,5271216 +triton/backends/nvidia/lib/cupti/libpcsamplingutil.so,sha256=5vongwd5dPsnZb-py66_mAc233Tuv5lMWcdZaYiuyDs,970064 +triton/backends/nvidia/lib/libdevice.10.bc,sha256=XC-uN8huaMOjhgWpX1EtfRLV89uYYxC-R_VzBKpype4,473728 +triton/compiler/__init__.py,sha256=0NEunzjGCNEVOhYZLDI4pDi_zAaYAgTXNm8U5uxbdL0,242 +triton/compiler/__pycache__/__init__.cpython-311.pyc,, +triton/compiler/__pycache__/code_generator.cpython-311.pyc,, +triton/compiler/__pycache__/compiler.cpython-311.pyc,, +triton/compiler/__pycache__/errors.cpython-311.pyc,, +triton/compiler/__pycache__/make_launcher.cpython-311.pyc,, +triton/compiler/code_generator.py,sha256=Nkp9HdXymGenQROPg8W0UyWeJApdUfNk8k9xls7b9EI,62153 +triton/compiler/compiler.py,sha256=LiNMHZOnyulJNBtguFZ_glkUEo7VmOHYRsi8GanWWtg,18470 +triton/compiler/errors.py,sha256=I9Y15pDWcL9heY4SWWdLeMDtW6Iiq2pFXzKfJ6dY_C0,1732 +triton/compiler/make_launcher.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/errors.py,sha256=8WfnuRKLG578mgY6cBA3ECruVMf9ULEKFNgRcJ6IhWM,89 +triton/instrumentation/libGPUInstrumentationTestLib.so,sha256=1p5bOT_tO07-zKfvulPpRG0Tg58AIZ0OxFRP_b0cOZM,6260824 +triton/instrumentation/libPrintLoadStoreMemSpaces.so,sha256=qFrlIMgly6NtBla13cgQyhcps1YH6QTwIVwCCG4Me04,8831672 +triton/language/__init__.py,sha256=8gybBY5MBcoXi3K28AVXY-oSaTWxtNIyNbp6fzh-Pn0,5366 +triton/language/__pycache__/__init__.cpython-311.pyc,, +triton/language/__pycache__/_utils.cpython-311.pyc,, +triton/language/__pycache__/core.cpython-311.pyc,, +triton/language/__pycache__/math.cpython-311.pyc,, +triton/language/__pycache__/random.cpython-311.pyc,, +triton/language/__pycache__/semantic.cpython-311.pyc,, +triton/language/__pycache__/standard.cpython-311.pyc,, +triton/language/_utils.py,sha256=bkp98MH2y3mfSI7h1u_T33VPwYqsbnIJkjuwIsNsfE4,646 +triton/language/core.py,sha256=-YP51tb5h69SApfI_jGFYBro99YLrKuICskya9_uH2c,107314 +triton/language/extra/__init__.py,sha256=XRXFvr7416pRsh_Rh-X6qV66SiEyVDVbxp4GSAE1mfc,655 +triton/language/extra/__pycache__/__init__.cpython-311.pyc,, +triton/language/extra/__pycache__/libdevice.cpython-311.pyc,, +triton/language/extra/cuda/__init__.py,sha256=JqiuryHnWRkfFztXgxbiQ62XA4dEKhsjhIHGobLuzcQ,414 +triton/language/extra/cuda/__pycache__/__init__.cpython-311.pyc,, +triton/language/extra/cuda/__pycache__/_experimental_tma.cpython-311.pyc,, +triton/language/extra/cuda/__pycache__/libdevice.cpython-311.pyc,, +triton/language/extra/cuda/__pycache__/utils.cpython-311.pyc,, +triton/language/extra/cuda/_experimental_tma.py,sha256=vTZHUoUrdqC3Wp2T7Lwjl4G3MKp1AhRFoC15WqjTj2o,3420 +triton/language/extra/cuda/libdevice.py,sha256=crwXcdixYPuvzVOQ0e5styRAwQrUg0RRRlqek7QvXRw,56165 +triton/language/extra/cuda/utils.py,sha256=e1BslV7lZGhi2uVIlo5lI9dcN61HUMIU2asPaRjsyIo,4379 +triton/language/extra/hip/__init__.py,sha256=ieSER4LeX9_0horChGUUVwpuKAprkuka8uGAkEBDyDM,49 +triton/language/extra/hip/__pycache__/__init__.cpython-311.pyc,, +triton/language/extra/hip/__pycache__/libdevice.cpython-311.pyc,, +triton/language/extra/hip/libdevice.py,sha256=EVraUfeXzQmN3F5Lleg2mohVcbFWOWlLaAH1nkbqtV4,16841 +triton/language/extra/libdevice.py,sha256=Dki14elRNmQsz-Ytw9CnOaLCCnte4T6cI8bOzWjN63A,6318 +triton/language/math.py,sha256=thYBX3JOVTNI9bAZ9zJN7BMPe7r5hNQzAPppx8L92i8,7442 +triton/language/random.py,sha256=VP5yLL43mlVpWrlHjnPTRDd89enW4FWv980Dv2__Gyo,6906 +triton/language/semantic.py,sha256=EChVVc1RXiHKVHFPyOucFzzKawkrXpUaF65e7ijtJwc,87858 +triton/language/standard.py,sha256=8tTnMYLmjt3GI3V3shWLfYSYzLPFBkK5x0xV0_S-OUM,14442 +triton/profiler/__init__.py,sha256=6cz3wpkQx8ujHSe-hstUuVqQFptiqeGy8AVUPUR0Bks,249 +triton/profiler/__pycache__/__init__.cpython-311.pyc,, +triton/profiler/__pycache__/flags.cpython-311.pyc,, +triton/profiler/__pycache__/hook.cpython-311.pyc,, +triton/profiler/__pycache__/language.cpython-311.pyc,, +triton/profiler/__pycache__/profile.cpython-311.pyc,, +triton/profiler/__pycache__/proton.cpython-311.pyc,, +triton/profiler/__pycache__/scope.cpython-311.pyc,, +triton/profiler/__pycache__/state.cpython-311.pyc,, +triton/profiler/__pycache__/viewer.cpython-311.pyc,, +triton/profiler/flags.py,sha256=BFBKQnozRN9Jp18_S5MuIeu5CJMW7_I38pM55qOg2oQ,604 +triton/profiler/hook.py,sha256=hOXc3pN3c31eGqJ4rwdMVjnTK76_Cc9IVlr_tAWOYmc,1155 +triton/profiler/language.py,sha256=g38TM6hHBkmJtTWD4vRD-0jl9vTF27quWKr1zbX6PpA,436 +triton/profiler/profile.py,sha256=E6kLvexxHewfd5z0nejqtuE5YDd8gG6xDrkqhd_DXGY,7139 +triton/profiler/proton.py,sha256=u9--f28vWGJj5dqvlrUop3ZSrk9WjnV-Nmd5kkgT_dU,3864 +triton/profiler/scope.py,sha256=0FdPkga2fOEv8DIan0Vu0BNB6RIspEhqRELq-mLIY9I,3661 +triton/profiler/state.py,sha256=Mp5kcU4xTwZopfXrsgjEE5bQ2HJZR3242e0KkmVw-EQ,1346 +triton/profiler/viewer.py,sha256=N0hkmaKzQ4cdFSY9l9Ai7mdeSGV0UysSl9qE_ws3nuw,18245 +triton/runtime/__init__.py,sha256=mKL5cqIBDUw2WO80NRCh4s1G8KYaqgM59TTAbTkPPjQ,621 +triton/runtime/__pycache__/__init__.cpython-311.pyc,, +triton/runtime/__pycache__/_allocation.cpython-311.pyc,, +triton/runtime/__pycache__/autotuner.cpython-311.pyc,, +triton/runtime/__pycache__/build.cpython-311.pyc,, +triton/runtime/__pycache__/cache.cpython-311.pyc,, +triton/runtime/__pycache__/driver.cpython-311.pyc,, +triton/runtime/__pycache__/errors.cpython-311.pyc,, +triton/runtime/__pycache__/interpreter.cpython-311.pyc,, +triton/runtime/__pycache__/jit.cpython-311.pyc,, +triton/runtime/_allocation.py,sha256=zaW4B7I7c-2rkVuN7IZaUB6IQSI1t4FvnTPZH-r7DTk,798 +triton/runtime/autotuner.py,sha256=0ku0wjPo8xOvom6P4uEVZHsgPkxAFOqP1LjUVue0HLM,17854 +triton/runtime/build.py,sha256=CAs_rDfwOAmAVDyNSPLiJ7rohgdg62ayPIHEeB_SWcI,1777 +triton/runtime/cache.py,sha256=Vs9l4DeRhKXyB-hfDBrp5v85OO6vkkXTHTVjZ7zu0xg,10260 +triton/runtime/driver.py,sha256=VZ-883Xri71R72lHB6usIpLo3gGLbZJkAlLP3ewWSpc,1509 +triton/runtime/errors.py,sha256=CwfJXciwel_-K3BfQfKUpLPDWrSyTnGsfJkqJojrdfQ,1052 +triton/runtime/interpreter.py,sha256=RVzNGSXyLlg14LgjJ5BZ3qbqfK49FccG-pXaIXXXE2g,59331 +triton/runtime/jit.py,sha256=jnMaMATWM3LU-s2QJPGeWVH5EGG78dT5aEUkGEhbpKc,34892 +triton/testing.py,sha256=ivFf1Fq9frmfVahaVUp0bgJxmvVZNACZfj3Sai6zfAs,20048 +triton/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/tools/__pycache__/__init__.cpython-311.pyc,, +triton/tools/__pycache__/build_extern.cpython-311.pyc,, +triton/tools/__pycache__/compile.cpython-311.pyc,, +triton/tools/__pycache__/disasm.cpython-311.pyc,, +triton/tools/__pycache__/experimental_descriptor.cpython-311.pyc,, +triton/tools/__pycache__/link.cpython-311.pyc,, +triton/tools/__pycache__/mxfp.cpython-311.pyc,, +triton/tools/build_extern.py,sha256=jCr-2hu3nLGBIJhCGUQ1jAyzLttughjkiPGEwRFjLR0,13673 +triton/tools/compile.py,sha256=CP_-yqEd55ejkc2_OYVE7q0Eyh9xErk8KJy2BcdCV0Y,7129 +triton/tools/disasm.py,sha256=BBO4bALdLcWgWDLhQdYHLlTx3oo8g_d8maeE_Uu-FmU,5088 +triton/tools/experimental_descriptor.py,sha256=0Wqy96Cc6YLh9o0eTknW-Lfvha6lfRSfe8bswkcPHMs,1260 +triton/tools/extra/cuda/compile.c,sha256=Me7beHPc6WNTwjg85H84DUMCRu4KJdVK2hNNgvlhBZ4,2126 +triton/tools/extra/cuda/compile.h,sha256=n9QKIFZTL4RSsiXtAxBP9XGSnxjyaevQQ9bBpwDsvAg,332 +triton/tools/link.py,sha256=u7qtfZRLriZkAMEGNvj8YF-k1cthmLL7BwHYqBgT63E,11871 +triton/tools/mxfp.py,sha256=YQdpBrGkOVNOtnLeRjMCeVFHWkSwUubGeWsItIjO8TU,11737 diff --git a/shared/package-files/bc/bc7a15433098630d4cd49985e810c3d6e82df5b1b745341b29f8a9872fe4d037/test_kane3.cpython-311.pyc b/shared/package-files/bc/bc7a15433098630d4cd49985e810c3d6e82df5b1b745341b29f8a9872fe4d037/test_kane3.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f79703d00af3b9b7374f181e993db51a5364c7fc Binary files /dev/null and b/shared/package-files/bc/bc7a15433098630d4cd49985e810c3d6e82df5b1b745341b29f8a9872fe4d037/test_kane3.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc7b31d9367c15b26e951a0a54e49f78e9055439600d3a365aeafb68763d1318/__init__.cpython-311.pyc b/shared/package-files/bc/bc7b31d9367c15b26e951a0a54e49f78e9055439600d3a365aeafb68763d1318/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bb06f160306d062518e70d96cf476bb7ed6de03 Binary files /dev/null and b/shared/package-files/bc/bc7b31d9367c15b26e951a0a54e49f78e9055439600d3a365aeafb68763d1318/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc8993e7e1025e4436d6828bd17605893a8ae8dc8cd3d729cc136803fdf80905/version.py b/shared/package-files/bc/bc8993e7e1025e4436d6828bd17605893a8ae8dc8cd3d729cc136803fdf80905/version.py new file mode 100644 index 0000000000000000000000000000000000000000..2223ee9c8cab2495034a57d4585625feb81a8330 --- /dev/null +++ b/shared/package-files/bc/bc8993e7e1025e4436d6828bd17605893a8ae8dc8cd3d729cc136803fdf80905/version.py @@ -0,0 +1,348 @@ +# +# distutils/version.py +# +# Implements multiple version numbering conventions for the +# Python Module Distribution Utilities. +# +# $Id$ +# + +"""Provides classes to represent module version numbers (one class for +each style of version numbering). There are currently two such classes +implemented: StrictVersion and LooseVersion. + +Every version number class implements the following interface: + * the 'parse' method takes a string and parses it to some internal + representation; if the string is an invalid version number, + 'parse' raises a ValueError exception + * the class constructor takes an optional string argument which, + if supplied, is passed to 'parse' + * __str__ reconstructs the string that was passed to 'parse' (or + an equivalent string -- ie. one that will generate an equivalent + version number instance) + * __repr__ generates Python code to recreate the version number instance + * _cmp compares the current instance with either another instance + of the same class or a string (which will be parsed to an instance + of the same class, thus must follow the same rules) +""" + +import contextlib +import re +import warnings + + +@contextlib.contextmanager +def suppress_known_deprecation(): + with warnings.catch_warnings(record=True) as ctx: + warnings.filterwarnings( + action='default', + category=DeprecationWarning, + message="distutils Version classes are deprecated.", + ) + yield ctx + + +class Version: + """Abstract base class for version numbering classes. Just provides + constructor (__init__) and reproducer (__repr__), because those + seem to be the same for all version numbering classes; and route + rich comparisons to _cmp. + """ + + def __init__(self, vstring=None): + if vstring: + self.parse(vstring) + warnings.warn( + "distutils Version classes are deprecated. Use packaging.version instead.", + DeprecationWarning, + stacklevel=2, + ) + + def __repr__(self): + return f"{self.__class__.__name__} ('{self}')" + + def __eq__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c == 0 + + def __lt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c < 0 + + def __le__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c <= 0 + + def __gt__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c > 0 + + def __ge__(self, other): + c = self._cmp(other) + if c is NotImplemented: + return c + return c >= 0 + + +# Interface for version-number classes -- must be implemented +# by the following classes (the concrete ones -- Version should +# be treated as an abstract class). +# __init__ (string) - create and take same action as 'parse' +# (string parameter is optional) +# parse (string) - convert a string representation to whatever +# internal representation is appropriate for +# this style of version numbering +# __str__ (self) - convert back to a string; should be very similar +# (if not identical to) the string supplied to parse +# __repr__ (self) - generate Python code to recreate +# the instance +# _cmp (self, other) - compare two version numbers ('other' may +# be an unparsed version string, or another +# instance of your version class) + + +class StrictVersion(Version): + """Version numbering for anal retentives and software idealists. + Implements the standard interface for version number classes as + described above. A version number consists of two or three + dot-separated numeric components, with an optional "pre-release" tag + on the end. The pre-release tag consists of the letter 'a' or 'b' + followed by a number. If the numeric components of two version + numbers are equal, then one with a pre-release tag will always + be deemed earlier (lesser) than one without. + + The following are valid version numbers (shown in the order that + would be obtained by sorting according to the supplied cmp function): + + 0.4 0.4.0 (these two are equivalent) + 0.4.1 + 0.5a1 + 0.5b3 + 0.5 + 0.9.6 + 1.0 + 1.0.4a3 + 1.0.4b1 + 1.0.4 + + The following are examples of invalid version numbers: + + 1 + 2.7.2.2 + 1.3.a4 + 1.3pl1 + 1.3c4 + + The rationale for this version numbering system will be explained + in the distutils documentation. + """ + + version_re = re.compile( + r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII + ) + + def parse(self, vstring): + match = self.version_re.match(vstring) + if not match: + raise ValueError(f"invalid version number '{vstring}'") + + (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6) + + if patch: + self.version = tuple(map(int, [major, minor, patch])) + else: + self.version = tuple(map(int, [major, minor])) + (0,) + + if prerelease: + self.prerelease = (prerelease[0], int(prerelease_num)) + else: + self.prerelease = None + + def __str__(self): + if self.version[2] == 0: + vstring = '.'.join(map(str, self.version[0:2])) + else: + vstring = '.'.join(map(str, self.version)) + + if self.prerelease: + vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) + + return vstring + + def _cmp(self, other): + if isinstance(other, str): + with suppress_known_deprecation(): + other = StrictVersion(other) + elif not isinstance(other, StrictVersion): + return NotImplemented + + if self.version == other.version: + # versions match; pre-release drives the comparison + return self._cmp_prerelease(other) + + return -1 if self.version < other.version else 1 + + def _cmp_prerelease(self, other): + """ + case 1: self has prerelease, other doesn't; other is greater + case 2: self doesn't have prerelease, other does: self is greater + case 3: both or neither have prerelease: compare them! + """ + if self.prerelease and not other.prerelease: + return -1 + elif not self.prerelease and other.prerelease: + return 1 + + if self.prerelease == other.prerelease: + return 0 + elif self.prerelease < other.prerelease: + return -1 + else: + return 1 + + +# end class StrictVersion + + +# The rules according to Greg Stein: +# 1) a version number has 1 or more numbers separated by a period or by +# sequences of letters. If only periods, then these are compared +# left-to-right to determine an ordering. +# 2) sequences of letters are part of the tuple for comparison and are +# compared lexicographically +# 3) recognize the numeric components may have leading zeroes +# +# The LooseVersion class below implements these rules: a version number +# string is split up into a tuple of integer and string components, and +# comparison is a simple tuple comparison. This means that version +# numbers behave in a predictable and obvious way, but a way that might +# not necessarily be how people *want* version numbers to behave. There +# wouldn't be a problem if people could stick to purely numeric version +# numbers: just split on period and compare the numbers as tuples. +# However, people insist on putting letters into their version numbers; +# the most common purpose seems to be: +# - indicating a "pre-release" version +# ('alpha', 'beta', 'a', 'b', 'pre', 'p') +# - indicating a post-release patch ('p', 'pl', 'patch') +# but of course this can't cover all version number schemes, and there's +# no way to know what a programmer means without asking him. +# +# The problem is what to do with letters (and other non-numeric +# characters) in a version number. The current implementation does the +# obvious and predictable thing: keep them as strings and compare +# lexically within a tuple comparison. This has the desired effect if +# an appended letter sequence implies something "post-release": +# eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002". +# +# However, if letters in a version number imply a pre-release version, +# the "obvious" thing isn't correct. Eg. you would expect that +# "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison +# implemented here, this just isn't so. +# +# Two possible solutions come to mind. The first is to tie the +# comparison algorithm to a particular set of semantic rules, as has +# been done in the StrictVersion class above. This works great as long +# as everyone can go along with bondage and discipline. Hopefully a +# (large) subset of Python module programmers will agree that the +# particular flavour of bondage and discipline provided by StrictVersion +# provides enough benefit to be worth using, and will submit their +# version numbering scheme to its domination. The free-thinking +# anarchists in the lot will never give in, though, and something needs +# to be done to accommodate them. +# +# Perhaps a "moderately strict" version class could be implemented that +# lets almost anything slide (syntactically), and makes some heuristic +# assumptions about non-digits in version number strings. This could +# sink into special-case-hell, though; if I was as talented and +# idiosyncratic as Larry Wall, I'd go ahead and implement a class that +# somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is +# just as happy dealing with things like "2g6" and "1.13++". I don't +# think I'm smart enough to do it right though. +# +# In any case, I've coded the test suite for this module (see +# ../test/test_version.py) specifically to fail on things like comparing +# "1.2a2" and "1.2". That's not because the *code* is doing anything +# wrong, it's because the simple, obvious design doesn't match my +# complicated, hairy expectations for real-world version numbers. It +# would be a snap to fix the test suite to say, "Yep, LooseVersion does +# the Right Thing" (ie. the code matches the conception). But I'd rather +# have a conception that matches common notions about version numbers. + + +class LooseVersion(Version): + """Version numbering for anarchists and software realists. + Implements the standard interface for version number classes as + described above. A version number consists of a series of numbers, + separated by either periods or strings of letters. When comparing + version numbers, the numeric components will be compared + numerically, and the alphabetic components lexically. The following + are all valid version numbers, in no particular order: + + 1.5.1 + 1.5.2b2 + 161 + 3.10a + 8.02 + 3.4j + 1996.07.12 + 3.2.pl0 + 3.1.1.6 + 2g6 + 11g + 0.960923 + 2.2beta29 + 1.13++ + 5.5.kw + 2.0b1pl0 + + In fact, there is no such thing as an invalid version number under + this scheme; the rules for comparison are simple and predictable, + but may not always give the results you want (for some definition + of "want"). + """ + + component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) + + def parse(self, vstring): + # I've given up on thinking I can reconstruct the version string + # from the parsed tuple -- so I just store the string here for + # use by __str__ + self.vstring = vstring + components = [x for x in self.component_re.split(vstring) if x and x != '.'] + for i, obj in enumerate(components): + try: + components[i] = int(obj) + except ValueError: + pass + + self.version = components + + def __str__(self): + return self.vstring + + def __repr__(self): + return f"LooseVersion ('{self}')" + + def _cmp(self, other): + if isinstance(other, str): + other = LooseVersion(other) + elif not isinstance(other, LooseVersion): + return NotImplemented + + if self.version == other.version: + return 0 + if self.version < other.version: + return -1 + if self.version > other.version: + return 1 + + +# end class LooseVersion diff --git a/shared/package-files/bc/bc8eb56422e8580cf0614e215340094bc3ab8bcbc05843f3143094a229685519/test_mincost.py b/shared/package-files/bc/bc8eb56422e8580cf0614e215340094bc3ab8bcbc05843f3143094a229685519/test_mincost.py new file mode 100644 index 0000000000000000000000000000000000000000..edc6262213300b3853419b2604e49722c418934a --- /dev/null +++ b/shared/package-files/bc/bc8eb56422e8580cf0614e215340094bc3ab8bcbc05843f3143094a229685519/test_mincost.py @@ -0,0 +1,475 @@ +import bz2 +import importlib.resources +import pickle + +import pytest + +import networkx as nx + + +class TestMinCostFlow: + def test_simple_digraph(self): + G = nx.DiGraph() + G.add_node("a", demand=-5) + G.add_node("d", demand=5) + G.add_edge("a", "b", weight=3, capacity=4) + G.add_edge("a", "c", weight=6, capacity=10) + G.add_edge("b", "d", weight=1, capacity=9) + G.add_edge("c", "d", weight=2, capacity=5) + flowCost, H = nx.network_simplex(G) + soln = {"a": {"b": 4, "c": 1}, "b": {"d": 4}, "c": {"d": 1}, "d": {}} + assert flowCost == 24 + assert nx.min_cost_flow_cost(G) == 24 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 24 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 24 + assert nx.cost_of_flow(G, H) == 24 + assert H == soln + + def test_negcycle_infcap(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=5) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("c", "a", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("d", "c", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + + def test_sum_demands_not_zero(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=4) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("a", "c", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("c", "d", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_no_flow_satisfying_demands(self): + G = nx.DiGraph() + G.add_node("s", demand=-5) + G.add_node("t", demand=5) + G.add_edge("s", "a", weight=1, capacity=3) + G.add_edge("a", "b", weight=3) + G.add_edge("a", "c", weight=-6) + G.add_edge("b", "d", weight=1) + G.add_edge("c", "d", weight=-2) + G.add_edge("d", "t", weight=1, capacity=3) + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_transshipment(self): + G = nx.DiGraph() + G.add_node("a", demand=1) + G.add_node("b", demand=-2) + G.add_node("c", demand=-2) + G.add_node("d", demand=3) + G.add_node("e", demand=-4) + G.add_node("f", demand=-4) + G.add_node("g", demand=3) + G.add_node("h", demand=2) + G.add_node("r", demand=3) + G.add_edge("a", "c", weight=3) + G.add_edge("r", "a", weight=2) + G.add_edge("b", "a", weight=9) + G.add_edge("r", "c", weight=0) + G.add_edge("b", "r", weight=-6) + G.add_edge("c", "d", weight=5) + G.add_edge("e", "r", weight=4) + G.add_edge("e", "f", weight=3) + G.add_edge("h", "b", weight=4) + G.add_edge("f", "d", weight=7) + G.add_edge("f", "h", weight=12) + G.add_edge("g", "d", weight=12) + G.add_edge("f", "g", weight=-1) + G.add_edge("h", "g", weight=-10) + flowCost, H = nx.network_simplex(G) + soln = { + "a": {"c": 0}, + "b": {"a": 0, "r": 2}, + "c": {"d": 3}, + "d": {}, + "e": {"r": 3, "f": 1}, + "f": {"d": 0, "g": 3, "h": 2}, + "g": {"d": 0}, + "h": {"b": 0, "g": 0}, + "r": {"a": 1, "c": 1}, + } + assert flowCost == 41 + assert nx.min_cost_flow_cost(G) == 41 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 41 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 41 + assert nx.cost_of_flow(G, H) == 41 + assert H == soln + + def test_max_flow_min_cost(self): + G = nx.DiGraph() + G.add_edge("s", "a", bandwidth=6) + G.add_edge("s", "c", bandwidth=10, cost=10) + G.add_edge("a", "b", cost=6) + G.add_edge("b", "d", bandwidth=8, cost=7) + G.add_edge("c", "d", cost=10) + G.add_edge("d", "t", bandwidth=5, cost=5) + soln = { + "s": {"a": 5, "c": 0}, + "a": {"b": 5}, + "b": {"d": 5}, + "c": {"d": 0}, + "d": {"t": 5}, + "t": {}, + } + flow = nx.max_flow_min_cost(G, "s", "t", capacity="bandwidth", weight="cost") + assert flow == soln + assert nx.cost_of_flow(G, flow, weight="cost") == 90 + + G.add_edge("t", "s", cost=-100) + flowCost, flow = nx.capacity_scaling(G, capacity="bandwidth", weight="cost") + G.remove_edge("t", "s") + assert flowCost == -410 + assert flow["t"]["s"] == 5 + del flow["t"]["s"] + assert flow == soln + assert nx.cost_of_flow(G, flow, weight="cost") == 90 + + def test_digraph1(self): + # From Bradley, S. P., Hax, A. C. and Magnanti, T. L. Applied + # Mathematical Programming. Addison-Wesley, 1977. + G = nx.DiGraph() + G.add_node(1, demand=-20) + G.add_node(4, demand=5) + G.add_node(5, demand=15) + G.add_edges_from( + [ + (1, 2, {"capacity": 15, "weight": 4}), + (1, 3, {"capacity": 8, "weight": 4}), + (2, 3, {"weight": 2}), + (2, 4, {"capacity": 4, "weight": 2}), + (2, 5, {"capacity": 10, "weight": 6}), + (3, 4, {"capacity": 15, "weight": 1}), + (3, 5, {"capacity": 5, "weight": 3}), + (4, 5, {"weight": 2}), + (5, 3, {"capacity": 4, "weight": 1}), + ] + ) + flowCost, H = nx.network_simplex(G) + soln = { + 1: {2: 12, 3: 8}, + 2: {3: 8, 4: 4, 5: 0}, + 3: {4: 11, 5: 5}, + 4: {5: 10}, + 5: {3: 0}, + } + assert flowCost == 150 + assert nx.min_cost_flow_cost(G) == 150 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 150 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 150 + assert H == soln + assert nx.cost_of_flow(G, H) == 150 + + def test_digraph2(self): + # Example from ticket #430 from mfrasca. Original source: + # http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/mincost.4up.pdf, slide 11. + G = nx.DiGraph() + G.add_edge("s", 1, capacity=12) + G.add_edge("s", 2, capacity=6) + G.add_edge("s", 3, capacity=14) + G.add_edge(1, 2, capacity=11, weight=4) + G.add_edge(2, 3, capacity=9, weight=6) + G.add_edge(1, 4, capacity=5, weight=5) + G.add_edge(1, 5, capacity=2, weight=12) + G.add_edge(2, 5, capacity=4, weight=4) + G.add_edge(2, 6, capacity=2, weight=6) + G.add_edge(3, 6, capacity=31, weight=3) + G.add_edge(4, 5, capacity=18, weight=4) + G.add_edge(5, 6, capacity=9, weight=5) + G.add_edge(4, "t", capacity=3) + G.add_edge(5, "t", capacity=7) + G.add_edge(6, "t", capacity=22) + flow = nx.max_flow_min_cost(G, "s", "t") + soln = { + 1: {2: 6, 4: 5, 5: 1}, + 2: {3: 6, 5: 4, 6: 2}, + 3: {6: 20}, + 4: {5: 2, "t": 3}, + 5: {6: 0, "t": 7}, + 6: {"t": 22}, + "s": {1: 12, 2: 6, 3: 14}, + "t": {}, + } + assert flow == soln + + G.add_edge("t", "s", weight=-100) + flowCost, flow = nx.capacity_scaling(G) + G.remove_edge("t", "s") + assert flow["t"]["s"] == 32 + assert flowCost == -3007 + del flow["t"]["s"] + assert flow == soln + assert nx.cost_of_flow(G, flow) == 193 + + def test_digraph3(self): + """Combinatorial Optimization: Algorithms and Complexity, + Papadimitriou Steiglitz at page 140 has an example, 7.1, but that + admits multiple solutions, so I alter it a bit. From ticket #430 + by mfrasca.""" + + G = nx.DiGraph() + G.add_edge("s", "a") + G["s"]["a"].update({0: 2, 1: 4}) + G.add_edge("s", "b") + G["s"]["b"].update({0: 2, 1: 1}) + G.add_edge("a", "b") + G["a"]["b"].update({0: 5, 1: 2}) + G.add_edge("a", "t") + G["a"]["t"].update({0: 1, 1: 5}) + G.add_edge("b", "a") + G["b"]["a"].update({0: 1, 1: 3}) + G.add_edge("b", "t") + G["b"]["t"].update({0: 3, 1: 2}) + + "PS.ex.7.1: testing main function" + sol = nx.max_flow_min_cost(G, "s", "t", capacity=0, weight=1) + flow = sum(v for v in sol["s"].values()) + assert 4 == flow + assert 23 == nx.cost_of_flow(G, sol, weight=1) + assert sol["s"] == {"a": 2, "b": 2} + assert sol["a"] == {"b": 1, "t": 1} + assert sol["b"] == {"a": 0, "t": 3} + assert sol["t"] == {} + + G.add_edge("t", "s") + G["t"]["s"].update({1: -100}) + flowCost, sol = nx.capacity_scaling(G, capacity=0, weight=1) + G.remove_edge("t", "s") + flow = sum(v for v in sol["s"].values()) + assert 4 == flow + assert sol["t"]["s"] == 4 + assert flowCost == -377 + del sol["t"]["s"] + assert sol["s"] == {"a": 2, "b": 2} + assert sol["a"] == {"b": 1, "t": 1} + assert sol["b"] == {"a": 0, "t": 3} + assert sol["t"] == {} + assert nx.cost_of_flow(G, sol, weight=1) == 23 + + def test_zero_capacity_edges(self): + """Address issue raised in ticket #617 by arv.""" + G = nx.DiGraph() + G.add_edges_from( + [ + (1, 2, {"capacity": 1, "weight": 1}), + (1, 5, {"capacity": 1, "weight": 1}), + (2, 3, {"capacity": 0, "weight": 1}), + (2, 5, {"capacity": 1, "weight": 1}), + (5, 3, {"capacity": 2, "weight": 1}), + (5, 4, {"capacity": 0, "weight": 1}), + (3, 4, {"capacity": 2, "weight": 1}), + ] + ) + G.nodes[1]["demand"] = -1 + G.nodes[2]["demand"] = -1 + G.nodes[4]["demand"] = 2 + + flowCost, H = nx.network_simplex(G) + soln = {1: {2: 0, 5: 1}, 2: {3: 0, 5: 1}, 3: {4: 2}, 4: {}, 5: {3: 2, 4: 0}} + assert flowCost == 6 + assert nx.min_cost_flow_cost(G) == 6 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 6 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 6 + assert H == soln + assert nx.cost_of_flow(G, H) == 6 + + def test_digon(self): + """Check if digons are handled properly. Taken from ticket + #618 by arv.""" + nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})] + edges = [ + (1, 2, {"capacity": 3, "weight": 600000}), + (2, 1, {"capacity": 2, "weight": 0}), + (2, 3, {"capacity": 5, "weight": 714285}), + (3, 2, {"capacity": 2, "weight": 0}), + ] + G = nx.DiGraph(edges) + G.add_nodes_from(nodes) + flowCost, H = nx.network_simplex(G) + soln = {1: {2: 0}, 2: {1: 0, 3: 4}, 3: {2: 0}} + assert flowCost == 2857140 + assert nx.min_cost_flow_cost(G) == 2857140 + assert H == soln + assert nx.min_cost_flow(G) == soln + assert nx.cost_of_flow(G, H) == 2857140 + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 2857140 + assert H == soln + assert nx.cost_of_flow(G, H) == 2857140 + + def test_deadend(self): + """Check if one-node cycles are handled properly. Taken from ticket + #2906 from @sshraven.""" + G = nx.DiGraph() + + G.add_nodes_from(range(5), demand=0) + G.nodes[4]["demand"] = -13 + G.nodes[3]["demand"] = 13 + + G.add_edges_from([(0, 2), (0, 3), (2, 1)], capacity=20, weight=0.1) + pytest.raises(nx.NetworkXUnfeasible, nx.min_cost_flow, G) + + def test_infinite_capacity_neg_digon(self): + """An infinite capacity negative cost digon results in an unbounded + instance.""" + nodes = [(1, {}), (2, {"demand": -4}), (3, {"demand": 4})] + edges = [ + (1, 2, {"weight": -600}), + (2, 1, {"weight": 0}), + (2, 3, {"capacity": 5, "weight": 714285}), + (3, 2, {"capacity": 2, "weight": 0}), + ] + G = nx.DiGraph(edges) + G.add_nodes_from(nodes) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + + def test_finite_capacity_neg_digon(self): + """The digon should receive the maximum amount of flow it can handle. + Taken from ticket #749 by @chuongdo.""" + G = nx.DiGraph() + G.add_edge("a", "b", capacity=1, weight=-1) + G.add_edge("b", "a", capacity=1, weight=-1) + min_cost = -2 + assert nx.min_cost_flow_cost(G) == min_cost + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {"a": {"b": 1}, "b": {"a": 1}} + assert nx.cost_of_flow(G, H) == -2 + + def test_multidigraph(self): + """Multidigraphs are acceptable.""" + G = nx.MultiDiGraph() + G.add_weighted_edges_from([(1, 2, 1), (2, 3, 2)], weight="capacity") + flowCost, H = nx.network_simplex(G) + assert flowCost == 0 + assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}} + + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 0 + assert H == {1: {2: {0: 0}}, 2: {3: {0: 0}}, 3: {}} + + def test_negative_selfloops(self): + """Negative selfloops should cause an exception if uncapacitated and + always be saturated otherwise. + """ + G = nx.DiGraph() + G.add_edge(1, 1, weight=-1) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + G[1][1]["capacity"] = 2 + flowCost, H = nx.network_simplex(G) + assert flowCost == -2 + assert H == {1: {1: 2}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {1: {1: 2}} + + G = nx.MultiDiGraph() + G.add_edge(1, 1, "x", weight=-1) + G.add_edge(1, 1, "y", weight=1) + pytest.raises(nx.NetworkXUnbounded, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnbounded, nx.capacity_scaling, G) + G[1][1]["x"]["capacity"] = 2 + flowCost, H = nx.network_simplex(G) + assert flowCost == -2 + assert H == {1: {1: {"x": 2, "y": 0}}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == -2 + assert H == {1: {1: {"x": 2, "y": 0}}} + + def test_bone_shaped(self): + # From #1283 + G = nx.DiGraph() + G.add_node(0, demand=-4) + G.add_node(1, demand=2) + G.add_node(2, demand=2) + G.add_node(3, demand=4) + G.add_node(4, demand=-2) + G.add_node(5, demand=-2) + G.add_edge(0, 1, capacity=4) + G.add_edge(0, 2, capacity=4) + G.add_edge(4, 3, capacity=4) + G.add_edge(5, 3, capacity=4) + G.add_edge(0, 3, capacity=0) + flowCost, H = nx.network_simplex(G) + assert flowCost == 0 + assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}} + flowCost, H = nx.capacity_scaling(G) + assert flowCost == 0 + assert H == {0: {1: 2, 2: 2, 3: 0}, 1: {}, 2: {}, 3: {}, 4: {3: 2}, 5: {3: 2}} + + def test_exceptions(self): + G = nx.Graph() + pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G) + pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G) + G = nx.MultiGraph() + pytest.raises(nx.NetworkXNotImplemented, nx.network_simplex, G) + pytest.raises(nx.NetworkXNotImplemented, nx.capacity_scaling, G) + G = nx.DiGraph() + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + # pytest.raises(nx.NetworkXError, nx.capacity_scaling, G) + G.add_node(0, demand=float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G.nodes[0]["demand"] = 0 + G.add_node(1, demand=0) + G.add_edge(0, 1, weight=-float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G[0][1]["weight"] = 0 + G.add_edge(0, 0, weight=float("inf")) + pytest.raises(nx.NetworkXError, nx.network_simplex, G) + # pytest.raises(nx.NetworkXError, nx.capacity_scaling, G) + G[0][0]["weight"] = 0 + G[0][1]["capacity"] = -1 + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + # pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + G[0][1]["capacity"] = 0 + G[0][0]["capacity"] = -1 + pytest.raises(nx.NetworkXUnfeasible, nx.network_simplex, G) + # pytest.raises(nx.NetworkXUnfeasible, nx.capacity_scaling, G) + + def test_large(self): + fname = ( + importlib.resources.files("networkx.algorithms.flow.tests") + / "netgen-2.gpickle.bz2" + ) + with bz2.BZ2File(fname, "rb") as f: + G = pickle.load(f) + flowCost, flowDict = nx.network_simplex(G) + assert 6749969302 == flowCost + assert 6749969302 == nx.cost_of_flow(G, flowDict) + flowCost, flowDict = nx.capacity_scaling(G) + assert 6749969302 == flowCost + assert 6749969302 == nx.cost_of_flow(G, flowDict) diff --git a/shared/package-files/bc/bc8f44b8231dd4f31835b647d9b1d6f711cf612e434bdd903a6024d640b5d9c4/test_secondquant.py b/shared/package-files/bc/bc8f44b8231dd4f31835b647d9b1d6f711cf612e434bdd903a6024d640b5d9c4/test_secondquant.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f60fab05497aead65ad748460802c9c29740ce --- /dev/null +++ b/shared/package-files/bc/bc8f44b8231dd4f31835b647d9b1d6f711cf612e434bdd903a6024d640b5d9c4/test_secondquant.py @@ -0,0 +1,1301 @@ +from sympy.functions.elementary.complexes import conjugate +from sympy.functions.elementary.exponential import exp +from sympy.physics.secondquant import ( + Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis, + matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta, + AnnihilateBoson, CreateBoson, BosonicOperator, + F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion, + evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks, + PermutationOperator, simplify_index_permutations, + _sort_anticommuting_fermions, _get_ordered_dummies, + substitute_dummies, FockStateBosonKet, + ContractionAppliesOnlyToFermions +) + +from sympy.concrete.summations import Sum +from sympy.core.function import (Function, expand) +from sympy.core.numbers import (I, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.printing.repr import srepr +from sympy.simplify.simplify import simplify + +from sympy.testing.pytest import slow, raises +from sympy.printing.latex import latex + + +def test_PermutationOperator(): + p, q, r, s = symbols('p,q,r,s') + f, g, h, i = map(Function, 'fghi') + P = PermutationOperator + assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p) + assert P(p, q).get_permuted(f(p, q)) == -f(q, p) + assert P(p, q).get_permuted(f(p)) == f(p) + expr = (f(p)*g(q)*h(r)*i(s) + - f(q)*g(p)*h(r)*i(s) + - f(p)*g(q)*h(s)*i(r) + + f(q)*g(p)*h(s)*i(r)) + perms = [P(p, q), P(r, s)] + assert (simplify_index_permutations(expr, perms) == + P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s)) + assert latex(P(p, q)) == 'P(pq)' + + p1, p2 = symbols('p1,p2') + assert latex(P(p1,p2) == 'P(p_{1}p_{2})') + +def test_index_permutations_with_dummies(): + a, b, c, d = symbols('a b c d') + p, q, r, s = symbols('p q r s', cls=Dummy) + f, g = map(Function, 'fg') + P = PermutationOperator + + # No dummy substitution necessary + expr = f(a, b, p, q) - f(b, a, p, q) + assert simplify_index_permutations( + expr, [P(a, b)]) == P(a, b)*f(a, b, p, q) + + # Cases where dummy substitution is needed + expected = P(a, b)*substitute_dummies(f(a, b, p, q)) + + expr = f(a, b, p, q) - f(b, a, q, p) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + expr = f(a, b, q, p) - f(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + # A case where nothing can be done + expr = f(a, b, q, p) - g(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expr == result + + +def test_dagger(): + i, j, n, m = symbols('i,j,n,m') + assert Dagger(1) == 1 + assert Dagger(1.0) == 1.0 + assert Dagger(2*I) == -2*I + assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0 + assert Dagger(BKet([n])) == BBra([n]) + assert Dagger(B(0)) == Bd(0) + assert Dagger(Bd(0)) == B(0) + assert Dagger(B(n)) == Bd(n) + assert Dagger(Bd(n)) == B(n) + assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1) + assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute + assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n) + assert Dagger(B(n)**10) == Dagger(B(n))**10 + assert Dagger('a') == Dagger(Symbol('a')) + assert Dagger(Dagger('a')) == Symbol('a') + assert Dagger(exp(2 * I)) == exp(-2 * I) + assert Dagger(i) == conjugate(i) + + +def test_operator(): + i, j = symbols('i,j') + o = BosonicOperator(i) + assert o.state == i + assert o.is_symbolic + o = BosonicOperator(1) + assert o.state == 1 + assert not o.is_symbolic + + +def test_create(): + i, j, n, m, p1 = symbols('i,j,n,m,p1') + o = Bd(i) + assert latex(o) == "{b^\\dagger_{i}}" + assert latex(Bd(p1)) == "{b^\\dagger_{p_{1}}}" + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate(): + i, j, n, m, p1 = symbols('i,j,n,m,p1') + o = B(i) + assert latex(o) == "b_{i}" + assert latex(B(p1)) == "b_{p_{1}}" + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1]) + o = B(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_basic_state(): + i, j, n, m = symbols('i,j,n,m') + s = BosonState([0, 1, 2, 3, 4]) + assert len(s) == 5 + assert s.args[0] == tuple(range(5)) + assert s.up(0) == BosonState([1, 1, 2, 3, 4]) + assert s.down(4) == BosonState([0, 1, 2, 3, 3]) + for i in range(5): + assert s.up(i).down(i) == s + assert s.down(0) == 0 + for i in range(5): + assert s[i] == i + s = BosonState([n, m]) + assert s.down(0) == BosonState([n - 1, m]) + assert s.up(0) == BosonState([n + 1, m]) + + +def test_basic_apply(): + n = symbols("n") + e = B(0)*BKet([n]) + assert apply_operators(e) == sqrt(n)*BKet([n - 1]) + e = Bd(0)*BKet([n]) + assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1]) + + +def test_complex_apply(): + n, m = symbols("n,m") + o = Bd(0)*B(0)*Bd(1)*B(0) + e = apply_operators(o*BKet([n, m])) + answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m]) + assert expand(e) == expand(answer) + + +def test_number_operator(): + n = symbols("n") + o = Bd(0)*B(0) + e = apply_operators(o*BKet([n])) + assert e == n*BKet([n]) + + +def test_inner_product(): + i, j, k, l = symbols('i,j,k,l') + s1 = BBra([0]) + s2 = BKet([1]) + assert InnerProduct(s1, Dagger(s1)) == 1 + assert InnerProduct(s1, s2) == 0 + s1 = BBra([i, j]) + s2 = BKet([k, l]) + r = InnerProduct(s1, s2) + assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l) + + +def test_symbolic_matrix_elements(): + n, m = symbols('n,m') + s1 = BBra([n]) + s2 = BKet([m]) + o = B(0) + e = apply_operators(s1*o*s2) + assert e == sqrt(m)*KroneckerDelta(n, m - 1) + + +def test_matrix_elements(): + b = VarBosonicBasis(5) + o = B(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i, i + 1] == sqrt(i + 1) + o = Bd(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i + 1, i] == sqrt(i + 1) + + +def test_fixed_bosonic_basis(): + b = FixedBosonicBasis(2, 2) + # assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))] + state = b.state(1) + assert state == FockStateBosonKet((1, 1)) + assert b.index(state) == 1 + assert b.state(1) == b[1] + assert len(b) == 3 + assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + + +@slow +def test_sho(): + n, m = symbols('n,m') + h_n = Bd(n)*B(n)*(n + S.Half) + H = Sum(h_n, (n, 0, 5)) + o = H.doit(deep=False) + b = FixedBosonicBasis(2, 6) + m = matrix_rep(o, b) + # We need to double check these energy values to make sure that they + # are correct and have the proper degeneracies! + diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11] + for i in range(len(diag)): + assert diag[i] == m[i, i] + + +def test_commutation(): + n, m = symbols("n,m", above_fermi=True) + c = Commutator(B(0), Bd(0)) + assert c == 1 + c = Commutator(Bd(0), B(0)) + assert c == -1 + c = Commutator(B(n), Bd(0)) + assert c == KroneckerDelta(n, 0) + c = Commutator(B(0), B(0)) + assert c == 0 + c = Commutator(B(0), Bd(0)) + e = simplify(apply_operators(c*BKet([n]))) + assert e == BKet([n]) + c = Commutator(B(0), B(1)) + e = simplify(apply_operators(c*BKet([n, m]))) + assert e == 0 + + c = Commutator(F(m), Fd(m)) + assert c == +1 - 2*NO(Fd(m)*F(m)) + c = Commutator(Fd(m), F(m)) + assert c.expand() == -1 + 2*NO(Fd(m)*F(m)) + + C = Commutator + X, Y, Z = symbols('X,Y,Z', commutative=False) + assert C(C(X, Y), Z) != 0 + assert C(C(X, Z), Y) != 0 + assert C(Y, C(X, Z)) != 0 + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + D = KroneckerDelta + + assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a)) + assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a) + assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0 + + c1 = Commutator(F(a), Fd(a)) + assert Commutator.eval(c1, c1) == 0 + c = Commutator(Fd(a)*F(i),Fd(b)*F(j)) + assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]' + assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))' + assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]' + + +def test_create_f(): + i, j, n, m = symbols('i,j,n,m') + o = Fd(i) + assert isinstance(o, CreateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Fd(1) + assert o.apply_operator(FKet([n])) == FKet([1, n]) + assert o.apply_operator(FKet([n])) == -FKet([n, 1]) + o = Fd(n) + assert o.apply_operator(FKet([])) == FKet([n]) + + vacuum = FKet([], fermi_level=4) + assert vacuum == FKet([], fermi_level=4) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + p1 = symbols("p1") + + assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4) + assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4) + + assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p) + assert repr(Fd(p)) == 'CreateFermion(p)' + assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))" + assert latex(Fd(p)) == r'{a^\dagger_{p}}' + assert latex(Fd(p1)) == r'{a^\dagger_{p_{1}}}' + assert latex(FKet([a,i], 1)) == r"\left|\left( a, \ i\right)\right\rangle" + assert latex(FKet([j,i,b,a], 2)) == r"\left|\left( a, \ b, \ i, \ j\right)\right\rangle" + + +def test_annihilate_f(): + i, j, n, m = symbols('i,j,n,m') + o = F(i) + assert isinstance(o, AnnihilateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = F(1) + assert o.apply_operator(FKet([1, n])) == FKet([n]) + assert o.apply_operator(FKet([n, 1])) == -FKet([n]) + o = F(n) + assert o.apply_operator(FKet([n])) == FKet([]) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + p1 = symbols('p1') + + assert F(i).apply_operator(FKet([i, j, k], 4)) == 0 + assert F(a).apply_operator(FKet([i, b, k], 4)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 3)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4) + assert str(F(p)) == 'f(p)' + assert repr(F(p)) == 'AnnihilateFermion(p)' + assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))" + assert latex(F(p)) == 'a_{p}' + assert latex(F(p1)) == 'a_{p_{1}}' + + +def test_create_b(): + i, j, n, m = symbols('i,j,n,m') + o = Bd(i) + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate_b(): + i, j, n, m = symbols('i,j,n,m') + o = B(i) + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + + +def test_wicks(): + p, q, r, s = symbols('p,q,r,s', above_fermi=True) + + # Testing for particles only + + str = F(p)*Fd(q) + assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q) + str = Fd(p)*F(q) + assert wicks(str) == NO(Fd(p)*F(q)) + + str = F(p)*Fd(q)*F(r)*Fd(s) + nstr = wicks(str) + fasit = NO( + KroneckerDelta(p, q)*KroneckerDelta(r, s) + + KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s) + + KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q) + - KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q) + - AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s)) + assert nstr == fasit + + assert (p*q*nstr).expand() == wicks(p*q*str) + assert (nstr*p*q*2).expand() == wicks(str*p*q*2) + + # Testing CC equations particles and holes + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) == + NO(F(a)*F(i)*F(j)*Fd(b)) + + KroneckerDelta(a, b)*NO(F(i)*F(j))) + assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) == + NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) - + KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k))) + + expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l)) + assert (expr == + -KroneckerDelta(i, k)*NO(Fd(j)*F(l)) - + KroneckerDelta(j, l)*NO(Fd(i)*F(k)) - + KroneckerDelta(i, k)*KroneckerDelta(j, l) + + KroneckerDelta(i, l)*NO(Fd(j)*F(k)) + + NO(Fd(i)*Fd(j)*F(k)*F(l))) + expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d)) + assert (expr == + -KroneckerDelta(a, c)*NO(F(b)*Fd(d)) - + KroneckerDelta(b, d)*NO(F(a)*Fd(c)) - + KroneckerDelta(a, c)*KroneckerDelta(b, d) + + KroneckerDelta(a, d)*NO(F(b)*Fd(c)) + + NO(F(a)*F(b)*Fd(c)*Fd(d))) + + +def test_NO(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) == + NO(Fd(p)*F(q)) + NO(Fd(a)*F(b))) + assert (NO(Fd(i)*NO(F(j)*Fd(a))) == + NO(Fd(i)*F(j)*Fd(a))) + assert NO(1) == 1 + assert NO(i) == i + assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) == + NO(Fd(a)*Fd(b)*F(c)) + + NO(Fd(a)*Fd(b)*F(d))) + + assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b) + assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i) + + assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) == + NO(Fd(a)*F(q)) + NO(Fd(i)*F(q))) + assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) == + NO(Fd(p)*F(a)) + NO(Fd(p)*F(i))) + + expr = NO(Fd(p)*F(q))._remove_brackets() + assert wicks(expr) == NO(expr) + + assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a)) + + no = NO(Fd(a)*F(i)*F(b)*Fd(j)) + l1 = list(no.iter_q_creators()) + assert l1 == [0, 1] + l2 = list(no.iter_q_annihilators()) + assert l2 == [3, 2] + no = NO(Fd(a)*Fd(i)) + assert no.has_q_creators == 1 + assert no.has_q_annihilators == -1 + assert str(no) == ':CreateFermion(a)*CreateFermion(i):' + assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))' + assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}' + raises(NotImplementedError, lambda: NO(Bd(p)*F(q))) + + +def test_sorting(): + i, j = symbols('i,j', below_fermi=True) + a, b = symbols('a,b', above_fermi=True) + p, q = symbols('p,q') + + # p, q + assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0) + assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1) + + # i, p + assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1) + assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1) + assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0) + + # a, p + assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0) + assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1) + assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1) + + # i, a + assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0) + assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1) + assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0) + + +def test_contraction(): + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j) + assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b) + assert contraction(F(a), Fd(i)) == 0 + assert contraction(Fd(a), F(i)) == 0 + assert contraction(F(i), Fd(a)) == 0 + assert contraction(Fd(i), F(a)) == 0 + assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p) + restr = evaluate_deltas(contraction(Fd(p), F(q))) + assert restr.is_only_below_fermi + restr = evaluate_deltas(contraction(F(p), Fd(q))) + assert restr.is_only_above_fermi + raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b))) + + +def test_evaluate_deltas(): + i, j, k = symbols('i,j,k') + + r = KroneckerDelta(i, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k) + + r = KroneckerDelta(1, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(1, k) + + r = KroneckerDelta(j, 2) * KroneckerDelta(k, j) + assert evaluate_deltas(r) == KroneckerDelta(2, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1) + assert evaluate_deltas(r) == 0 + + r = (KroneckerDelta(0, i) * KroneckerDelta(0, j) + * KroneckerDelta(1, j) * KroneckerDelta(1, j)) + assert evaluate_deltas(r) == 0 + + +def test_Tensors(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s') + + AT = AntiSymmetricTensor + assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j)) + assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i)) + assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i)) + assert AT('t', (a, a), (i, j)) == 0 + assert AT('t', (a, b), (i, i)) == 0 + assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j)) + assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j)) + + tabij = AT('t', (a, b), (i, j)) + assert tabij.has(a) + assert tabij.has(b) + assert tabij.has(i) + assert tabij.has(j) + assert tabij.subs(b, c) == AT('t', (a, c), (i, j)) + assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j)) + assert tabij.symbol == Symbol('t') + assert latex(tabij) == '{t^{ab}_{ij}}' + assert str(tabij) == 't((_a, _b),(_i, _j))' + + assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j)) + assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j)) + + a1, a2, a3, a4 = symbols('alpha1:5') + u_alpha1234 = AntiSymmetricTensor("u", (a1, a2), (a3, a4)) + + assert latex(u_alpha1234) == r'{u^{\alpha_{1}\alpha_{2}}_{\alpha_{3}\alpha_{4}}}' + assert str(u_alpha1234) == 'u((alpha1, alpha2),(alpha3, alpha4))' + + +def test_fully_contracted(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + Fock = (AntiSymmetricTensor('f', (p,), (q,))* + NO(Fd(p)*F(q))) + V = (AntiSymmetricTensor('v', (p, q), (r, s))* + NO(Fd(p)*Fd(q)*F(s)*F(r)))/4 + + Fai = wicks(NO(Fd(i)*F(a))*Fock, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Fai == AntiSymmetricTensor('f', (a,), (i,)) + Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j)) + + +def test_substitute_dummies_without_dummies(): + i, j = symbols('i,j') + assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2 + assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1 + + +def test_substitute_dummies_NO_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j)) + - att(j, i)*NO(Fd(j)*F(i))) == 0 + + +def test_substitute_dummies_SQ_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*Fd(i)*F(j) + - att(j, i)*Fd(j)*F(i)) == 0 + + +def test_substitute_dummies_new_indices(): + i, j = symbols('i j', below_fermi=True, cls=Dummy) + a, b = symbols('a b', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + f = Function('f') + assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0 + + +def test_substitute_dummies_substitution_order(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + f = Function('f') + from sympy.utilities.iterables import variations + for permut in variations([i, j, k, l], 4): + assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0 + + +def test_dummy_order_inner_outer_lines_VT1T1T1(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k), + v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l), + v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k), + v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + exprs = [ + # permut t <=> swapping external lines, not equivalent + # except if v has certain symmetries. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut v <=> swapping external lines, not equivalent + # except if v has certain symmetries. + # + # Note that in contrast to above, these permutations have identical + # dummy order. That is because the proximity to external indices + # has higher influence on the canonical dummy ordering than the + # position of a dummy on the factors. In fact, the terms here are + # similar in structure as the result of the dummy substitutions above. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut t and v <=> swapping internal lines, equivalent. + # Canonical dummy order is different, and a consistent + # substitution reveals the equivalence. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_get_subNO(): + p, q, r = symbols('p,q,r') + assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q)) + + +def test_equivalent_internal_lines_VT1T1(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ # permute v. Different dummy order. Not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, i)*t(b, j), + v(i, j, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(i, j, a, b)*t(b, i)*t(a, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, j)*t(b, i), + v(i, j, b, a)*t(b, i)*t(a, j), + v(j, i, b, a)*t(b, j)*t(a, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(ijcd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + # v(abcd)t(abij)t(jicd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(cdij) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + exprs = [ + # permute v. Same dummy order, not equivalent. + # + # This test show that the dummy order may not be sensitive to all + # index permutations. The following expressions have identical + # structure as the resulting terms from of the dummy substitutions + # in the test above. Here, all expressions have the same dummy + # order, so they cannot be simplified by means of dummy + # substitution. In order to simplify further, it is necessary to + # exploit symmetries in the objects, for instance if t or v is + # antisymmetric. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, i, j), + v(i, j, b, a)*t(a, b, i, j), + v(j, i, b, a)*t(a, b, i, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + v(i, j, a, b)*t(a, b, i, j), + v(i, j, a, b)*t(b, a, i, j), + v(i, j, a, b)*t(a, b, j, i), + v(i, j, a, b)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, j, i), + v(i, j, b, a)*t(b, a, i, j), + v(j, i, b, a)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_well_defined(): + aa, bb = symbols('a b', above_fermi=True) + k, l, m = symbols('k l m', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + + A = Function('A') + B = Function('B') + C = Function('C') + dums = _get_ordered_dummies + + # We go through all key components in the order of increasing priority, + # and consider only fully orderable expressions. Non-orderable expressions + # are tested elsewhere. + + # pos in first factor determines sort order + assert dums(A(k, l)*B(l, k)) == [k, l] + assert dums(A(l, k)*B(l, k)) == [l, k] + assert dums(A(k, l)*B(k, l)) == [k, l] + assert dums(A(l, k)*B(k, l)) == [l, k] + + # factors involving the index + assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m] + + # same, but with factor order determined by non-dummies + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + + # index range + assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p] + assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p] + assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p] + assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p] + assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p] + assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p] + assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p] + assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p] + assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p] + assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p] + assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p] + assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p] + + +def test_dummy_order_ambiguous(): + aa, bb = symbols('a b', above_fermi=True) + i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy) + a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy) + + A = Function('A') + B = Function('B') + + from sympy.utilities.iterables import variations + + # A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def atv(*args): + return AntiSymmetricTensor('v', args[:2], args[2:] ) + + +def att(*args): + if len(args) == 4: + return AntiSymmetricTensor('t', args[:2], args[2:] ) + elif len(args) == 2: + return AntiSymmetricTensor('t', (args[0],), (args[1],)) + + +def test_dummy_order_inner_outer_lines_VT1T1T1_AT(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k), + atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l), + atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k), + atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + # non-equivalent substitutions (change of sign) + exprs = [ + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == -substitute_dummies(permut) + + # equivalent substitutions + exprs = [ + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT1T1_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ # permute v. Different dummy order. Not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, i)*att(b, j), + atv(i, j, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(i, j, a, b)*att(b, i)*att(a, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, j)*att(b, i), + atv(i, j, b, a)*att(b, i)*att(a, j), + atv(j, i, b, a)*att(b, j)*att(a, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2_AT(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(ijcd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # atv(abcd)att(abij)att(jicd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(cdij) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ + # permute v. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, i, j), + atv(i, j, b, a)*att(a, b, i, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + atv(i, j, a, b)*att(a, b, i, j), + atv(i, j, a, b)*att(b, a, i, j), + atv(i, j, a, b)*att(a, b, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, j, i), + atv(i, j, b, a)*att(b, a, i, j), + atv(j, i, b, a)*att(b, a, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs_AT(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_issue_19661(): + a = Symbol('0') + assert latex(Commutator(Bd(a)**2, B(a)) + ) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]' + + +def test_canonical_ordering_AntiSymmetricTensor(): + v = symbols("v") + + c, d = symbols(('c','d'), above_fermi=True, + cls=Dummy) + k, l = symbols(('k','l'), below_fermi=True, + cls=Dummy) + + # formerly, the left gave either the left or the right + assert AntiSymmetricTensor(v, (k, l), (d, c) + ) == -AntiSymmetricTensor(v, (l, k), (d, c)) diff --git a/shared/package-files/bc/bc90ab822137e8190e88156dd967ff1b591f3adda3b51c70527cb6268b8120a9/sample.h b/shared/package-files/bc/bc90ab822137e8190e88156dd967ff1b591f3adda3b51c70527cb6268b8120a9/sample.h new file mode 100644 index 0000000000000000000000000000000000000000..8e8efa5b781a9f7807f262241a0f67e0bad5cde6 --- /dev/null +++ b/shared/package-files/bc/bc90ab822137e8190e88156dd967ff1b591f3adda3b51c70527cb6268b8120a9/sample.h @@ -0,0 +1,41 @@ +/* sample.h -- group data by sample. + + Copyright (C) 2010 Broad Institute. + + Author: Heng Li + +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. */ + +#ifndef BAM_SAMPLE_H +#define BAM_SAMPLE_H + +#include "htslib/kstring.h" + +typedef struct { + int n, m; + char **smpl; + void *rg2smid, *sm2id; +} bam_sample_t; + +bam_sample_t *bam_smpl_init(void); +int bam_smpl_add(bam_sample_t *sm, const char *abs, const char *txt); +int bam_smpl_rg2smid(const bam_sample_t *sm, const char *fn, const char *rg, kstring_t *str); +void bam_smpl_destroy(bam_sample_t *sm); + +#endif diff --git a/shared/package-files/bc/bc9139304a3cf0eda9d82c633456fe5b3fdc34a541fb4a0472df3d098d5d944a/degree_seq.py b/shared/package-files/bc/bc9139304a3cf0eda9d82c633456fe5b3fdc34a541fb4a0472df3d098d5d944a/degree_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..d920f85de14772a5be594816a19626e4c05e0c1b --- /dev/null +++ b/shared/package-files/bc/bc9139304a3cf0eda9d82c633456fe5b3fdc34a541fb4a0472df3d098d5d944a/degree_seq.py @@ -0,0 +1,867 @@ +"""Generate graphs with a given degree sequence or expected degree sequence.""" + +import heapq +import math +from itertools import chain, combinations, zip_longest +from operator import itemgetter + +import networkx as nx +from networkx.utils import py_random_state, random_weighted_sample + +__all__ = [ + "configuration_model", + "directed_configuration_model", + "expected_degree_graph", + "havel_hakimi_graph", + "directed_havel_hakimi_graph", + "degree_sequence_tree", + "random_degree_sequence_graph", +] + +chaini = chain.from_iterable + + +def _to_stublist(degree_sequence): + """Returns a list of degree-repeated node numbers. + + ``degree_sequence`` is a list of nonnegative integers representing + the degrees of nodes in a graph. + + This function returns a list of node numbers with multiplicities + according to the given degree sequence. For example, if the first + element of ``degree_sequence`` is ``3``, then the first node number, + ``0``, will appear at the head of the returned list three times. The + node numbers are assumed to be the numbers zero through + ``len(degree_sequence) - 1``. + + Examples + -------- + + >>> degree_sequence = [1, 2, 3] + >>> _to_stublist(degree_sequence) + [0, 1, 1, 2, 2, 2] + + If a zero appears in the sequence, that means the node exists but + has degree zero, so that number will be skipped in the returned + list:: + + >>> degree_sequence = [2, 0, 1] + >>> _to_stublist(degree_sequence) + [0, 0, 2] + + """ + return list(chaini([n] * d for n, d in enumerate(degree_sequence))) + + +def _configuration_model( + deg_sequence, create_using, directed=False, in_deg_sequence=None, seed=None +): + """Helper function for generating either undirected or directed + configuration model graphs. + + ``deg_sequence`` is a list of nonnegative integers representing the + degree of the node whose label is the index of the list element. + + ``create_using`` see :func:`~networkx.empty_graph`. + + ``directed`` and ``in_deg_sequence`` are required if you want the + returned graph to be generated using the directed configuration + model algorithm. If ``directed`` is ``False``, then ``deg_sequence`` + is interpreted as the degree sequence of an undirected graph and + ``in_deg_sequence`` is ignored. Otherwise, if ``directed`` is + ``True``, then ``deg_sequence`` is interpreted as the out-degree + sequence and ``in_deg_sequence`` as the in-degree sequence of a + directed graph. + + .. note:: + + ``deg_sequence`` and ``in_deg_sequence`` need not be the same + length. + + ``seed`` is a random.Random or numpy.random.RandomState instance + + This function returns a graph, directed if and only if ``directed`` + is ``True``, generated according to the configuration model + algorithm. For more information on the algorithm, see the + :func:`configuration_model` or :func:`directed_configuration_model` + functions. + + """ + n = len(deg_sequence) + G = nx.empty_graph(n, create_using) + # If empty, return the null graph immediately. + if n == 0: + return G + # Build a list of available degree-repeated nodes. For example, + # for degree sequence [3, 2, 1, 1, 1], the "stub list" is + # initially [0, 0, 0, 1, 1, 2, 3, 4], that is, node 0 has degree + # 3 and thus is repeated 3 times, etc. + # + # Also, shuffle the stub list in order to get a random sequence of + # node pairs. + if directed: + pairs = zip_longest(deg_sequence, in_deg_sequence, fillvalue=0) + # Unzip the list of pairs into a pair of lists. + out_deg, in_deg = zip(*pairs) + + out_stublist = _to_stublist(out_deg) + in_stublist = _to_stublist(in_deg) + + seed.shuffle(out_stublist) + seed.shuffle(in_stublist) + else: + stublist = _to_stublist(deg_sequence) + # Choose a random balanced bipartition of the stublist, which + # gives a random pairing of nodes. In this implementation, we + # shuffle the list and then split it in half. + n = len(stublist) + half = n // 2 + seed.shuffle(stublist) + out_stublist, in_stublist = stublist[:half], stublist[half:] + G.add_edges_from(zip(out_stublist, in_stublist)) + return G + + +@py_random_state(2) +@nx._dispatchable(graphs=None, returns_graph=True) +def configuration_model(deg_sequence, create_using=None, seed=None): + """Returns a random graph with the given degree sequence. + + The configuration model generates a random pseudograph (graph with + parallel edges and self loops) by randomly assigning edges to + match the given degree sequence. + + Parameters + ---------- + deg_sequence : list of nonnegative integers + Each list entry corresponds to the degree of a node. + create_using : NetworkX graph constructor, optional (default MultiGraph) + Graph type to create. If graph instance, then cleared before populated. + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + G : MultiGraph + A graph with the specified degree sequence. + Nodes are labeled starting at 0 with an index + corresponding to the position in deg_sequence. + + Raises + ------ + NetworkXError + If the degree sequence does not have an even sum. + + See Also + -------- + is_graphical + + Notes + ----- + As described by Newman [1]_. + + A non-graphical degree sequence (not realizable by some simple + graph) is allowed since this function returns graphs with self + loops and parallel edges. An exception is raised if the degree + sequence does not have an even sum. + + This configuration model construction process can lead to + duplicate edges and loops. You can remove the self-loops and + parallel edges (see below) which will likely result in a graph + that doesn't have the exact degree sequence specified. + + The density of self-loops and parallel edges tends to decrease as + the number of nodes increases. However, typically the number of + self-loops will approach a Poisson distribution with a nonzero mean, + and similarly for the number of parallel edges. Consider a node + with *k* stubs. The probability of being joined to another stub of + the same node is basically (*k* - *1*) / *N*, where *k* is the + degree and *N* is the number of nodes. So the probability of a + self-loop scales like *c* / *N* for some constant *c*. As *N* grows, + this means we expect *c* self-loops. Similarly for parallel edges. + + References + ---------- + .. [1] M.E.J. Newman, "The structure and function of complex networks", + SIAM REVIEW 45-2, pp 167-256, 2003. + + Examples + -------- + You can create a degree sequence following a particular distribution + by using the one of the distribution functions in + :mod:`~networkx.utils.random_sequence` (or one of your own). For + example, to create an undirected multigraph on one hundred nodes + with degree sequence chosen from the power law distribution: + + >>> sequence = nx.random_powerlaw_tree_sequence(100, tries=5000) + >>> G = nx.configuration_model(sequence) + >>> len(G) + 100 + >>> actual_degrees = [d for v, d in G.degree()] + >>> actual_degrees == sequence + True + + The returned graph is a multigraph, which may have parallel + edges. To remove any parallel edges from the returned graph: + + >>> G = nx.Graph(G) + + Similarly, to remove self-loops: + + >>> G.remove_edges_from(nx.selfloop_edges(G)) + + """ + if sum(deg_sequence) % 2 != 0: + msg = "Invalid degree sequence: sum of degrees must be even, not odd" + raise nx.NetworkXError(msg) + + G = nx.empty_graph(0, create_using, default=nx.MultiGraph) + if G.is_directed(): + raise nx.NetworkXNotImplemented("not implemented for directed graphs") + + G = _configuration_model(deg_sequence, G, seed=seed) + + return G + + +@py_random_state(3) +@nx._dispatchable(graphs=None, returns_graph=True) +def directed_configuration_model( + in_degree_sequence, out_degree_sequence, create_using=None, seed=None +): + """Returns a directed_random graph with the given degree sequences. + + The configuration model generates a random directed pseudograph + (graph with parallel edges and self loops) by randomly assigning + edges to match the given degree sequences. + + Parameters + ---------- + in_degree_sequence : list of nonnegative integers + Each list entry corresponds to the in-degree of a node. + out_degree_sequence : list of nonnegative integers + Each list entry corresponds to the out-degree of a node. + create_using : NetworkX graph constructor, optional (default MultiDiGraph) + Graph type to create. If graph instance, then cleared before populated. + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + G : MultiDiGraph + A graph with the specified degree sequences. + Nodes are labeled starting at 0 with an index + corresponding to the position in deg_sequence. + + Raises + ------ + NetworkXError + If the degree sequences do not have the same sum. + + See Also + -------- + configuration_model + + Notes + ----- + Algorithm as described by Newman [1]_. + + A non-graphical degree sequence (not realizable by some simple + graph) is allowed since this function returns graphs with self + loops and parallel edges. An exception is raised if the degree + sequences does not have the same sum. + + This configuration model construction process can lead to + duplicate edges and loops. You can remove the self-loops and + parallel edges (see below) which will likely result in a graph + that doesn't have the exact degree sequence specified. This + "finite-size effect" decreases as the size of the graph increases. + + References + ---------- + .. [1] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J. + Random graphs with arbitrary degree distributions and their applications + Phys. Rev. E, 64, 026118 (2001) + + Examples + -------- + One can modify the in- and out-degree sequences from an existing + directed graph in order to create a new directed graph. For example, + here we modify the directed path graph: + + >>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)]) + >>> din = list(d for n, d in D.in_degree()) + >>> dout = list(d for n, d in D.out_degree()) + >>> din.append(1) + >>> dout[0] = 2 + >>> # We now expect an edge from node 0 to a new node, node 3. + ... D = nx.directed_configuration_model(din, dout) + + The returned graph is a directed multigraph, which may have parallel + edges. To remove any parallel edges from the returned graph: + + >>> D = nx.DiGraph(D) + + Similarly, to remove self-loops: + + >>> D.remove_edges_from(nx.selfloop_edges(D)) + + """ + if sum(in_degree_sequence) != sum(out_degree_sequence): + msg = "Invalid degree sequences: sequences must have equal sums" + raise nx.NetworkXError(msg) + + if create_using is None: + create_using = nx.MultiDiGraph + + G = _configuration_model( + out_degree_sequence, + create_using, + directed=True, + in_deg_sequence=in_degree_sequence, + seed=seed, + ) + + name = "directed configuration_model {} nodes {} edges" + return G + + +@py_random_state(1) +@nx._dispatchable(graphs=None, returns_graph=True) +def expected_degree_graph(w, seed=None, selfloops=True): + r"""Returns a random graph with given expected degrees. + + Given a sequence of expected degrees $W=(w_0,w_1,\ldots,w_{n-1})$ + of length $n$ this algorithm assigns an edge between node $u$ and + node $v$ with probability + + .. math:: + + p_{uv} = \frac{w_u w_v}{\sum_k w_k} . + + Parameters + ---------- + w : list + The list of expected degrees. + selfloops: bool (default=True) + Set to False to remove the possibility of self-loop edges. + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + + Returns + ------- + Graph + + Examples + -------- + >>> z = [10 for i in range(100)] + >>> G = nx.expected_degree_graph(z) + + Notes + ----- + The nodes have integer labels corresponding to index of expected degrees + input sequence. + + The complexity of this algorithm is $\mathcal{O}(n+m)$ where $n$ is the + number of nodes and $m$ is the expected number of edges. + + The model in [1]_ includes the possibility of self-loop edges. + Set selfloops=False to produce a graph without self loops. + + For finite graphs this model doesn't produce exactly the given + expected degree sequence. Instead the expected degrees are as + follows. + + For the case without self loops (selfloops=False), + + .. math:: + + E[deg(u)] = \sum_{v \ne u} p_{uv} + = w_u \left( 1 - \frac{w_u}{\sum_k w_k} \right) . + + + NetworkX uses the standard convention that a self-loop edge counts 2 + in the degree of a node, so with self loops (selfloops=True), + + .. math:: + + E[deg(u)] = \sum_{v \ne u} p_{uv} + 2 p_{uu} + = w_u \left( 1 + \frac{w_u}{\sum_k w_k} \right) . + + References + ---------- + .. [1] Fan Chung and L. Lu, Connected components in random graphs with + given expected degree sequences, Ann. Combinatorics, 6, + pp. 125-145, 2002. + .. [2] Joel Miller and Aric Hagberg, + Efficient generation of networks with given expected degrees, + in Algorithms and Models for the Web-Graph (WAW 2011), + Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732, + pp. 115-126, 2011. + """ + n = len(w) + G = nx.empty_graph(n) + + # If there are no nodes are no edges in the graph, return the empty graph. + if n == 0 or max(w) == 0: + return G + + rho = 1 / sum(w) + # Sort the weights in decreasing order. The original order of the + # weights dictates the order of the (integer) node labels, so we + # need to remember the permutation applied in the sorting. + order = sorted(enumerate(w), key=itemgetter(1), reverse=True) + mapping = {c: u for c, (u, v) in enumerate(order)} + seq = [v for u, v in order] + last = n + if not selfloops: + last -= 1 + for u in range(last): + v = u + if not selfloops: + v += 1 + factor = seq[u] * rho + p = min(seq[v] * factor, 1) + while v < n and p > 0: + if p != 1: + r = seed.random() + v += math.floor(math.log(r, 1 - p)) + if v < n: + q = min(seq[v] * factor, 1) + if seed.random() < q / p: + G.add_edge(mapping[u], mapping[v]) + v += 1 + p = q + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def havel_hakimi_graph(deg_sequence, create_using=None): + """Returns a simple graph with given degree sequence constructed + using the Havel-Hakimi algorithm. + + Parameters + ---------- + deg_sequence: list of integers + Each integer corresponds to the degree of a node (need not be sorted). + create_using : NetworkX graph constructor, optional (default=nx.Graph) + Graph type to create. If graph instance, then cleared before populated. + Directed graphs are not allowed. + + Raises + ------ + NetworkXException + For a non-graphical degree sequence (i.e. one + not realizable by some simple graph). + + Notes + ----- + The Havel-Hakimi algorithm constructs a simple graph by + successively connecting the node of highest degree to other nodes + of highest degree, resorting remaining nodes by degree, and + repeating the process. The resulting graph has a high + degree-associativity. Nodes are labeled 1,.., len(deg_sequence), + corresponding to their position in deg_sequence. + + The basic algorithm is from Hakimi [1]_ and was generalized by + Kleitman and Wang [2]_. + + References + ---------- + .. [1] Hakimi S., On Realizability of a Set of Integers as + Degrees of the Vertices of a Linear Graph. I, + Journal of SIAM, 10(3), pp. 496-506 (1962) + .. [2] Kleitman D.J. and Wang D.L. + Algorithms for Constructing Graphs and Digraphs with Given Valences + and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973) + """ + if not nx.is_graphical(deg_sequence): + raise nx.NetworkXError("Invalid degree sequence") + + p = len(deg_sequence) + G = nx.empty_graph(p, create_using) + if G.is_directed(): + raise nx.NetworkXError("Directed graphs are not supported") + num_degs = [[] for i in range(p)] + dmax, dsum, n = 0, 0, 0 + for d in deg_sequence: + # Process only the non-zero integers + if d > 0: + num_degs[d].append(n) + dmax, dsum, n = max(dmax, d), dsum + d, n + 1 + # Return graph if no edges + if n == 0: + return G + + modstubs = [(0, 0)] * (dmax + 1) + # Successively reduce degree sequence by removing the maximum degree + while n > 0: + # Retrieve the maximum degree in the sequence + while len(num_degs[dmax]) == 0: + dmax -= 1 + # If there are not enough stubs to connect to, then the sequence is + # not graphical + if dmax > n - 1: + raise nx.NetworkXError("Non-graphical integer sequence") + + # Remove largest stub in list + source = num_degs[dmax].pop() + n -= 1 + # Reduce the next dmax largest stubs + mslen = 0 + k = dmax + for i in range(dmax): + while len(num_degs[k]) == 0: + k -= 1 + target = num_degs[k].pop() + G.add_edge(source, target) + n -= 1 + if k > 1: + modstubs[mslen] = (k - 1, target) + mslen += 1 + # Add back to the list any nonzero stubs that were removed + for i in range(mslen): + (stubval, stubtarget) = modstubs[i] + num_degs[stubval].append(stubtarget) + n += 1 + + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def directed_havel_hakimi_graph(in_deg_sequence, out_deg_sequence, create_using=None): + """Returns a directed graph with the given degree sequences. + + Parameters + ---------- + in_deg_sequence : list of integers + Each list entry corresponds to the in-degree of a node. + out_deg_sequence : list of integers + Each list entry corresponds to the out-degree of a node. + create_using : NetworkX graph constructor, optional (default DiGraph) + Graph type to create. If graph instance, then cleared before populated. + + Returns + ------- + G : DiGraph + A graph with the specified degree sequences. + Nodes are labeled starting at 0 with an index + corresponding to the position in deg_sequence + + Raises + ------ + NetworkXError + If the degree sequences are not digraphical. + + See Also + -------- + configuration_model + + Notes + ----- + Algorithm as described by Kleitman and Wang [1]_. + + References + ---------- + .. [1] D.J. Kleitman and D.L. Wang + Algorithms for Constructing Graphs and Digraphs with Given Valences + and Factors Discrete Mathematics, 6(1), pp. 79-88 (1973) + """ + in_deg_sequence = nx.utils.make_list_of_ints(in_deg_sequence) + out_deg_sequence = nx.utils.make_list_of_ints(out_deg_sequence) + + # Process the sequences and form two heaps to store degree pairs with + # either zero or nonzero out degrees + sumin, sumout = 0, 0 + nin, nout = len(in_deg_sequence), len(out_deg_sequence) + maxn = max(nin, nout) + G = nx.empty_graph(maxn, create_using, default=nx.DiGraph) + if maxn == 0: + return G + maxin = 0 + stubheap, zeroheap = [], [] + for n in range(maxn): + in_deg, out_deg = 0, 0 + if n < nout: + out_deg = out_deg_sequence[n] + if n < nin: + in_deg = in_deg_sequence[n] + if in_deg < 0 or out_deg < 0: + raise nx.NetworkXError( + "Invalid degree sequences. Sequence values must be positive." + ) + sumin, sumout, maxin = sumin + in_deg, sumout + out_deg, max(maxin, in_deg) + if in_deg > 0: + stubheap.append((-1 * out_deg, -1 * in_deg, n)) + elif out_deg > 0: + zeroheap.append((-1 * out_deg, n)) + if sumin != sumout: + raise nx.NetworkXError( + "Invalid degree sequences. Sequences must have equal sums." + ) + heapq.heapify(stubheap) + heapq.heapify(zeroheap) + + modstubs = [(0, 0, 0)] * (maxin + 1) + # Successively reduce degree sequence by removing the maximum + while stubheap: + # Remove first value in the sequence with a non-zero in degree + (freeout, freein, target) = heapq.heappop(stubheap) + freein *= -1 + if freein > len(stubheap) + len(zeroheap): + raise nx.NetworkXError("Non-digraphical integer sequence") + + # Attach arcs from the nodes with the most stubs + mslen = 0 + for i in range(freein): + if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0][0]): + (stubout, stubsource) = heapq.heappop(zeroheap) + stubin = 0 + else: + (stubout, stubin, stubsource) = heapq.heappop(stubheap) + if stubout == 0: + raise nx.NetworkXError("Non-digraphical integer sequence") + G.add_edge(stubsource, target) + # Check if source is now totally connected + if stubout + 1 < 0 or stubin < 0: + modstubs[mslen] = (stubout + 1, stubin, stubsource) + mslen += 1 + + # Add the nodes back to the heaps that still have available stubs + for i in range(mslen): + stub = modstubs[i] + if stub[1] < 0: + heapq.heappush(stubheap, stub) + else: + heapq.heappush(zeroheap, (stub[0], stub[2])) + if freeout < 0: + heapq.heappush(zeroheap, (freeout, target)) + + return G + + +@nx._dispatchable(graphs=None, returns_graph=True) +def degree_sequence_tree(deg_sequence, create_using=None): + """Make a tree for the given degree sequence. + + A tree has #nodes-#edges=1 so + the degree sequence must have + len(deg_sequence)-sum(deg_sequence)/2=1 + """ + # The sum of the degree sequence must be even (for any undirected graph). + degree_sum = sum(deg_sequence) + if degree_sum % 2 != 0: + msg = "Invalid degree sequence: sum of degrees must be even, not odd" + raise nx.NetworkXError(msg) + if len(deg_sequence) - degree_sum // 2 != 1: + msg = ( + "Invalid degree sequence: tree must have number of nodes equal" + " to one less than the number of edges" + ) + raise nx.NetworkXError(msg) + G = nx.empty_graph(0, create_using) + if G.is_directed(): + raise nx.NetworkXError("Directed Graph not supported") + + # Sort all degrees greater than 1 in decreasing order. + # + # TODO Does this need to be sorted in reverse order? + deg = sorted((s for s in deg_sequence if s > 1), reverse=True) + + # make path graph as backbone + n = len(deg) + 2 + nx.add_path(G, range(n)) + last = n + + # add the leaves + for source in range(1, n - 1): + nedges = deg.pop() - 2 + for target in range(last, last + nedges): + G.add_edge(source, target) + last += nedges + + # in case we added one too many + if len(G) > len(deg_sequence): + G.remove_node(0) + return G + + +@py_random_state(1) +@nx._dispatchable(graphs=None, returns_graph=True) +def random_degree_sequence_graph(sequence, seed=None, tries=10): + r"""Returns a simple random graph with the given degree sequence. + + If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the + algorithm produces almost uniform random graphs in $O(m d_m)$ time + where $m$ is the number of edges. + + Parameters + ---------- + sequence : list of integers + Sequence of degrees + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + tries : int, optional + Maximum number of tries to create a graph + + Returns + ------- + G : Graph + A graph with the specified degree sequence. + Nodes are labeled starting at 0 with an index + corresponding to the position in the sequence. + + Raises + ------ + NetworkXUnfeasible + If the degree sequence is not graphical. + NetworkXError + If a graph is not produced in specified number of tries + + See Also + -------- + is_graphical, configuration_model + + Notes + ----- + The generator algorithm [1]_ is not guaranteed to produce a graph. + + References + ---------- + .. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi, + A sequential algorithm for generating random graphs. + Algorithmica, Volume 58, Number 4, 860-910, + DOI: 10.1007/s00453-009-9340-1 + + Examples + -------- + >>> sequence = [1, 2, 2, 3] + >>> G = nx.random_degree_sequence_graph(sequence, seed=42) + >>> sorted(d for n, d in G.degree()) + [1, 2, 2, 3] + """ + DSRG = DegreeSequenceRandomGraph(sequence, seed) + for try_n in range(tries): + try: + return DSRG.generate() + except nx.NetworkXUnfeasible: + pass + raise nx.NetworkXError(f"failed to generate graph in {tries} tries") + + +class DegreeSequenceRandomGraph: + # class to generate random graphs with a given degree sequence + # use random_degree_sequence_graph() + def __init__(self, degree, rng): + self.rng = rng + self.degree = list(degree) + if not nx.is_graphical(self.degree): + raise nx.NetworkXUnfeasible("degree sequence is not graphical") + # node labels are integers 0,...,n-1 + self.m = sum(self.degree) / 2.0 # number of edges + try: + self.dmax = max(self.degree) # maximum degree + except ValueError: + self.dmax = 0 + + def generate(self): + # remaining_degree is mapping from int->remaining degree + self.remaining_degree = dict(enumerate(self.degree)) + # add all nodes to make sure we get isolated nodes + self.graph = nx.Graph() + self.graph.add_nodes_from(self.remaining_degree) + # remove zero degree nodes + for n, d in list(self.remaining_degree.items()): + if d == 0: + del self.remaining_degree[n] + if len(self.remaining_degree) > 0: + # build graph in three phases according to how many unmatched edges + self.phase1() + self.phase2() + self.phase3() + return self.graph + + def update_remaining(self, u, v, aux_graph=None): + # decrement remaining nodes, modify auxiliary graph if in phase3 + if aux_graph is not None: + # remove edges from auxiliary graph + aux_graph.remove_edge(u, v) + if self.remaining_degree[u] == 1: + del self.remaining_degree[u] + if aux_graph is not None: + aux_graph.remove_node(u) + else: + self.remaining_degree[u] -= 1 + if self.remaining_degree[v] == 1: + del self.remaining_degree[v] + if aux_graph is not None: + aux_graph.remove_node(v) + else: + self.remaining_degree[v] -= 1 + + def p(self, u, v): + # degree probability + return 1 - self.degree[u] * self.degree[v] / (4.0 * self.m) + + def q(self, u, v): + # remaining degree probability + norm = max(self.remaining_degree.values()) ** 2 + return self.remaining_degree[u] * self.remaining_degree[v] / norm + + def suitable_edge(self): + """Returns True if and only if an arbitrary remaining node can + potentially be joined with some other remaining node. + + """ + nodes = iter(self.remaining_degree) + u = next(nodes) + return any(v not in self.graph[u] for v in nodes) + + def phase1(self): + # choose node pairs from (degree) weighted distribution + rem_deg = self.remaining_degree + while sum(rem_deg.values()) >= 2 * self.dmax**2: + u, v = sorted(random_weighted_sample(rem_deg, 2, self.rng)) + if self.graph.has_edge(u, v): + continue + if self.rng.random() < self.p(u, v): # accept edge + self.graph.add_edge(u, v) + self.update_remaining(u, v) + + def phase2(self): + # choose remaining nodes uniformly at random and use rejection sampling + remaining_deg = self.remaining_degree + rng = self.rng + while len(remaining_deg) >= 2 * self.dmax: + while True: + u, v = sorted(rng.sample(list(remaining_deg.keys()), 2)) + if self.graph.has_edge(u, v): + continue + if rng.random() < self.q(u, v): + break + if rng.random() < self.p(u, v): # accept edge + self.graph.add_edge(u, v) + self.update_remaining(u, v) + + def phase3(self): + # build potential remaining edges and choose with rejection sampling + potential_edges = combinations(self.remaining_degree, 2) + # build auxiliary graph of potential edges not already in graph + H = nx.Graph( + [(u, v) for (u, v) in potential_edges if not self.graph.has_edge(u, v)] + ) + rng = self.rng + while self.remaining_degree: + if not self.suitable_edge(): + raise nx.NetworkXUnfeasible("no suitable edges left") + while True: + u, v = sorted(rng.choice(list(H.edges()))) + if rng.random() < self.q(u, v): + break + if rng.random() < self.p(u, v): # accept edge + self.graph.add_edge(u, v) + self.update_remaining(u, v, aux_graph=H) diff --git a/shared/package-files/bc/bc9160f6ccee397a13752ead1a0a57abc6597b6b0eeb7d061e6557127e4a4679/glu_ops.h b/shared/package-files/bc/bc9160f6ccee397a13752ead1a0a57abc6597b6b0eeb7d061e6557127e4a4679/glu_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..599b8e2002f112e5ff8f1f3df53dab29a0483ae0 --- /dev/null +++ b/shared/package-files/bc/bc9160f6ccee397a13752ead1a0a57abc6597b6b0eeb7d061e6557127e4a4679/glu_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API glu_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::glu"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, int64_t dim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, at::Tensor & out); +}; + +struct TORCH_API glu { + using schema = at::Tensor (const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::glu"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "glu(Tensor self, int dim=-1) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/bc/bc92420cff4aac62622e1e5fa19fe2f8fee0c7fc7954b722e59b7a331d8fc607/sigmoid_backward_ops.h b/shared/package-files/bc/bc92420cff4aac62622e1e5fa19fe2f8fee0c7fc7954b722e59b7a331d8fc607/sigmoid_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f0a02605ec89b83ab736ec9a2dd70d505093aa55 --- /dev/null +++ b/shared/package-files/bc/bc92420cff4aac62622e1e5fa19fe2f8fee0c7fc7954b722e59b7a331d8fc607/sigmoid_backward_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API sigmoid_backward_grad_input { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::sigmoid_backward"; + static constexpr const char* overload_name = "grad_input"; + static constexpr const char* schema_str = "sigmoid_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & output, at::Tensor & grad_input); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & output, at::Tensor & grad_input); +}; + +struct TORCH_API sigmoid_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::sigmoid_backward"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor"; + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & output); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & output); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/bc/bc930eb581b4bf16100a27ffced9d84d49bfd77800a5fcc588dc4285179f38d8/test_link_analysis.py b/shared/package-files/bc/bc930eb581b4bf16100a27ffced9d84d49bfd77800a5fcc588dc4285179f38d8/test_link_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..6e46056eeb0c47fc6fd8ac333e1bcf1f000d6c56 --- /dev/null +++ b/shared/package-files/bc/bc930eb581b4bf16100a27ffced9d84d49bfd77800a5fcc588dc4285179f38d8/test_link_analysis.py @@ -0,0 +1,218 @@ +import itertools + +import pytest + +import networkx as nx +from networkx.algorithms import bipartite + +pytest.importorskip("scipy") + + +class TestBipartiteLinkAnalysis: + @classmethod + def setup_class(cls): + cls.davis_southern_women_graph = nx.davis_southern_women_graph() + cls.women_bipartite_set = { + node + for node, bipartite in cls.davis_southern_women_graph.nodes( + data="bipartite" + ) + if bipartite == 0 + } + cls.gnmk_random_graph = nx.bipartite.generators.gnmk_random_graph( + 5 * 10**2, 10**2, 5 * 10**2, seed=27 + ) + cls.gnmk_random_graph_top_nodes = { + node + for node, bipartite in cls.gnmk_random_graph.nodes(data="bipartite") + if bipartite == 0 + } + + def test_collaborative_filtering_birank(self): + elist = [ + ("u1", "p1", 5), + ("u2", "p1", 5), + ("u2", "p2", 4), + ("u3", "p1", 3), + ("u3", "p3", 2), + ] + item_recommendation_graph = nx.DiGraph() + item_recommendation_graph.add_weighted_edges_from(elist, weight="rating") + product_nodes = ("p1", "p2", "p3") + u1_query = { + product: rating + for _, product, rating in item_recommendation_graph.edges( + nbunch="u1", data="rating" + ) + } + u1_birank_results = bipartite.birank( + item_recommendation_graph, + product_nodes, + alpha=0.8, + beta=1.0, + top_personalization=u1_query, + weight="rating", + ) + + assert u1_birank_results["p2"] > u1_birank_results["p3"] + + u1_birank_results_unweighted = bipartite.birank( + item_recommendation_graph, + product_nodes, + alpha=0.8, + beta=1.0, + top_personalization=u1_query, + weight=None, + ) + + assert u1_birank_results_unweighted["p2"] == pytest.approx( + u1_birank_results_unweighted["p3"], rel=2e-6 + ) + + def test_davis_birank(self): + scores = bipartite.birank( + self.davis_southern_women_graph, self.women_bipartite_set + ) + answer = { + "Laura Mandeville": 0.07, + "Olivia Carleton": 0.04, + "Frances Anderson": 0.05, + "Pearl Oglethorpe": 0.04, + "Katherina Rogers": 0.06, + "Flora Price": 0.04, + "Dorothy Murchison": 0.04, + "Helen Lloyd": 0.06, + "Theresa Anderson": 0.07, + "Eleanor Nye": 0.05, + "Evelyn Jefferson": 0.07, + "Sylvia Avondale": 0.07, + "Charlotte McDowd": 0.05, + "Verne Sanderson": 0.05, + "Myra Liddel": 0.05, + "Brenda Rogers": 0.07, + "Ruth DeSand": 0.05, + "Nora Fayette": 0.07, + "E8": 0.11, + "E7": 0.09, + "E10": 0.07, + "E9": 0.1, + "E13": 0.05, + "E3": 0.07, + "E12": 0.07, + "E11": 0.06, + "E2": 0.05, + "E5": 0.08, + "E6": 0.08, + "E14": 0.05, + "E4": 0.06, + "E1": 0.05, + } + + for node, value in answer.items(): + assert scores[node] == pytest.approx(value, abs=1e-2) + + def test_davis_birank_with_personalization(self): + women_personalization = {"Laura Mandeville": 1} + scores = bipartite.birank( + self.davis_southern_women_graph, + self.women_bipartite_set, + top_personalization=women_personalization, + ) + answer = { + "Laura Mandeville": 0.29, + "Olivia Carleton": 0.02, + "Frances Anderson": 0.06, + "Pearl Oglethorpe": 0.04, + "Katherina Rogers": 0.04, + "Flora Price": 0.02, + "Dorothy Murchison": 0.03, + "Helen Lloyd": 0.04, + "Theresa Anderson": 0.08, + "Eleanor Nye": 0.05, + "Evelyn Jefferson": 0.09, + "Sylvia Avondale": 0.05, + "Charlotte McDowd": 0.06, + "Verne Sanderson": 0.04, + "Myra Liddel": 0.03, + "Brenda Rogers": 0.08, + "Ruth DeSand": 0.05, + "Nora Fayette": 0.05, + "E8": 0.11, + "E7": 0.1, + "E10": 0.04, + "E9": 0.07, + "E13": 0.03, + "E3": 0.11, + "E12": 0.04, + "E11": 0.03, + "E2": 0.1, + "E5": 0.11, + "E6": 0.1, + "E14": 0.03, + "E4": 0.06, + "E1": 0.1, + } + + for node, value in answer.items(): + assert scores[node] == pytest.approx(value, abs=1e-2) + + def test_birank_empty_bipartite_set(self): + G = nx.Graph() + all_nodes = [1, 2, 3] + G.add_nodes_from(all_nodes) + + # Test with empty bipartite set + with pytest.raises(nx.NetworkXAlgorithmError): + bipartite.birank(G, all_nodes) + + @pytest.mark.parametrize( + "damping_factor,value", itertools.product(["alpha", "beta"], [-0.1, 1.1]) + ) + def test_birank_invalid_alpha_beta(self, damping_factor, value): + kwargs = {damping_factor: value} + with pytest.raises(nx.NetworkXAlgorithmError): + bipartite.birank( + self.davis_southern_women_graph, self.women_bipartite_set, **kwargs + ) + + def test_birank_power_iteration_failed_convergence(self): + with pytest.raises(nx.PowerIterationFailedConvergence): + bipartite.birank( + self.davis_southern_women_graph, self.women_bipartite_set, max_iter=1 + ) + + @pytest.mark.parametrize( + "personalization,alpha,beta", + itertools.product( + [ + # Concentrated case + lambda x: 1000 if x == 0 else 0, + # Uniform case + lambda x: 5, + # Zero case + lambda x: 0, + ], + [i / 2 for i in range(3)], + [i / 2 for i in range(3)], + ), + ) + def test_gnmk_convergence_birank(self, personalization, alpha, beta): + top_personalization_dict = { + node: personalization(node) for node in self.gnmk_random_graph_top_nodes + } + bipartite.birank( + self.gnmk_random_graph, + self.gnmk_random_graph_top_nodes, + top_personalization=top_personalization_dict, + alpha=alpha, + beta=beta, + ) + + def test_negative_personalization(self): + top_personalization_dict = {0: -1} + with pytest.raises(nx.NetworkXAlgorithmError): + bipartite.birank( + self.gnmk_random_graph, + self.gnmk_random_graph_top_nodes, + top_personalization=top_personalization_dict, + ) diff --git a/shared/package-files/bc/bc95372c9bc37bbc61df1386a838f39ccd1803f12d041297bba7b2519a50cc3d/linear.cpython-311.pyc b/shared/package-files/bc/bc95372c9bc37bbc61df1386a838f39ccd1803f12d041297bba7b2519a50cc3d/linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5331231a3266d4e840ae5cb1120f4a21f02aefd Binary files /dev/null and b/shared/package-files/bc/bc95372c9bc37bbc61df1386a838f39ccd1803f12d041297bba7b2519a50cc3d/linear.cpython-311.pyc differ diff --git a/shared/package-files/bc/bc9d3c1ec4f06b5cf683d29229f494252c0ca03c38fa0656671321061aac2088/debug_macros.h b/shared/package-files/bc/bc9d3c1ec4f06b5cf683d29229f494252c0ca03c38fa0656671321061aac2088/debug_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..60b295bd313a991e8fd82320a6a267076428af26 --- /dev/null +++ b/shared/package-files/bc/bc9d3c1ec4f06b5cf683d29229f494252c0ca03c38fa0656671321061aac2088/debug_macros.h @@ -0,0 +1,102 @@ +#pragma once + +#include + +#ifdef __cplusplus +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +#define unlikely(x) (x) +#else +#define unlikely(x) __builtin_expect((x), 0) +#endif + +#define NULL_CHECK(val) \ + if (unlikely((val) == NULL)) { \ + fprintf(stderr, "NULL ERROR: %s:%d\n", __FILE__, __LINE__); \ + PyErr_Print(); \ + abort(); \ + } else { \ + } + +// CHECK might be previously declared +#undef CHECK +#define CHECK(cond) \ + if (unlikely(!(cond))) { \ + fprintf(stderr, "DEBUG CHECK FAILED: %s:%d\n", __FILE__, __LINE__); \ + abort(); \ + } else { \ + } + +// Uncomment next line to print debug message +// #define TORCHDYNAMO_DEBUG 1 +#ifdef TORCHDYNAMO_DEBUG + +#define DEBUG_CHECK(cond) CHECK(cond) +#define DEBUG_NULL_CHECK(val) NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__, __VA_ARGS__) +#define DEBUG_TRACE0(msg) \ + fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__) + +#else + +#define DEBUG_CHECK(cond) +#define DEBUG_NULL_CHECK(val) +#define DEBUG_TRACE(msg, ...) +#define DEBUG_TRACE0(msg) + +#endif + +inline _PyFrameEvalFunction _debug_set_eval_frame( + PyThreadState* tstate, + _PyFrameEvalFunction eval_frame) { + _PyFrameEvalFunction prev = + _PyInterpreterState_GetEvalFrameFunc(tstate->interp); + _PyInterpreterState_SetEvalFrameFunc(tstate->interp, eval_frame); + return prev; +} + +// Inspect PyObject*'s from C/C++ at the Python level, in pdb. +// e.g. +// +// PyObject* obj1 = PyList_New(...); +// PyObject* obj2 = PyObject_CallFunction(...); +// INSPECT(obj1, obj2); +// (pdb) p args[0] +// # list +// (pdb) p args[1] +// # some object +// (pdb) p args[1].some_attr +// # etc. +// +// Implementation: set eval frame callback to default, call +// torch._dynamo.utils._breakpoint_for_c_dynamo, reset eval frame callback. +#define INSPECT(...) \ + { \ + PyThreadState* cur_tstate = PyThreadState_Get(); \ + _PyFrameEvalFunction prev_eval_frame = \ + _debug_set_eval_frame(cur_tstate, &_PyEval_EvalFrameDefault); \ + PyObject* torch__dynamo_utils_module = \ + PyImport_ImportModule("torch._dynamo.utils"); \ + NULL_CHECK(torch__dynamo_utils_module); \ + PyObject* breakpoint_for_c_dynamo_fn = PyObject_GetAttrString( \ + torch__dynamo_utils_module, "_breakpoint_for_c_dynamo"); \ + NULL_CHECK(breakpoint_for_c_dynamo_fn); \ + PyObject_CallFunctionObjArgs( \ + breakpoint_for_c_dynamo_fn, __VA_ARGS__, NULL); \ + _debug_set_eval_frame(cur_tstate, prev_eval_frame); \ + Py_DECREF(breakpoint_for_c_dynamo_fn); \ + Py_DECREF(torch__dynamo_utils_module); \ + } + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/shared/package-files/bc/bca261fb38035945bb3725f1b6fda1a3a6952d75fc0483dfcc28a0110e5de88e/hip_fp16.h b/shared/package-files/bc/bca261fb38035945bb3725f1b6fda1a3a6952d75fc0483dfcc28a0110e5de88e/hip_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..67def4ee1aacda39153f9b4e37f319a69d83af5e --- /dev/null +++ b/shared/package-files/bc/bca261fb38035945bb3725f1b6fda1a3a6952d75fc0483dfcc28a0110e5de88e/hip_fp16.h @@ -0,0 +1,36 @@ +/* +Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. + +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. +*/ + +#ifndef HIP_INCLUDE_HIP_HIP_FP16_H +#define HIP_INCLUDE_HIP_HIP_FP16_H + +#include + +#if defined(__HIP_PLATFORM_AMD__) && !defined(__HIP_PLATFORM_NVIDIA__) +#include +#elif !defined(__HIP_PLATFORM_AMD__) && defined(__HIP_PLATFORM_NVIDIA__) +#include "cuda_fp16.h" +#else +#error("Must define exactly one of __HIP_PLATFORM_AMD__ or __HIP_PLATFORM_NVIDIA__"); +#endif + +#endif diff --git a/shared/package-files/bc/bca371d5ad4a752ba7f0e20f132eb6554937f7411ec3a5f25601d035b8cf4457/test_base.py b/shared/package-files/bc/bca371d5ad4a752ba7f0e20f132eb6554937f7411ec3a5f25601d035b8cf4457/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf6c6099abab66d7a3fc78606c0eaf2c4298421 --- /dev/null +++ b/shared/package-files/bc/bca371d5ad4a752ba7f0e20f132eb6554937f7411ec3a5f25601d035b8cf4457/test_base.py @@ -0,0 +1,460 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_extension_array_dtype + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + NaT, + PeriodIndex, + Series, + TimedeltaIndex, +) +import pandas._testing as tm +from pandas.core.groupby.groupby import DataError +from pandas.core.groupby.grouper import Grouper +from pandas.core.indexes.datetimes import date_range +from pandas.core.indexes.period import period_range +from pandas.core.indexes.timedeltas import timedelta_range +from pandas.core.resample import _asfreq_compat + +# a fixture value can be overridden by the test parameter value. Note that the +# value of the fixture can be overridden this way even if the test doesn't use +# it directly (doesn't mention it in the function prototype). +# see https://docs.pytest.org/en/latest/fixture.html#override-a-fixture-with-direct-test-parametrization # noqa: E501 +# in this module we override the fixture values defined in conftest.py +# tuples of '_index_factory,_series_name,_index_start,_index_end' +DATE_RANGE = (date_range, "dti", datetime(2005, 1, 1), datetime(2005, 1, 10)) +PERIOD_RANGE = (period_range, "pi", datetime(2005, 1, 1), datetime(2005, 1, 10)) +TIMEDELTA_RANGE = (timedelta_range, "tdi", "1 day", "10 day") + +all_ts = pytest.mark.parametrize( + "_index_factory,_series_name,_index_start,_index_end", + [DATE_RANGE, PERIOD_RANGE, TIMEDELTA_RANGE], +) + + +@pytest.fixture +def create_index(_index_factory): + def _create_index(*args, **kwargs): + """return the _index_factory created using the args, kwargs""" + return _index_factory(*args, **kwargs) + + return _create_index + + +@pytest.mark.parametrize("freq", ["2D", "1h"]) +@pytest.mark.parametrize( + "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE] +) +def test_asfreq(series_and_frame, freq, create_index): + obj = series_and_frame + + result = obj.resample(freq).asfreq() + new_index = create_index(obj.index[0], obj.index[-1], freq=freq) + expected = obj.reindex(new_index) + tm.assert_almost_equal(result, expected) + + +@pytest.mark.parametrize( + "_index_factory,_series_name,_index_start,_index_end", [DATE_RANGE, TIMEDELTA_RANGE] +) +def test_asfreq_fill_value(series, create_index): + # test for fill value during resampling, issue 3715 + + ser = series + + result = ser.resample("1h").asfreq() + new_index = create_index(ser.index[0], ser.index[-1], freq="1h") + expected = ser.reindex(new_index) + tm.assert_series_equal(result, expected) + + # Explicit cast to float to avoid implicit cast when setting None + frame = ser.astype("float").to_frame("value") + frame.iloc[1] = None + result = frame.resample("1h").asfreq(fill_value=4.0) + new_index = create_index(frame.index[0], frame.index[-1], freq="1h") + expected = frame.reindex(new_index, fill_value=4.0) + tm.assert_frame_equal(result, expected) + + +@all_ts +def test_resample_interpolate(frame): + # GH#12925 + df = frame + warn = None + if isinstance(df.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = df.resample("1min").asfreq().interpolate() + expected = df.resample("1min").interpolate() + tm.assert_frame_equal(result, expected) + + +def test_raises_on_non_datetimelike_index(): + # this is a non datetimelike index + xp = DataFrame() + msg = ( + "Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, " + "but got an instance of 'RangeIndex'" + ) + with pytest.raises(TypeError, match=msg): + xp.resample("YE") + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +def test_resample_empty_series(freq, empty_series_dti, resample_method): + # GH12771 & GH12868 + + ser = empty_series_dti + if freq == "ME" and isinstance(ser.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + ser.resample(freq) + return + elif freq == "ME" and isinstance(ser.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + warn = None + if isinstance(ser.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq) + result = getattr(rs, resample_method)() + + if resample_method == "ohlc": + expected = DataFrame( + [], index=ser.index[:0].copy(), columns=["open", "high", "low", "close"] + ) + expected.index = _asfreq_compat(ser.index, freq) + tm.assert_frame_equal(result, expected, check_dtype=False) + else: + expected = ser.copy() + expected.index = _asfreq_compat(ser.index, freq) + tm.assert_series_equal(result, expected, check_dtype=False) + + tm.assert_index_equal(result.index, expected.index) + assert result.index.freq == expected.index.freq + + +@all_ts +@pytest.mark.parametrize( + "freq", + [ + pytest.param("ME", marks=pytest.mark.xfail(reason="Don't know why this fails")), + "D", + "h", + ], +) +def test_resample_nat_index_series(freq, series, resample_method): + # GH39227 + + ser = series.copy() + ser.index = PeriodIndex([NaT] * len(ser), freq=freq) + + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = ser.resample(freq) + result = getattr(rs, resample_method)() + + if resample_method == "ohlc": + expected = DataFrame( + [], index=ser.index[:0].copy(), columns=["open", "high", "low", "close"] + ) + tm.assert_frame_equal(result, expected, check_dtype=False) + else: + expected = ser[:0].copy() + tm.assert_series_equal(result, expected, check_dtype=False) + tm.assert_index_equal(result.index, expected.index) + assert result.index.freq == expected.index.freq + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +@pytest.mark.parametrize("resample_method", ["count", "size"]) +def test_resample_count_empty_series(freq, empty_series_dti, resample_method): + # GH28427 + ser = empty_series_dti + if freq == "ME" and isinstance(ser.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + ser.resample(freq) + return + elif freq == "ME" and isinstance(ser.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + warn = None + if isinstance(ser.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq) + + result = getattr(rs, resample_method)() + + index = _asfreq_compat(ser.index, freq) + + expected = Series([], dtype="int64", index=index, name=ser.name) + + tm.assert_series_equal(result, expected) + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +def test_resample_empty_dataframe(empty_frame_dti, freq, resample_method): + # GH13212 + df = empty_frame_dti + # count retains dimensions too + if freq == "ME" and isinstance(df.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + df.resample(freq, group_keys=False) + return + elif freq == "ME" and isinstance(df.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + warn = None + if isinstance(df.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = df.resample(freq, group_keys=False) + result = getattr(rs, resample_method)() + if resample_method == "ohlc": + # TODO: no tests with len(df.columns) > 0 + mi = MultiIndex.from_product([df.columns, ["open", "high", "low", "close"]]) + expected = DataFrame( + [], index=df.index[:0].copy(), columns=mi, dtype=np.float64 + ) + expected.index = _asfreq_compat(df.index, freq) + + elif resample_method != "size": + expected = df.copy() + else: + # GH14962 + expected = Series([], dtype=np.int64) + + expected.index = _asfreq_compat(df.index, freq) + + tm.assert_index_equal(result.index, expected.index) + assert result.index.freq == expected.index.freq + tm.assert_almost_equal(result, expected) + + # test size for GH13212 (currently stays as df) + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +def test_resample_count_empty_dataframe(freq, empty_frame_dti): + # GH28427 + + empty_frame_dti["a"] = [] + + if freq == "ME" and isinstance(empty_frame_dti.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + empty_frame_dti.resample(freq) + return + elif freq == "ME" and isinstance(empty_frame_dti.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + warn = None + if isinstance(empty_frame_dti.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = empty_frame_dti.resample(freq) + result = rs.count() + + index = _asfreq_compat(empty_frame_dti.index, freq) + + expected = DataFrame(dtype="int64", index=index, columns=Index(["a"], dtype=object)) + + tm.assert_frame_equal(result, expected) + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +def test_resample_size_empty_dataframe(freq, empty_frame_dti): + # GH28427 + + empty_frame_dti["a"] = [] + + if freq == "ME" and isinstance(empty_frame_dti.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + empty_frame_dti.resample(freq) + return + elif freq == "ME" and isinstance(empty_frame_dti.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(empty_frame_dti.index, PeriodIndex): + warn = FutureWarning + with tm.assert_produces_warning(warn, match=msg): + rs = empty_frame_dti.resample(freq) + result = rs.size() + + index = _asfreq_compat(empty_frame_dti.index, freq) + + expected = Series([], dtype="int64", index=index) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "index", + [ + PeriodIndex([], freq="M", name="a"), + DatetimeIndex([], name="a"), + TimedeltaIndex([], name="a"), + ], +) +@pytest.mark.parametrize("dtype", [float, int, object, "datetime64[ns]"]) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") +def test_resample_empty_dtypes(index, dtype, resample_method): + # Empty series were sometimes causing a segfault (for the functions + # with Cython bounds-checking disabled) or an IndexError. We just run + # them to ensure they no longer do. (GH #10228) + warn = None + if isinstance(index, PeriodIndex): + # GH#53511 + index = PeriodIndex([], freq="B", name=index.name) + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + + empty_series_dti = Series([], index, dtype) + with tm.assert_produces_warning(warn, match=msg): + rs = empty_series_dti.resample("d", group_keys=False) + try: + getattr(rs, resample_method)() + except DataError: + # Ignore these since some combinations are invalid + # (ex: doing mean with dtype of np.object_) + pass + + +@all_ts +@pytest.mark.parametrize("freq", ["ME", "D", "h"]) +def test_apply_to_empty_series(empty_series_dti, freq): + # GH 14313 + ser = empty_series_dti + + if freq == "ME" and isinstance(empty_series_dti.index, TimedeltaIndex): + msg = ( + "Resampling on a TimedeltaIndex requires fixed-duration `freq`, " + "e.g. '24h' or '3D', not " + ) + with pytest.raises(ValueError, match=msg): + empty_series_dti.resample(freq) + return + elif freq == "ME" and isinstance(empty_series_dti.index, PeriodIndex): + # index is PeriodIndex, so convert to corresponding Period freq + freq = "M" + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(empty_series_dti.index, PeriodIndex): + warn = FutureWarning + + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq, group_keys=False) + + result = rs.apply(lambda x: 1) + with tm.assert_produces_warning(warn, match=msg): + expected = ser.resample(freq).apply("sum") + + tm.assert_series_equal(result, expected, check_dtype=False) + + +@all_ts +def test_resampler_is_iterable(series): + # GH 15314 + freq = "h" + tg = Grouper(freq=freq, convention="start") + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(series.index, PeriodIndex): + warn = FutureWarning + + with tm.assert_produces_warning(warn, match=msg): + grouped = series.groupby(tg) + + with tm.assert_produces_warning(warn, match=msg): + resampled = series.resample(freq) + for (rk, rv), (gk, gv) in zip(resampled, grouped): + assert rk == gk + tm.assert_series_equal(rv, gv) + + +@all_ts +def test_resample_quantile(series): + # GH 15023 + ser = series + q = 0.75 + freq = "h" + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(series.index, PeriodIndex): + warn = FutureWarning + with tm.assert_produces_warning(warn, match=msg): + result = ser.resample(freq).quantile(q) + expected = ser.resample(freq).agg(lambda x: x.quantile(q)).rename(ser.name) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_skipna(any_real_nullable_dtype, skipna, how): + # GH#57019 + if is_extension_array_dtype(any_real_nullable_dtype): + na_value = Series(dtype=any_real_nullable_dtype).dtype.na_value + else: + na_value = np.nan + df = DataFrame( + { + "a": [2, 1, 1, 2], + "b": [na_value, 3.0, na_value, 4.0], + "c": [na_value, 3.0, na_value, 4.0], + }, + index=date_range("2020-01-01", periods=4, freq="D"), + dtype=any_real_nullable_dtype, + ) + rs = df.resample("ME") + method = getattr(rs, how) + result = method(skipna=skipna) + + gb = df.groupby(df.shape[0] * [pd.to_datetime("2020-01-31")]) + expected = getattr(gb, how)(skipna=skipna) + expected.index.freq = "ME" + tm.assert_frame_equal(result, expected) diff --git a/shared/package-files/bc/bca5db835dac7d61540823370600ded4ed27afcfe1d7eadba38c9d2bf2bb1cd4/vec512_bfloat16.h b/shared/package-files/bc/bca5db835dac7d61540823370600ded4ed27afcfe1d7eadba38c9d2bf2bb1cd4/vec512_bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..f116929f8b088c32b2e09e19cf6a2f764babe06e --- /dev/null +++ b/shared/package-files/bc/bca5db835dac7d61540823370600ded4ed27afcfe1d7eadba38c9d2bf2bb1cd4/vec512_bfloat16.h @@ -0,0 +1,1673 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include + +#if defined(CPU_CAPABILITY_AVX512) +#define SLEEF_STATIC_LIBS +#include +#endif + + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +#ifndef SLEEF_CONST +#if (defined(__GNUC__) || defined(__CLANG__)) && !defined(__INTEL_COMPILER) +#define SLEEF_CONST const +#else +#define SLEEF_CONST +#endif +#define SLEEF_CONST_OLD SLEEF_CONST +#else +#define SLEEF_CONST_OLD +#endif + +// bfloat16 conversion +static inline void cvtbf16_fp32(const __m256i& a, __m512& o) { + o = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(a), 16)); +} + +static inline void cvtbf16_fp32(const __m512i& a, __m512& o1, __m512& o2) { + __m256i lo = _mm512_extracti32x8_epi32(a, 0); + __m256i hi = _mm512_extracti32x8_epi32(a, 1); + cvtbf16_fp32(lo, o1); + cvtbf16_fp32(hi, o2); +} + +static inline __m256i cvtfp32_bf16(const __m512& src) { + __m512i value = _mm512_castps_si512(src); + __m512i nan = _mm512_set1_epi32(0xffff); + auto mask_value = _mm512_cmp_ps_mask(src, src, _CMP_ORD_Q); + __m512i ones = _mm512_set1_epi32(0x1); + __m512i vec_bias = _mm512_set1_epi32(0x7fff); + // uint32_t lsb = (input >> 16) & 1; + auto t_value = _mm512_and_si512(_mm512_srli_epi32(value, 16), ones); + // uint32_t rounding_bias = 0x7fff + lsb; + t_value = _mm512_add_epi32(t_value, vec_bias); + // input += rounding_bias; + t_value = _mm512_add_epi32(t_value, value); + // input = input >> 16; + t_value = _mm512_srli_epi32(t_value, 16); + // Check NaN before converting back to bf16 + t_value = _mm512_mask_blend_epi32(mask_value, nan, t_value); + return _mm512_cvtusepi32_epi16(t_value); +} + +static inline __m512i cvtfp32_bf16(const __m512& a, const __m512& b) { + __m512i lo = _mm512_castps_si512(a); + __m512i hi = _mm512_castps_si512(b); + __m512i nan = _mm512_set1_epi32(0xffff); + auto mask_lo = _mm512_cmp_ps_mask(a, a, _CMP_ORD_Q); + auto mask_hi = _mm512_cmp_ps_mask(b, b, _CMP_ORD_Q); + __m512i ones = _mm512_set1_epi32(0x1); + __m512i vec_bias = _mm512_set1_epi32(0x7fff); + // uint32_t lsb = (input >> 16) & 1; + auto t_lo = _mm512_and_si512(_mm512_srli_epi32(lo, 16), ones); + auto t_hi = _mm512_and_si512(_mm512_srli_epi32(hi, 16), ones); + // uint32_t rounding_bias = 0x7fff + lsb; + t_lo = _mm512_add_epi32(t_lo, vec_bias); + t_hi = _mm512_add_epi32(t_hi, vec_bias); + // input += rounding_bias; + t_lo = _mm512_add_epi32(t_lo, lo); + t_hi = _mm512_add_epi32(t_hi, hi); + // input = input >> 16; + t_lo = _mm512_srli_epi32(t_lo, 16); + t_hi = _mm512_srli_epi32(t_hi, 16); + // Check NaN before converting back to bf16 + t_lo = _mm512_mask_blend_epi32(mask_lo, nan, t_lo); + t_hi = _mm512_mask_blend_epi32(mask_hi, nan, t_hi); + + t_lo = _mm512_packus_epi32(t_lo, t_hi); // t_hi[4-7] t_lo[4-7] t_hi[0-4] t_lo[0-4] + __m512i idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); + return _mm512_permutexvar_epi64(idx, t_lo); +} + +static inline __m512i merge_compare_result(const __m512& a, const __m512& b) { + __m512i lo = _mm512_castps_si512(a); + __m512i hi = _mm512_castps_si512(b); + lo = _mm512_srli_epi32(lo, 16); + hi = _mm512_srli_epi32(hi, 16); + auto out = _mm512_packus_epi32(lo, hi); + __m512i idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); + return _mm512_permutexvar_epi64(idx, out); +} + +// float16 conversion +static inline void cvtfp16_fp32(const __m256i& a, __m512& o) { + o = _mm512_cvtph_ps(a); +} + +static inline void cvtfp16_fp32(const __m512i& a, __m512& o1, __m512& o2) { + __m256i lo = _mm512_extracti32x8_epi32(a, 0); + __m256i hi = _mm512_extracti32x8_epi32(a, 1); + cvtfp16_fp32(lo, o1); + cvtfp16_fp32(hi, o2); +} + +static inline __m256i cvtfp32_fp16(const __m512& src) { + return _mm512_cvtps_ph( + src, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); +} + +static inline __m512i cvtfp32_fp16(const __m512& a, const __m512& b) { + __m256i lo = _mm512_cvtps_ph( + a, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + __m256i hi = _mm512_cvtps_ph( + b, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + __m512 t_lo = _mm512_castsi512_ps(_mm512_castsi256_si512(lo)); + __m256 t_hi = _mm256_castsi256_ps(hi); + return _mm512_castps_si512(_mm512_insertf32x8(t_lo, t_hi, 1)); +} + +// dtype conversion between float16/bfloat16 and float32 +template , int> = 0> +inline void cvt_to_fp32(const __m256i& a, __m512& o); +template <> inline void cvt_to_fp32(const __m256i& a, __m512& o) { + cvtbf16_fp32(a, o); +} +template <> inline void cvt_to_fp32(const __m256i& a, __m512& o) { + cvtfp16_fp32(a, o); +} + +template , int> = 0> +inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2); +template <> inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2) { + cvtbf16_fp32(a, o1, o2); +} +template <> inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2) { + cvtfp16_fp32(a, o1, o2); +} + +template , int> = 0> +inline __m512i cvt_from_fp32(const __m512& a, const __m512& b); +template <> inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return cvtfp32_bf16(a, b); +} +template <> inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return merge_compare_result(a, b); +} +template <> inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return cvtfp32_fp16(a, b); +} +template <> inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return cvtfp32_fp16(a, b); +} + +template +class Vectorized16 { +static_assert( + is_reduced_floating_point_v, + "Support only float16 and bfloat16."); +private: + __m512i values; +public: + using value_type = uint16_t; + using size_type = int; + static constexpr size_type size() { + return 32; + } + Vectorized16() {} + Vectorized16(__m512i v) : values(v) {} + Vectorized16(T val) { + value_type uw = val.x; + values = _mm512_set1_epi16(uw); + } + Vectorized16(T val1, T val2, T val3, T val4, + T val5, T val6, T val7, T val8, + T val9, T val10, T val11, T val12, + T val13, T val14, T val15, T val16, + T val17, T val18, T val19, T val20, + T val21, T val22, T val23, T val24, + T val25, T val26, T val27, T val28, + T val29, T val30, T val31, T val32) { + values = _mm512_set_epi16( + val32.x, val31.x, val30.x, val29.x, val28.x, val27.x, val26.x, val25.x, + val24.x, val23.x, val22.x, val21.x, val20.x, val19.x, val18.x, val17.x, + val16.x, val15.x, val14.x, val13.x, val12.x, val11.x, val10.x, val9.x, + val8.x, val7.x, val6.x, val5.x, val4.x, val3.x, val2.x, val1.x); + } + operator __m512i() const { + return values; + } + T& operator[](int idx) = delete; + const T& operator[](int idx) const = delete; + int zero_mask() const { + // returns an integer mask where all zero elements are translated to 1-bit and others are translated to 0-bit + return _mm512_cmpeq_epi16_mask(values, _mm512_set1_epi16(0)); + } + static Vectorized loadu(const void* ptr, int16_t count = size()) { + if (count == size()) + return _mm512_loadu_si512(reinterpret_cast(ptr)); + + __mmask32 mask = (1ULL << count) - 1; + return _mm512_maskz_loadu_epi16(mask, ptr); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + __mmask32 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi16(ptr, mask, values); + } + } + template + static Vectorized blend(const Vectorized& a, const Vectorized& b) { + return _mm512_mask_blend_epi16(mask, a.values, b.values); + } + static Vectorized blendv(const Vectorized& a, + const Vectorized& b, const Vectorized& mask) { + auto all_ones = _mm512_set1_epi16(0xFFFF); + auto mask_ = _mm512_cmp_epi16_mask(mask, all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi16(mask_, a.values, b.values); + } + template + static Vectorized arange(T base = 0.f, step_t step = static_cast(1)) { + return Vectorized( + base, base + step, base + 2 * step, base + 3 * step, + base + 4 * step, base + 5 * step, base + 6 * step, base + 7 * step, + base + 8 * step, base + 9 * step, base + 10 * step, base + 11 * step, + base + 12 * step, base + 13 * step, base + 14 * step, base + 15 * step, + base + 16 * step, base + 17 * step, base + 18 * step, base + 19 * step, + base + 20 * step, base + 21 * step, base + 22 * step, base + 23 * step, + base + 24 * step, base + 25 * step, base + 26 * step, base + 27 * step, + base + 28 * step, base + 29 * step, base + 30 * step, base + 31 * step); + } + static Vectorized set(const Vectorized& a, + const Vectorized& b, int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + case 8: + return blend<255>(a, b); + case 9: + return blend<511>(a, b); + case 10: + return blend<1023>(a, b); + case 11: + return blend<2047>(a, b); + case 12: + return blend<4095>(a, b); + case 13: + return blend<8191>(a, b); + case 14: + return blend<16383>(a, b); + case 15: + return blend<32767>(a, b); + case 16: + return blend<65535>(a, b); + case 17: + return blend<131071>(a, b); + case 18: + return blend<262143>(a, b); + case 19: + return blend<524287>(a, b); + case 20: + return blend<1048575>(a, b); + case 21: + return blend<2097151>(a, b); + case 22: + return blend<4194303>(a, b); + case 23: + return blend<8388607>(a, b); + case 24: + return blend<16777215>(a, b); + case 25: + return blend<33554431>(a, b); + case 26: + return blend<67108863>(a, b); + case 27: + return blend<134217727>(a, b); + case 28: + return blend<268435455>(a, b); + case 29: + return blend<536870911>(a, b); + case 30: + return blend<1073741823>(a, b); + case 31: + return blend<2147483647>(a, b); + } + return b; + } + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wignored-qualifiers" + + Vectorized map(SLEEF_CONST __m512 (*SLEEF_CONST_OLD vop)(__m512)) const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + const auto o1 = vop(lo); + const auto o2 = vop(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized isnan() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __mmask16 lo_mask, hi_mask; + __m512 zero = _mm512_set1_ps(0.0); + __m512i zeroi = _mm512_castps_si512(zero); + lo_mask = _mm512_cmp_ps_mask(lo, zero, _CMP_UNORD_Q); + lo = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zeroi, lo_mask, 0xFFFF'FFFF)); + hi_mask = _mm512_cmp_ps_mask(hi, zero, _CMP_UNORD_Q); + hi = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zeroi, hi_mask, 0xFFFF'FFFF)); + return merge_compare_result(lo, hi); + } + #pragma clang diagnostic pop + Vectorized abs() const { + return _mm512_andnot_si512(_mm512_set1_epi16(0x8000), values); + } + Vectorized angle() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto angle_lambda = [](__m512 values) { + const auto zero_vec = _mm512_set1_ps(0.f); + const auto nan_vec = _mm512_set1_ps(NAN); + const auto not_nan_mask = _mm512_cmp_ps_mask(values, values, _CMP_EQ_OQ); + const auto non_nan_mask_vec = _mm512_mask_set1_epi32(_mm512_castps_si512(zero_vec), + not_nan_mask, 0xFFFFFFFF); + const auto nan_mask = _mm512_cmp_ps_mask(_mm512_castsi512_ps(non_nan_mask_vec), + zero_vec, _CMP_EQ_OQ); + const auto pi = _mm512_set1_ps(c10::pi); + + const auto neg_mask = _mm512_cmp_ps_mask(values, zero_vec, _CMP_LT_OQ); + auto angle = _mm512_mask_blend_ps(neg_mask, zero_vec, pi); + angle = _mm512_mask_blend_ps(nan_mask, angle, nan_vec); + return angle; + }; + auto o1 = angle_lambda(lo); + auto o2 = angle_lambda(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi16(0); + } + Vectorized conj() const { + return *this; + } + Vectorized acos() const { + return map(Sleef_acosf16_u10); + } + Vectorized acosh() const { + return map(Sleef_acoshf16_u10); + } + Vectorized asin() const { + return map(Sleef_asinf16_u10); + } + Vectorized asinh() const { + return map(Sleef_asinhf16_u10); + } + Vectorized atan() const { + return map(Sleef_atanf16_u10); + } + Vectorized atanh() const { + return map(Sleef_atanhf16_u10); + } + Vectorized atan2(const Vectorized &b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_atan2f16_u10(lo, b1); + auto o2 = Sleef_atan2f16_u10(hi, b2); + return cvt_from_fp32(o1, o2); + } + Vectorized copysign(const Vectorized &sign) const { + // copy sign bit (0x8000) from sign and remaining bits from values + __m512i mask_value = _mm512_set1_epi32(~0x80008000); + __m512i mask_signbit = _mm512_set1_epi32(0x80008000); + return Vectorized( + _mm512_or_si512( + _mm512_and_si512(values, mask_value), + _mm512_and_si512(sign, mask_signbit))); + } + Vectorized erf() const { + return map(Sleef_erff16_u10); + } + Vectorized erfc() const { + return map(Sleef_erfcf16_u15); + } + Vectorized erfinv() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + for (int64_t i = 0; i < size() / 2; i++) { + tmp1[i] = calc_erfinv(tmp1[i]); + tmp2[i] = calc_erfinv(tmp2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized exp() const { + return map(Sleef_expf16_u10); + } + Vectorized exp2() const { + return map(Sleef_exp2f16_u10); + } + Vectorized expm1() const { + return map(Sleef_expm1f16_u10); + } + Vectorized exp_u20() const { + return exp(); + } + Vectorized fmod(const Vectorized & q) const { + __m512 x_lo, x_hi; + cvt_to_fp32(values, x_lo, x_hi); + __m512 q_lo, q_hi; + cvtbf16_fp32(q.values, q_lo, q_hi); + auto o1 = Sleef_fmodf16(x_lo, q_lo); + auto o2 = Sleef_fmodf16(x_hi, q_hi); + return cvt_from_fp32(o1, o2); + } + Vectorized hypot(const Vectorized &b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_hypotf16_u05(lo, b1); + auto o2 = Sleef_hypotf16_u05(hi, b2); + return cvt_from_fp32(o1, o2); + } + Vectorized i0() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + for (int64_t i = 0; i < size() / 2; i++) { + tmp1[i] = calc_i0(tmp1[i]); + tmp2[i] = calc_i0(tmp2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized i0e() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + constexpr auto sz = size(); + __at_align__ float tmp1[sz / 2], tmp2[sz / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + + for (auto i = decltype(sz){0}; i < sz / 2; i++) { + tmp1[i] = calc_i0e(tmp1[i]); + tmp2[i] = calc_i0e(tmp2[i]); + } + const auto o1 = _mm512_loadu_ps(tmp1); + const auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized digamma() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + constexpr auto sz = size(); + __at_align__ float tmp1[sz / 2], tmp2[sz / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + + for (auto i = decltype(sz){0}; i < sz / 2; i++) { + tmp1[i] = calc_digamma(tmp1[i]); + tmp2[i] = calc_digamma(tmp2[i]); + } + const auto o1 = _mm512_loadu_ps(tmp1); + const auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized igamma(const Vectorized &x) const { + __m512 lo, hi; + __m512 xlo, xhi; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(x.values, xlo, xhi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + __at_align__ float tmpx1[size() / 2], tmpx2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmpx1), xlo); + _mm512_storeu_ps(reinterpret_cast(tmpx2), xhi); + for (int64_t i = 0; i < size() / 2; ++i) { + tmp1[i] = calc_igamma(tmp1[i], tmpx1[i]); + tmp2[i] = calc_igamma(tmp2[i], tmpx2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + + Vectorized igammac(const Vectorized &x) const { + __m512 lo, hi; + __m512 xlo, xhi; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(x.values, xlo, xhi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + __at_align__ float tmpx1[size() / 2], tmpx2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmpx1), xlo); + _mm512_storeu_ps(reinterpret_cast(tmpx2), xhi); + for (int64_t i = 0; i < size() / 2; ++i) { + tmp1[i] = calc_igammac(tmp1[i], tmpx1[i]); + tmp2[i] = calc_igammac(tmp2[i], tmpx2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized log() const { + return map(Sleef_logf16_u10); + } + Vectorized log2() const { + return map(Sleef_log2f16_u10); + } + Vectorized log10() const { + return map(Sleef_log10f16_u10); + } + Vectorized log1p() const { + return map(Sleef_log1pf16_u10); + } + Vectorized sin() const { + return map(Sleef_sinf16_u10); + } + Vectorized sinh() const { + return map(Sleef_sinhf16_u10); + } + Vectorized cos() const { + return map(Sleef_cosf16_u10); + } + Vectorized cosh() const { + return map(Sleef_coshf16_u10); + } + Vectorized ceil() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_ceil_ps(lo); + auto o2 = _mm512_ceil_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized floor() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_floor_ps(lo); + auto o2 = _mm512_floor_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized neg() const { + return _mm512_xor_si512(values, _mm512_set1_epi16(0x8000)); + } + Vectorized round() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_roundscale_ps(lo, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + auto o2 = _mm512_roundscale_ps(hi, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return cvt_from_fp32(o1, o2); + } + Vectorized tan() const { + return map(Sleef_tanf16_u10); + } + Vectorized tanh() const { + return map(Sleef_tanhf16_u10); + } + Vectorized trunc() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_roundscale_ps(lo, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + auto o2 = _mm512_roundscale_ps(hi, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + return cvt_from_fp32(o1, o2); + } + Vectorized lgamma() const { + return map(Sleef_lgammaf16_u10); + } + Vectorized sqrt() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_sqrt_ps(lo); + auto o2 = _mm512_sqrt_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized reciprocal() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto ones = _mm512_set1_ps(1); + auto o1 = _mm512_div_ps(ones, lo); + auto o2 = _mm512_div_ps(ones, hi); + return cvt_from_fp32(o1, o2); + } + Vectorized rsqrt() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto ones = _mm512_set1_ps(1); + auto o1 = _mm512_div_ps(ones, _mm512_sqrt_ps(lo)); + auto o2 = _mm512_div_ps(ones, _mm512_sqrt_ps(hi)); + return cvt_from_fp32(o1, o2); + } + Vectorized pow(const Vectorized &b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_powf16_u10(lo, b1); + auto o2 = Sleef_powf16_u10(hi, b2); + return cvt_from_fp32(o1, o2); + } +private: + template + Vectorized inline binary_compare(const VectorizedType& b, Op op) const { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvt_to_fp32(values, a_lo, a_hi); + cvt_to_fp32(b.values, b_lo, b_hi); + auto o1 = op(a_lo, b_lo); + auto o2 = op(a_hi, b_hi); + return cvt_from_fp32(o1, o2); + } + +public: + Vectorized inline operator>(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GT_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator<(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LT_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator>=(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GE_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator<=(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LE_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator==(const Vectorized16& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_EQ_OQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator!=(const Vectorized16& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_NEQ_UQ); + return _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } +}; + +template +static inline Vectorized binary_op_as_fp32(const Vectorized& a, const Vectorized& b, Op op) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvt_to_fp32(__m512i(a), a_lo, a_hi); + cvt_to_fp32(__m512i(b), b_lo, b_hi); + auto o1 = op(a_lo, b_lo); + auto o2 = op(a_hi, b_hi); + return cvt_from_fp32(o1, o2); +} + +template <> +class Vectorized: public Vectorized16 { +public: + using Vectorized16::Vectorized16; + + using value_type = BFloat16; + + Vectorized frac() const; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_add_ps(x, y); }); +} +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_sub_ps(x, y); }); +} +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_mul_ps(x, y); }); +} +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_div_ps(x, y); }); +} +Vectorized inline operator&(const Vectorized& a, const Vectorized& b) { + return _mm512_and_si512(a, b); +} +Vectorized inline operator|(const Vectorized& a, const Vectorized& b) { + return _mm512_or_si512(a, b); +} +Vectorized inline operator^(const Vectorized& a, const Vectorized& b) { + return _mm512_xor_si512(a, b); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +// frac. Implement this here so we can use subtraction +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + auto max_lo = _mm512_max_ps(a_lo, b_lo); + auto max_hi = _mm512_max_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_set1_epi32(nan_lo_mask)); + auto nan_hi = _mm512_castsi512_ps(_mm512_set1_epi32(nan_hi_mask)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(max_lo, nan_lo); + auto o2 = _mm512_or_ps(max_hi, nan_hi); + return cvtfp32_bf16(o1, o2); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512i zero_vec = _mm512_set1_epi32(0); + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + auto min_lo = _mm512_min_ps(a_lo, b_lo); + auto min_hi = _mm512_min_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, nan_lo_mask, + 0xFFFFFFFF)); + auto nan_hi = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, nan_hi_mask, + 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(min_lo, nan_lo); + auto o2 = _mm512_or_ps(min_hi, nan_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp(const Vectorized& a, + const Vectorized& min, const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + __m512 max_lo, max_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(min), min_lo, min_hi); + cvtbf16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, _mm512_max_ps(min_lo, a_lo)); + auto o2 = _mm512_min_ps(max_hi, _mm512_max_ps(min_hi, a_hi)); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 max_lo, max_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, a_lo); + auto o2 = _mm512_min_ps(max_hi, a_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(min), min_lo, min_hi); + auto o1 = _mm512_max_ps(min_lo, a_lo); + auto o2 = _mm512_max_ps(min_hi, a_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +inline void convert(const BFloat16* src, BFloat16* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); i += Vectorized::size()) { + auto vsrc = _mm512_loadu_si512(reinterpret_cast<__m512i*>((void*)(src + i))); + _mm512_storeu_si512(reinterpret_cast<__m512i*>((void*)(dst + i)), vsrc); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +inline void convert(const float* src, BFloat16* dst, int64_t n) { + int64_t i; + for (i = 0; i + Vectorized::size() <= n; i += Vectorized::size()) { + __m512 a = _mm512_loadu_ps(&src[i]); + __m512 b = _mm512_loadu_ps(&src[i + 16]); + + __m512i bf = cvtfp32_bf16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +inline void convert(const double* src, BFloat16* dst, int64_t n) { + auto load_float = [](const double *src) -> __m512 { + // Load one float vector from an array of doubles + __m256 a = _mm512_cvtpd_ps(_mm512_loadu_pd(src)); + __m256 b = _mm512_cvtpd_ps(_mm512_loadu_pd(src + 8)); + return _mm512_insertf32x8(_mm512_castps256_ps512(a), b, 1); + }; + + int64_t i; + for (i = 0; i + Vectorized::size() <= n; i += Vectorized::size()) { + __m512 a = load_float(&src[i]); + __m512 b = load_float(&src[i + 16]); + + __m512i bf = cvtfp32_bf16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +Vectorized inline fmadd(const Vectorized& a, + const Vectorized& b, const Vectorized& c) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512 c_lo, c_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + cvtbf16_fp32(__m512i(c), c_lo, c_hi); + auto o1 = _mm512_fmadd_ps(a_lo, b_lo, c_lo); + auto o2 = _mm512_fmadd_ps(a_hi, b_hi, c_hi); + return cvtfp32_bf16(o1, o2); +} + +static inline void _transpose_mxn_half_16_16(__m256i t[], __m512i u[]) { + __m512i r[8]; + // a0a1 a2a3 a4a5 a6a7 a8a9 a10a11 a12a13 a14a15 e0e1 e2e3 e4e5 e6e7 e8e9 e10e11 e12e13 e14e15 + // b0-b15 f0-f15 + // c0-c15 g0-g15 + // d0-d15 h0-h15 + // i0-i15 m0-m15 + // j0-j15 n0-n15 + // k0-k15 o0-o15 + // l0-l15 p0-p15 +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; i++) { + r[i] = _mm512_inserti64x4(_mm512_castsi256_si512(t[i]), t[i + 4], 0x01); + r[i + 4] = _mm512_inserti64x4(_mm512_castsi256_si512(t[i + 8]), t[i + 12], 0x01); + } + + // u0: a0a1 b0b1 a2a3 b2b3 a8a9 b8b9 a10a11 b10b11 e0e1 f0f1 e2e3 f2f3 e8e9 f8f9 e10e11 f10f11 + // u1: a4a5 b4b5 a6a7 b6b7 a12a13 b12b13 a14a15 b14b15 e4e5 f4f5 e6e7 f6f7 e12e13 f12f13 e14e15 f14f15 + // u2: c0c1 d0d1 c2c3 d2d3 c8c9 d8d9 c10c11 d10d11 g0g1 h0h1 g2g3 h2h3 g8g9 h8h9 g10g11 h10h11 + // u3: c4c5 d4b5 c6c7 d6b7 c12c13 d12d13 c14c15 d14d15 g4g5 h4h5 g6g7 h6h7 g12g13 h12h13 g14g15 h14h15 + // i j m n + // k l o p +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 8; i += 2) { + u[i] = _mm512_unpacklo_epi32(r[i], r[i + 1]); + u[i + 1] = _mm512_unpackhi_epi32(r[i], r[i + 1]); + } + + // r0: a0a1 b0b1 c0c1 d0d1 a8a9 b8b9 c8c9 d8d9 e0e1 f0f1 g0g1 h0h1 e8e9 f8f9 g8g9 h8h9 + // r1: a2a3 b2b3 c2c3 d2d3 a10a11 b10b11 c10c11 d10d11 e2e3 f2f3 g2g3 h2h3 e10e11 f10f11 g10g11 h10h11 + // r2: a4a5 b4b5 c4c5 d4b5 a12a13 b12b13 c12c13 d12d13 + // r3: a6a7 b6b7 c6c7 d6b7 a14a15 b14b15 c14c15 d14d15 + // r4: i j k l m n o p + r[0] = _mm512_unpacklo_epi64(u[0], u[2]); + r[1] = _mm512_unpackhi_epi64(u[0], u[2]); + r[2] = _mm512_unpacklo_epi64(u[1], u[3]); + r[3] = _mm512_unpackhi_epi64(u[1], u[3]); + r[4] = _mm512_unpacklo_epi64(u[4], u[6]); + r[5] = _mm512_unpackhi_epi64(u[4], u[6]); + r[6] = _mm512_unpacklo_epi64(u[5], u[7]); + r[7] = _mm512_unpackhi_epi64(u[5], u[7]); + + __m512i const1 = _mm512_set_epi32( + 0x00370035, + 0x00330031, + 0x00270025, + 0x00230021, + 0x00170015, + 0x00130011, + 0x00070005, + 0x00030001, + 0x00360034, + 0x00320030, + 0x00260024, + 0x00220020, + 0x00160014, + 0x00120010, + 0x00060004, + 0x00020000); + __m512i const2 = _mm512_set_epi32( + 0x003f003d, + 0x003b0039, + 0x002f002d, + 0x002b0029, + 0x001f001d, + 0x001b0019, + 0x000f000d, + 0x000b0009, + 0x003e003c, + 0x003a0038, + 0x002e002c, + 0x002a0028, + 0x001e001c, + 0x001a0018, + 0x000e000c, + 0x000a0008); + // merge values from two regs + // 0-- 1-- + // 8-- 9-- + // 2-- 3-- + // 10-- 11-- + // 4-- 5-- + // 12-- 13-- + // 6-- 7-- + // 14-- 15-- +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; i++) { + u[i] = _mm512_permutex2var_epi16(r[i], const1, r[i + 4]); + u[i + 4] = _mm512_permutex2var_epi16(r[i], const2, r[i + 4]); + } +} + +// TODO(Leslie): Add the AVX2 Version of transpose_mxn for BFloat16 and Float16 +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L1483-L1607 +template<> +inline void transpose_mxn( + const BFloat16* src, + int64_t ld_src, + BFloat16* dst, + int64_t ld_dst) { + __m256i t[16]; + // load from src to registers + // a: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 + // b: b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 + // c: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 + // d: d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 + // e: e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 e13 e14 e15 + // f: f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 + // g: g0 g1 g2 g3 g4 g5 g6 g7 g8 g9 g10 g11 g12 g13 g14 g15 + // h: h0 h1 h2 h3 h4 h5 h6 h7 h8 h9 h10 h11 h12 h13 h14 h15 + // i: i0 i1 i2 i3 i4 i5 i6 i7 i8 i9 i10 i11 i12 i13 i14 i15 + // j: j0 j1 j2 j3 j4 j5 j6 j7 j8 j9 j10 j11 j12 j13 j14 j15 + // k: k0 k1 k2 k3 k4 k5 k6 k7 k8 k9 k10 k11 k12 k13 k14 k15 + // l: l0 l1 l2 l3 l4 l5 l6 l7 l8 l9 l10 l11 l12 l13 l14 l15 + // m: m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15 + // n: n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 + // o: o0 o1 o2 o3 o4 o5 o6 o7 o8 o9 o10 o11 o12 o13 o14 o15 + // p: p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; i++) { + t[i] = _mm256_loadu_si256(reinterpret_cast(src + i * ld_src)); + } + + __m512i u[8]; + _transpose_mxn_half_16_16(t, u); + +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; i++) { + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x0)); + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2 + 1) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x01)); + } +} + +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L1483-L1607 +template<> +inline void transpose_mxn( + const Half* src, + int64_t ld_src, + Half* dst, + int64_t ld_dst) { + __m256i t[16]; + // load from src to registers + // Same matrix indices as above transpose_mxn +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; i++) { + t[i] = _mm256_loadu_si256(reinterpret_cast(src + i * ld_src)); + } + + __m512i u[8]; + _transpose_mxn_half_16_16(t, u); + +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; i++) { + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x0)); + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2 + 1) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x01)); + } +} + +static inline void _transpose_mxn_half_32_32(__m512i r[], __m512i d[]) { + // t[0]: 0 32 1 33 2 34 3 35 8 40 9 41 10 42 11 43 16 ... 59 + // t[1]: 4 36 5 37 6 38 7 39 12 44 13 45 14 46 15 47 20 ... 63 + // t[2]: 64 96 65 97 66 98 67 99 72 104 73 105 74 106 75 ... 123 + // t[3]: 68 100 69 101 70 102 71 103 76 108 77 109 78 110 79 111 84 ... 127 + // t[4]: 128 160 129 161 130 162 131 163 136 168 137 169 138 170 139 171 144 ... 187 + // t[5]: 132 164 133 165 134 166 135 167 140 172 141 173 142 174 143 175 148 ... 191 + // t[6]: 192 224 193 225 194 226 195 227 200 232 201 233 202 234 203 235 208 ... 251 + // t[7]: 196 228 197 229 198 230 199 231 204 236 205 237 206 238 207 239 212 ... 255 + // t[8]: 256 288 257 289 258 290 259 291 264 296 265 297 266 298 267 299 272 ... 315 + // t[9]: 260 292 261 293 262 294 263 295 268 300 269 301 270 302 271 303 276 ... 319 + // t[10]: 320 352 321 353 322 354 323 355 328 360 329 361 330 362 331 363 336 ... 379 + // t[11]: 324 356 325 357 326 358 327 359 332 364 333 365 334 366 335 367 340 ... 383 + // t[12]: 384 416 385 417 386 418 387 419 392 424 393 425 394 426 395 427 400 ... 443 + // t[13]: 388 420 389 421 390 422 391 423 396 428 397 429 398 430 399 431 404 ... 447 + // t[14]: 448 480 449 481 450 482 451 483 456 488 457 489 458 490 459 491 464 ... 507 + // t[15]: 452 484 453 485 454 486 455 487 460 492 461 493 462 494 463 495 468 ... 511 + // t[16]: 512 544 513 545 514 546 515 547 520 552 521 553 522 554 523 555 528 ... 571 + // ... + // t[31]: 964 996 965 997 966 998 967 999 972 1004 973 1005 974 1006 975 1007 980 ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; ++i) { + d[i * 2] = _mm512_unpacklo_epi16(r[i * 2], r[i * 2 + 1]); + d[i * 2 + 1] = _mm512_unpackhi_epi16(r[i * 2], r[i * 2 + 1]); + } + + // t[0]: 0 32 64 96 1 33 65 97 8 40 72 104 9 41 73 105 16 ... 121 + // t[1]: 2 34 66 98 3 35 67 99 10 42 74 106 11 43 75 107 18 ... 123 + // t[2]: 4 36 68 100 5 37 69 101 12 44 76 108 13 45 77 109 20 ... 125 + // t[3]: 6 38 70 102 7 39 71 103 14 46 78 110 15 47 79 111 22 ... 127 + // t[4]: 128 160 192 224 129 161 193 225 136 168 200 232 137 169 201 233 144 ... 249 + // t[5]: 130 162 194 226 131 163 195 227 138 170 202 234 139 171 203 235 146 ... 251 + // t[6]: 132 164 196 228 133 165 197 229 140 172 204 236 141 173 205 237 148 ... 253 + // t[7]: 134 166 198 230 135 167 199 231 142 174 206 238 143 175 207 239 150 ... 255 + // t[8]: 256 288 320 352 257 289 321 353 264 296 328 360 265 297 329 361 272 ... 377 + // t[9]: 258 290 322 354 259 291 323 355 266 298 330 362 267 299 331 363 274 ... 379 + // t[10]: 260 292 324 356 261 293 325 357 268 300 332 364 269 301 333 365 276 ... 381 + // t[11]: 262 294 326 358 263 295 327 359 270 302 334 366 271 303 335 367 278 ... 383 + // t[12]: 384 416 448 480 385 417 449 481 392 424 456 488 393 425 457 489 400 ... 505 + // t[13]: 386 418 450 482 387 419 451 483 394 426 458 490 395 427 459 491 402 ... 507 + // t[14]: 388 420 452 484 389 421 453 485 396 428 460 492 397 429 461 493 404 ... 509 + // t[15]: 390 422 454 486 391 423 455 487 398 430 462 494 399 431 463 495 406 ... 511 + // t[16]: 512 544 576 608 513 545 577 609 520 552 584 616 521 553 585 617 528 ... 633 + // ... + // t[31]: 902 934 966 998 903 935 967 999 910 942 974 1006 911 943 975 1007 918 ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; ++i) { + r[i * 4] = _mm512_unpacklo_epi32(d[i * 4], d[i * 4 + 2]); + r[i * 4 + 1] = _mm512_unpackhi_epi32(d[i * 4], d[i * 4 + 2]); + r[i * 4 + 2] = _mm512_unpacklo_epi32(d[i * 4 + 1], d[i * 4 + 3]); + r[i * 4 + 3] = _mm512_unpackhi_epi32(d[i * 4 + 1], d[i * 4 + 3]); + } + + // t[0]: 0 32 64 96 128 160 192 224 8 40 72 104 136 168 200 232 16 ... 248 + // t[1]: 1 33 65 97 129 161 193 225 9 41 73 105 137 169 201 233 17 ... 249 + // t[2]: 2 34 66 98 130 162 194 226 10 42 74 106 138 170 202 234 18 ... 250 + // t[3]: 3 35 67 99 131 163 195 227 11 43 75 107 139 171 203 235 19 ... 251 + // t[4]: 4 36 68 100 132 164 196 228 12 44 76 108 140 172 204 236 20 ... 252 + // t[5]: 5 37 69 101 133 165 197 229 13 45 77 109 141 173 205 237 21 ... 253 + // t[6]: 6 38 70 102 134 166 198 230 14 46 78 110 142 174 206 238 22 ... 254 + // t[7]: 7 39 71 103 135 167 199 231 15 47 79 111 143 175 207 239 23 ... 255 + // t[8]: 256 288 320 352 384 416 448 480 264 296 328 360 392 424 456 488 272 ... 504 + // t[9]: 257 289 321 353 385 417 449 481 265 297 329 361 393 425 457 489 273 ... 505 + // t[10]: 258 290 322 354 386 418 450 482 266 298 330 362 394 426 458 490 274 ... 506 + // t[11]: 259 291 323 355 387 419 451 483 267 299 331 363 395 427 459 491 275 ... 507 + // t[12]: 260 292 324 356 388 420 452 484 268 300 332 364 396 428 460 492 276 ... 508 + // t[13]: 261 293 325 357 389 421 453 485 269 301 333 365 397 429 461 493 277 ... 509 + // t[14]: 262 294 326 358 390 422 454 486 270 302 334 366 398 430 462 494 278 ... 510 + // t[15]: 263 295 327 359 391 423 455 487 271 303 335 367 399 431 463 495 279 ... 511 + // t[16]: 512 544 576 608 640 672 704 736 520 552 584 616 648 680 712 744 528 ... 760 + // ... + // t[31]: 775 807 839 871 903 935 967 999 783 815 847 879 911 943 975 1007 791 ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; ++i) { + d[i * 8] = _mm512_unpacklo_epi64(r[i * 8], r[i * 8 + 4]); + d[i * 8 + 1] = _mm512_unpackhi_epi64(r[i * 8], r[i * 8 + 4]); + d[i * 8 + 2] = _mm512_unpacklo_epi64(r[i * 8 + 1], r[i * 8 + 5]); + d[i * 8 + 3] = _mm512_unpackhi_epi64(r[i * 8 + 1], r[i * 8 + 5]); + d[i * 8 + 4] = _mm512_unpacklo_epi64(r[i * 8 + 2], r[i * 8 + 6]); + d[i * 8 + 5] = _mm512_unpackhi_epi64(r[i * 8 + 2], r[i * 8 + 6]); + d[i * 8 + 6] = _mm512_unpacklo_epi64(r[i * 8 + 3], r[i * 8 + 7]); + d[i * 8 + 7] = _mm512_unpackhi_epi64(r[i * 8 + 3], r[i * 8 + 7]); + } + + // t[0]: 0 32 64 96 128 160 192 224 256 288 320 352 384 416 448 480 16 ... 496 + // t[1]: 1 33 65 97 129 161 193 225 257 289 321 353 385 417 449 481 17 ... 497 + // t[2]: 2 34 66 98 130 162 194 226 258 290 322 354 386 418 450 482 18 ... 498 + // t[3]: 3 35 67 99 131 163 195 227 259 291 323 355 387 419 451 483 19 ... 499 + // t[4]: 4 36 68 100 132 164 196 228 260 292 324 356 388 420 452 484 20 ... 500 + // t[5]: 5 37 69 101 133 165 197 229 261 293 325 357 389 421 453 485 21 ... 501 + // t[6]: 6 38 70 102 134 166 198 230 262 294 326 358 390 422 454 486 22 ... 502 + // t[7]: 7 39 71 103 135 167 199 231 263 295 327 359 391 423 455 487 23 ... 503 + // t[8]: 8 40 72 104 136 168 200 232 264 296 328 360 392 424 456 488 24 ... 504 + // t[9]: 9 41 73 105 137 169 201 233 265 297 329 361 393 425 457 489 25 ... 505 + // t[10]: 10 42 74 106 138 170 202 234 266 298 330 362 394 426 458 490 26 ... 506 + // t[11]: 11 43 75 107 139 171 203 235 267 299 331 363 395 427 459 491 27 ... 507 + // t[12]: 12 44 76 108 140 172 204 236 268 300 332 364 396 428 460 492 28 ... 508 + // t[13]: 13 45 77 109 141 173 205 237 269 301 333 365 397 429 461 493 29 ... 509 + // t[14]: 14 46 78 110 142 174 206 238 270 302 334 366 398 430 462 494 30 ... 510 + // t[15]: 15 47 79 111 143 175 207 239 271 303 335 367 399 431 463 495 31 ... 511 + // t[16]: 512 544 576 608 640 672 704 736 768 800 832 864 896 928 960 992 528 ... 1008 + // ... + // t[31]: 527 559 591 623 655 687 719 751 783 815 847 879 911 943 975 1007 543 ... 1023 + __m512i const1 = _mm512_set_epi64( + 0x000000000000000d, + 0x000000000000000c, + 0x0000000000000005, + 0x0000000000000004, + 0x0000000000000009, + 0x0000000000000008, + 0x0000000000000001, + 0x0000000000000000); + __m512i const2 = _mm512_set_epi64( + 0x000000000000000f, + 0x000000000000000e, + 0x0000000000000007, + 0x0000000000000006, + 0x000000000000000b, + 0x000000000000000a, + 0x0000000000000003, + 0x0000000000000002); +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; ++i) { + r[i] = _mm512_permutex2var_epi64(d[i], /*idx*/const1, d[i + 8]); + r[i + 8] = _mm512_permutex2var_epi64(d[i], /*idx*/const2, d[i + 8]); + r[i + 16] = _mm512_permutex2var_epi64(d[i + 16], /*idx*/const1, d[i + 24]); + r[i + 24] = _mm512_permutex2var_epi64(d[i + 16], /*idx*/const2, d[i + 24]); + } + + // t[0]: 0 32 64 96 128 160 192 224 256 288 320 352 384 416 448 480 512 544 ... 992 + // t[1]: 1 33 65 97 129 161 193 225 257 289 321 353 385 417 449 481 513 545 ... 993 + // t[2]: 2 34 66 98 130 162 194 226 258 290 322 354 386 418 450 482 514 546 ... 994 + // t[3]: 3 35 67 99 131 163 195 227 259 291 323 355 387 419 451 483 515 547 ... 995 + // t[4]: 4 36 68 100 132 164 196 228 260 292 324 356 388 420 452 484 516 548 ... 996 + // t[5]: 5 37 69 101 133 165 197 229 261 293 325 357 389 421 453 485 517 549 ... 997 + // t[6]: 6 38 70 102 134 166 198 230 262 294 326 358 390 422 454 486 518 550 ... 998 + // t[7]: 7 39 71 103 135 167 199 231 263 295 327 359 391 423 455 487 519 551 ... 999 + // t[8]: 8 40 72 104 136 168 200 232 264 296 328 360 392 424 456 488 520 552 ... 1000 + // t[9]: 9 41 73 105 137 169 201 233 265 297 329 361 393 425 457 489 521 553 ... 1001 + // t[10]: 10 42 74 106 138 170 202 234 266 298 330 362 394 426 458 490 522 554 ... 1002 + // t[11]: 11 43 75 107 139 171 203 235 267 299 331 363 395 427 459 491 523 555 ... 1003 + // t[12]: 12 44 76 108 140 172 204 236 268 300 332 364 396 428 460 492 524 556 ... 1004 + // t[13]: 13 45 77 109 141 173 205 237 269 301 333 365 397 429 461 493 525 557 ... 1005 + // t[14]: 14 46 78 110 142 174 206 238 270 302 334 366 398 430 462 494 526 558 ... 1006 + // t[15]: 15 47 79 111 143 175 207 239 271 303 335 367 399 431 463 495 527 559 ... 1007 + // t[16]: 16 48 80 112 144 176 208 240 272 304 336 368 400 432 464 496 528 560 ... 1008 + // ... + // t[31]: 31 63 95 127 159 191 223 255 287 319 351 383 415 447 479 511 543 575 ... 1023 + __m512i const3 = _mm512_set_epi64( + 0x000000000000000b, + 0x000000000000000a, + 0x0000000000000009, + 0x0000000000000008, + 0x0000000000000003, + 0x0000000000000002, + 0x0000000000000001, + 0x0000000000000000); + __m512i const4 = _mm512_set_epi64( + 0x000000000000000f, + 0x000000000000000e, + 0x000000000000000d, + 0x000000000000000c, + 0x0000000000000007, + 0x0000000000000006, + 0x0000000000000005, + 0x0000000000000004); +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; ++i) { + d[i] = _mm512_permutex2var_epi64(r[i], /*idx*/const3, r[i + 16]); + d[i + 16] = _mm512_permutex2var_epi64(r[i], /*idx*/const4, r[i + 16]); + } +} + +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#LL19C6-L19C6 +template<> +inline void transpose_mxn(const BFloat16* src, int64_t ld_src, BFloat16* dst, int64_t ld_dst, int M, int N) { + // load from src + TORCH_CHECK(M <= 32 && N <= 32, "transpose_mxn expects M, N <= 32."); + __m512i r[32]; + int i; + if (N == 32) { + for (i = 0; i < M; ++i) { + r[i] = _mm512_loadu_si512(&src[i * ld_src]); + } + } else { + __mmask32 src_mask = (1 << N) - 1; + for (i = 0; i < M; ++i) { + r[i] = _mm512_maskz_loadu_epi16(src_mask, &src[i * ld_src]); + } + } + for (; i < 32; ++i) { + r[i] = _mm512_setzero_si512(); + } + + __m512i d[32]; + _transpose_mxn_half_32_32(r, d); + + // store to dst + if (M == 32) { + for (i = 0; i < N; ++i) { + _mm512_storeu_si512(&dst[i * ld_dst], d[i]); + } + } else { + __mmask32 dst_mask = (1 << M) - 1; + for (i = 0; i < N; ++i) { + _mm512_mask_storeu_epi16(&dst[i * ld_dst], dst_mask, d[i]); + } + } +} + +template && ((M <= 32 && M != 16) || (N <= 32 && N != 16)), int> = 0> +inline void transpose_mxn(const BFloat16* src, int64_t ld_src, BFloat16* dst, int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +template<> +inline void transpose_mxn(const Half* src, int64_t ld_src, Half* dst, int64_t ld_dst, int M, int N) { + TORCH_CHECK(M <= 32 && N <= 32, "transpose_mxn expects M, N <= 32."); + // load from src + __m512i r[32]; + int i; + if (N == 32) { + for (i = 0; i < M; ++i) { + r[i] = _mm512_loadu_si512(&src[i * ld_src]); + } + } else { + __mmask32 src_mask = (1 << N) - 1; + for (i = 0; i < M; ++i) { + r[i] = _mm512_maskz_loadu_epi16(src_mask, &src[i * ld_src]); + } + } + for (; i < 32; ++i) { + r[i] = _mm512_setzero_si512(); + } + + __m512i d[32]; + _transpose_mxn_half_32_32(r, d); + + // store to dst + if (M == 32) { + for (i = 0; i < N; ++i) { + _mm512_storeu_si512(&dst[i * ld_dst], d[i]); + } + } else { + __mmask32 dst_mask = (1 << M) - 1; + for (i = 0; i < N; ++i) { + _mm512_mask_storeu_epi16(&dst[i * ld_dst], dst_mask, d[i]); + } + } +} + +template && ((M <= 32 && M != 16) || (N <= 32 && N != 16)), int> = 0> +inline void transpose_mxn(const Half* src, int64_t ld_src, Half* dst, int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +template <> +class Vectorized: public Vectorized16 { +public: + using Vectorized16::Vectorized16; + + using value_type = Half; + + Vectorized frac() const; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_add_ps(x, y); }); +} +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_sub_ps(x, y); }); +} +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_mul_ps(x, y); }); +} +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { return _mm512_div_ps(x, y); }); +} + +Vectorized inline operator&(const Vectorized& a, const Vectorized& b) { + return _mm512_and_si512(a, b); +} +Vectorized inline operator|(const Vectorized& a, const Vectorized& b) { + return _mm512_or_si512(a, b); +} +Vectorized inline operator^(const Vectorized& a, const Vectorized& b) { + return _mm512_xor_si512(a, b); +} + +inline Vectorized Vectorized::eq(const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne(const Vectorized& other) const { + return (*this != other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt(const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge(const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt(const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le(const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +// frac. Implement this here so we can use subtraction +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + auto max_lo = _mm512_max_ps(a_lo, b_lo); + auto max_hi = _mm512_max_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_set1_epi32(nan_lo_mask)); + auto nan_hi = _mm512_castsi512_ps(_mm512_set1_epi32(nan_hi_mask)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(max_lo, nan_lo); + auto o2 = _mm512_or_ps(max_hi, nan_hi); + return cvtfp32_fp16(o1, o2); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512i zero_vec = _mm512_set1_epi32(0); + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + auto min_lo = _mm512_min_ps(a_lo, b_lo); + auto min_hi = _mm512_min_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, nan_lo_mask, + 0xFFFFFFFF)); + auto nan_hi = _mm512_castsi512_ps(_mm512_mask_set1_epi32(zero_vec, nan_hi_mask, + 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(min_lo, nan_lo); + auto o2 = _mm512_or_ps(min_hi, nan_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp(const Vectorized& a, + const Vectorized& min, const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + __m512 max_lo, max_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(min), min_lo, min_hi); + cvtfp16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, _mm512_max_ps(min_lo, a_lo)); + auto o2 = _mm512_min_ps(max_hi, _mm512_max_ps(min_hi, a_hi)); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp_max(const Vectorized& a, const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 max_lo, max_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, a_lo); + auto o2 = _mm512_min_ps(max_hi, a_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp_min(const Vectorized& a, const Vectorized& min) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(min), min_lo, min_hi); + auto o1 = _mm512_max_ps(min_lo, a_lo); + auto o2 = _mm512_max_ps(min_hi, a_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +inline void convert(const Half* src, Half* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); i += Vectorized::size()) { + auto vsrc = _mm512_loadu_si512(reinterpret_cast<__m512i*>((void*)(src + i))); + _mm512_storeu_si512(reinterpret_cast<__m512i*>((void*)(dst + i)), vsrc); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +inline void convert(const float* src, Half* dst, int64_t n) { + int64_t i; + for (i = 0; i + Vectorized::size() <= n; i += Vectorized::size()) { + __m512 a = _mm512_loadu_ps(&src[i]); + __m512 b = _mm512_loadu_ps(&src[i + 16]); + + __m512i bf = cvtfp32_fp16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +inline void convert(const double* src, Half* dst, int64_t n) { + auto load_float = [](const double *src) -> __m512 { + // Load one float vector from an array of doubles + __m256 a = _mm512_cvtpd_ps(_mm512_loadu_pd(src)); + __m256 b = _mm512_cvtpd_ps(_mm512_loadu_pd(src + 8)); + return _mm512_insertf32x8(_mm512_castps256_ps512(a), b, 1); + }; + + int64_t i; + for (i = 0; i + Vectorized::size() <= n; i += Vectorized::size()) { + __m512 a = load_float(&src[i]); + __m512 b = load_float(&src[i + 16]); + + __m512i bf = cvtfp32_fp16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +Vectorized inline fmadd(const Vectorized& a, + const Vectorized& b, const Vectorized& c) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512 c_lo, c_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + cvtfp16_fp32(__m512i(c), c_lo, c_hi); + auto o1 = _mm512_fmadd_ps(a_lo, b_lo, c_lo); + auto o2 = _mm512_fmadd_ps(a_hi, b_hi, c_hi); + return cvtfp32_fp16(o1, o2); +} + +#define CONVERT_VECTORIZED_INIT(type, name) \ +inline std::tuple, Vectorized> convert_##name##_float(const Vectorized& a) { \ + __m512 o1, o2; \ + cvt_to_fp32(__m512i(a), o1, o2); \ + return std::make_tuple(o1, o2); \ +} \ +\ +inline Vectorized convert_float_##name(const Vectorized& a, const Vectorized& b) { \ + return cvt_from_fp32(__m512(a), __m512(b)); \ +} +CONVERT_VECTORIZED_INIT(BFloat16, bfloat16) +CONVERT_VECTORIZED_INIT(Half, half) + +#else //defined(CPU_CAPABILITY_AVX512) + +#define CONVERT_NON_VECTORIZED_INIT(type, name) \ +inline std::tuple, Vectorized> convert_##name##_float(const Vectorized& a) { \ + constexpr int64_t K = Vectorized::size(); \ + __at_align__ float arr[K]; \ + __at_align__ type arr2[K]; \ + a.store(arr2); \ + for (const auto k : c10::irange(K)) { \ + arr[k] = c10::convert(arr2[k]); \ + } \ + return std::make_tuple( \ + Vectorized::loadu(arr), \ + Vectorized::loadu(arr + Vectorized::size())); \ +} \ +\ +inline Vectorized convert_float_##name(const Vectorized& a, const Vectorized& b) { \ + constexpr int64_t K = Vectorized::size(); \ + __at_align__ float arr[K]; \ + __at_align__ type arr2[K]; \ + a.store(arr); \ + b.store(arr + Vectorized::size()); \ + for (const auto k : c10::irange(K)) { \ + arr2[k] = c10::convert(arr[k]); \ + } \ + return Vectorized::loadu(arr2); \ +} +CONVERT_NON_VECTORIZED_INIT(BFloat16, bfloat16) +CONVERT_NON_VECTORIZED_INIT(Half, half) + +#endif // defined(CPU_CAPABILITY_AVX512) + +#if defined(CPU_CAPABILITY_AVX512) +#define LOAD_FP32_VECTORIZED_INIT(type, name) \ +inline void load_fp32_from_##name(const type *data, Vectorized& out) { \ + auto values = _mm256_loadu_si256(reinterpret_cast(data)); \ + __m512 out_values; \ + cvt_to_fp32(values, out_values); \ + out = out_values; \ +} \ +\ +inline void load_fp32_from_##name(const type *data, Vectorized& out1, Vectorized& out2) { \ + auto vec = Vectorized::loadu(data); \ + __m512 out1_values, out2_values; \ + cvt_to_fp32(vec, out1_values, out2_values); \ + out1 = out1_values; \ + out2 = out2_values; \ +} +LOAD_FP32_VECTORIZED_INIT(BFloat16, bf16) +LOAD_FP32_VECTORIZED_INIT(Half, fp16) + +#else // defined(CPU_CAPABILITY_AVX512) +#define LOAD_FP32_NON_VECTORIZED_INIT(type, name) \ +inline void load_fp32_from_##name(const type *data, Vectorized& out) { \ + __at_align__ float values[Vectorized::size()]; \ + for (const auto k : c10::irange(Vectorized::size())) { \ + values[k] = data[k]; \ + } \ + out = Vectorized::loadu(values); \ +} \ +\ +inline void load_fp32_from_##name(const type *data, Vectorized& out1, Vectorized& out2) { \ + load_fp32_from_##name(data, out1); \ + data += Vectorized::size(); \ + load_fp32_from_##name(data, out2); \ +} +LOAD_FP32_NON_VECTORIZED_INIT(BFloat16, bf16) +LOAD_FP32_NON_VECTORIZED_INIT(Half, fp16) + +#endif +}} diff --git a/shared/package-files/bc/bca622f62c871bb8550120a846696c165ccb6334d7f9d8ef6dcf70d1b33912dd/test_beamsearch.cpython-311.pyc b/shared/package-files/bc/bca622f62c871bb8550120a846696c165ccb6334d7f9d8ef6dcf70d1b33912dd/test_beamsearch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f5e07956cf8cfd9da44ce7bc013d1ef76703d42 Binary files /dev/null and b/shared/package-files/bc/bca622f62c871bb8550120a846696c165ccb6334d7f9d8ef6dcf70d1b33912dd/test_beamsearch.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcaaadabf846f3bb4df07ff1313ba9b959dfa280604f581ad153f14f79da49e1/special_logit_compositeimplicitautograd_dispatch.h b/shared/package-files/bc/bcaaadabf846f3bb4df07ff1313ba9b959dfa280604f581ad153f14f79da49e1/special_logit_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..298a2979e47591bea6a1f81935c5324eae6b7ba3 --- /dev/null +++ b/shared/package-files/bc/bcaaadabf846f3bb4df07ff1313ba9b959dfa280604f581ad153f14f79da49e1/special_logit_compositeimplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor special_logit(const at::Tensor & self, ::std::optional eps=::std::nullopt); +TORCH_API at::Tensor & special_logit_out(at::Tensor & out, const at::Tensor & self, ::std::optional eps=::std::nullopt); +TORCH_API at::Tensor & special_logit_outf(const at::Tensor & self, ::std::optional eps, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/bc/bcaab72bdee4d210409ce837f279b011d7fb7040d5afdad357209e2689606f80/test_install_data.py b/shared/package-files/bc/bcaab72bdee4d210409ce837f279b011d7fb7040d5afdad357209e2689606f80/test_install_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c800f86c645d86fcb11aa3bef1513325ef163132 --- /dev/null +++ b/shared/package-files/bc/bcaab72bdee4d210409ce837f279b011d7fb7040d5afdad357209e2689606f80/test_install_data.py @@ -0,0 +1,74 @@ +"""Tests for distutils.command.install_data.""" + +import os +import pathlib +from distutils.command.install_data import install_data +from distutils.tests import support + +import pytest + + +@pytest.mark.usefixtures('save_env') +class TestInstallData( + support.TempdirManager, +): + def test_simple_run(self): + pkg_dir, dist = self.create_dist() + cmd = install_data(dist) + cmd.install_dir = inst = os.path.join(pkg_dir, 'inst') + + # data_files can contain + # - simple files + # - a Path object + # - a tuple with a path, and a list of file + one = os.path.join(pkg_dir, 'one') + self.write_file(one, 'xxx') + inst2 = os.path.join(pkg_dir, 'inst2') + two = os.path.join(pkg_dir, 'two') + self.write_file(two, 'xxx') + three = pathlib.Path(pkg_dir) / 'three' + self.write_file(three, 'xxx') + + cmd.data_files = [one, (inst2, [two]), three] + assert cmd.get_inputs() == [one, (inst2, [two]), three] + + # let's run the command + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 3 + rthree = os.path.split(one)[-1] + assert os.path.exists(os.path.join(inst, rthree)) + rtwo = os.path.split(two)[-1] + assert os.path.exists(os.path.join(inst2, rtwo)) + rone = os.path.split(one)[-1] + assert os.path.exists(os.path.join(inst, rone)) + cmd.outfiles = [] + + # let's try with warn_dir one + cmd.warn_dir = True + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 3 + assert os.path.exists(os.path.join(inst, rthree)) + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) + cmd.outfiles = [] + + # now using root and empty dir + cmd.root = os.path.join(pkg_dir, 'root') + inst5 = os.path.join(pkg_dir, 'inst5') + four = os.path.join(cmd.install_dir, 'four') + self.write_file(four, 'xx') + cmd.data_files = [one, (inst2, [two]), three, ('inst5', [four]), (inst5, [])] + cmd.ensure_finalized() + cmd.run() + + # let's check the result + assert len(cmd.get_outputs()) == 5 + assert os.path.exists(os.path.join(inst, rthree)) + assert os.path.exists(os.path.join(inst2, rtwo)) + assert os.path.exists(os.path.join(inst, rone)) diff --git a/shared/package-files/bc/bcaf8f76cba8ace3275929c4913de25094489139d880ed93e8c9c6c43807239a/async_utils.py b/shared/package-files/bc/bcaf8f76cba8ace3275929c4913de25094489139d880ed93e8c9c6c43807239a/async_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c140205c50a3df9863ce1ab610b0c62a483f1b --- /dev/null +++ b/shared/package-files/bc/bcaf8f76cba8ace3275929c4913de25094489139d880ed93e8c9c6c43807239a/async_utils.py @@ -0,0 +1,99 @@ +import inspect +import typing as t +from functools import WRAPPER_ASSIGNMENTS +from functools import wraps + +from .utils import _PassArg +from .utils import pass_eval_context + +if t.TYPE_CHECKING: + import typing_extensions as te + +V = t.TypeVar("V") + + +def async_variant(normal_func): # type: ignore + def decorator(async_func): # type: ignore + pass_arg = _PassArg.from_obj(normal_func) + need_eval_context = pass_arg is None + + if pass_arg is _PassArg.environment: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].is_async) + + else: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].environment.is_async) + + # Take the doc and annotations from the sync function, but the + # name from the async function. Pallets-Sphinx-Themes + # build_function_directive expects __wrapped__ to point to the + # sync function. + async_func_attrs = ("__module__", "__name__", "__qualname__") + normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) + + @wraps(normal_func, assigned=normal_func_attrs) + @wraps(async_func, assigned=async_func_attrs, updated=()) + def wrapper(*args, **kwargs): # type: ignore + b = is_async(args) + + if need_eval_context: + args = args[1:] + + if b: + return async_func(*args, **kwargs) + + return normal_func(*args, **kwargs) + + if need_eval_context: + wrapper = pass_eval_context(wrapper) + + wrapper.jinja_async_variant = True # type: ignore[attr-defined] + return wrapper + + return decorator + + +_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} + + +async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": + # Avoid a costly call to isawaitable + if type(value) in _common_primitives: + return t.cast("V", value) + + if inspect.isawaitable(value): + return await t.cast("t.Awaitable[V]", value) + + return value + + +class _IteratorToAsyncIterator(t.Generic[V]): + def __init__(self, iterator: "t.Iterator[V]"): + self._iterator = iterator + + def __aiter__(self) -> "te.Self": + return self + + async def __anext__(self) -> V: + try: + return next(self._iterator) + except StopIteration as e: + raise StopAsyncIteration(e.value) from e + + +def auto_aiter( + iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> "t.AsyncIterator[V]": + if hasattr(iterable, "__aiter__"): + return iterable.__aiter__() + else: + return _IteratorToAsyncIterator(iter(iterable)) + + +async def auto_to_list( + value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> t.List["V"]: + return [x async for x in auto_aiter(value)] diff --git a/shared/package-files/bc/bcb13ec5930e7ccc881874ad0c88973bebb7a6d2fac755ec8bdecc6f6d2a5ea7/GemmRocblas.h b/shared/package-files/bc/bcb13ec5930e7ccc881874ad0c88973bebb7a6d2fac755ec8bdecc6f6d2a5ea7/GemmRocblas.h new file mode 100644 index 0000000000000000000000000000000000000000..182d597fe29c557741899889cbdb4de027fbed45 --- /dev/null +++ b/shared/package-files/bc/bcb13ec5930e7ccc881874ad0c88973bebb7a6d2fac755ec8bdecc6f6d2a5ea7/GemmRocblas.h @@ -0,0 +1,273 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include +#include + +#define ROCBLAS_BETA_FEATURES_API +#include + +#define TORCH_ROCBLAS_CHECK(EXPR) \ + do { \ + rocblas_status __err = EXPR; \ + TORCH_CHECK(__err == rocblas_status_success, \ + "rocblas error: ", \ + rocblas_status_to_string(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +namespace at::cuda::tunable { + +template +constexpr rocblas_datatype RocBlasDataTypeFor(); + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f64_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f16_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_bf16_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor>() { + return rocblas_datatype_f32_c; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor>() { + return rocblas_datatype_f64_c; +} + +template +constexpr rocblas_datatype RocBlasComputeTypeFor(); + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + return rocblas_datatype_f64_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + // Note that we're returning the _compute_ type for a given datatype. + // As of 12/2022, using compute type FP16 for 16-bit floats was much + // slower than using compute type FP32. So we use FP32 compute even for + // FP16 datatypes. This is how GEMM is implemented even in the function + // rocblasGemmHelper (see fpgeneric.h) + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + // Note that we're returning the _compute_ type for a given datatype. + // As of 12/2022, using compute type FP16 for 16-bit floats was much + // slower than using compute type FP32. So we use FP32 compute even for + // BF16 datatypes. This is how GEMM is implemented even in the function + // rocblasGemmHelper (see fpgeneric.h) + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor>() { + return rocblas_datatype_f32_c; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor>() { + return rocblas_datatype_f64_c; +} + +template +auto DoCastForHalfOrBfloat16(const T fp) { + return fp; +} + +template <> +inline auto DoCastForHalfOrBfloat16(const Half fp) { + // alpha and beta should be the same as compute_type, in Half case it is float. + float h = fp; + return h; +} + +template <> +inline auto DoCastForHalfOrBfloat16(const BFloat16 fp) { + // alpha and beta should be the same as compute_type, in bfloat16 case it is float. + float h = fp; + return h; +} + +static rocblas_operation _rocblasOpFromChar(char op) { + switch (op) { + case 'n': + case 'N': + return rocblas_operation_none; + case 't': + case 'T': + return rocblas_operation_transpose; + case 'c': + case 'C': + return rocblas_operation_conjugate_transpose; + } + TORCH_CHECK(false, + "_rocblasOpFromChar input should be 't', 'n' or 'c' but got `", op, "`"); +} + +template +class RocblasGemmOp : public Callable> { + public: + RocblasGemmOp(int solution) : solution_{solution} {} + + TuningStatus Call(const GemmParams* params) override { + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + auto h_a = DoCastForHalfOrBfloat16(params->alpha); + auto h_b = DoCastForHalfOrBfloat16(params->beta); + auto status = rocblas_gemm_ex( + (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(), + _rocblasOpFromChar(params->transa), + _rocblasOpFromChar(params->transb), + params->m, params->n, params->k, + &h_a, + params->a, input_output_type, params->lda, + params->b, input_output_type, params->ldb, + &h_b, + params->c, input_output_type, params->ldc, + params->c, input_output_type, params->ldc, + compute_type, + rocblas_gemm_algo_solution_index, + solution_, + rocblas_gemm_flags_none); + if (status != rocblas_status_success) { + return FAIL; + } + return OK; + } + + private: + int solution_; +}; + +template +auto GetRocBlasGemmTypeStringAndOps() { + rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(); + int solution_size; + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + // Get the number of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + nullptr, + &solution_size)); + std::vector solutions(solution_size); + // Get the list of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + solutions.data(), + &solution_size)); + std::vector>>>> ret; + for (size_t i = 0; i < solutions.size(); ++i) { + auto callable = std::make_unique>(solutions[i]); + ret.emplace_back(std::make_pair(fmt::sprintf("Gemm_Rocblas_%d", solutions[i]), std::move(callable))); + } + return ret; +} + +template +class RocblasGemmStridedBatchedOp : public Callable> { + public: + RocblasGemmStridedBatchedOp(int solution) : solution_{solution} {} + + TuningStatus Call(const GemmStridedBatchedParams* params) override { + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + auto h_a = DoCastForHalfOrBfloat16(params->alpha); + auto h_b = DoCastForHalfOrBfloat16(params->beta); + auto status = rocblas_gemm_strided_batched_ex( + (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(), + _rocblasOpFromChar(params->transa), + _rocblasOpFromChar(params->transb), + params->m, params->n, params->k, + &h_a, + params->a, input_output_type, params->lda, params->stride_a, + params->b, input_output_type, params->ldb, params->stride_b, + &h_b, + params->c, input_output_type, params->ldc, params->stride_c, + params->c, input_output_type, params->ldc, params->stride_c, + params->batch, + compute_type, + rocblas_gemm_algo_solution_index, + solution_, + rocblas_gemm_flags_none); + if (status != rocblas_status_success) { + return FAIL; + } + return OK; + } + + private: + int solution_; +}; + +template +auto GetRocBlasGemmStridedBatchedTypeStringAndOps() { + rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(); + int solution_size; + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + // Get the number of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + nullptr, + &solution_size)); + std::vector solutions(solution_size); + // Get the list of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + solutions.data(), + &solution_size)); + // Sort the solutions in ascending order to make the solution vector deterministic across runs + std::sort(solutions.begin(), solutions.end()); + + std::vector>>>> ret; + for (size_t i = 0; i < solutions.size(); ++i) { + auto callable = std::make_unique>(solutions[i]); + ret.emplace_back(std::make_pair(c10::str("Gemm_Rocblas_", solutions[i]), std::move(callable))); + } + return ret; +} + +} // namespace at::cuda::tunable diff --git a/shared/package-files/bc/bcb699f29780c52cb4730add11a94a9d402990ab297dad388b0d4caff65c8a8d/roctracer_ext.h b/shared/package-files/bc/bcb699f29780c52cb4730add11a94a9d402990ab297dad388b0d4caff65c8a8d/roctracer_ext.h new file mode 100644 index 0000000000000000000000000000000000000000..9fc4f6a67dc6e46053ac9a929b584cab00bc0368 --- /dev/null +++ b/shared/package-files/bc/bcb699f29780c52cb4730add11a94a9d402990ab297dad388b0d4caff65c8a8d/roctracer_ext.h @@ -0,0 +1,81 @@ +/* Copyright (c) 2018-2022 Advanced Micro Devices, Inc. + + 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. */ + +//////////////////////////////////////////////////////////////////////////////// +// +// ROC Tracer Extension API +// +// The API provides functionality for application annotation with event and +// external ranges correlation +// +//////////////////////////////////////////////////////////////////////////////// + +#ifndef ROCTRACER_EXT_H_ +#define ROCTRACER_EXT_H_ + +#include "roctracer.h" + +/* Extension API opcodes */ +typedef enum { + ACTIVITY_EXT_OP_MARK = 0, + ACTIVITY_EXT_OP_EXTERN_ID = 1 +} activity_ext_op_t; + +typedef void (*roctracer_start_cb_t)(); +typedef void (*roctracer_stop_cb_t)(); +typedef struct { + roctracer_start_cb_t start_cb; + roctracer_stop_cb_t stop_cb; +} roctracer_ext_properties_t; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +//////////////////////////////////////////////////////////////////////////////// +// Application annotation API + +// Tracing start API +void ROCTRACER_API roctracer_start() ROCTRACER_VERSION_4_1; + +// Tracing stop API +void ROCTRACER_API roctracer_stop() ROCTRACER_VERSION_4_1; + +//////////////////////////////////////////////////////////////////////////////// +// External correlation id API + +// Notifies that the calling thread is entering an external API region. +// Push an external correlation id for the calling thread. +roctracer_status_t ROCTRACER_API +roctracer_activity_push_external_correlation_id(activity_correlation_id_t id) + ROCTRACER_VERSION_4_1; + +// Notifies that the calling thread is leaving an external API region. +// Pop an external correlation id for the calling thread. +// 'lastId' returns the last external correlation if not NULL +roctracer_status_t ROCTRACER_API +roctracer_activity_pop_external_correlation_id( + activity_correlation_id_t* last_id) ROCTRACER_VERSION_4_1; + +#ifdef __cplusplus +} // extern "C" block +#endif // __cplusplus + +#endif // ROCTRACER_EXT_H_ diff --git a/shared/package-files/bc/bcb8822977735898b6e5f8caa7bbb9c4abf11785b9c1b57967ba6442016bb178/_dispatch.py b/shared/package-files/bc/bcb8822977735898b6e5f8caa7bbb9c4abf11785b9c1b57967ba6442016bb178/_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..a4df48f403121f45bd784177060495414d3aec8d --- /dev/null +++ b/shared/package-files/bc/bcb8822977735898b6e5f8caa7bbb9c4abf11785b9c1b57967ba6442016bb178/_dispatch.py @@ -0,0 +1,472 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates +import contextlib +import functools +import logging +import operator +import warnings +from collections.abc import Sequence +from typing import cast, Optional + +import torch +import torch.distributed as dist +import torch.distributed.tensor._api as dtensor +import torch.distributed.tensor._random as random +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta +from torch.distributed.tensor._op_schema import ( + _is_inplace_op, + _is_out_variant_op, + OpInfo, + OpSchema, + OutputSpecType, +) +from torch.distributed.tensor._random import is_rng_supported_mesh +from torch.distributed.tensor._redistribute import redistribute_local_tensor +from torch.distributed.tensor._sharding_prop import ShardingPropagator +from torch.distributed.tensor._tp_conv import ( + convolution_backward_handler, + convolution_handler, +) +from torch.distributed.tensor._utils import try_find_mesh_from_args +from torch.distributed.tensor.placement_types import Partial, Placement, Replicate + + +try: + from torch.utils import _cxx_pytree as pytree +except ImportError: + from torch.utils import _pytree as pytree # type: ignore[no-redef] + +aten = torch.ops.aten +logger = logging.getLogger(__name__) + + +def decompose_handler( + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], +) -> object: + """ + Decomposes a op to core ATen op, this handler is mostly here + for inference mode usage where the ops are not core aten ops. + """ + r = op_call.decompose(*args, **kwargs) + if r is not NotImplemented: + return r + else: + raise RuntimeError("Decomposition failed") + + +def is_same_size_handler( + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], +) -> bool: + lhs = cast(torch.Tensor, args[0]) + rhs = cast(torch.Tensor, args[1]) + return lhs.shape == rhs.shape + + +def found_inf_reduce_handler( + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], +) -> None: + op_info = dtensor.DTensor._op_dispatcher.unwrap_to_op_info(op_call, args, kwargs) + local_tensor_args = pytree.tree_unflatten( + cast(list[object], op_info.local_args), + op_info.args_tree_spec, # type: ignore[arg-type] + ) + local_tensor_args = cast(tuple[object, ...], local_tensor_args) + op_call(*local_tensor_args, **op_info.local_kwargs) + + grad_dtensor = cast(list[dtensor.DTensor], args[0])[0] + grad_placements = grad_dtensor.placements + mesh = grad_dtensor.device_mesh + + found_inf_placements: list[Placement] = [] + for placement in grad_placements: + if isinstance(placement, Replicate): + found_inf_placements.append(placement) + else: + found_inf_placements.append(Partial("max")) + + target_tensor = cast(torch.Tensor, args[1]) + spec = DTensorSpec( + mesh=mesh, + placements=tuple(found_inf_placements), + tensor_meta=TensorMeta( + shape=target_tensor.size(), + stride=target_tensor.stride(), + dtype=target_tensor.dtype, + ), + ) + found_inf_dtensor = dtensor.DTensor( + local_tensor=target_tensor, spec=spec, requires_grad=False + ) + found_inf = found_inf_dtensor.full_tensor() + target_tensor.copy_(found_inf) + + +class OpDispatcher: + """ + Op dispatching class instance to handle args/kwargs pre-processing (un-wrapping), sharding + propagation, redistribute local args, local compute, and post-processing (re-wrapping). It + also handles any op specific logic if necessary. + + NOTE: Given the runtime overhead of Tensor subclass (__torch_dispatch__), the OpDispatcher + is designed to minimize the CPU overhead by using the tricks of proper unflattening, faster + pytree if needed, and leveraging various caching mechanisms implemented in the sharding + propagation and redistribute modules. The CPU overhead is critical to eager mode performance, + one need to carefully measure the CPU overhead when making significant changes to the + OpDispatcher and ShardingPropagator. + """ + + def __init__(self) -> None: + self.sharding_propagator = ShardingPropagator() + self._random_ops = { + aten.native_dropout.default, + aten.normal_.default, + aten.rand_like.default, + aten.randn_like.default, + aten.randint_like.default, + aten.randint_like.low_dtype, + aten.randint_like.low_dtype_out, + aten.uniform_.default, + aten.bernoulli.default, + aten.bernoulli_.float, + } + self._custom_op_handlers = { + aten.linear.default: decompose_handler, + aten.matmul.default: decompose_handler, + aten.is_same_size.default: is_same_size_handler, + aten.convolution.default: convolution_handler, + aten.convolution_backward.default: convolution_backward_handler, + aten._amp_foreach_non_finite_check_and_unscale_.default: found_inf_reduce_handler, + } + + # This flag is used internally to control whether we treat the torch.Tensor(non-DTensor) + # as implicitly replicated or we throw error to user. + # NOTE: It is EXTREMELY UNSAFE to turn this flag on by default so we intentionally leave + # it as False by default. + self._allow_implicit_replication = False + + def dispatch( + self, + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], + ) -> object: + """ + Main dispatching logic + """ + # operators that does not need to go through sharding propagation + if op_call in self._custom_op_handlers: + return self._custom_op_handlers[op_call](op_call, args, kwargs) # type: ignore[operator] + + # extract local tensor and sharding infos to a OpInfo + op_info = self.unwrap_to_op_info(op_call, args, kwargs) + logger.debug("Dispatching op_call: %s", op_info.schema) + + self.sharding_propagator.propagate(op_info) + output_sharding = op_info.output_sharding + logger.debug("output_sharding for %s: %s", op_call, output_sharding) + assert output_sharding is not None, "output sharding should not be None" + + mesh = op_info.compute_mesh + if mesh.get_coordinate() is not None: + # computation that happens in the current rank of the mesh, normal case + if output_sharding.needs_redistribute: + # If sharding propagation decision needs redistribute, perform redistribute + # on args first, which could potentially modify args (i.e. allgather certain arg) + assert output_sharding.redistribute_schema is not None + self.redistribute_local_args( + op_info, output_sharding.redistribute_schema + ) + + local_tensor_args = ( + pytree.tree_unflatten( + cast(list[object], op_info.local_args), op_info.args_tree_spec + ) + if op_info.args_tree_spec + else op_info.local_args + ) + + # run local op computation with potentially modified args/kwargs + local_tensor_args = cast(tuple[object, ...], local_tensor_args) + if op_call in self._random_ops: + if not random._rng_tracker and is_rng_supported_mesh(mesh): + # Default to `OffsetBasedRNGTracker` if the parallelism API + # did not already construct one + random._rng_tracker = random.OffsetBasedRNGTracker(mesh) + + first_arg, first_local_arg = ( + cast(dtensor.DTensor, args[0]), + cast(torch.Tensor, local_tensor_args[0]), + ) + rng_context = ( + random._rng_tracker._distribute_region(first_arg._spec) + if random._rng_tracker and not first_local_arg.is_meta + else contextlib.nullcontext() + ) + # For DTensor random operator, run it within a RNGTracker context to + # ensure the random number generator is properly distributed. + with rng_context: + local_results = op_call(*local_tensor_args, **op_info.local_kwargs) + else: + # normal case, run local sharded op computation + local_results = op_call(*local_tensor_args, **op_info.local_kwargs) + + else: + # For a non-participating device (happens on rank that does not belong to + # the device mesh), we do: + # 1. if the return type is scalar, set the local result to None. + # 2. if the return type is Tensor or List[Tensor], return empty + # tensor(s) with correct dtype. + spec = output_sharding.output_spec + ret_list = op_info.schema.op._schema.returns + + if spec is None: + # For a scalar return type, the non-participating device has None + # as its local result + local_results = None + else: + + def default_tensor(spec: DTensorSpec) -> torch.Tensor: + if spec.tensor_meta is not None: + shape = spec.tensor_meta.shape + dtype = spec.tensor_meta.dtype + if len(shape) == 0: + # scalar tensor + return torch.zeros((), dtype=dtype) + else: + # non-scalar tensor + return torch.tensor([], dtype=dtype) + else: + raise RuntimeError(f"{spec} has no tensor metadata.") + + if isinstance(spec, DTensorSpec): + # return a Tensor value + local_results = default_tensor(spec) + elif isinstance(spec, Sequence): + # return a List[Tensor] value + local_results = [ + default_tensor(s) if s is not None else None for s in spec + ] + assert isinstance(local_results, list) + if None in local_results: + ret_type = str(ret_list[0].type) + raise NotImplementedError( + f"return type {ret_type} in DTensor op is not supported" + ) + + if output_sharding.output_spec is None: + if op_call == aten.equal.default: + # For equal operator, The local results from all devices should be all-gathered + # and a reduce op (AND) will be performed on the list of results to ensure SPMD + # execution. We can extend this for more ops if necessary. + obj_list = [None for _ in range(dist.get_world_size())] + dist.all_gather_object(obj_list, local_results) # type: ignore[possibly-undefined] + obj_list = list(filter(lambda x: x is not None, obj_list)) + # perform reduce on the collection with AND op + local_results = functools.reduce(operator.and_, obj_list, True) + + if _is_inplace_op(op_call): + # inplace op should return self instead of re-wrapping + if output_sharding.output_spec is not None: + return args[0] + else: + return None + elif _is_out_variant_op(op_call): + # out variant could possibly have multiple out args (i.e. lu_unpack.out) + output_specs = ( + (output_sharding.output_spec,) + if not isinstance(output_sharding.output_spec, tuple) + else output_sharding.output_spec + ) + out_dts = [] + spec_idx = 0 + for argument in op_call._schema.arguments: + if argument.is_out: + out_dt = cast(dtensor.DTensor, kwargs[argument.name]) + out_dt._spec = cast(DTensorSpec, output_specs[spec_idx]) + out_dts.append(out_dt) + spec_idx += 1 + + assert len(out_dts) >= 1, "out variant should have at least one out arg" + return tuple(out_dts) if len(out_dts) > 1 else out_dts[0] + else: + return self.wrap(local_results, output_sharding.output_spec) # type: ignore[possibly-undefined] + + @staticmethod + def redistribute_local_args( + op_info: OpInfo, + suggested_input_schema: OpSchema, + ) -> None: + # NOTE: it's very rare that we need to reshard kwargs so we intentionally skip it + if op_info.args_tree_spec is not None: + flatten_args_schema_to_reshard = tuple( + pytree.tree_leaves(suggested_input_schema.args_schema) + ) + else: + flatten_args_schema_to_reshard = suggested_input_schema.args_schema + + new_local_args: list[object] = [] + for i, arg_spec in enumerate(op_info.flat_args_schema): + reshard_arg_spec = flatten_args_schema_to_reshard[i] + if isinstance(arg_spec, DTensorSpec): + local_tensor = cast(torch.Tensor, op_info.local_args[i]) + if arg_spec != reshard_arg_spec: + resharded_local_tensor = redistribute_local_tensor( + local_tensor, arg_spec, reshard_arg_spec + ) + new_local_args.append(resharded_local_tensor) + else: + new_local_args.append(local_tensor) + else: + new_local_args.append(reshard_arg_spec) + + op_info.local_args = tuple(new_local_args) + + def unwrap_to_op_info( + self, + op_call: torch._ops.OpOverload, + args: tuple[object, ...], + kwargs: dict[str, object], + ) -> OpInfo: + # get runtime schema info to determine whether to use pytree to flatten inputs + runtime_schema_info = self.sharding_propagator.op_to_schema_info.get( + op_call, None + ) + + if runtime_schema_info is not None and runtime_schema_info.needs_pytree: + # flatten args/kwargs when op says necessary + tree_args, args_spec = pytree.tree_flatten(args) + args_list: Sequence[object] = tree_args + else: + args_list, args_spec = args, None + + args_schema: list[object] = [] + kwargs_schema: dict[str, object] = {} + local_args: list[object] = [] + local_kwargs: dict[str, object] = {} + compute_mesh: Optional[DeviceMesh] = None + + for arg in args_list: + if isinstance(arg, dtensor.DTensor): + local_args.append(arg._local_tensor) + args_schema.append(arg._spec) + if compute_mesh is None: + # record the first compute device mesh from args + compute_mesh = arg.device_mesh + elif isinstance(arg, torch.Tensor): + compute_mesh = compute_mesh or try_find_mesh_from_args( + op_call, args_list + ) + args_schema.append( + self._try_replicate_spec_for_scalar_tensor( + op_call, arg, compute_mesh + ) + ) + local_args.append(arg) + else: + # non DTensor/Tensor args (i.e. int/float/bool), just add to args_schema/local_args + args_schema.append(arg) + local_args.append(arg) + + for k, v in kwargs.items(): + if isinstance(v, dtensor.DTensor): + local_kwargs[k] = v._local_tensor + kwargs_schema[k] = v._spec + elif isinstance(v, torch.Tensor): + compute_mesh = compute_mesh or try_find_mesh_from_args( + op_call, args_list + ) + kwargs_schema[k] = self._try_replicate_spec_for_scalar_tensor( + op_call, v, compute_mesh + ) + local_kwargs[k] = v + else: + # non DTensor/Tensor args (i.e. int/float/bool), just add to args_schema/local_args + kwargs_schema[k] = v + local_kwargs[k] = v + + assert compute_mesh is not None, ( + f"found no DeviceMesh from dtensor args for {op_call}!" + ) + op_info = OpInfo( + compute_mesh, + OpSchema( + op_call, + ( + pytree.tree_unflatten(args_schema, args_spec) + if args_spec + else tuple(args_schema) + ), + kwargs_schema, + schema_info=runtime_schema_info, + ), + args_schema, + tuple(local_args), + local_kwargs, + args_spec, + ) + return op_info + + @staticmethod + def wrap(res: object, spec: OutputSpecType) -> object: + if isinstance(res, torch.Tensor): + if spec is not None: + assert isinstance(spec, DTensorSpec), ( + f"output spec does not match with output! Expected DTensorSpec, got {spec}." + ) + return dtensor.DTensor(res, spec, requires_grad=res.requires_grad) + else: + # if output does not have a DTensorSpec due to specific ops, it must be a scalar tensor + assert res.ndim == 0, "output tensor should be scalar!" + return res + elif isinstance(res, (list, tuple)): + assert spec is not None and isinstance(spec, (list, tuple)), ( + f"output spec does not match with output! Expected list/tuple, got {spec}." + ) + res_list = [] + for e, s in zip(res, spec): + res_list.append(OpDispatcher.wrap(e, s)) + + return tuple(res_list) if isinstance(res, tuple) else res_list + else: + # if the res contains only non tensor values (i.e. int/float/none), we simply return it + # without rewrapping to DTensor. + return res + + def _try_replicate_spec_for_scalar_tensor( + self, + op_call: torch._ops.OpOverload, + tensor_arg: torch.Tensor, + compute_mesh: DeviceMesh, + ) -> DTensorSpec: + # util function to produce a replicate spec for a scalar tensor arg/kwarg + if tensor_arg.numel() == 1 and tensor_arg.ndim == 1: + warnings.warn( + "Found a non-scalar tensor with numel=1 and ndim!=0, " + "we are implicitly creating a replicated DTensor for it. " + "However, please consider changing it to a scalar tensor " + "or explicitly create a DTensor under distributed enviroment." + ) + + if tensor_arg.numel() == 1 or self._allow_implicit_replication: + # scalar tensor can be safely treated as replicated + replication_spec = DTensorSpec( + compute_mesh, + (Replicate(),) * compute_mesh.ndim, + tensor_meta=TensorMeta( + shape=tensor_arg.shape, + stride=tensor_arg.stride(), + dtype=tensor_arg.dtype, + ), + ) + else: + raise RuntimeError( + f"{op_call}: got mixed torch.Tensor and DTensor, need to convert all" + " torch.Tensor to DTensor before calling distributed operators!" + ) + return replication_spec diff --git a/shared/package-files/bc/bcc81e179a3ce58e19e9b9c8415cde152de362325a50cc8eebf7c7ba53c750ee/test_recognition.cpython-311.pyc b/shared/package-files/bc/bcc81e179a3ce58e19e9b9c8415cde152de362325a50cc8eebf7c7ba53c750ee/test_recognition.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3897b1fa29317fd81b11e1ccf26e0dba01507912 Binary files /dev/null and b/shared/package-files/bc/bcc81e179a3ce58e19e9b9c8415cde152de362325a50cc8eebf7c7ba53c750ee/test_recognition.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcca997ddb278d6a5d94095fcbaba26db6afd18fcc4fb72903fcbb6f245b67ac/unsupported_operator.cpython-311.pyc b/shared/package-files/bc/bcca997ddb278d6a5d94095fcbaba26db6afd18fcc4fb72903fcbb6f245b67ac/unsupported_operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad707b321c90a1fb8103d769dd3fdb4f860afb9f Binary files /dev/null and b/shared/package-files/bc/bcca997ddb278d6a5d94095fcbaba26db6afd18fcc4fb72903fcbb6f245b67ac/unsupported_operator.cpython-311.pyc differ diff --git a/shared/package-files/bc/bccb576e8e857b4e485b0c88345e89812895e575a7e172c5a51f0b0783820449/wintypes.cpython-311.pyc b/shared/package-files/bc/bccb576e8e857b4e485b0c88345e89812895e575a7e172c5a51f0b0783820449/wintypes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d4adc8457b0812d581dac144f29ad4c84a100de Binary files /dev/null and b/shared/package-files/bc/bccb576e8e857b4e485b0c88345e89812895e575a7e172c5a51f0b0783820449/wintypes.cpython-311.pyc differ diff --git a/shared/package-files/bc/bccbce95fecd1195c4507cf35d2ae6b83571dfd303e2a066714468eb3dce0988/context.cpython-311.pyc b/shared/package-files/bc/bccbce95fecd1195c4507cf35d2ae6b83571dfd303e2a066714468eb3dce0988/context.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6b7e240682fa59f4bdcc05ce3b0804f711d61ff Binary files /dev/null and b/shared/package-files/bc/bccbce95fecd1195c4507cf35d2ae6b83571dfd303e2a066714468eb3dce0988/context.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcceadfe5815ea50566c1630a66dd2e287c140543150faf92a40d0aeb41c42ba/archive.py b/shared/package-files/bc/bcceadfe5815ea50566c1630a66dd2e287c140543150faf92a40d0aeb41c42ba/archive.py new file mode 100644 index 0000000000000000000000000000000000000000..13a4da8df7c9405297cdd7d37476be2f725b2f57 --- /dev/null +++ b/shared/package-files/bc/bcceadfe5815ea50566c1630a66dd2e287c140543150faf92a40d0aeb41c42ba/archive.py @@ -0,0 +1,75 @@ +import operator + +from fsspec import AbstractFileSystem +from fsspec.utils import tokenize + + +class AbstractArchiveFileSystem(AbstractFileSystem): + """ + A generic superclass for implementing Archive-based filesystems. + + Currently, it is shared amongst + :class:`~fsspec.implementations.zip.ZipFileSystem`, + :class:`~fsspec.implementations.libarchive.LibArchiveFileSystem` and + :class:`~fsspec.implementations.tar.TarFileSystem`. + """ + + def __str__(self): + return f"" + + __repr__ = __str__ + + def ukey(self, path): + return tokenize(path, self.fo, self.protocol) + + def _all_dirnames(self, paths): + """Returns *all* directory names for each path in paths, including intermediate + ones. + + Parameters + ---------- + paths: Iterable of path strings + """ + if len(paths) == 0: + return set() + + dirnames = {self._parent(path) for path in paths} - {self.root_marker} + return dirnames | self._all_dirnames(dirnames) + + def info(self, path, **kwargs): + self._get_dirs() + path = self._strip_protocol(path) + if path in {"", "/"} and self.dir_cache: + return {"name": "", "type": "directory", "size": 0} + if path in self.dir_cache: + return self.dir_cache[path] + elif path + "/" in self.dir_cache: + return self.dir_cache[path + "/"] + else: + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + self._get_dirs() + paths = {} + for p, f in self.dir_cache.items(): + p = p.rstrip("/") + if "/" in p: + root = p.rsplit("/", 1)[0] + else: + root = "" + if root == path.rstrip("/"): + paths[p] = f + elif all( + (a == b) + for a, b in zip(path.split("/"), [""] + p.strip("/").split("/")) + ): + # root directory entry + ppath = p.rstrip("/").split("/", 1)[0] + if ppath not in paths: + out = {"name": ppath, "size": 0, "type": "directory"} + paths[ppath] = out + if detail: + out = sorted(paths.values(), key=operator.itemgetter("name")) + return out + else: + return sorted(paths) diff --git a/shared/package-files/bc/bcd52282b140ad18d2592eaec4656320a17b3373fddf63fd819ec0007c56e693/_creation.py b/shared/package-files/bc/bcd52282b140ad18d2592eaec4656320a17b3373fddf63fd819ec0007c56e693/_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..e513b8d856035634b48c2c4d1bcdb2e0da627e57 --- /dev/null +++ b/shared/package-files/bc/bcd52282b140ad18d2592eaec4656320a17b3373fddf63fd819ec0007c56e693/_creation.py @@ -0,0 +1,276 @@ +""" +This module contains tensor creation utilities. +""" + +import collections.abc +import functools +import math +import warnings +from typing import cast, Optional, Union + +import torch + + +_INTEGRAL_TYPES = [ + torch.uint8, + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint16, + torch.uint32, + torch.uint64, +] +_FLOATING_TYPES = [torch.float16, torch.bfloat16, torch.float32, torch.float64] +_FLOATING_8BIT_TYPES = [ + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, +] +_COMPLEX_TYPES = [torch.complex32, torch.complex64, torch.complex128] +_BOOLEAN_OR_INTEGRAL_TYPES = [torch.bool, *_INTEGRAL_TYPES] +_FLOATING_OR_COMPLEX_TYPES = [*_FLOATING_TYPES, *_COMPLEX_TYPES] + + +def _uniform_random_(t: torch.Tensor, low: float, high: float) -> torch.Tensor: + # uniform_ requires to-from <= std::numeric_limits::max() + # Work around this by scaling the range before and after the PRNG + if high - low >= torch.finfo(t.dtype).max: + return t.uniform_(low / 2, high / 2).mul_(2) + else: + return t.uniform_(low, high) + + +def make_tensor( + *shape: Union[int, torch.Size, list[int], tuple[int, ...]], + dtype: torch.dtype, + device: Union[str, torch.device], + low: Optional[float] = None, + high: Optional[float] = None, + requires_grad: bool = False, + noncontiguous: bool = False, + exclude_zero: bool = False, + memory_format: Optional[torch.memory_format] = None, +) -> torch.Tensor: + r"""Creates a tensor with the given :attr:`shape`, :attr:`device`, and :attr:`dtype`, and filled with + values uniformly drawn from ``[low, high)``. + + If :attr:`low` or :attr:`high` are specified and are outside the range of the :attr:`dtype`'s representable + finite values then they are clamped to the lowest or highest representable finite value, respectively. + If ``None``, then the following table describes the default values for :attr:`low` and :attr:`high`, + which depend on :attr:`dtype`. + + +---------------------------+------------+----------+ + | ``dtype`` | ``low`` | ``high`` | + +===========================+============+==========+ + | boolean type | ``0`` | ``2`` | + +---------------------------+------------+----------+ + | unsigned integral type | ``0`` | ``10`` | + +---------------------------+------------+----------+ + | signed integral types | ``-9`` | ``10`` | + +---------------------------+------------+----------+ + | floating types | ``-9`` | ``9`` | + +---------------------------+------------+----------+ + | complex types | ``-9`` | ``9`` | + +---------------------------+------------+----------+ + + Args: + shape (Tuple[int, ...]): Single integer or a sequence of integers defining the shape of the output tensor. + dtype (:class:`torch.dtype`): The data type of the returned tensor. + device (Union[str, torch.device]): The device of the returned tensor. + low (Optional[Number]): Sets the lower limit (inclusive) of the given range. If a number is provided it is + clamped to the least representable finite value of the given dtype. When ``None`` (default), + this value is determined based on the :attr:`dtype` (see the table above). Default: ``None``. + high (Optional[Number]): Sets the upper limit (exclusive) of the given range. If a number is provided it is + clamped to the greatest representable finite value of the given dtype. When ``None`` (default) this value + is determined based on the :attr:`dtype` (see the table above). Default: ``None``. + + .. deprecated:: 2.1 + + Passing ``low==high`` to :func:`~torch.testing.make_tensor` for floating or complex types is deprecated + since 2.1 and will be removed in 2.3. Use :func:`torch.full` instead. + + requires_grad (Optional[bool]): If autograd should record operations on the returned tensor. Default: ``False``. + noncontiguous (Optional[bool]): If `True`, the returned tensor will be noncontiguous. This argument is + ignored if the constructed tensor has fewer than two elements. Mutually exclusive with ``memory_format``. + exclude_zero (Optional[bool]): If ``True`` then zeros are replaced with the dtype's small positive value + depending on the :attr:`dtype`. For bool and integer types zero is replaced with one. For floating + point types it is replaced with the dtype's smallest positive normal number (the "tiny" value of the + :attr:`dtype`'s :func:`~torch.finfo` object), and for complex types it is replaced with a complex number + whose real and imaginary parts are both the smallest positive normal number representable by the complex + type. Default ``False``. + memory_format (Optional[torch.memory_format]): The memory format of the returned tensor. Mutually exclusive + with ``noncontiguous``. + + Raises: + ValueError: If ``requires_grad=True`` is passed for integral `dtype` + ValueError: If ``low >= high``. + ValueError: If either :attr:`low` or :attr:`high` is ``nan``. + ValueError: If both :attr:`noncontiguous` and :attr:`memory_format` are passed. + TypeError: If :attr:`dtype` isn't supported by this function. + + Examples: + >>> # xdoctest: +SKIP + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) + >>> from torch.testing import make_tensor + >>> # Creates a float tensor with values in [-1, 1) + >>> make_tensor((3,), device='cpu', dtype=torch.float32, low=-1, high=1) + >>> # xdoctest: +SKIP + tensor([ 0.1205, 0.2282, -0.6380]) + >>> # Creates a bool tensor on CUDA + >>> make_tensor((2, 2), device='cuda', dtype=torch.bool) + tensor([[False, False], + [False, True]], device='cuda:0') + """ + + def modify_low_high( + low: Optional[float], + high: Optional[float], + *, + lowest_inclusive: float, + highest_exclusive: float, + default_low: float, + default_high: float, + ) -> tuple[float, float]: + """ + Modifies (and raises ValueError when appropriate) low and high values given by the user (input_low, input_high) + if required. + """ + + def clamp(a: float, l: float, h: float) -> float: + return min(max(a, l), h) + + low = low if low is not None else default_low + high = high if high is not None else default_high + + if any(isinstance(value, float) and math.isnan(value) for value in [low, high]): + raise ValueError( + f"`low` and `high` cannot be NaN, but got {low=} and {high=}" + ) + elif low == high and dtype in _FLOATING_OR_COMPLEX_TYPES: + warnings.warn( + "Passing `low==high` to `torch.testing.make_tensor` for floating or complex types " + "is deprecated since 2.1 and will be removed in 2.3. " + "Use `torch.full(...)` instead.", + FutureWarning, + stacklevel=3, + ) + elif low >= high: + raise ValueError(f"`low` must be less than `high`, but got {low} >= {high}") + elif high < lowest_inclusive or low >= highest_exclusive: + raise ValueError( + f"The value interval specified by `low` and `high` is [{low}, {high}), " + f"but {dtype} only supports [{lowest_inclusive}, {highest_exclusive})" + ) + + low = clamp(low, lowest_inclusive, highest_exclusive) + high = clamp(high, lowest_inclusive, highest_exclusive) + + if dtype in _BOOLEAN_OR_INTEGRAL_TYPES: + # 1. `low` is ceiled to avoid creating values smaller than `low` and thus outside the specified interval + # 2. Following the same reasoning as for 1., `high` should be floored. However, the higher bound of + # `torch.randint` is exclusive, and thus we need to ceil here as well. + return math.ceil(low), math.ceil(high) + + return low, high + + if len(shape) == 1 and isinstance(shape[0], collections.abc.Sequence): + shape = shape[0] # type: ignore[assignment] + shape = cast(tuple[int, ...], tuple(shape)) + + if noncontiguous and memory_format is not None: + raise ValueError( + f"The parameters `noncontiguous` and `memory_format` are mutually exclusive, " + f"but got {noncontiguous=} and {memory_format=}" + ) + + if requires_grad and dtype in _BOOLEAN_OR_INTEGRAL_TYPES: + raise ValueError( + f"`requires_grad=True` is not supported for boolean and integral dtypes, but got {dtype=}" + ) + + noncontiguous = noncontiguous and functools.reduce(lambda x, y: x * y, shape, 1) > 1 + if noncontiguous: + # Double the size of the shape in the last dimension, so that we have + # non-identical values when we make the non-contiguous operation. + shape = cast(tuple[int, ...], (*shape[:-1], 2 * shape[-1])) + + if dtype is torch.bool: + low, high = cast( + tuple[int, int], + modify_low_high( + low, + high, + lowest_inclusive=0, + highest_exclusive=2, + default_low=0, + default_high=2, + ), + ) + result = torch.randint(low, high, shape, device=device, dtype=dtype) + elif dtype in _BOOLEAN_OR_INTEGRAL_TYPES: + low, high = cast( + tuple[int, int], + modify_low_high( + low, + high, + lowest_inclusive=torch.iinfo(dtype).min, + highest_exclusive=torch.iinfo(dtype).max + # In theory, `highest_exclusive` should always be the maximum value + 1. However, `torch.randint` + # internally converts the bounds to an int64 and would overflow. In other words: `torch.randint` cannot + # sample 2**63 - 1, i.e. the maximum value of `torch.int64` and we need to account for that here. + + (1 if dtype is not torch.int64 else 0), + # This is incorrect for `torch.uint8`, but since we clamp to `lowest`, i.e. 0 for `torch.uint8`, + # _after_ we use the default value, we don't need to special case it here + default_low=-9, + default_high=10, + ), + ) + result = torch.randint(low, high, shape, device=device, dtype=dtype) + elif dtype in _FLOATING_OR_COMPLEX_TYPES: + low, high = modify_low_high( + low, + high, + lowest_inclusive=torch.finfo(dtype).min, + highest_exclusive=torch.finfo(dtype).max, + default_low=-9, + default_high=9, + ) + result = torch.empty(shape, device=device, dtype=dtype) + _uniform_random_( + torch.view_as_real(result) if dtype in _COMPLEX_TYPES else result, low, high + ) + elif dtype in _FLOATING_8BIT_TYPES: + low, high = modify_low_high( + low, + high, + lowest_inclusive=torch.finfo(dtype).min, + highest_exclusive=torch.finfo(dtype).max, + default_low=-9, + default_high=9, + ) + result = torch.empty(shape, device=device, dtype=torch.float32) + _uniform_random_(result, low, high) + result = result.to(dtype) + else: + raise TypeError( + f"The requested dtype '{dtype}' is not supported by torch.testing.make_tensor()." + " To request support, file an issue at: https://github.com/pytorch/pytorch/issues" + ) + + if noncontiguous: + # Offset by 1 to also catch offsetting issues + result = result[..., 1::2] + elif memory_format is not None: + result = result.clone(memory_format=memory_format) + + if exclude_zero: + result[result == 0] = ( + 1 if dtype in _BOOLEAN_OR_INTEGRAL_TYPES else torch.finfo(dtype).tiny + ) + + if dtype in _FLOATING_OR_COMPLEX_TYPES: + result.requires_grad = requires_grad + + return result diff --git a/shared/package-files/bc/bcd5d0db049262035a7c30f76870ac931be466be64eab12c2a6c6d4d9383239b/kcomponents.py b/shared/package-files/bc/bcd5d0db049262035a7c30f76870ac931be466be64eab12c2a6c6d4d9383239b/kcomponents.py new file mode 100644 index 0000000000000000000000000000000000000000..fe52e39b587abb48ddd65d616521bd047ba82cbc --- /dev/null +++ b/shared/package-files/bc/bcd5d0db049262035a7c30f76870ac931be466be64eab12c2a6c6d4d9383239b/kcomponents.py @@ -0,0 +1,367 @@ +"""Fast approximation for k-component structure""" + +import itertools +from collections import defaultdict +from collections.abc import Mapping +from functools import cached_property + +import networkx as nx +from networkx.algorithms.approximation import local_node_connectivity +from networkx.exception import NetworkXError +from networkx.utils import not_implemented_for + +__all__ = ["k_components"] + + +@not_implemented_for("directed") +@nx._dispatchable(name="approximate_k_components") +def k_components(G, min_density=0.95): + r"""Returns the approximate k-component structure of a graph G. + + A `k`-component is a maximal subgraph of a graph G that has, at least, + node connectivity `k`: we need to remove at least `k` nodes to break it + into more components. `k`-components have an inherent hierarchical + structure because they are nested in terms of connectivity: a connected + graph can contain several 2-components, each of which can contain + one or more 3-components, and so forth. + + This implementation is based on the fast heuristics to approximate + the `k`-component structure of a graph [1]_. Which, in turn, it is based on + a fast approximation algorithm for finding good lower bounds of the number + of node independent paths between two nodes [2]_. + + Parameters + ---------- + G : NetworkX graph + Undirected graph + + min_density : Float + Density relaxation threshold. Default value 0.95 + + Returns + ------- + k_components : dict + Dictionary with connectivity level `k` as key and a list of + sets of nodes that form a k-component of level `k` as values. + + Raises + ------ + NetworkXNotImplemented + If G is directed. + + Examples + -------- + >>> # Petersen graph has 10 nodes and it is triconnected, thus all + >>> # nodes are in a single component on all three connectivity levels + >>> from networkx.algorithms import approximation as apxa + >>> G = nx.petersen_graph() + >>> k_components = apxa.k_components(G) + + Notes + ----- + The logic of the approximation algorithm for computing the `k`-component + structure [1]_ is based on repeatedly applying simple and fast algorithms + for `k`-cores and biconnected components in order to narrow down the + number of pairs of nodes over which we have to compute White and Newman's + approximation algorithm for finding node independent paths [2]_. More + formally, this algorithm is based on Whitney's theorem, which states + an inclusion relation among node connectivity, edge connectivity, and + minimum degree for any graph G. This theorem implies that every + `k`-component is nested inside a `k`-edge-component, which in turn, + is contained in a `k`-core. Thus, this algorithm computes node independent + paths among pairs of nodes in each biconnected part of each `k`-core, + and repeats this procedure for each `k` from 3 to the maximal core number + of a node in the input graph. + + Because, in practice, many nodes of the core of level `k` inside a + bicomponent actually are part of a component of level k, the auxiliary + graph needed for the algorithm is likely to be very dense. Thus, we use + a complement graph data structure (see `AntiGraph`) to save memory. + AntiGraph only stores information of the edges that are *not* present + in the actual auxiliary graph. When applying algorithms to this + complement graph data structure, it behaves as if it were the dense + version. + + See also + -------- + k_components + + References + ---------- + .. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion: + Visualization and Heuristics for Fast Computation. + https://arxiv.org/pdf/1503.04476v1 + + .. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for + Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 + https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind + + .. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness: + A hierarchical conception of social groups. + American Sociological Review 68(1), 103--28. + https://doi.org/10.2307/3088904 + + """ + # Dictionary with connectivity level (k) as keys and a list of + # sets of nodes that form a k-component as values + k_components = defaultdict(list) + # make a few functions local for speed + node_connectivity = local_node_connectivity + k_core = nx.k_core + core_number = nx.core_number + biconnected_components = nx.biconnected_components + combinations = itertools.combinations + # Exact solution for k = {1,2} + # There is a linear time algorithm for triconnectivity, if we had an + # implementation available we could start from k = 4. + for component in nx.connected_components(G): + # isolated nodes have connectivity 0 + comp = set(component) + if len(comp) > 1: + k_components[1].append(comp) + for bicomponent in nx.biconnected_components(G): + # avoid considering dyads as bicomponents + bicomp = set(bicomponent) + if len(bicomp) > 2: + k_components[2].append(bicomp) + # There is no k-component of k > maximum core number + # \kappa(G) <= \lambda(G) <= \delta(G) + g_cnumber = core_number(G) + max_core = max(g_cnumber.values()) + for k in range(3, max_core + 1): + C = k_core(G, k, core_number=g_cnumber) + for nodes in biconnected_components(C): + # Build a subgraph SG induced by the nodes that are part of + # each biconnected component of the k-core subgraph C. + if len(nodes) < k: + continue + SG = G.subgraph(nodes) + # Build auxiliary graph + H = _AntiGraph() + H.add_nodes_from(SG.nodes()) + for u, v in combinations(SG, 2): + K = node_connectivity(SG, u, v, cutoff=k) + if k > K: + H.add_edge(u, v) + for h_nodes in biconnected_components(H): + if len(h_nodes) <= k: + continue + SH = H.subgraph(h_nodes) + for Gc in _cliques_heuristic(SG, SH, k, min_density): + for k_nodes in biconnected_components(Gc): + Gk = nx.k_core(SG.subgraph(k_nodes), k) + if len(Gk) <= k: + continue + k_components[k].append(set(Gk)) + return k_components + + +def _cliques_heuristic(G, H, k, min_density): + h_cnumber = nx.core_number(H) + for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)): + cands = {n for n, c in h_cnumber.items() if c == c_value} + # Skip checking for overlap for the highest core value + if i == 0: + overlap = False + else: + overlap = set.intersection( + *[{x for x in H[n] if x not in cands} for n in cands] + ) + if overlap and len(overlap) < k: + SH = H.subgraph(cands | overlap) + else: + SH = H.subgraph(cands) + sh_cnumber = nx.core_number(SH) + SG = nx.k_core(G.subgraph(SH), k) + while not (_same(sh_cnumber) and nx.density(SH) >= min_density): + # This subgraph must be writable => .copy() + SH = H.subgraph(SG).copy() + if len(SH) <= k: + break + sh_cnumber = nx.core_number(SH) + sh_deg = dict(SH.degree()) + min_deg = min(sh_deg.values()) + SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg) + SG = nx.k_core(G.subgraph(SH), k) + else: + yield SG + + +def _same(measure, tol=0): + vals = set(measure.values()) + if (max(vals) - min(vals)) <= tol: + return True + return False + + +class _AntiGraph(nx.Graph): + """ + Class for complement graphs. + + The main goal is to be able to work with big and dense graphs with + a low memory footprint. + + In this class you add the edges that *do not exist* in the dense graph, + the report methods of the class return the neighbors, the edges and + the degree as if it was the dense graph. Thus it's possible to use + an instance of this class with some of NetworkX functions. In this + case we only use k-core, connected_components, and biconnected_components. + """ + + all_edge_dict = {"weight": 1} + + def single_edge_dict(self): + return self.all_edge_dict + + edge_attr_dict_factory = single_edge_dict # type: ignore[assignment] + + def __getitem__(self, n): + """Returns a dict of neighbors of node n in the dense graph. + + Parameters + ---------- + n : node + A node in the graph. + + Returns + ------- + adj_dict : dictionary + The adjacency dictionary for nodes connected to n. + + """ + all_edge_dict = self.all_edge_dict + return dict.fromkeys(set(self._adj) - set(self._adj[n]) - {n}, all_edge_dict) + + def neighbors(self, n): + """Returns an iterator over all neighbors of node n in the + dense graph. + """ + try: + return iter(set(self._adj) - set(self._adj[n]) - {n}) + except KeyError as err: + raise NetworkXError(f"The node {n} is not in the graph.") from err + + class AntiAtlasView(Mapping): + """An adjacency inner dict for AntiGraph""" + + def __init__(self, graph, node): + self._graph = graph + self._atlas = graph._adj[node] + self._node = node + + def __len__(self): + return len(self._graph) - len(self._atlas) - 1 + + def __iter__(self): + return (n for n in self._graph if n not in self._atlas and n != self._node) + + def __getitem__(self, nbr): + nbrs = set(self._graph._adj) - set(self._atlas) - {self._node} + if nbr in nbrs: + return self._graph.all_edge_dict + raise KeyError(nbr) + + class AntiAdjacencyView(AntiAtlasView): + """An adjacency outer dict for AntiGraph""" + + def __init__(self, graph): + self._graph = graph + self._atlas = graph._adj + + def __len__(self): + return len(self._atlas) + + def __iter__(self): + return iter(self._graph) + + def __getitem__(self, node): + if node not in self._graph: + raise KeyError(node) + return self._graph.AntiAtlasView(self._graph, node) + + @cached_property + def adj(self): + return self.AntiAdjacencyView(self) + + def subgraph(self, nodes): + """This subgraph method returns a full AntiGraph. Not a View""" + nodes = set(nodes) + G = _AntiGraph() + G.add_nodes_from(nodes) + for n in G: + Gnbrs = G.adjlist_inner_dict_factory() + G._adj[n] = Gnbrs + for nbr, d in self._adj[n].items(): + if nbr in G._adj: + Gnbrs[nbr] = d + G._adj[nbr][n] = d + G.graph = self.graph + return G + + class AntiDegreeView(nx.reportviews.DegreeView): + def __iter__(self): + all_nodes = set(self._succ) + for n in self._nodes: + nbrs = all_nodes - set(self._succ[n]) - {n} + yield (n, len(nbrs)) + + def __getitem__(self, n): + nbrs = set(self._succ) - set(self._succ[n]) - {n} + # AntiGraph is a ThinGraph so all edges have weight 1 + return len(nbrs) + (n in nbrs) + + @cached_property + def degree(self): + """Returns an iterator for (node, degree) and degree for single node. + + The node degree is the number of edges adjacent to the node. + + Parameters + ---------- + nbunch : iterable container, optional (default=all nodes) + A container of nodes. The container will be iterated + through once. + + weight : string or None, optional (default=None) + The edge attribute that holds the numerical value used + as a weight. If None, then each edge has weight 1. + The degree is the sum of the edge weights adjacent to the node. + + Returns + ------- + deg: + Degree of the node, if a single node is passed as argument. + nd_iter : an iterator + The iterator returns two-tuples of (node, degree). + + See Also + -------- + degree + + Examples + -------- + >>> G = nx.path_graph(4) + >>> G.degree(0) # node 0 with degree 1 + 1 + >>> list(G.degree([0, 1])) + [(0, 1), (1, 2)] + + """ + return self.AntiDegreeView(self) + + def adjacency(self): + """Returns an iterator of (node, adjacency set) tuples for all nodes + in the dense graph. + + This is the fastest way to look at every edge. + For directed graphs, only outgoing adjacencies are included. + + Returns + ------- + adj_iter : iterator + An iterator of (node, adjacency set) for all nodes in + the graph. + + """ + for n in self._adj: + yield (n, set(self._adj) - set(self._adj[n]) - {n}) diff --git a/shared/package-files/bc/bcda5516300058f00b1882206fb5769931bc7584d95722182a2dd59860ba6d0a/__init__.cpython-311.pyc b/shared/package-files/bc/bcda5516300058f00b1882206fb5769931bc7584d95722182a2dd59860ba6d0a/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c993dd45f46bad55590f5a0062827679dc887968 Binary files /dev/null and b/shared/package-files/bc/bcda5516300058f00b1882206fb5769931bc7584d95722182a2dd59860ba6d0a/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcdcba621ef227697c8386e02a51067d1dcc1953744fa6f8fe589671c244a337/__init__.cpython-311.pyc b/shared/package-files/bc/bcdcba621ef227697c8386e02a51067d1dcc1953744fa6f8fe589671c244a337/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6fe0b500e85bb878f37e073ceb269633ac53308 Binary files /dev/null and b/shared/package-files/bc/bcdcba621ef227697c8386e02a51067d1dcc1953744fa6f8fe589671c244a337/__init__.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcdfe98ffae77e968a35ce652e83229bf171bd117f043ddbff189914feb77b31/pyprojecttoml.cpython-311.pyc b/shared/package-files/bc/bcdfe98ffae77e968a35ce652e83229bf171bd117f043ddbff189914feb77b31/pyprojecttoml.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8db6ee213398dd68cca1592c9c9740b2669b8bee Binary files /dev/null and b/shared/package-files/bc/bcdfe98ffae77e968a35ce652e83229bf171bd117f043ddbff189914feb77b31/pyprojecttoml.cpython-311.pyc differ diff --git a/shared/package-files/bc/bce2aaf9a4b1bc69f73e836a8c6087258f64e226e47ef733085bca5d2e221a5c/vec_half.h b/shared/package-files/bc/bce2aaf9a4b1bc69f73e836a8c6087258f64e226e47ef733085bca5d2e221a5c/vec_half.h new file mode 100644 index 0000000000000000000000000000000000000000..c7c90cc95b470a9eed0898147364d52c46f24908 --- /dev/null +++ b/shared/package-files/bc/bce2aaf9a4b1bc69f73e836a8c6087258f64e226e47ef733085bca5d2e221a5c/vec_half.h @@ -0,0 +1,151 @@ +#pragma once + +#include +#include + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) && \ + !defined(__APPLE__) +static inline uint16_t float2half_scalar(float val) { +#if defined(CPU_CAPABILITY_AVX2) +#if defined(_MSC_VER) + __m256 v = _mm256_set1_ps(val); + __m128i o = + _mm256_cvtps_ph(v, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return static_cast(_mm_cvtsi128_si32(o)); +#else + return _cvtss_sh(val, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); +#endif +#elif defined(CPU_CAPABILITY_AVX512) + __m512 v = _mm512_set1_ps(val); + __m256i o = + _mm512_cvtps_ph(v, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return static_cast( + _mm_cvtsi128_si32(_mm256_castsi256_si128(o))); +#endif +} + +static inline float half2float_scalar(uint16_t val) { +#if defined(CPU_CAPABILITY_AVX2) +#if defined(_MSC_VER) + __m128i v = _mm_cvtsi32_si128(val); + __m256 o = _mm256_cvtph_ps(v); + return _mm256_cvtss_f32(o); +#else + return _cvtsh_ss(val); +#endif +#elif defined(CPU_CAPABILITY_AVX512) + __m256i v = + _mm256_setr_epi16(val, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + __m512 o = _mm512_cvtph_ps(v); + return _mm512_cvtss_f32(o); +#endif +} + +#endif + +// Transpose a [2, 32] matrix to [32, 2] +// Note: the output leading dimension should be 2, +// that is, the output must be contiguous +template > +static inline void transpose_pad_2x32_block( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int krem = 2, + int nrem = 32) { +#if defined(CPU_CAPABILITY_AVX512) + __m512i r0, r1; + __m512i d0, d1; + // load + if (nrem < 32) { + __mmask32 mask_krem_v = (1LL << nrem) - 1; + r0 = _mm512_maskz_loadu_epi16(mask_krem_v, src); + // if krem is not 2, pad with zeros + if (krem == 2) { + r1 = _mm512_maskz_loadu_epi16(mask_krem_v, src + ld_src); + } else { + r1 = _mm512_setzero_si512(); + } + } else { + r0 = _mm512_loadu_si512(reinterpret_cast(src)); + if (krem == 2) { + r1 = _mm512_loadu_si512(reinterpret_cast(src + ld_src)); + } else { + r1 = _mm512_setzero_si512(); + } + } + // transpose + d0 = _mm512_unpacklo_epi16(r0, r1); + d1 = _mm512_unpackhi_epi16(r0, r1); + r0 = _mm512_shuffle_i32x4(d0, d1, 0x88); + r1 = _mm512_shuffle_i32x4(d0, d1, 0xdd); + d0 = _mm512_shuffle_i32x4(r0, r1, 0x88); + d1 = _mm512_shuffle_i32x4(r0, r1, 0xdd); + + // store + if (nrem < 16) { + __mmask32 mask_rem_v = (1LL << (nrem * 2)) - 1; + _mm512_mask_storeu_epi16(dst, mask_rem_v, d0); + } else if (nrem == 16) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + } else if (nrem < 32) { + __mmask32 mask_rem_v = (1LL << (nrem * 2 - 32)) - 1; + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + _mm512_mask_storeu_epi16( + reinterpret_cast<__m512i*>(dst + 32), mask_rem_v, d1); + } else { + // normal store + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 32), d1); + } +#else +TORCH_CHECK(false, "transpose_pad_2x32_block is only supported when avx512 is supported") +#endif +} + +// To use AMX to accelerate GEMM, +// reorder the memory format [K, N] -> [K/2, N, 2] +// Note: If K % 2 != 0, pad K implicitly +template > +static inline void pack_vnni2( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int64_t K, + int64_t N) { +#if defined(CPU_CAPABILITY_AVX512) + int64_t bk = 0; + int64_t _K = K / 2 * 2; + int64_t _N = N / 32 * 32; + for (; bk < _K; bk += 2) { + int64_t bn = 0; + for (; bn < _N; bn += 32) { + transpose_pad_2x32_block(src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_2x32_block(src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 2, nrem); + } + } + if (K % 2 == 1) { + int64_t bn = 0; + for (; bn < _N; bn += 32) { + transpose_pad_2x32_block(src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 1); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_2x32_block(src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 1, nrem); + } + } +#else +TORCH_CHECK(false, "pack_vnni2 is only supported when avx512 is supported") +#endif +} + + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/shared/package-files/bc/bce38adbf3b689f1086a42a5b5247039dff6e62eec93afd838aafdb03a08a91b/hardsigmoid_native.h b/shared/package-files/bc/bce38adbf3b689f1086a42a5b5247039dff6e62eec93afd838aafdb03a08a91b/hardsigmoid_native.h new file mode 100644 index 0000000000000000000000000000000000000000..69a25c78319abd9c45e9cd8c7680dd34d191766f --- /dev/null +++ b/shared/package-files/bc/bce38adbf3b689f1086a42a5b5247039dff6e62eec93afd838aafdb03a08a91b/hardsigmoid_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_hardsigmoid_out : public at::meta::structured_hardsigmoid { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +TORCH_API at::Tensor hardsigmoid_quantized_cpu(const at::Tensor & self); +TORCH_API at::Tensor & hardsigmoid_out_quantized_cpu(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/bc/bce6a62a1c07920929270b3f8162805b916c0be362b6311634560ad33646f638/tunable.cpython-311.pyc b/shared/package-files/bc/bce6a62a1c07920929270b3f8162805b916c0be362b6311634560ad33646f638/tunable.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..407d198f5dcf4cd335d8f77fd8a233c688e9a45d Binary files /dev/null and b/shared/package-files/bc/bce6a62a1c07920929270b3f8162805b916c0be362b6311634560ad33646f638/tunable.cpython-311.pyc differ diff --git a/shared/package-files/bc/bcecb38c45904e9b065cb39ad87f1e8646a152260105c2af108fffe9842dcdda/test_reduction.py b/shared/package-files/bc/bcecb38c45904e9b065cb39ad87f1e8646a152260105c2af108fffe9842dcdda/test_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..db04862e4ea0797ffcc1562bbcb603448131fae8 --- /dev/null +++ b/shared/package-files/bc/bcecb38c45904e9b065cb39ad87f1e8646a152260105c2af108fffe9842dcdda/test_reduction.py @@ -0,0 +1,125 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Series, + array, +) +import pandas._testing as tm + + +@pytest.mark.parametrize( + "op, expected", + [ + ["sum", np.int64(3)], + ["prod", np.int64(2)], + ["min", np.int64(1)], + ["max", np.int64(2)], + ["mean", np.float64(1.5)], + ["median", np.float64(1.5)], + ["var", np.float64(0.5)], + ["std", np.float64(0.5**0.5)], + ["skew", pd.NA], + ["kurt", pd.NA], + ["any", True], + ["all", True], + ], +) +def test_series_reductions(op, expected): + ser = Series([1, 2], dtype="Int64") + result = getattr(ser, op)() + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "op, expected", + [ + ["sum", Series([3], index=["a"], dtype="Int64")], + ["prod", Series([2], index=["a"], dtype="Int64")], + ["min", Series([1], index=["a"], dtype="Int64")], + ["max", Series([2], index=["a"], dtype="Int64")], + ["mean", Series([1.5], index=["a"], dtype="Float64")], + ["median", Series([1.5], index=["a"], dtype="Float64")], + ["var", Series([0.5], index=["a"], dtype="Float64")], + ["std", Series([0.5**0.5], index=["a"], dtype="Float64")], + ["skew", Series([pd.NA], index=["a"], dtype="Float64")], + ["kurt", Series([pd.NA], index=["a"], dtype="Float64")], + ["any", Series([True], index=["a"], dtype="boolean")], + ["all", Series([True], index=["a"], dtype="boolean")], + ], +) +def test_dataframe_reductions(op, expected): + df = DataFrame({"a": array([1, 2], dtype="Int64")}) + result = getattr(df, op)() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "op, expected", + [ + ["sum", array([1, 3], dtype="Int64")], + ["prod", array([1, 3], dtype="Int64")], + ["min", array([1, 3], dtype="Int64")], + ["max", array([1, 3], dtype="Int64")], + ["mean", array([1, 3], dtype="Float64")], + ["median", array([1, 3], dtype="Float64")], + ["var", array([pd.NA], dtype="Float64")], + ["std", array([pd.NA], dtype="Float64")], + ["skew", array([pd.NA], dtype="Float64")], + ["any", array([True, True], dtype="boolean")], + ["all", array([True, True], dtype="boolean")], + ], +) +def test_groupby_reductions(op, expected): + df = DataFrame( + { + "A": ["a", "b", "b"], + "B": array([1, None, 3], dtype="Int64"), + } + ) + result = getattr(df.groupby("A"), op)() + expected = DataFrame(expected, index=pd.Index(["a", "b"], name="A"), columns=["B"]) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op, expected", + [ + ["sum", Series([4, 4], index=["B", "C"], dtype="Float64")], + ["prod", Series([3, 3], index=["B", "C"], dtype="Float64")], + ["min", Series([1, 1], index=["B", "C"], dtype="Float64")], + ["max", Series([3, 3], index=["B", "C"], dtype="Float64")], + ["mean", Series([2, 2], index=["B", "C"], dtype="Float64")], + ["median", Series([2, 2], index=["B", "C"], dtype="Float64")], + ["var", Series([2, 2], index=["B", "C"], dtype="Float64")], + ["std", Series([2**0.5, 2**0.5], index=["B", "C"], dtype="Float64")], + ["skew", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")], + ["kurt", Series([pd.NA, pd.NA], index=["B", "C"], dtype="Float64")], + ["any", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")], + ["all", Series([True, True, True], index=["A", "B", "C"], dtype="boolean")], + ], +) +def test_mixed_reductions(op, expected, using_infer_string): + if op in ["any", "all"] and using_infer_string: + expected = expected.astype("bool") + df = DataFrame( + { + "A": ["a", "b", "b"], + "B": [1, None, 3], + "C": array([1, None, 3], dtype="Int64"), + } + ) + + # series + result = getattr(df.C, op)() + tm.assert_equal(result, expected["C"]) + + # frame + if op in ["any", "all"]: + result = getattr(df, op)() + else: + result = getattr(df, op)(numeric_only=True) + tm.assert_series_equal(result, expected) diff --git a/shared/package-files/bc/bcecb4cf5429ae2a20d0b57f5d3459295b051c6bf3ec422cc873371a5a88541f/_batch_norm_impl_index_compositeimplicitautograd_dispatch.h b/shared/package-files/bc/bcecb4cf5429ae2a20d0b57f5d3459295b051c6bf3ec422cc873371a5a88541f/_batch_norm_impl_index_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..36632c475b1e3e47ba5d78b60790c573f4eec7ef --- /dev/null +++ b/shared/package-files/bc/bcecb4cf5429ae2a20d0b57f5d3459295b051c6bf3ec422cc873371a5a88541f/_batch_norm_impl_index_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API ::std::tuple _batch_norm_impl_index(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, const ::std::optional & running_mean, const ::std::optional & running_var, bool training, double momentum, double eps, bool cudnn_enabled); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/bc/bced24fa84664c01331d7ac6ac4dc69ba146a7b0a2db3c32c77a169dbd379dde/nll_loss2d_backward.h b/shared/package-files/bc/bced24fa84664c01331d7ac6ac4dc69ba146a7b0a2db3c32c77a169dbd379dde/nll_loss2d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..3b27c2d1ad345bcc35d9ae1821c93ff4fc1e7629 --- /dev/null +++ b/shared/package-files/bc/bced24fa84664c01331d7ac6ac4dc69ba146a7b0a2db3c32c77a169dbd379dde/nll_loss2d_backward.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template >> + at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template >> + at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss2d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template >> + at::Tensor & nll_loss2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & nll_loss2d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); +} +namespace symint { + template >> + at::Tensor & nll_loss2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight, at::Tensor & grad_input) { + return at::_ops::nll_loss2d_backward_grad_input::call(grad_output, self, target, weight, reduction, ignore_index, total_weight, grad_input); + } +} + +// aten::nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor +inline at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); +} +namespace symint { + template >> + at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, int64_t ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); + } +} + +// aten::nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor +inline at::Tensor nll_loss2d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); +} +namespace symint { + template >> + at::Tensor nll_loss2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, c10::SymInt ignore_index, const at::Tensor & total_weight) { + return at::_ops::nll_loss2d_backward::call(grad_output, self, target, weight, reduction, ignore_index, total_weight); + } +} + +} diff --git a/shared/package-files/bc/bcf50c5e9e33d1604d18cd2c648c6d7d97dbc2645b7d4f7ad61b9e992ad17c6b/upsample_nearest1d_backward.h b/shared/package-files/bc/bcf50c5e9e33d1604d18cd2c648c6d7d97dbc2645b7d4f7ad61b9e992ad17c6b/upsample_nearest1d_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..7baa8f1db5fa21e7277245369a5ee381d7977795 --- /dev/null +++ b/shared/package-files/bc/bcf50c5e9e33d1604d18cd2c648c6d7d97dbc2645b7d4f7ad61b9e992ad17c6b/upsample_nearest1d_backward.h @@ -0,0 +1,92 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_nearest1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales, grad_input); +} +namespace symint { + template >> + at::Tensor & upsample_nearest1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales, grad_input); + } +} + +// aten::upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_nearest1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales, at::Tensor & grad_input) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales, grad_input); +} +namespace symint { + template >> + at::Tensor & upsample_nearest1d_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales, at::Tensor & grad_input) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales, grad_input); + } +} + +// aten::upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_nearest1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, output_size, input_size, scales, grad_input); +} +namespace symint { + template >> + at::Tensor & upsample_nearest1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, output_size, input_size, scales, grad_input); + } +} + +// aten::upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) +inline at::Tensor & upsample_nearest1d_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales, at::Tensor & grad_input) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, output_size, input_size, scales, grad_input); +} +namespace symint { + template >> + at::Tensor & upsample_nearest1d_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales, at::Tensor & grad_input) { + return at::_ops::upsample_nearest1d_backward_grad_input::call(grad_output, output_size, input_size, scales, grad_input); + } +} + +// aten::upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor +inline at::Tensor upsample_nearest1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales); +} +namespace symint { + template >> + at::Tensor upsample_nearest1d_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), scales); + } +} + +// aten::upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor +inline at::Tensor upsample_nearest1d_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward::call(grad_output, output_size, input_size, scales); +} +namespace symint { + template >> + at::Tensor upsample_nearest1d_backward(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, ::std::optional scales=::std::nullopt) { + return at::_ops::upsample_nearest1d_backward::call(grad_output, output_size, input_size, scales); + } +} + +} diff --git a/shared/package-files/bc/bcf53c31ba64eff36c70c0be828acda1786c42390e8602b662228ea3ebba0ef6/kernighan_lin.py b/shared/package-files/bc/bcf53c31ba64eff36c70c0be828acda1786c42390e8602b662228ea3ebba0ef6/kernighan_lin.py new file mode 100644 index 0000000000000000000000000000000000000000..f6397d82be6fa94273a81a613411cc6a74d8c4cc --- /dev/null +++ b/shared/package-files/bc/bcf53c31ba64eff36c70c0be828acda1786c42390e8602b662228ea3ebba0ef6/kernighan_lin.py @@ -0,0 +1,139 @@ +"""Functions for computing the Kernighan–Lin bipartition algorithm.""" + +from itertools import count + +import networkx as nx +from networkx.algorithms.community.community_utils import is_partition +from networkx.utils import BinaryHeap, not_implemented_for, py_random_state + +__all__ = ["kernighan_lin_bisection"] + + +def _kernighan_lin_sweep(edges, side): + """ + This is a modified form of Kernighan-Lin, which moves single nodes at a + time, alternating between sides to keep the bisection balanced. We keep + two min-heaps of swap costs to make optimal-next-move selection fast. + """ + costs0, costs1 = costs = BinaryHeap(), BinaryHeap() + for u, side_u, edges_u in zip(count(), side, edges): + cost_u = sum(w if side[v] else -w for v, w in edges_u) + costs[side_u].insert(u, cost_u if side_u else -cost_u) + + def _update_costs(costs_x, x): + for y, w in edges[x]: + costs_y = costs[side[y]] + cost_y = costs_y.get(y) + if cost_y is not None: + cost_y += 2 * (-w if costs_x is costs_y else w) + costs_y.insert(y, cost_y, True) + + i = 0 + totcost = 0 + while costs0 and costs1: + u, cost_u = costs0.pop() + _update_costs(costs0, u) + v, cost_v = costs1.pop() + _update_costs(costs1, v) + totcost += cost_u + cost_v + i += 1 + yield totcost, i, (u, v) + + +@not_implemented_for("directed") +@py_random_state(4) +@nx._dispatchable(edge_attrs="weight") +def kernighan_lin_bisection(G, partition=None, max_iter=10, weight="weight", seed=None): + """Partition a graph into two blocks using the Kernighan–Lin + algorithm. + + This algorithm partitions a network into two sets by iteratively + swapping pairs of nodes to reduce the edge cut between the two sets. The + pairs are chosen according to a modified form of Kernighan-Lin [1]_, which + moves node individually, alternating between sides to keep the bisection + balanced. + + Parameters + ---------- + G : NetworkX graph + Graph must be undirected. + + partition : tuple + Pair of iterables containing an initial partition. If not + specified, a random balanced partition is used. + + max_iter : int + Maximum number of times to attempt swaps to find an + improvement before giving up. + + weight : key + Edge data key to use as weight. If None, the weights are all + set to one. + + seed : integer, random_state, or None (default) + Indicator of random number generation state. + See :ref:`Randomness`. + Only used if partition is None + + Returns + ------- + partition : tuple + A pair of sets of nodes representing the bipartition. + + Raises + ------ + NetworkXError + If partition is not a valid partition of the nodes of the graph. + + References + ---------- + .. [1] Kernighan, B. W.; Lin, Shen (1970). + "An efficient heuristic procedure for partitioning graphs." + *Bell Systems Technical Journal* 49: 291--307. + Oxford University Press 2011. + + """ + n = len(G) + labels = list(G) + seed.shuffle(labels) + index = {v: i for i, v in enumerate(labels)} + + if partition is None: + side = [0] * (n // 2) + [1] * ((n + 1) // 2) + else: + try: + A, B = partition + except (TypeError, ValueError) as err: + raise nx.NetworkXError("partition must be two sets") from err + if not is_partition(G, (A, B)): + raise nx.NetworkXError("partition invalid") + side = [0] * n + for a in A: + side[index[a]] = 1 + + if G.is_multigraph(): + edges = [ + [ + (index[u], sum(e.get(weight, 1) for e in d.values())) + for u, d in G[v].items() + ] + for v in labels + ] + else: + edges = [ + [(index[u], e.get(weight, 1)) for u, e in G[v].items()] for v in labels + ] + + for i in range(max_iter): + costs = list(_kernighan_lin_sweep(edges, side)) + min_cost, min_i, _ = min(costs) + if min_cost >= 0: + break + + for _, _, (u, v) in costs[:min_i]: + side[u] = 1 + side[v] = 0 + + A = {u for u, s in zip(labels, side) if s == 0} + B = {u for u, s in zip(labels, side) if s == 1} + return A, B diff --git a/shared/package-files/bc/bcfa4260190e9bc29787066a021ebb62258554724a23d41e57916d8687e2056f/_segment_reduce_backward_cuda_dispatch.h b/shared/package-files/bc/bcfa4260190e9bc29787066a021ebb62258554724a23d41e57916d8687e2056f/_segment_reduce_backward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5b58e45b49184badfc26ac658282ac17d120f57f --- /dev/null +++ b/shared/package-files/bc/bcfa4260190e9bc29787066a021ebb62258554724a23d41e57916d8687e2056f/_segment_reduce_backward_cuda_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor _segment_reduce_backward(const at::Tensor & grad, const at::Tensor & output, const at::Tensor & data, c10::string_view reduce, const ::std::optional & lengths={}, const ::std::optional & offsets={}, int64_t axis=0, const ::std::optional & initial=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/bc/bcfe5769b5487b3b005116caeb9a7c3ff41f3c8350c21a25d1deb607b06bdecd/holonomic.py b/shared/package-files/bc/bcfe5769b5487b3b005116caeb9a7c3ff41f3c8350c21a25d1deb607b06bdecd/holonomic.py new file mode 100644 index 0000000000000000000000000000000000000000..e31c4d4511d4c07aa4049a62253cdb060758cf3d --- /dev/null +++ b/shared/package-files/bc/bcfe5769b5487b3b005116caeb9a7c3ff41f3c8350c21a25d1deb607b06bdecd/holonomic.py @@ -0,0 +1,2765 @@ +""" +This module implements Holonomic Functions and +various operations on them. +""" + +from sympy.core import Add, Mul, Pow +from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi, + equal_valued, int_valued) +from sympy.core.singleton import S +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, Symbol +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import binomial, factorial, rf +from sympy.functions.elementary.exponential import exp_polar, exp, log +from sympy.functions.elementary.hyperbolic import (cosh, sinh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin, sinc) +from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi) +from sympy.functions.special.gamma_functions import gamma +from sympy.functions.special.hyper import hyper, meijerg +from sympy.integrals import meijerint +from sympy.matrices import Matrix +from sympy.polys.rings import PolyElement +from sympy.polys.fields import FracElement +from sympy.polys.domains import QQ, RR +from sympy.polys.polyclasses import DMF +from sympy.polys.polyroots import roots +from sympy.polys.polytools import Poly +from sympy.polys.matrices import DomainMatrix +from sympy.printing import sstr +from sympy.series.limits import limit +from sympy.series.order import Order +from sympy.simplify.hyperexpand import hyperexpand +from sympy.simplify.simplify import nsimplify +from sympy.solvers.solvers import solve + +from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators +from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError, + SingularityError, NotHolonomicError) + + +def _find_nonzero_solution(r, homosys): + ones = lambda shape: DomainMatrix.ones(shape, r.domain) + particular, nullspace = r._solve(homosys) + nullity = nullspace.shape[0] + nullpart = ones((1, nullity)) * nullspace + sol = (particular + nullpart).transpose() + return sol + + + +def DifferentialOperators(base, generator): + r""" + This function is used to create annihilators using ``Dx``. + + Explanation + =========== + + Returns an Algebra of Differential Operators also called Weyl Algebra + and the operator for differentiation i.e. the ``Dx`` operator. + + Parameters + ========== + + base: + Base polynomial ring for the algebra. + The base polynomial ring is the ring of polynomials in :math:`x` that + will appear as coefficients in the operators. + generator: + Generator of the algebra which can + be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D". + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy.abc import x + >>> from sympy.holonomic.holonomic import DifferentialOperators + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + >>> R + Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] + >>> Dx*x + (1) + (x)*Dx + """ + + ring = DifferentialOperatorAlgebra(base, generator) + return (ring, ring.derivative_operator) + + +class DifferentialOperatorAlgebra: + r""" + An Ore Algebra is a set of noncommutative polynomials in the + intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`. + It follows the commutation rule: + + .. math :: + Dxa = \sigma(a)Dx + \delta(a) + + for :math:`a \subset A`. + + Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A` + is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`. + + If one takes the sigma as identity map and delta as the standard derivation + then it becomes the algebra of Differential Operators also called + a Weyl Algebra i.e. an algebra whose elements are Differential Operators. + + This class represents a Weyl Algebra and serves as the parent ring for + Differential Operators. + + Examples + ======== + + >>> from sympy import ZZ + >>> from sympy import symbols + >>> from sympy.holonomic.holonomic import DifferentialOperators + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') + >>> R + Univariate Differential Operator Algebra in intermediate Dx over the base ring + ZZ[x] + + See Also + ======== + + DifferentialOperator + """ + + def __init__(self, base, generator): + # the base polynomial ring for the algebra + self.base = base + # the operator representing differentiation i.e. `Dx` + self.derivative_operator = DifferentialOperator( + [base.zero, base.one], self) + + if generator is None: + self.gen_symbol = Symbol('Dx', commutative=False) + else: + if isinstance(generator, str): + self.gen_symbol = Symbol(generator, commutative=False) + elif isinstance(generator, Symbol): + self.gen_symbol = generator + + def __str__(self): + string = 'Univariate Differential Operator Algebra in intermediate '\ + + sstr(self.gen_symbol) + ' over the base ring ' + \ + (self.base).__str__() + + return string + + __repr__ = __str__ + + def __eq__(self, other): + return self.base == other.base and \ + self.gen_symbol == other.gen_symbol + + +class DifferentialOperator: + """ + Differential Operators are elements of Weyl Algebra. The Operators + are defined by a list of polynomials in the base ring and the + parent ring of the Operator i.e. the algebra it belongs to. + + Explanation + =========== + + Takes a list of polynomials for each power of ``Dx`` and the + parent ring which must be an instance of DifferentialOperatorAlgebra. + + A Differential Operator can be created easily using + the operator ``Dx``. See examples below. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + + >>> DifferentialOperator([0, 1, x**2], R) + (1)*Dx + (x**2)*Dx**2 + + >>> (x*Dx*x + 1 - Dx**2)**2 + (2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4 + + See Also + ======== + + DifferentialOperatorAlgebra + """ + + _op_priority = 20 + + def __init__(self, list_of_poly, parent): + """ + Parameters + ========== + + list_of_poly: + List of polynomials belonging to the base ring of the algebra. + parent: + Parent algebra of the operator. + """ + + # the parent ring for this operator + # must be an DifferentialOperatorAlgebra object + self.parent = parent + base = self.parent.base + self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0] + # sequence of polynomials in x for each power of Dx + # the list should not have trailing zeroes + # represents the operator + # convert the expressions into ring elements using from_sympy + for i, j in enumerate(list_of_poly): + if not isinstance(j, base.dtype): + list_of_poly[i] = base.from_sympy(sympify(j)) + else: + list_of_poly[i] = base.from_sympy(base.to_sympy(j)) + + self.listofpoly = list_of_poly + # highest power of `Dx` + self.order = len(self.listofpoly) - 1 + + def __mul__(self, other): + """ + Multiplies two DifferentialOperator and returns another + DifferentialOperator instance using the commutation rule + Dx*a = a*Dx + a' + """ + + listofself = self.listofpoly + if isinstance(other, DifferentialOperator): + listofother = other.listofpoly + elif isinstance(other, self.parent.base.dtype): + listofother = [other] + else: + listofother = [self.parent.base.from_sympy(sympify(other))] + + # multiplies a polynomial `b` with a list of polynomials + def _mul_dmp_diffop(b, listofother): + if isinstance(listofother, list): + return [i * b for i in listofother] + return [b * listofother] + + sol = _mul_dmp_diffop(listofself[0], listofother) + + # compute Dx^i * b + def _mul_Dxi_b(b): + sol1 = [self.parent.base.zero] + sol2 = [] + + if isinstance(b, list): + for i in b: + sol1.append(i) + sol2.append(i.diff()) + else: + sol1.append(self.parent.base.from_sympy(b)) + sol2.append(self.parent.base.from_sympy(b).diff()) + + return _add_lists(sol1, sol2) + + for i in range(1, len(listofself)): + # find Dx^i * b in ith iteration + listofother = _mul_Dxi_b(listofother) + # solution = solution + listofself[i] * (Dx^i * b) + sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) + + return DifferentialOperator(sol, self.parent) + + def __rmul__(self, other): + if not isinstance(other, DifferentialOperator): + + if not isinstance(other, self.parent.base.dtype): + other = (self.parent.base).from_sympy(sympify(other)) + + sol = [other * j for j in self.listofpoly] + return DifferentialOperator(sol, self.parent) + + def __add__(self, other): + if isinstance(other, DifferentialOperator): + + sol = _add_lists(self.listofpoly, other.listofpoly) + return DifferentialOperator(sol, self.parent) + + list_self = self.listofpoly + if not isinstance(other, self.parent.base.dtype): + list_other = [((self.parent).base).from_sympy(sympify(other))] + else: + list_other = [other] + sol = [list_self[0] + list_other[0]] + list_self[1:] + return DifferentialOperator(sol, self.parent) + + __radd__ = __add__ + + def __sub__(self, other): + return self + (-1) * other + + def __rsub__(self, other): + return (-1) * self + other + + def __neg__(self): + return -1 * self + + def __truediv__(self, other): + return self * (S.One / other) + + def __pow__(self, n): + if n == 1: + return self + result = DifferentialOperator([self.parent.base.one], self.parent) + if n == 0: + return result + # if self is `Dx` + if self.listofpoly == self.parent.derivative_operator.listofpoly: + sol = [self.parent.base.zero]*n + [self.parent.base.one] + return DifferentialOperator(sol, self.parent) + x = self + while True: + if n % 2: + result *= x + n >>= 1 + if not n: + break + x *= x + return result + + def __str__(self): + listofpoly = self.listofpoly + print_str = '' + + for i, j in enumerate(listofpoly): + if j == self.parent.base.zero: + continue + + j = self.parent.base.to_sympy(j) + + if i == 0: + print_str += '(' + sstr(j) + ')' + continue + + if print_str: + print_str += ' + ' + + if i == 1: + print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol) + continue + + print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i) + + return print_str + + __repr__ = __str__ + + def __eq__(self, other): + if isinstance(other, DifferentialOperator): + return self.listofpoly == other.listofpoly and \ + self.parent == other.parent + return self.listofpoly[0] == other and \ + all(i is self.parent.base.zero for i in self.listofpoly[1:]) + + def is_singular(self, x0): + """ + Checks if the differential equation is singular at x0. + """ + + base = self.parent.base + return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x) + + +class HolonomicFunction: + r""" + A Holonomic Function is a solution to a linear homogeneous ordinary + differential equation with polynomial coefficients. This differential + equation can also be represented by an annihilator i.e. a Differential + Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions, + initial conditions can also be provided along with the annihilator. + + Explanation + =========== + + Holonomic functions have closure properties and thus forms a ring. + Given two Holonomic Functions f and g, their sum, product, + integral and derivative is also a Holonomic Function. + + For ordinary points initial condition should be a vector of values of + the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`. + + For regular singular points initial conditions can also be provided in this + format: + :math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}` + where s0, s1, ... are the roots of indicial equation and vectors + :math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial + terms of the associated power series. See Examples below. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + + >>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x + >>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x) + + >>> p + q # annihilator of e^x + sin(x) + HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1]) + + >>> p * q # annihilator of e^x * sin(x) + HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1]) + + An example of initial conditions for regular singular points, + the indicial equation has only one root `1/2`. + + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}) + HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]}) + + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr() + sqrt(x) + + To plot a Holonomic Function, one can use `.evalf()` for numerical + computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib. + + >>> import sympy.holonomic # doctest: +SKIP + >>> from sympy import var, sin # doctest: +SKIP + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> import numpy as np # doctest: +SKIP + >>> var("x") # doctest: +SKIP + >>> r = np.linspace(1, 5, 100) # doctest: +SKIP + >>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP + >>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + + """ + + _op_priority = 20 + + def __init__(self, annihilator, x, x0=0, y0=None): + """ + + Parameters + ========== + + annihilator: + Annihilator of the Holonomic Function, represented by a + `DifferentialOperator` object. + x: + Variable of the function. + x0: + The point at which initial conditions are stored. + Generally an integer. + y0: + The initial condition. The proper format for the initial condition + is described in class docstring. To make the function unique, + length of the vector `y0` should be equal to or greater than the + order of differential equation. + """ + + # initial condition + self.y0 = y0 + # the point for initial conditions, default is zero. + self.x0 = x0 + # differential operator L such that L.f = 0 + self.annihilator = annihilator + self.x = x + + def __str__(self): + if self._have_init_cond(): + str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\ + sstr(self.x), sstr(self.x0), sstr(self.y0)) + else: + str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\ + sstr(self.x)) + + return str_sol + + __repr__ = __str__ + + def unify(self, other): + """ + Unifies the base polynomial ring of a given two Holonomic + Functions. + """ + + R1 = self.annihilator.parent.base + R2 = other.annihilator.parent.base + + dom1 = R1.dom + dom2 = R2.dom + + if R1 == R2: + return (self, other) + + R = (dom1.unify(dom2)).old_poly_ring(self.x) + + newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol)) + + sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly] + sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly] + + sol1 = DifferentialOperator(sol1, newparent) + sol2 = DifferentialOperator(sol2, newparent) + + sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0) + sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0) + + return (sol1, sol2) + + def is_singularics(self): + """ + Returns True if the function have singular initial condition + in the dictionary format. + + Returns False if the function have ordinary initial condition + in the list format. + + Returns None for all other cases. + """ + + if isinstance(self.y0, dict): + return True + elif isinstance(self.y0, list): + return False + + def _have_init_cond(self): + """ + Checks if the function have initial condition. + """ + return bool(self.y0) + + def _singularics_to_ord(self): + """ + Converts a singular initial condition to ordinary if possible. + """ + a = list(self.y0)[0] + b = self.y0[a] + + if len(self.y0) == 1 and a == int(a) and a > 0: + a = int(a) + y0 = [S.Zero] * a + y0 += [j * factorial(a + i) for i, j in enumerate(b)] + + return HolonomicFunction(self.annihilator, self.x, self.x0, y0) + + def __add__(self, other): + # if the ground domains are different + if self.annihilator.parent.base != other.annihilator.parent.base: + a, b = self.unify(other) + return a + b + + deg1 = self.annihilator.order + deg2 = other.annihilator.order + dim = max(deg1, deg2) + R = self.annihilator.parent.base + K = R.get_field() + + rowsself = [self.annihilator] + rowsother = [other.annihilator] + gen = self.annihilator.parent.derivative_operator + + # constructing annihilators up to order dim + for i in range(dim - deg1): + diff1 = (gen * rowsself[-1]) + rowsself.append(diff1) + + for i in range(dim - deg2): + diff2 = (gen * rowsother[-1]) + rowsother.append(diff2) + + row = rowsself + rowsother + + # constructing the matrix of the ansatz + r = [] + + for expr in row: + p = [] + for i in range(dim + 1): + if i >= len(expr.listofpoly): + p.append(K.zero) + else: + p.append(K.new(expr.listofpoly[i].to_list())) + r.append(p) + + # solving the linear system using gauss jordan solver + r = DomainMatrix(r, (len(row), dim+1), K).transpose() + homosys = DomainMatrix.zeros((dim+1, 1), K) + sol = _find_nonzero_solution(r, homosys) + + # if a solution is not obtained then increasing the order by 1 in each + # iteration + while sol.is_zero_matrix: + dim += 1 + + diff1 = (gen * rowsself[-1]) + rowsself.append(diff1) + + diff2 = (gen * rowsother[-1]) + rowsother.append(diff2) + + row = rowsself + rowsother + r = [] + + for expr in row: + p = [] + for i in range(dim + 1): + if i >= len(expr.listofpoly): + p.append(K.zero) + else: + p.append(K.new(expr.listofpoly[i].to_list())) + r.append(p) + + # solving the linear system using gauss jordan solver + r = DomainMatrix(r, (len(row), dim+1), K).transpose() + homosys = DomainMatrix.zeros((dim+1, 1), K) + sol = _find_nonzero_solution(r, homosys) + + # taking only the coefficients needed to multiply with `self` + # can be also be done the other way by taking R.H.S and multiplying with + # `other` + sol = sol.flat()[:dim + 1 - deg1] + sol1 = _normalize(sol, self.annihilator.parent) + # annihilator of the solution + sol = sol1 * (self.annihilator) + sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False) + + if not (self._have_init_cond() and other._have_init_cond()): + return HolonomicFunction(sol, self.x) + + # both the functions have ordinary initial conditions + if self.is_singularics() == False and other.is_singularics() == False: + + # directly add the corresponding value + if self.x0 == other.x0: + # try to extended the initial conditions + # using the annihilator + y1 = _extend_y0(self, sol.order) + y2 = _extend_y0(other, sol.order) + y0 = [a + b for a, b in zip(y1, y2)] + return HolonomicFunction(sol, self.x, self.x0, y0) + + # change the initial conditions to a same point + selfat0 = self.annihilator.is_singular(0) + otherat0 = other.annihilator.is_singular(0) + if self.x0 == 0 and not selfat0 and not otherat0: + return self + other.change_ics(0) + if other.x0 == 0 and not selfat0 and not otherat0: + return self.change_ics(0) + other + + selfatx0 = self.annihilator.is_singular(self.x0) + otheratx0 = other.annihilator.is_singular(self.x0) + if not selfatx0 and not otheratx0: + return self + other.change_ics(self.x0) + return self.change_ics(other.x0) + other + + if self.x0 != other.x0: + return HolonomicFunction(sol, self.x) + + # if the functions have singular_ics + y1 = None + y2 = None + + if self.is_singularics() == False and other.is_singularics() == True: + # convert the ordinary initial condition to singular. + _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] + y1 = {S.Zero: _y0} + y2 = other.y0 + elif self.is_singularics() == True and other.is_singularics() == False: + _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] + y1 = self.y0 + y2 = {S.Zero: _y0} + elif self.is_singularics() == True and other.is_singularics() == True: + y1 = self.y0 + y2 = other.y0 + + # computing singular initial condition for the result + # taking union of the series terms of both functions + y0 = {} + for i in y1: + # add corresponding initial terms if the power + # on `x` is same + if i in y2: + y0[i] = [a + b for a, b in zip(y1[i], y2[i])] + else: + y0[i] = y1[i] + for i in y2: + if i not in y1: + y0[i] = y2[i] + return HolonomicFunction(sol, self.x, self.x0, y0) + + def integrate(self, limits, initcond=False): + """ + Integrates the given holonomic function. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1 + HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1]) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x)) + HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0]) + """ + + # to get the annihilator, just multiply by Dx from right + D = self.annihilator.parent.derivative_operator + + # if the function have initial conditions of the series format + if self.is_singularics() == True: + + r = self._singularics_to_ord() + if r: + return r.integrate(limits, initcond=initcond) + + # computing singular initial condition for the function + # produced after integration. + y0 = {} + for i in self.y0: + c = self.y0[i] + c2 = [] + for j, cj in enumerate(c): + if cj == 0: + c2.append(S.Zero) + + # if power on `x` is -1, the integration becomes log(x) + # TODO: Implement this case + elif i + j + 1 == 0: + raise NotImplementedError("logarithmic terms in the series are not supported") + else: + c2.append(cj / S(i + j + 1)) + y0[i + 1] = c2 + + if hasattr(limits, "__iter__"): + raise NotImplementedError("Definite integration for singular initial conditions") + + return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) + + # if no initial conditions are available for the function + if not self._have_init_cond(): + if initcond: + return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero]) + return HolonomicFunction(self.annihilator * D, self.x) + + # definite integral + # initial conditions for the answer will be stored at point `a`, + # where `a` is the lower limit of the integrand + if hasattr(limits, "__iter__"): + + if len(limits) == 3 and limits[0] == self.x: + x0 = self.x0 + a = limits[1] + b = limits[2] + definite = True + + else: + definite = False + + y0 = [S.Zero] + y0 += self.y0 + + indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) + + if not definite: + return indefinite_integral + + # use evalf to get the values at `a` + if x0 != a: + try: + indefinite_expr = indefinite_integral.to_expr() + except (NotHyperSeriesError, NotPowerSeriesError): + indefinite_expr = None + + if indefinite_expr: + lower = indefinite_expr.subs(self.x, a) + if isinstance(lower, NaN): + lower = indefinite_expr.limit(self.x, a) + else: + lower = indefinite_integral.evalf(a) + + if b == self.x: + y0[0] = y0[0] - lower + return HolonomicFunction(self.annihilator * D, self.x, x0, y0) + + elif S(b).is_Number: + if indefinite_expr: + upper = indefinite_expr.subs(self.x, b) + if isinstance(upper, NaN): + upper = indefinite_expr.limit(self.x, b) + else: + upper = indefinite_integral.evalf(b) + + return upper - lower + + + # if the upper limit is `x`, the answer will be a function + if b == self.x: + return HolonomicFunction(self.annihilator * D, self.x, a, y0) + + # if the upper limits is a Number, a numerical value will be returned + elif S(b).is_Number: + try: + s = HolonomicFunction(self.annihilator * D, self.x, a,\ + y0).to_expr() + indefinite = s.subs(self.x, b) + if not isinstance(indefinite, NaN): + return indefinite + else: + return s.limit(self.x, b) + except (NotHyperSeriesError, NotPowerSeriesError): + return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b) + + return HolonomicFunction(self.annihilator * D, self.x) + + def diff(self, *args, **kwargs): + r""" + Differentiation of the given Holonomic function. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr() + cos(x) + >>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr() + 2*exp(2*x) + + See Also + ======== + + integrate + """ + kwargs.setdefault('evaluate', True) + if args: + if args[0] != self.x: + return S.Zero + elif len(args) == 2: + sol = self + for i in range(args[1]): + sol = sol.diff(args[0]) + return sol + + ann = self.annihilator + + # if the function is constant. + if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1: + return S.Zero + + # if the coefficient of y in the differential equation is zero. + # a shifting is done to compute the answer in this case. + elif ann.listofpoly[0] == ann.parent.base.zero: + + sol = DifferentialOperator(ann.listofpoly[1:], ann.parent) + + if self._have_init_cond(): + # if ordinary initial condition + if self.is_singularics() == False: + return HolonomicFunction(sol, self.x, self.x0, self.y0[1:]) + # TODO: support for singular initial condition + return HolonomicFunction(sol, self.x) + else: + return HolonomicFunction(sol, self.x) + + # the general algorithm + R = ann.parent.base + K = R.get_field() + + seq_dmf = [K.new(i.to_list()) for i in ann.listofpoly] + + # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0 + rhs = [i / seq_dmf[0] for i in seq_dmf[1:]] + rhs.insert(0, K.zero) + + # differentiate both lhs and rhs + sol = _derivate_diff_eq(rhs, K) + + # add the term y' in lhs to rhs + sol = _add_lists(sol, [K.zero, K.one]) + + sol = _normalize(sol[1:], self.annihilator.parent, negative=False) + + if not self._have_init_cond() or self.is_singularics() == True: + return HolonomicFunction(sol, self.x) + + y0 = _extend_y0(self, sol.order + 1)[1:] + return HolonomicFunction(sol, self.x, self.x0, y0) + + def __eq__(self, other): + if self.annihilator != other.annihilator or self.x != other.x: + return False + if self._have_init_cond() and other._have_init_cond(): + return self.x0 == other.x0 and self.y0 == other.y0 + return True + + def __mul__(self, other): + ann_self = self.annihilator + + if not isinstance(other, HolonomicFunction): + other = sympify(other) + + if other.has(self.x): + raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.") + + if not self._have_init_cond(): + return self + y0 = _extend_y0(self, ann_self.order) + y1 = [(Poly.new(j, self.x) * other).rep for j in y0] + return HolonomicFunction(ann_self, self.x, self.x0, y1) + + if self.annihilator.parent.base != other.annihilator.parent.base: + a, b = self.unify(other) + return a * b + + ann_other = other.annihilator + + a = ann_self.order + b = ann_other.order + + R = ann_self.parent.base + K = R.get_field() + + list_self = [K.new(j.to_list()) for j in ann_self.listofpoly] + list_other = [K.new(j.to_list()) for j in ann_other.listofpoly] + + # will be used to reduce the degree + self_red = [-list_self[i] / list_self[a] for i in range(a)] + + other_red = [-list_other[i] / list_other[b] for i in range(b)] + + # coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g) + coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)] + coeff_mul[0][0] = K.one + + # making the ansatz + lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]] + lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose() + + homo_sys = DomainMatrix.zeros((a*b, 1), K) + + sol = _find_nonzero_solution(lin_sys, homo_sys) + + # until a non trivial solution is found + while sol.is_zero_matrix: + + # updating the coefficients Dx^i(f).Dx^j(g) for next degree + for i in range(a - 1, -1, -1): + for j in range(b - 1, -1, -1): + coeff_mul[i][j + 1] += coeff_mul[i][j] + coeff_mul[i + 1][j] += coeff_mul[i][j] + if isinstance(coeff_mul[i][j], K.dtype): + coeff_mul[i][j] = DMFdiff(coeff_mul[i][j], K) + else: + coeff_mul[i][j] = coeff_mul[i][j].diff(self.x) + + # reduce the terms to lower power using annihilators of f, g + for i in range(a + 1): + if coeff_mul[i][b].is_zero: + continue + for j in range(b): + coeff_mul[i][j] += other_red[j] * coeff_mul[i][b] + coeff_mul[i][b] = K.zero + + # not d2 + 1, as that is already covered in previous loop + for j in range(b): + if coeff_mul[a][j] == 0: + continue + for i in range(a): + coeff_mul[i][j] += self_red[i] * coeff_mul[a][j] + coeff_mul[a][j] = K.zero + + lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)]) + lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose() + + sol = _find_nonzero_solution(lin_sys, homo_sys) + + sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False) + + if not (self._have_init_cond() and other._have_init_cond()): + return HolonomicFunction(sol_ann, self.x) + + if self.is_singularics() == False and other.is_singularics() == False: + + # if both the conditions are at same point + if self.x0 == other.x0: + + # try to find more initial conditions + y0_self = _extend_y0(self, sol_ann.order) + y0_other = _extend_y0(other, sol_ann.order) + # h(x0) = f(x0) * g(x0) + y0 = [y0_self[0] * y0_other[0]] + + # coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg) + for i in range(1, min(len(y0_self), len(y0_other))): + coeff = [[0 for i in range(i + 1)] for j in range(i + 1)] + for j in range(i + 1): + for k in range(i + 1): + if j + k == i: + coeff[j][k] = binomial(i, j) + + sol = 0 + for j in range(i + 1): + for k in range(i + 1): + sol += coeff[j][k]* y0_self[j] * y0_other[k] + + y0.append(sol) + + return HolonomicFunction(sol_ann, self.x, self.x0, y0) + + # if the points are different, consider one + selfat0 = self.annihilator.is_singular(0) + otherat0 = other.annihilator.is_singular(0) + + if self.x0 == 0 and not selfat0 and not otherat0: + return self * other.change_ics(0) + if other.x0 == 0 and not selfat0 and not otherat0: + return self.change_ics(0) * other + + selfatx0 = self.annihilator.is_singular(self.x0) + otheratx0 = other.annihilator.is_singular(self.x0) + if not selfatx0 and not otheratx0: + return self * other.change_ics(self.x0) + return self.change_ics(other.x0) * other + + if self.x0 != other.x0: + return HolonomicFunction(sol_ann, self.x) + + # if the functions have singular_ics + y1 = None + y2 = None + + if self.is_singularics() == False and other.is_singularics() == True: + _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] + y1 = {S.Zero: _y0} + y2 = other.y0 + elif self.is_singularics() == True and other.is_singularics() == False: + _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] + y1 = self.y0 + y2 = {S.Zero: _y0} + elif self.is_singularics() == True and other.is_singularics() == True: + y1 = self.y0 + y2 = other.y0 + + y0 = {} + # multiply every possible pair of the series terms + for i in y1: + for j in y2: + k = min(len(y1[i]), len(y2[j])) + c = [sum((y1[i][b] * y2[j][a - b] for b in range(a + 1)), + start=S.Zero) for a in range(k)] + if not i + j in y0: + y0[i + j] = c + else: + y0[i + j] = [a + b for a, b in zip(c, y0[i + j])] + return HolonomicFunction(sol_ann, self.x, self.x0, y0) + + __rmul__ = __mul__ + + def __sub__(self, other): + return self + other * -1 + + def __rsub__(self, other): + return self * -1 + other + + def __neg__(self): + return -1 * self + + def __truediv__(self, other): + return self * (S.One / other) + + def __pow__(self, n): + if self.annihilator.order <= 1: + ann = self.annihilator + parent = ann.parent + + if self.y0 is None: + y0 = None + else: + y0 = [list(self.y0)[0] ** n] + + p0 = ann.listofpoly[0] + p1 = ann.listofpoly[1] + + p0 = (Poly.new(p0, self.x) * n).rep + + sol = [parent.base.to_sympy(i) for i in [p0, p1]] + dd = DifferentialOperator(sol, parent) + return HolonomicFunction(dd, self.x, self.x0, y0) + if n < 0: + raise NotHolonomicError("Negative Power on a Holonomic Function") + Dx = self.annihilator.parent.derivative_operator + result = HolonomicFunction(Dx, self.x, S.Zero, [S.One]) + if n == 0: + return result + x = self + while True: + if n % 2: + result *= x + n >>= 1 + if not n: + break + x *= x + return result + + def degree(self): + """ + Returns the highest power of `x` in the annihilator. + """ + return max(i.degree() for i in self.annihilator.listofpoly) + + def composition(self, expr, *args, **kwargs): + """ + Returns function after composition of a holonomic + function with an algebraic function. The method cannot compute + initial conditions for the result by itself, so they can be also be + provided. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) + HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1]) + >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0]) + HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0]) + + See Also + ======== + + from_hyper + """ + + R = self.annihilator.parent + a = self.annihilator.order + diff = expr.diff(self.x) + listofpoly = self.annihilator.listofpoly + + for i, j in enumerate(listofpoly): + if isinstance(j, self.annihilator.parent.base.dtype): + listofpoly[i] = self.annihilator.parent.base.to_sympy(j) + + r = listofpoly[a].subs({self.x:expr}) + subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)] + coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a)) + coeffs[0] = S.One + system = [coeffs] + homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose() + while True: + coeffs_next = [p.diff(self.x) for p in coeffs] + for i in range(a - 1): + coeffs_next[i + 1] += (coeffs[i] * diff) + for i in range(a): + coeffs_next[i] += (coeffs[-1] * subs[i] * diff) + coeffs = coeffs_next + # check for linear relations + system.append(coeffs) + sol, taus = (Matrix(system).transpose() + ).gauss_jordan_solve(homogeneous) + if sol.is_zero_matrix is not True: + break + + tau = list(taus)[0] + sol = sol.subs(tau, 1) + sol = _normalize(sol[0:], R, negative=False) + + # if initial conditions are given for the resulting function + if args: + return HolonomicFunction(sol, self.x, args[0], args[1]) + return HolonomicFunction(sol, self.x) + + def to_sequence(self, lb=True): + r""" + Finds recurrence relation for the coefficients in the series expansion + of the function about :math:`x_0`, where :math:`x_0` is the point at + which the initial condition is stored. + + Explanation + =========== + + If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]` + is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the + smallest ``n`` for which the recurrence holds true. + + If the point :math:`x_0` is regular singular, a list of solutions in + the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`. + Each tuple in this vector represents a recurrence relation :math:`R` + associated with a root of the indicial equation ``p``. Conditions of + a different format can also be provided in this case, see the + docstring of HolonomicFunction class. + + If it's not possible to numerically compute a initial condition, + it is returned as a symbol :math:`C_j`, denoting the coefficient of + :math:`(x - x_0)^j` in the power series about :math:`x_0`. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() + [(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)] + >>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence() + [(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)] + >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence() + [(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)] + + See Also + ======== + + HolonomicFunction.series + + References + ========== + + .. [1] https://hal.inria.fr/inria-00070025/document + .. [2] https://www3.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf + + """ + + if self.x0 != 0: + return self.shift_x(self.x0).to_sequence() + + # check whether a power series exists if the point is singular + if self.annihilator.is_singular(self.x0): + return self._frobenius(lb=lb) + + dict1 = {} + n = Symbol('n', integer=True) + dom = self.annihilator.parent.base.dom + R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') + + # substituting each term of the form `x^k Dx^j` in the + # annihilator, according to the formula below: + # x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo)) + # for explanation see [2]. + for i, j in enumerate(self.annihilator.listofpoly): + + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + + for k in range(degree + 1): + coeff = listofdmp[degree - k] + + if coeff == 0: + continue + + if (i - k, k) in dict1: + dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i)) + else: + dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i)) + + + sol = [] + keylist = [i[0] for i in dict1] + lower = min(keylist) + upper = max(keylist) + degree = self.degree() + + # the recurrence relation holds for all values of + # n greater than smallest_n, i.e. n >= smallest_n + smallest_n = lower + degree + dummys = {} + eqs = [] + unknowns = [] + + # an appropriate shift of the recurrence + for j in range(lower, upper + 1): + if j in keylist: + temp = sum((v.subs(n, n - lower) + for k, v in dict1.items() if k[0] == j), + start=S.Zero) + sol.append(temp) + else: + sol.append(S.Zero) + + # the recurrence relation + sol = RecurrenceOperator(sol, R) + + # computing the initial conditions for recurrence + order = sol.order + all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') + all_roots = all_roots.keys() + + if all_roots: + max_root = max(all_roots) + 1 + smallest_n = max(max_root, smallest_n) + order += smallest_n + + y0 = _extend_y0(self, order) + # u(n) = y^n(0)/factorial(n) + u0 = [j / factorial(i) for i, j in enumerate(y0)] + + # if sufficient conditions can't be computed then + # try to use the series method i.e. + # equate the coefficients of x^k in the equation formed by + # substituting the series in differential equation, to zero. + if len(u0) < order: + + for i in range(degree): + eq = S.Zero + + for j in dict1: + + if i + j[0] < 0: + dummys[i + j[0]] = S.Zero + + elif i + j[0] < len(u0): + dummys[i + j[0]] = u0[i + j[0]] + + elif not i + j[0] in dummys: + dummys[i + j[0]] = Symbol('C_%s' %(i + j[0])) + unknowns.append(dummys[i + j[0]]) + + if j[1] <= i: + eq += dict1[j].subs(n, i) * dummys[i + j[0]] + + eqs.append(eq) + + # solve the system of equations formed + soleqs = solve(eqs, *unknowns) + + if isinstance(soleqs, dict): + + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + + if dummys[i] in soleqs: + u0.append(soleqs[dummys[i]]) + + else: + u0.append(dummys[i]) + + if lb: + return [(HolonomicSequence(sol, u0), smallest_n)] + return [HolonomicSequence(sol, u0)] + + for i in range(len(u0), order): + + if i not in dummys: + dummys[i] = Symbol('C_%s' %i) + + s = False + for j in soleqs: + if dummys[i] in j: + u0.append(j[dummys[i]]) + s = True + if not s: + u0.append(dummys[i]) + + if lb: + return [(HolonomicSequence(sol, u0), smallest_n)] + + return [HolonomicSequence(sol, u0)] + + def _frobenius(self, lb=True): + # compute the roots of indicial equation + indicialroots = self._indicial() + + reals = [] + compl = [] + for i in ordered(indicialroots.keys()): + if i.is_real: + reals.extend([i] * indicialroots[i]) + else: + a, b = i.as_real_imag() + compl.extend([(i, a, b)] * indicialroots[i]) + + # sort the roots for a fixed ordering of solution + compl.sort(key=lambda x : x[1]) + compl.sort(key=lambda x : x[2]) + reals.sort() + + # grouping the roots, roots differ by an integer are put in the same group. + grp = [] + + for i in reals: + if len(grp) == 0: + grp.append([i]) + continue + for j in grp: + if int_valued(j[0] - i): + j.append(i) + break + else: + grp.append([i]) + + # True if none of the roots differ by an integer i.e. + # each element in group have only one member + independent = all(len(i) == 1 for i in grp) + + allpos = all(i >= 0 for i in reals) + allint = all(int_valued(i) for i in reals) + + # if initial conditions are provided + # then use them. + if self.is_singularics() == True: + rootstoconsider = [] + for i in ordered(self.y0.keys()): + for j in ordered(indicialroots.keys()): + if equal_valued(j, i): + rootstoconsider.append(i) + + elif allpos and allint: + rootstoconsider = [min(reals)] + + elif independent: + rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl] + + elif not allint: + rootstoconsider = [i for i in reals if not int(i) == i] + + elif not allpos: + + if not self._have_init_cond() or S(self.y0[0]).is_finite == False: + rootstoconsider = [min(reals)] + + else: + posroots = [i for i in reals if i >= 0] + rootstoconsider = [min(posroots)] + + n = Symbol('n', integer=True) + dom = self.annihilator.parent.base.dom + R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') + + finalsol = [] + char = ord('C') + + for p in rootstoconsider: + dict1 = {} + + for i, j in enumerate(self.annihilator.listofpoly): + + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + + for k in range(degree + 1): + coeff = listofdmp[degree - k] + + if coeff == 0: + continue + + if (i - k, k - i) in dict1: + dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) + else: + dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) + + sol = [] + keylist = [i[0] for i in dict1] + lower = min(keylist) + upper = max(keylist) + degree = max(i[1] for i in dict1) + degree2 = min(i[1] for i in dict1) + + smallest_n = lower + degree + dummys = {} + eqs = [] + unknowns = [] + + for j in range(lower, upper + 1): + if j in keylist: + temp = sum((v.subs(n, n - lower) + for k, v in dict1.items() if k[0] == j), + start=S.Zero) + sol.append(temp) + else: + sol.append(S.Zero) + + # the recurrence relation + sol = RecurrenceOperator(sol, R) + + # computing the initial conditions for recurrence + order = sol.order + all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') + all_roots = all_roots.keys() + + if all_roots: + max_root = max(all_roots) + 1 + smallest_n = max(max_root, smallest_n) + order += smallest_n + + u0 = [] + + if self.is_singularics() == True: + u0 = self.y0[p] + + elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1: + y0 = _extend_y0(self, order + int(p)) + # u(n) = y^n(0)/factorial(n) + if len(y0) > int(p): + u0 = [y0[i] / factorial(i) for i in range(int(p), len(y0))] + + if len(u0) < order: + + for i in range(degree2, degree): + eq = S.Zero + + for j in dict1: + if i + j[0] < 0: + dummys[i + j[0]] = S.Zero + + elif i + j[0] < len(u0): + dummys[i + j[0]] = u0[i + j[0]] + + elif not i + j[0] in dummys: + letter = chr(char) + '_%s' %(i + j[0]) + dummys[i + j[0]] = Symbol(letter) + unknowns.append(dummys[i + j[0]]) + + if j[1] <= i: + eq += dict1[j].subs(n, i) * dummys[i + j[0]] + + eqs.append(eq) + + # solve the system of equations formed + soleqs = solve(eqs, *unknowns) + + if isinstance(soleqs, dict): + + for i in range(len(u0), order): + + if i not in dummys: + letter = chr(char) + '_%s' %i + dummys[i] = Symbol(letter) + + if dummys[i] in soleqs: + u0.append(soleqs[dummys[i]]) + + else: + u0.append(dummys[i]) + + if lb: + finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) + continue + else: + finalsol.append((HolonomicSequence(sol, u0), p)) + continue + + for i in range(len(u0), order): + + if i not in dummys: + letter = chr(char) + '_%s' %i + dummys[i] = Symbol(letter) + + s = False + for j in soleqs: + if dummys[i] in j: + u0.append(j[dummys[i]]) + s = True + if not s: + u0.append(dummys[i]) + if lb: + finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) + + else: + finalsol.append((HolonomicSequence(sol, u0), p)) + char += 1 + return finalsol + + def series(self, n=6, coefficient=False, order=True, _recur=None): + r""" + Finds the power series expansion of given holonomic function about :math:`x_0`. + + Explanation + =========== + + A list of series might be returned if :math:`x_0` is a regular point with + multiple roots of the indicial equation. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x + 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x) + x - x**3/6 + x**5/120 - x**7/5040 + O(x**8) + + See Also + ======== + + HolonomicFunction.to_sequence + """ + + if _recur is None: + recurrence = self.to_sequence() + else: + recurrence = _recur + + if isinstance(recurrence, tuple) and len(recurrence) == 2: + recurrence = recurrence[0] + constantpower = 0 + elif isinstance(recurrence, tuple) and len(recurrence) == 3: + constantpower = recurrence[1] + recurrence = recurrence[0] + + elif len(recurrence) == 1 and len(recurrence[0]) == 2: + recurrence = recurrence[0][0] + constantpower = 0 + elif len(recurrence) == 1 and len(recurrence[0]) == 3: + constantpower = recurrence[0][1] + recurrence = recurrence[0][0] + else: + return [self.series(_recur=i) for i in recurrence] + + n = n - int(constantpower) + l = len(recurrence.u0) - 1 + k = recurrence.recurrence.order + x = self.x + x0 = self.x0 + seq_dmp = recurrence.recurrence.listofpoly + R = recurrence.recurrence.parent.base + K = R.get_field() + seq = [K.new(j.to_list()) for j in seq_dmp] + sub = [-seq[i] / seq[k] for i in range(k)] + sol = list(recurrence.u0) + + if l + 1 < n: + # use the initial conditions to find the next term + for i in range(l + 1 - k, n - k): + coeff = sum((DMFsubs(sub[j], i) * sol[i + j] + for j in range(k) if i + j >= 0), start=S.Zero) + sol.append(coeff) + + if coefficient: + return sol + + ser = sum((x**(i + constantpower) * j for i, j in enumerate(sol)), + start=S.Zero) + if order: + ser += Order(x**(n + int(constantpower)), x) + if x0 != 0: + return ser.subs(x, x - x0) + return ser + + def _indicial(self): + """ + Computes roots of the Indicial equation. + """ + + if self.x0 != 0: + return self.shift_x(self.x0)._indicial() + + list_coeff = self.annihilator.listofpoly + R = self.annihilator.parent.base + x = self.x + s = R.zero + y = R.one + + def _pole_degree(poly): + root_all = roots(R.to_sympy(poly), x, filter='Z') + if 0 in root_all.keys(): + return root_all[0] + else: + return 0 + + degree = max(j.degree() for j in list_coeff) + inf = 10 * (max(1, degree) + max(1, self.annihilator.order)) + + deg = lambda q: inf if q.is_zero else _pole_degree(q) + b = min(deg(q) - j for j, q in enumerate(list_coeff)) + + for i, j in enumerate(list_coeff): + listofdmp = j.all_coeffs() + degree = len(listofdmp) - 1 + if 0 <= i + b <= degree: + s = s + listofdmp[degree - i - b] * y + y *= R.from_sympy(x - i) + + return roots(R.to_sympy(s), x) + + def evalf(self, points, method='RK4', h=0.05, derivatives=False): + r""" + Finds numerical value of a holonomic function using numerical methods. + (RK4 by default). A set of points (real or complex) must be provided + which will be the path for the numerical integration. + + Explanation + =========== + + The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical + values will be computed at each point in this order + :math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`. + + Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import QQ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') + + A straight line on the real axis from (0 to 1) + + >>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] + + Runge-Kutta 4th order on e^x from 0.1 to 1. + Exact solution at 1 is 2.71828182845905 + + >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r) + [1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069, + 1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232, + 2.45960141378007, 2.71827974413517] + + Euler's method for the same + + >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler') + [1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881, + 2.357947691, 2.5937424601] + + One can also observe that the value obtained using Runge-Kutta 4th order + is much more accurate than Euler's method. + """ + + from sympy.holonomic.numerical import _evalf + lp = False + + # if a point `b` is given instead of a mesh + if not hasattr(points, "__iter__"): + lp = True + b = S(points) + if self.x0 == b: + return _evalf(self, [b], method=method, derivatives=derivatives)[-1] + + if not b.is_Number: + raise NotImplementedError + + a = self.x0 + if a > b: + h = -h + n = int((b - a) / h) + points = [a + h] + for i in range(n - 1): + points.append(points[-1] + h) + + for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x): + if i == self.x0 or i in points: + raise SingularityError(self, i) + + if lp: + return _evalf(self, points, method=method, derivatives=derivatives)[-1] + return _evalf(self, points, method=method, derivatives=derivatives) + + def change_x(self, z): + """ + Changes only the variable of Holonomic Function, for internal + purposes. For composition use HolonomicFunction.composition() + """ + + dom = self.annihilator.parent.base.dom + R = dom.old_poly_ring(z) + parent, _ = DifferentialOperators(R, 'Dx') + sol = [R(j.to_list()) for j in self.annihilator.listofpoly] + sol = DifferentialOperator(sol, parent) + return HolonomicFunction(sol, z, self.x0, self.y0) + + def shift_x(self, a): + """ + Substitute `x + a` for `x`. + """ + + x = self.x + listaftershift = self.annihilator.listofpoly + base = self.annihilator.parent.base + + sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift] + sol = DifferentialOperator(sol, self.annihilator.parent) + x0 = self.x0 - a + if not self._have_init_cond(): + return HolonomicFunction(sol, x) + return HolonomicFunction(sol, x, x0, self.y0) + + def to_hyper(self, as_list=False, _recur=None): + r""" + Returns a hypergeometric function (or linear combination of them) + representing the given holonomic function. + + Explanation + =========== + + Returns an answer of the form: + `a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots` + + This is very useful as one can now use ``hyperexpand`` to find the + symbolic expressions/functions. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> # sin(x) + >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper() + x*hyper((), (3/2,), -x**2/4) + >>> # exp(x) + >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper() + hyper((), (), x) + + See Also + ======== + + from_hyper, from_meijerg + """ + + if _recur is None: + recurrence = self.to_sequence() + else: + recurrence = _recur + + if isinstance(recurrence, tuple) and len(recurrence) == 2: + smallest_n = recurrence[1] + recurrence = recurrence[0] + constantpower = 0 + elif isinstance(recurrence, tuple) and len(recurrence) == 3: + smallest_n = recurrence[2] + constantpower = recurrence[1] + recurrence = recurrence[0] + elif len(recurrence) == 1 and len(recurrence[0]) == 2: + smallest_n = recurrence[0][1] + recurrence = recurrence[0][0] + constantpower = 0 + elif len(recurrence) == 1 and len(recurrence[0]) == 3: + smallest_n = recurrence[0][2] + constantpower = recurrence[0][1] + recurrence = recurrence[0][0] + else: + sol = self.to_hyper(as_list=as_list, _recur=recurrence[0]) + for i in recurrence[1:]: + sol += self.to_hyper(as_list=as_list, _recur=i) + return sol + + u0 = recurrence.u0 + r = recurrence.recurrence + x = self.x + x0 = self.x0 + + # order of the recurrence relation + m = r.order + + # when no recurrence exists, and the power series have finite terms + if m == 0: + nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R') + + sol = S.Zero + for j, i in enumerate(nonzeroterms): + + if i < 0 or not int_valued(i): + continue + + i = int(i) + if i < len(u0): + if isinstance(u0[i], (PolyElement, FracElement)): + u0[i] = u0[i].as_expr() + sol += u0[i] * x**i + + else: + sol += Symbol('C_%s' %j) * x**i + + if isinstance(sol, (PolyElement, FracElement)): + sol = sol.as_expr() * x**constantpower + else: + sol = sol * x**constantpower + if as_list: + if x0 != 0: + return [(sol.subs(x, x - x0), )] + return [(sol, )] + if x0 != 0: + return sol.subs(x, x - x0) + return sol + + if smallest_n + m > len(u0): + raise NotImplementedError("Can't compute sufficient Initial Conditions") + + # check if the recurrence represents a hypergeometric series + if any(i != r.parent.base.zero for i in r.listofpoly[1:-1]): + raise NotHyperSeriesError(self, self.x0) + + a = r.listofpoly[0] + b = r.listofpoly[-1] + + # the constant multiple of argument of hypergeometric function + if isinstance(a.LC(), (PolyElement, FracElement)): + c = - (S(a.LC().as_expr()) * m**(a.degree())) / (S(b.LC().as_expr()) * m**(b.degree())) + else: + c = - (S(a.LC()) * m**(a.degree())) / (S(b.LC()) * m**(b.degree())) + + sol = 0 + + arg1 = roots(r.parent.base.to_sympy(a), recurrence.n) + arg2 = roots(r.parent.base.to_sympy(b), recurrence.n) + + # iterate through the initial conditions to find + # the hypergeometric representation of the given + # function. + # The answer will be a linear combination + # of different hypergeometric series which satisfies + # the recurrence. + if as_list: + listofsol = [] + for i in range(smallest_n + m): + + # if the recurrence relation doesn't hold for `n = i`, + # then a Hypergeometric representation doesn't exist. + # add the algebraic term a * x**i to the solution, + # where a is u0[i] + if i < smallest_n: + if as_list: + listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), )) + else: + sol += S(u0[i]) * x**i + continue + + # if the coefficient u0[i] is zero, then the + # independent hypergeomtric series starting with + # x**i is not a part of the answer. + if S(u0[i]) == 0: + continue + + ap = [] + bq = [] + + # substitute m * n + i for n + for k in ordered(arg1.keys()): + ap.extend([nsimplify((i - k) / m)] * arg1[k]) + + for k in ordered(arg2.keys()): + bq.extend([nsimplify((i - k) / m)] * arg2[k]) + + # convention of (k + 1) in the denominator + if 1 in bq: + bq.remove(1) + else: + ap.append(1) + if as_list: + listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0))) + else: + sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i + if as_list: + return listofsol + sol = sol * x**constantpower + if x0 != 0: + return sol.subs(x, x - x0) + + return sol + + def to_expr(self): + """ + Converts a Holonomic Function back to elementary functions. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators + >>> from sympy import ZZ + >>> from sympy import symbols, S + >>> x = symbols('x') + >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') + >>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr() + besselj(1, x) + >>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr() + x*log(x + 1) + log(x + 1) + 1 + + """ + + return hyperexpand(self.to_hyper()).simplify() + + def change_ics(self, b, lenics=None): + """ + Changes the point `x0` to ``b`` for initial conditions. + + Examples + ======== + + >>> from sympy.holonomic import expr_to_holonomic + >>> from sympy import symbols, sin, exp + >>> x = symbols('x') + + >>> expr_to_holonomic(sin(x)).change_ics(1) + HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)]) + + >>> expr_to_holonomic(exp(x)).change_ics(2) + HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)]) + """ + + symbolic = True + + if lenics is None and len(self.y0) > self.annihilator.order: + lenics = len(self.y0) + dom = self.annihilator.parent.base.domain + + try: + sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom) + except (NotPowerSeriesError, NotHyperSeriesError): + symbolic = False + + if symbolic and sol.x0 == b: + return sol + + y0 = self.evalf(b, derivatives=True) + return HolonomicFunction(self.annihilator, self.x, b, y0) + + def to_meijerg(self): + """ + Returns a linear combination of Meijer G-functions. + + Examples + ======== + + >>> from sympy.holonomic import expr_to_holonomic + >>> from sympy import sin, cos, hyperexpand, log, symbols + >>> x = symbols('x') + >>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg()) + sin(x) + cos(x) + >>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() + log(x) + + See Also + ======== + + to_hyper + """ + + # convert to hypergeometric first + rep = self.to_hyper(as_list=True) + sol = S.Zero + + for i in rep: + if len(i) == 1: + sol += i[0] + + elif len(i) == 2: + sol += i[0] * _hyper_to_meijerg(i[1]) + + return sol + + +def from_hyper(func, x0=0, evalf=False): + r""" + Converts a hypergeometric function to holonomic. + ``func`` is the Hypergeometric Function and ``x0`` is the point at + which initial conditions are required. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import from_hyper + >>> from sympy import symbols, hyper, S + >>> x = symbols('x') + >>> from_hyper(hyper([], [S(3)/2], x**2/4)) + HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)]) + """ + + a = func.ap + b = func.bq + z = func.args[2] + x = z.atoms(Symbol).pop() + R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') + + # generalized hypergeometric differential equation + xDx = x*Dx + r1 = 1 + for ai in a: # XXX gives sympify error if Mul is used with list of all factors + r1 *= xDx + ai + xDx_1 = xDx - 1 + # r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error + r2 = Dx + for bi in b: + r2 *= xDx_1 + bi + sol = r1 - r2 + + simp = hyperexpand(func) + + if simp in (Infinity, NegativeInfinity): + return HolonomicFunction(sol, x).composition(z) + + # if the function is known symbolically + if not isinstance(simp, hyper): + y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False) + while not y0: + # if values don't exist at 0, then try to find initial + # conditions at 1. If it doesn't exist at 1 too then + # try 2 and so on. + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + if isinstance(simp, hyper): + x0 = 1 + # use evalf if the function can't be simplified + y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False) + return HolonomicFunction(sol, x).composition(z, x0, y0) + + return HolonomicFunction(sol, x).composition(z) + + +def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ): + """ + Converts a Meijer G-function to Holonomic. + ``func`` is the G-Function and ``x0`` is the point at + which initial conditions are required. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import from_meijerg + >>> from sympy import symbols, meijerg, S + >>> x = symbols('x') + >>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4)) + HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)]) + """ + + a = func.ap + b = func.bq + n = len(func.an) + m = len(func.bm) + p = len(a) + z = func.args[2] + x = z.atoms(Symbol).pop() + R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx') + + # compute the differential equation satisfied by the + # Meijer G-function. + xDx = x*Dx + xDx1 = xDx + 1 + r1 = x*(-1)**(m + n - p) + for ai in a: # XXX gives sympify error if args given in list + r1 *= xDx1 - ai + # r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error + r2 = 1 + for bi in b: + r2 *= xDx - bi + sol = r1 - r2 + + if not initcond: + return HolonomicFunction(sol, x).composition(z) + + simp = hyperexpand(func) + + if simp in (Infinity, NegativeInfinity): + return HolonomicFunction(sol, x).composition(z) + + # computing initial conditions + if not isinstance(simp, meijerg): + y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, use_limit=False) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + if isinstance(simp, meijerg): + x0 = 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False) + while not y0: + x0 += 1 + y0 = _find_conditions(simp, x, x0, sol.order, evalf, use_limit=False) + + return HolonomicFunction(sol, x).composition(z, x0, y0) + + return HolonomicFunction(sol, x).composition(z) + + +x_1 = Dummy('x_1') +_lookup_table = None +domain_for_table = None +from sympy.integrals.meijerint import _mytype + + +def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True): + """ + Converts a function or an expression to a holonomic function. + + Parameters + ========== + + func: + The expression to be converted. + x: + variable for the function. + x0: + point at which initial condition must be computed. + y0: + One can optionally provide initial condition if the method + is not able to do it automatically. + lenics: + Number of terms in the initial condition. By default it is + equal to the order of the annihilator. + domain: + Ground domain for the polynomials in ``x`` appearing as coefficients + in the annihilator. + initcond: + Set it false if you do not want the initial conditions to be computed. + + Examples + ======== + + >>> from sympy.holonomic.holonomic import expr_to_holonomic + >>> from sympy import sin, exp, symbols + >>> x = symbols('x') + >>> expr_to_holonomic(sin(x)) + HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1]) + >>> expr_to_holonomic(exp(x)) + HolonomicFunction((-1) + (1)*Dx, x, 0, [1]) + + See Also + ======== + + sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table + """ + func = sympify(func) + syms = func.free_symbols + + if not x: + if len(syms) == 1: + x= syms.pop() + else: + raise ValueError("Specify the variable for the function") + elif x in syms: + syms.remove(x) + + extra_syms = list(syms) + + if domain is None: + if func.has(Float): + domain = RR + else: + domain = QQ + if len(extra_syms) != 0: + domain = domain[extra_syms].get_field() + + # try to convert if the function is polynomial or rational + solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond) + if solpoly: + return solpoly + + # create the lookup table + global _lookup_table, domain_for_table + if not _lookup_table: + domain_for_table = domain + _lookup_table = {} + _create_table(_lookup_table, domain=domain) + elif domain != domain_for_table: + domain_for_table = domain + _lookup_table = {} + _create_table(_lookup_table, domain=domain) + + # use the table directly to convert to Holonomic + if func.is_Function: + f = func.subs(x, x_1) + t = _mytype(f, x_1) + if t in _lookup_table: + l = _lookup_table[t] + sol = l[0][1].change_x(x) + else: + sol = _convert_meijerint(func, x, initcond=False, domain=domain) + if not sol: + raise NotImplementedError + if y0: + sol.y0 = y0 + if y0 or not initcond: + sol.x0 = x0 + return sol + if not lenics: + lenics = sol.annihilator.order + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + return HolonomicFunction(sol.annihilator, x, x0, _y0) + + if y0 or not initcond: + sol = sol.composition(func.args[0]) + if y0: + sol.y0 = y0 + sol.x0 = x0 + return sol + if not lenics: + lenics = sol.annihilator.order + + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + return sol.composition(func.args[0], x0, _y0) + + # iterate through the expression recursively + args = func.args + f = func.func + sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain) + + if f is Add: + for i in range(1, len(args)): + sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) + + elif f is Mul: + for i in range(1, len(args)): + sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) + + elif f is Pow: + sol = sol**args[1] + sol.x0 = x0 + if not sol: + raise NotImplementedError + if y0: + sol.y0 = y0 + if y0 or not initcond: + return sol + if sol.y0: + return sol + if not lenics: + lenics = sol.annihilator.order + if sol.annihilator.is_singular(x0): + r = sol._indicial() + l = list(r) + if len(r) == 1 and r[l[0]] == S.One: + r = l[0] + g = func / (x - x0)**r + singular_ics = _find_conditions(g, x, x0, lenics) + singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] + y0 = {r:singular_ics} + return HolonomicFunction(sol.annihilator, x, x0, y0) + + _y0 = _find_conditions(func, x, x0, lenics) + while not _y0: + x0 += 1 + _y0 = _find_conditions(func, x, x0, lenics) + + return HolonomicFunction(sol.annihilator, x, x0, _y0) + + +## Some helper functions ## + +def _normalize(list_of, parent, negative=True): + """ + Normalize a given annihilator + """ + + num = [] + denom = [] + base = parent.base + K = base.get_field() + lcm_denom = base.from_sympy(S.One) + list_of_coeff = [] + + # convert polynomials to the elements of associated + # fraction field + for i, j in enumerate(list_of): + if isinstance(j, base.dtype): + list_of_coeff.append(K.new(j.to_list())) + elif not isinstance(j, K.dtype): + list_of_coeff.append(K.from_sympy(sympify(j))) + else: + list_of_coeff.append(j) + + # corresponding numerators of the sequence of polynomials + num.append(list_of_coeff[i].numer()) + + # corresponding denominators + denom.append(list_of_coeff[i].denom()) + + # lcm of denominators in the coefficients + for i in denom: + lcm_denom = i.lcm(lcm_denom) + + if negative: + lcm_denom = -lcm_denom + + lcm_denom = K.new(lcm_denom.to_list()) + + # multiply the coefficients with lcm + for i, j in enumerate(list_of_coeff): + list_of_coeff[i] = j * lcm_denom + + gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).to_list()) + + # gcd of numerators in the coefficients + for i in num: + gcd_numer = i.gcd(gcd_numer) + + gcd_numer = K.new(gcd_numer.to_list()) + + # divide all the coefficients by the gcd + for i, j in enumerate(list_of_coeff): + frac_ans = j / gcd_numer + list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).to_list()) + + return DifferentialOperator(list_of_coeff, parent) + + +def _derivate_diff_eq(listofpoly, K): + """ + Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0 + where a0, a1,... are polynomials or rational functions. The function + returns b0, b1, b2... such that the differential equation + b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the + former equation. + """ + + sol = [] + a = len(listofpoly) - 1 + sol.append(DMFdiff(listofpoly[0], K)) + + for i, j in enumerate(listofpoly[1:]): + sol.append(DMFdiff(j, K) + listofpoly[i]) + + sol.append(listofpoly[a]) + return sol + + +def _hyper_to_meijerg(func): + """ + Converts a `hyper` to meijerg. + """ + ap = func.ap + bq = func.bq + + if any(i <= 0 and int(i) == i for i in ap): + return hyperexpand(func) + + z = func.args[2] + + # parameters of the `meijerg` function. + an = (1 - i for i in ap) + anp = () + bm = (S.Zero, ) + bmq = (1 - i for i in bq) + + k = S.One + + for i in bq: + k = k * gamma(i) + + for i in ap: + k = k / gamma(i) + + return k * meijerg(an, anp, bm, bmq, -z) + + +def _add_lists(list1, list2): + """Takes polynomial sequences of two annihilators a and b and returns + the list of polynomials of sum of a and b. + """ + if len(list1) <= len(list2): + sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] + else: + sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] + return sol + + +def _extend_y0(Holonomic, n): + """ + Tries to find more initial conditions by substituting the initial + value point in the differential equation. + """ + + if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True: + return Holonomic.y0 + + annihilator = Holonomic.annihilator + a = annihilator.order + + listofpoly = [] + + y0 = Holonomic.y0 + R = annihilator.parent.base + K = R.get_field() + + for j in annihilator.listofpoly: + if isinstance(j, annihilator.parent.base.dtype): + listofpoly.append(K.new(j.to_list())) + + if len(y0) < a or n <= len(y0): + return y0 + list_red = [-listofpoly[i] / listofpoly[a] + for i in range(a)] + y1 = y0[:min(len(y0), a)] + for _ in range(n - a): + sol = 0 + for a, b in zip(y1, list_red): + r = DMFsubs(b, Holonomic.x0) + if not getattr(r, 'is_finite', True): + return y0 + if isinstance(r, (PolyElement, FracElement)): + r = r.as_expr() + sol += a * r + y1.append(sol) + list_red = _derivate_diff_eq(list_red, K) + return y0 + y1[len(y0):] + + +def DMFdiff(frac, K): + # differentiate a DMF object represented as p/q + if not isinstance(frac, DMF): + return frac.diff() + + p = K.numer(frac) + q = K.denom(frac) + sol_num = - p * q.diff() + q * p.diff() + sol_denom = q**2 + return K((sol_num.to_list(), sol_denom.to_list())) + + +def DMFsubs(frac, x0, mpm=False): + # substitute the point x0 in DMF object of the form p/q + if not isinstance(frac, DMF): + return frac + + p = frac.num + q = frac.den + sol_p = S.Zero + sol_q = S.Zero + + if mpm: + from mpmath import mp + + for i, j in enumerate(reversed(p)): + if mpm: + j = sympify(j)._to_mpmath(mp.prec) + sol_p += j * x0**i + + for i, j in enumerate(reversed(q)): + if mpm: + j = sympify(j)._to_mpmath(mp.prec) + sol_q += j * x0**i + + if isinstance(sol_p, (PolyElement, FracElement)): + sol_p = sol_p.as_expr() + if isinstance(sol_q, (PolyElement, FracElement)): + sol_q = sol_q.as_expr() + + return sol_p / sol_q + + +def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True): + """ + Converts polynomials, rationals and algebraic functions to holonomic. + """ + + ispoly = func.is_polynomial() + if not ispoly: + israt = func.is_rational_function() + else: + israt = True + + if not (ispoly or israt): + basepoly, ratexp = func.as_base_exp() + if basepoly.is_polynomial() and ratexp.is_Number: + if isinstance(ratexp, Float): + ratexp = nsimplify(ratexp) + m, n = ratexp.p, ratexp.q + is_alg = True + else: + is_alg = False + else: + is_alg = True + + if not (ispoly or israt or is_alg): + return None + + R = domain.old_poly_ring(x) + _, Dx = DifferentialOperators(R, 'Dx') + + # if the function is constant + if not func.has(x): + return HolonomicFunction(Dx, x, 0, [func]) + + if ispoly: + # differential equation satisfied by polynomial + sol = func * Dx - func.diff(x) + sol = _normalize(sol.listofpoly, sol.parent, negative=False) + is_singular = sol.is_singular(x0) + + # try to compute the conditions for singular points + if y0 is None and x0 == 0 and is_singular: + rep = R.from_sympy(func).to_list() + for i, j in enumerate(reversed(rep)): + if j == 0: + continue + coeff = list(reversed(rep))[i:] + indicial = i + break + for i, j in enumerate(coeff): + if isinstance(j, (PolyElement, FracElement)): + coeff[i] = j.as_expr() + y0 = {indicial: S(coeff)} + + elif israt: + p, q = func.as_numer_denom() + # differential equation satisfied by rational + sol = p * q * Dx + p * q.diff(x) - q * p.diff(x) + sol = _normalize(sol.listofpoly, sol.parent, negative=False) + + elif is_alg: + sol = n * (x / m) * Dx - 1 + sol = HolonomicFunction(sol, x).composition(basepoly).annihilator + is_singular = sol.is_singular(x0) + + # try to compute the conditions for singular points + if y0 is None and x0 == 0 and is_singular and \ + (lenics is None or lenics <= 1): + rep = R.from_sympy(basepoly).to_list() + for i, j in enumerate(reversed(rep)): + if j == 0: + continue + if isinstance(j, (PolyElement, FracElement)): + j = j.as_expr() + + coeff = S(j)**ratexp + indicial = S(i) * ratexp + break + if isinstance(coeff, (PolyElement, FracElement)): + coeff = coeff.as_expr() + y0 = {indicial: S([coeff])} + + if y0 or not initcond: + return HolonomicFunction(sol, x, x0, y0) + + if not lenics: + lenics = sol.order + + if sol.is_singular(x0): + r = HolonomicFunction(sol, x, x0)._indicial() + l = list(r) + if len(r) == 1 and r[l[0]] == S.One: + r = l[0] + g = func / (x - x0)**r + singular_ics = _find_conditions(g, x, x0, lenics) + singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] + y0 = {r:singular_ics} + return HolonomicFunction(sol, x, x0, y0) + + y0 = _find_conditions(func, x, x0, lenics) + while not y0: + x0 += 1 + y0 = _find_conditions(func, x, x0, lenics) + + return HolonomicFunction(sol, x, x0, y0) + + +def _convert_meijerint(func, x, initcond=True, domain=QQ): + args = meijerint._rewrite1(func, x) + + if args: + fac, po, g, _ = args + else: + return None + + # lists for sum of meijerg functions + fac_list = [fac * i[0] for i in g] + t = po.as_base_exp() + s = t[1] if t[0] == x else S.Zero + po_list = [s + i[1] for i in g] + G_list = [i[2] for i in g] + + # finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z) + def _shift(func, s): + z = func.args[-1] + if z.has(I): + z = z.subs(exp_polar, exp) + + d = z.collect(x, evaluate=False) + b = list(d)[0] + a = d[b] + + t = b.as_base_exp() + b = t[1] if t[0] == x else S.Zero + r = s / b + an = (i + r for i in func.args[0][0]) + ap = (i + r for i in func.args[0][1]) + bm = (i + r for i in func.args[1][0]) + bq = (i + r for i in func.args[1][1]) + + return a**-r, meijerg((an, ap), (bm, bq), z) + + coeff, m = _shift(G_list[0], po_list[0]) + sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain) + + # add all the meijerg functions after converting to holonomic + for i in range(1, len(G_list)): + coeff, m = _shift(G_list[i], po_list[i]) + sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain) + + return sol + + +def _create_table(table, domain=QQ): + """ + Creates the look-up table. For a similar implementation + see meijerint._create_lookup_table. + """ + + def add(formula, annihilator, arg, x0=0, y0=()): + """ + Adds a formula in the dictionary + """ + table.setdefault(_mytype(formula, x_1), []).append((formula, + HolonomicFunction(annihilator, arg, x0, y0))) + + R = domain.old_poly_ring(x_1) + _, Dx = DifferentialOperators(R, 'Dx') + + # add some basic functions + add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1]) + add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0]) + add(exp(x_1), Dx - 1, x_1, 0, 1) + add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1]) + + add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) + add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)]) + add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) + + add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1]) + add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0]) + + add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1) + + add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + + add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) + + +def _find_conditions(func, x, x0, order, evalf=False, use_limit=True): + y0 = [] + for _ in range(order): + val = func.subs(x, x0) + if evalf: + val = val.evalf() + if use_limit and isinstance(val, NaN): + val = limit(func, x, x0) + if val.is_finite is False or isinstance(val, NaN): + return None + y0.append(val) + func = func.diff(x) + return y0 diff --git a/shared/package-files/cb/cb08cc4ab0ab0320007942f26f952677a73dbf1f64c9fe8c81a7ce1f65dc2e31/os.cpython-311.pyc b/shared/package-files/cb/cb08cc4ab0ab0320007942f26f952677a73dbf1f64c9fe8c81a7ce1f65dc2e31/os.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd4b650bb99ab46c99a94a93f8745cd85cd4ead7 Binary files /dev/null and b/shared/package-files/cb/cb08cc4ab0ab0320007942f26f952677a73dbf1f64c9fe8c81a7ce1f65dc2e31/os.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb08e264b7a8771f01f90b690543e07ba5cde5dd57663c8b88c9ab4fcbecbc98/vcfisec.c b/shared/package-files/cb/cb08e264b7a8771f01f90b690543e07ba5cde5dd57663c8b88c9ab4fcbecbc98/vcfisec.c new file mode 100644 index 0000000000000000000000000000000000000000..24a45685b083b82e63c101e1207aec92eb7dd071 --- /dev/null +++ b/shared/package-files/cb/cb08e264b7a8771f01f90b690543e07ba5cde5dd57663c8b88c9ab4fcbecbc98/vcfisec.c @@ -0,0 +1,707 @@ +/* vcfisec.c -- Create intersections, unions and complements of VCF files. + + Copyright (C) 2012-2023 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "filter.h" + +#define OP_PLUS 1 +#define OP_MINUS 2 +#define OP_EQUAL 3 +#define OP_VENN 4 +#define OP_COMPLEMENT 5 +#define OP_EXACT 6 + +// Logic of the filters: include or exclude sites which match the filters? +#define FLT_INCLUDE 1 +#define FLT_EXCLUDE 2 + +typedef struct +{ + int isec_op, isec_n, *write, iwrite, nwrite, output_type, n_threads, clevel; + int nflt, *flt_logic; + filter_t **flt; + char **flt_expr; + bcf_srs_t *files; + FILE *fh_log, *fh_sites; + htsFile **fh_out; + char **argv, *prefix, *output_fname, **fnames, *write_files, *targets_list, *regions_list; + char *isec_exact, *file_list; + int argc, record_cmd_line; + char *index_fn; + int write_index; +} +args_t; + +/** + * mkdir_p() - create new directory for a file $fname + * @fname: the file name to create the directory for, the part after last "/" is ignored + */ +void HTS_FORMAT(HTS_PRINTF_FMT, 1, 2) +mkdir_p(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(NULL, 0, fmt, ap) + 2; + va_end(ap); + + char *tmp = (char*)malloc(n); + if (!tmp) error("Couldn't allocate space for path: %s\n", strerror(errno)); + va_start(ap, fmt); + vsnprintf(tmp, n, fmt, ap); + va_end(ap); + + char *p = tmp+1; + while (*p) + { + while (*p && *p!='/') p++; + if ( !*p ) break; + char ctmp = *p; + *p = 0; + int ret = mkdir(tmp,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); + if ( ret!=0 && errno!=EEXIST ) error("Error creating directory %s: %s\n", tmp,strerror(errno)); + *p = ctmp; + while ( *p && *p=='/' ) p++; + } + free(tmp); +} + +/** + * open_file() - open new file creating the file name using vsnprintf + * @fname: if not NULL, on output will point to newly allocated fname string + * @mode: if NULL, only the file name string will be created + * @fmt: vsnprintf format and args + * + * Returns open file descriptor or NULL if mode is NULL. + */ +FILE * HTS_FORMAT(HTS_PRINTF_FMT, 3, 4) +open_file(char **fname, const char *mode, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(NULL, 0, fmt, ap) + 2; + va_end(ap); + + char *str = (char*)malloc(n); + va_start(ap, fmt); + vsnprintf(str, n, fmt, ap); + va_end(ap); + + mkdir_p("%s", str); + if ( !mode ) + { + if ( !fname ) error("Uh: expected fname or mode\n"); + *fname = str; + return NULL; + } + + FILE *fp = fopen(str,mode); + if ( fname ) *fname = str; + else free(str); + return fp; +} + +void isec_vcf(args_t *args) +{ + bcf_srs_t *files = args->files; + kstring_t str = {0,0,0}; + htsFile *out_fh = NULL; + + // When only one VCF is output, print VCF to stdout or -o file + int out_std = 0; + if ( args->nwrite==1 && !args->prefix ) out_std = 1; + if ( args->targets_list && files->nreaders==1 ) out_std = 1; + if ( out_std ) + { + char wmode[8]; + set_wmode(wmode,args->output_type,args->output_fname,args->clevel); + out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to %s: %s\n", args->output_fname? args->output_fname : "standard output", strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if (args->record_cmd_line) bcf_hdr_append_version(files->readers[args->iwrite].header,args->argc,args->argv,"bcftools_isec"); + if ( bcf_hdr_write(out_fh, files->readers[args->iwrite].header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname?args->output_fname:"standard output"); + if ( init_index2(out_fh,files->readers[args->iwrite].header, + args->output_fname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n", + args->output_fname?args->output_fname:"standard output"); + } + if ( !args->nwrite && !out_std && !args->prefix ) + fprintf(stderr,"Note: -w option not given, printing list of sites...\n"); + + int n; + while ( (n=bcf_sr_next_line(files)) ) + { + bcf_sr_t *reader = NULL; + bcf1_t *line = NULL; + int i, ret = 0; + for (i=0; inreaders; i++) + { + if ( !bcf_sr_has_line(files,i) ) continue; + + if ( args->nflt && args->flt[i] ) + { + bcf1_t *rec = bcf_sr_get_line(files, i); + int pass = filter_test(args->flt[i], rec, NULL); + if ( args->flt_logic[i] & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) + { + files->has_line[i] = 0; + n--; + continue; + } + } + + if ( !line ) + { + line = files->readers[i].buffer[0]; + reader = &files->readers[i]; + } + ret |= 1<isec_op) + { + case OP_COMPLEMENT: if ( n!=1 || !bcf_sr_has_line(files,0) ) continue; break; + case OP_EQUAL: if ( n != args->isec_n ) continue; break; + case OP_PLUS: if ( n < args->isec_n ) continue; break; + case OP_MINUS: if ( n > args->isec_n ) continue; break; + case OP_EXACT: + for (i=0; inreaders; i++) + if ( files->has_line[i] != args->isec_exact[i] ) break; + if ( inreaders ) continue; + break; + } + + if ( out_std ) + { + if ( bcf_sr_has_line(files,args->iwrite) && bcf_write1(out_fh, files->readers[args->iwrite].header, files->readers[args->iwrite].buffer[0])!=0 ) + error("[%s] Error: cannot write to %s\n", __func__, args->output_fname ? args->output_fname : "standard output"); + continue; + } + else if ( args->fh_sites ) + { + str.l = 0; + kputs(reader->header->id[BCF_DT_CTG][line->rid].key, &str); kputc('\t', &str); + kputw(line->pos+1, &str); kputc('\t', &str); + if (line->n_allele > 0) kputs(line->d.allele[0], &str); + else kputc('.', &str); + kputc('\t', &str); + if (line->n_allele > 1) kputs(line->d.allele[1], &str); + else kputc('.', &str); + for (i=2; in_allele; i++) + { + kputc(',', &str); + kputs(line->d.allele[i], &str); + } + kputc('\t', &str); + for (i=0; inreaders; i++) + kputc(bcf_sr_has_line(files,i)?'1':'0', &str); + kputc('\n', &str); + if ( fwrite(str.s,sizeof(char),str.l,args->fh_sites)!=str.l ) + error("[%s] Error: failed to write %d bytes to %s\n", __func__,(int)str.l,args->output_fname ? args->output_fname : "standard output"); + } + + if ( args->prefix ) + { + if ( args->isec_op==OP_VENN && ret==3 ) + { + if ( !args->nwrite || args->write[0] ) + { + if ( bcf_write1(args->fh_out[2], bcf_sr_get_header(files,0), bcf_sr_get_line(files,0))!=0 ) + error("[%s] Error: cannot write\n", __func__); + } + if ( !args->nwrite || args->write[1] ) + { + if ( bcf_write1(args->fh_out[3], bcf_sr_get_header(files,1), bcf_sr_get_line(files,1))!=0 ) + error("[%s] Error: cannot write\n", __func__); + } + } + else + { + for (i=0; inreaders; i++) + { + if ( !bcf_sr_has_line(files,i) ) continue; + if ( args->write && !args->write[i] ) continue; + if ( bcf_write1(args->fh_out[i], files->readers[i].header, files->readers[i].buffer[0])!=0 ) error("[%s] Error: cannot write\n", __func__); + } + } + } + } + if ( str.s ) free(str.s); + if ( out_fh ) + { + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"stdout"); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->output_fname? args->output_fname : "-"); + } +} + +static void add_filter(args_t *args, char *expr, int logic) +{ + args->nflt++; + args->flt_expr = (char**) realloc(args->flt_expr,sizeof(char*)*args->nflt); + args->flt_logic = (int*) realloc(args->flt_logic,sizeof(int)*args->nflt); + args->flt = (filter_t**) realloc(args->flt,sizeof(filter_t*)*args->nflt); + if ( expr[0]=='-' && expr[1]==0 ) + { + args->flt_expr[args->nflt-1] = NULL; + args->flt[args->nflt-1] = NULL; + } + else + args->flt_expr[args->nflt-1] = expr; + args->flt_logic[args->nflt-1] = logic; +} + +static void destroy_data(args_t *args); +static void init_data(args_t *args) +{ + int i; + if ( args->nflt ) + { + if ( args->nflt > 1 && args->nflt!=args->files->nreaders ) + error("Error: expected either one -i/-e option or as many as there are input files\n"); + if ( args->nflt < args->files->nreaders ) + { + if ( !args->flt_expr[0] ) error("Error: useless use of -i/-e\n"); + args->nflt = args->files->nreaders; + args->flt_expr = (char**) realloc(args->flt_expr,sizeof(char*)*args->nflt); + args->flt_logic = (int*) realloc(args->flt_logic,sizeof(int)*args->nflt); + args->flt = (filter_t**) realloc(args->flt,sizeof(filter_t*)*args->nflt); + for (i=1; inflt; i++) + { + args->flt_expr[i] = args->flt_expr[0]; + args->flt_logic[i] = args->flt_logic[0]; + args->flt[i] = filter_init(args->files->readers[i].header,args->flt_expr[i]); + } + args->flt[0] = filter_init(args->files->readers[0].header,args->flt_expr[0]); + } + else + { + for (i=0; ifiles->nreaders; i++) + { + if ( !args->flt_expr[i] ) continue; + args->flt[i] = filter_init(args->files->readers[i].header,args->flt_expr[i]); + } + } + } + + if ( args->isec_op==OP_EXACT ) + { + if ( strlen(args->isec_exact)!=args->files->nreaders ) + error("The number of files does not match the bitmask: %d vs %s\n", args->files->nreaders,args->isec_exact); + for (i=0; ifiles->nreaders; i++) + if ( args->isec_exact[i]!='0' && args->isec_exact[i]!='1' ) error("Unexpected bitmask: %s\n",args->isec_exact); + for (i=0; ifiles->nreaders; i++) + args->isec_exact[i] -= '0'; + } + + // Which files to write: parse the string passed with -w + char *p = args->write_files; + while (p && *p) + { + if ( !args->write ) args->write = (int*) calloc(args->files->nreaders,sizeof(int)); + if ( sscanf(p,"%d",&i)!=1 ) error("Could not parse --write %s\n", args->write_files); + if ( i<=0 || i>args->files->nreaders ) error("The index is out of range: %d (-w %s)\n", i, args->write_files); + args->write[i-1] = 1; + args->iwrite = i-1; + args->nwrite++; + while (*p && *p!=',') p++; + if ( *p==',' ) p++; + } + if ( args->nwrite>1 && !args->prefix ) error("Expected -p when multiple output files given: --write %s\n", args->write_files); + if ( args->isec_op==OP_COMPLEMENT && args->nwrite ) + { + if ( args->nwrite>1 ) error("Multiple files to -w make no sense with -C\n"); + if ( !args->write[0] ) error("Only -w1 makes sense with -C\n"); + } + + if ( args->prefix ) + { + // Init output directory and create the readme file + args->fh_log = open_file(NULL,"w","%s/README.txt", args->prefix); + if ( !args->fh_log ) error("%s/README.txt: %s\n", args->prefix, strerror(errno)); + + fprintf(args->fh_log,"This file was produced by vcfisec.\n"); + fprintf(args->fh_log,"The command line was:\tbcftools %s ", args->argv[0]); + int i; + for (i=1; iargc; i++) fprintf(args->fh_log," %s",args->argv[i]); + fprintf(args->fh_log,"\n\nUsing the following file names:\n"); + + const char *suffix = "vcf"; + if ( args->output_type & FT_BCF ) suffix = "bcf"; + else if ( args->output_type & FT_GZ ) suffix = "vcf.gz"; + + // Open output files and write the legend + if ( args->isec_op==OP_VENN ) + { + args->fh_out = (htsFile**) malloc(sizeof(htsFile*)*4); + args->fnames = (char**) calloc(4,sizeof(char*)); + + #define OPEN_FILE(i,j) { \ + open_file(&args->fnames[i], NULL, "%s/%04d.%s", args->prefix, i, suffix); \ + char wmode[8]; \ + set_wmode(wmode,args->output_type,args->fnames[i],args->clevel); \ + args->fh_out[i] = hts_open(args->fnames[i], wmode); \ + if ( !args->fh_out[i] ) error("Could not open %s\n", args->fnames[i]); \ + if ( args->n_threads ) hts_set_threads(args->fh_out[i], args->n_threads); \ + if (args->record_cmd_line) bcf_hdr_append_version(args->files->readers[j].header,args->argc,args->argv,"bcftools_isec"); \ + if ( bcf_hdr_write(args->fh_out[i], args->files->readers[j].header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->fnames[i]); \ + } + if ( !args->nwrite || args->write[0] ) + { + OPEN_FILE(0,0); + fprintf(args->fh_log,"%s\tfor records private to\t%s\n", args->fnames[0], args->files->readers[0].fname); + } + if ( !args->nwrite || args->write[1] ) + { + OPEN_FILE(1,1); + fprintf(args->fh_log,"%s\tfor records private to\t%s\n", args->fnames[1], args->files->readers[1].fname); + } + if ( !args->nwrite || args->write[0] ) + { + OPEN_FILE(2,0); + fprintf(args->fh_log,"%s\tfor records from %s shared by both\t%s %s\n", args->fnames[2], args->files->readers[0].fname, args->files->readers[0].fname, args->files->readers[1].fname); + } + if ( !args->nwrite || args->write[1] ) + { + OPEN_FILE(3,1); + fprintf(args->fh_log,"%s\tfor records from %s shared by both\t%s %s\n", args->fnames[3], args->files->readers[1].fname, args->files->readers[0].fname, args->files->readers[1].fname); + } + } + else + { + // Init one output file for each reader + args->fh_out = (htsFile**) calloc(args->files->nreaders, sizeof(htsFile*)); + args->fnames = (char**) calloc(args->files->nreaders, sizeof(char*)); + + for (i=0; ifiles->nreaders; i++) + { + if ( args->write && !args->write[i] ) continue; + if ( args->isec_op==OP_COMPLEMENT && i>0 ) break; + OPEN_FILE(i,i); + fprintf(args->fh_log,"%s\tfor stripped\t%s\n", args->fnames[i], args->files->readers[i].fname); + } + #undef OPEN_FILE + } + args->fh_sites = open_file(NULL, "w", "%s/sites.txt", args->prefix); + if ( !args->fh_sites ) error("%s/sites.txt: %s\n", args->prefix, strerror(errno)); + } + else { + if (args->output_fname) { + args->fh_sites = fopen(args->output_fname, "w"); + if ( args->fh_sites == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno)); + } + else + args->fh_sites = stdout; + } +} + +static void destroy_data(args_t *args) +{ + int i; + if ( args->nflt ) + { + for (i=0; inflt; i++) + { + if ( !args->flt[i] ) continue; + filter_destroy(args->flt[i]); + } + free(args->flt_expr); + free(args->flt); + free(args->flt_logic); + } + if ( args->prefix ) + { + fclose(args->fh_log); + int n = args->isec_op==OP_VENN ? 4 : args->files->nreaders; + for (i=0; ifnames[i] ) continue; + if ( hts_close(args->fh_out[i])!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fnames[i]); + int is_tbi = !args->write_index + || (args->write_index&127) == HTS_FMT_TBI; + if ( args->output_type==FT_VCF_GZ && is_tbi ) + { + tbx_conf_t conf = tbx_conf_vcf; + tbx_index_build(args->fnames[i], -1, &conf); + } + else if ( args->output_type==FT_BCF_GZ || !is_tbi ) + { + if ( bcf_index_build(args->fnames[i],14) ) error("Could not index %s\n", args->fnames[i]); + } + free(args->fnames[i]); + } + free(args->fh_out); + free(args->fnames); + if ( args->fh_sites ) fclose(args->fh_sites); + if ( args->write ) free(args->write); + } +} + +static void usage(void) +{ + fprintf(stderr, "\n"); + fprintf(stderr, "About: Create intersections, unions and complements of VCF files.\n"); + fprintf(stderr, "Usage: bcftools isec [options] [...]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " -c, --collapse STRING Treat as identical records with , see man page for details [none]\n"); + fprintf(stderr, " -C, --complement Output positions present only in the first file but missing in the others\n"); + fprintf(stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n"); + fprintf(stderr, " -f, --apply-filters LIST Require at least one of the listed FILTER strings (e.g. \"PASS,.\")\n"); + fprintf(stderr, " -i, --include EXPR Include only sites for which the expression is true\n"); + fprintf(stderr, " -l, --file-list FILE Read the input file names from the file\n"); + fprintf(stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(stderr, " -n, --nfiles [+-=~]INT Output positions present in this many (=), this many or more (+), this many or fewer (-), the exact (~) files\n"); + fprintf(stderr, " -o, --output FILE Write output to a file [standard output]\n"); + fprintf(stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(stderr, " -p, --prefix DIR If given, subset each of the input files accordingly, see also -w\n"); + fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(stderr, " --threads INT Use multithreading with worker threads [0]\n"); + fprintf(stderr, " -w, --write LIST List of files to write with -p given as 1-based indexes. By default, all files are written\n"); + fprintf(stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "Examples:\n"); + fprintf(stderr, " # Create intersection and complements of two sets saving the output in dir/*\n"); + fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir\n"); + fprintf(stderr, "\n"); + fprintf(stderr, " # Filter sites in A and B (but not in C) and create intersection\n"); + fprintf(stderr, " bcftools isec -e'MAF<0.01' -i'dbSNP=1' -e - A.vcf.gz B.vcf.gz C.vcf.gz -p dir\n"); + fprintf(stderr, "\n"); + fprintf(stderr, " # Extract and write records from A shared by both A and B using exact allele match\n"); + fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir -n =2 -w 1\n"); + fprintf(stderr, "\n"); + fprintf(stderr, " # Extract and write records from C found in A and C but not in B\n"); + fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz C.vcf.gz -p dir -n~101 -w 3\n"); + fprintf(stderr, "\n"); + fprintf(stderr, " # Extract records private to A or B comparing by position only\n"); + fprintf(stderr, " bcftools isec A.vcf.gz B.vcf.gz -p dir -n -1 -c all\n"); + fprintf(stderr, "\n"); + exit(1); +} + +int main_vcfisec(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->files = bcf_sr_init(); + args->argc = argc; args->argv = argv; + args->output_fname = NULL; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->clevel = -1; + int targets_is_file = 0, regions_is_file = 0; + int regions_overlap = 1; + int targets_overlap = 0; + + static struct option loptions[] = + { + {"help",no_argument,NULL,'h'}, + {"exclude",required_argument,NULL,'e'}, + {"include",required_argument,NULL,'i'}, + {"collapse",required_argument,NULL,'c'}, + {"complement",no_argument,NULL,'C'}, + {"apply-filters",required_argument,NULL,'f'}, + {"file-list",required_argument,NULL,'l'}, + {"nfiles",required_argument,NULL,'n'}, + {"prefix",required_argument,NULL,'p'}, + {"write",required_argument,NULL,'w'}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"targets-overlap",required_argument,NULL,4}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,3}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"no-version",no_argument,NULL,8}, + {"write-index",optional_argument,NULL,'W'}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "hc:r:R:p:n:w:t:T:Cf:o:O:i:e:l:W::",loptions,NULL)) >= 0) { + switch (c) { + case 'o': args->output_fname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'c': + if ( !strcmp(optarg,"snps") ) args->files->collapse |= COLLAPSE_SNPS; + else if ( !strcmp(optarg,"indels") ) args->files->collapse |= COLLAPSE_INDELS; + else if ( !strcmp(optarg,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS; + else if ( !strcmp(optarg,"any") ) args->files->collapse |= COLLAPSE_ANY; + else if ( !strcmp(optarg,"all") ) args->files->collapse |= COLLAPSE_ANY; + else if ( !strcmp(optarg,"some") ) args->files->collapse |= COLLAPSE_SOME; + else if ( !strcmp(optarg,"none") ) args->files->collapse = COLLAPSE_NONE; + else error("The --collapse string \"%s\" not recognised.\n", optarg); + break; + case 'f': args->files->apply_filters = optarg; break; + case 'C': + if ( args->isec_op!=0 && args->isec_op!=OP_COMPLEMENT ) error("Error: either -C or -n should be given, not both.\n"); + args->isec_op = OP_COMPLEMENT; break; + case 'l': args->file_list = optarg; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; regions_is_file = 1; break; + case 't': args->targets_list = optarg; break; + case 'T': args->targets_list = optarg; targets_is_file = 1; break; + case 'p': args->prefix = optarg; break; + case 'w': + if ( args->write_files ) error("The option -w accepts a list of indices and can be given only once\n"); + args->write_files = optarg; + break; + case 'i': add_filter(args, optarg, FLT_INCLUDE); break; + case 'e': add_filter(args, optarg, FLT_EXCLUDE); break; + case 'n': + { + if ( args->isec_op!=0 && args->isec_op==OP_COMPLEMENT ) error("Error: either -C or -n should be given, not both.\n"); + if ( args->isec_op!=0 ) error("Error: -n should be given only once.\n"); + char *p = optarg; + if ( *p=='-' ) { args->isec_op = OP_MINUS; p++; } + else if ( *p=='+' ) { args->isec_op = OP_PLUS; p++; } + else if ( *p=='=' ) { args->isec_op = OP_EQUAL; p++; } + else if ( *p=='~' ) { args->isec_op = OP_EXACT; p++; } + else if ( isdigit(*p) ) args->isec_op = OP_EQUAL; + else error("Could not parse --nfiles %s\n", optarg); + if ( args->isec_op == OP_EXACT ) args->isec_exact = p; + else if ( sscanf(p,"%d",&args->isec_n)!=1 ) error("Could not parse --nfiles %s\n", optarg); + } + break; + case 3 : + regions_overlap = parse_overlap_option(optarg); + if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 4 : + targets_overlap = parse_overlap_option(optarg); + if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 8 : args->record_cmd_line = 0; break; + case 'W': + if (!(args->write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + case 'h': + case '?': usage(); break; + default: error("Unknown argument: %s\n", optarg); + } + } + if ( argc-optind<1 && !args->file_list ) usage(); // no file given + + int nfiles = 0,i; + char **files = NULL; + if ( args->file_list ) + { + files = hts_readlines(args->file_list, &nfiles); + if ( !files ) error("Failed to read from %s\n", args->file_list); + } + if ( optind0; i--) files[n+i-1] = files[n+i-2]; + for (i=0; itargets_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap); + if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file,0)<0 ) + error("Failed to read the targets: %s\n", args->targets_list); + } + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + if ( nfiles==2 && !args->isec_op ) + { + args->isec_op = OP_VENN; + if ( !args->prefix ) error("Expected the -p option\n"); + } + if ( !args->isec_op ) + { + args->isec_op = OP_PLUS; + args->isec_n = 1; + } + args->files->require_index = 1; + for (i=0; ifiles, files[i]) ) error("Failed to open %s: %s\n", files[i],bcf_sr_strerror(args->files->errnum)); + free(files[i]); + } + free(files); + + init_data(args); + isec_vcf(args); + destroy_data(args); + bcf_sr_destroy(args->files); + free(args); + return 0; +} + diff --git a/shared/package-files/cb/cb0b3117cef0d9e238962f1b7bb5a2b9ae5b5e9d0d62131becb4bc2333c53b75/kernel.h b/shared/package-files/cb/cb0b3117cef0d9e238962f1b7bb5a2b9ae5b5e9d0d62131becb4bc2333c53b75/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..cfb6265f12904bf3c7c16f272f942ead1765b444 --- /dev/null +++ b/shared/package-files/cb/cb0b3117cef0d9e238962f1b7bb5a2b9ae5b5e9d0d62131becb4bc2333c53b75/kernel.h @@ -0,0 +1,753 @@ +// 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. + +// NOTE: API is EXPERIMENTAL and will change without going through a +// deprecation cycle + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/buffer.h" +#include "arrow/compute/exec.h" +#include "arrow/datum.h" +#include "arrow/device_allocation_type_set.h" +#include "arrow/memory_pool.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" + +// macOS defines PREALLOCATE as a preprocessor macro in the header sys/vnode.h. +// No other BSD seems to do so. The name is used as an identifier in MemAllocation enum. +#if defined(__APPLE__) && defined(PREALLOCATE) +# undef PREALLOCATE +#endif + +namespace arrow { +namespace compute { + +class FunctionOptions; + +/// \brief Base class for opaque kernel-specific state. For example, if there +/// is some kind of initialization required. +struct ARROW_EXPORT KernelState { + virtual ~KernelState() = default; +}; + +/// \brief Context/state for the execution of a particular kernel. +class ARROW_EXPORT KernelContext { + public: + // Can pass optional backreference; not used consistently for the + // moment but will be made so in the future + explicit KernelContext(ExecContext* exec_ctx, const Kernel* kernel = NULLPTR) + : exec_ctx_(exec_ctx), kernel_(kernel) {} + + /// \brief Allocate buffer from the context's memory pool. The contents are + /// not initialized. + Result> Allocate(int64_t nbytes); + + /// \brief Allocate buffer for bitmap from the context's memory pool. Like + /// Allocate, the contents of the buffer are not initialized but the last + /// byte is preemptively zeroed to help avoid ASAN or valgrind issues. + Result> AllocateBitmap(int64_t num_bits); + + /// \brief Assign the active KernelState to be utilized for each stage of + /// kernel execution. Ownership and memory lifetime of the KernelState must + /// be minded separately. + void SetState(KernelState* state) { state_ = state; } + + // Set kernel that is being invoked since some kernel + // implementations will examine the kernel state. + void SetKernel(const Kernel* kernel) { kernel_ = kernel; } + + KernelState* state() { return state_; } + + /// \brief Configuration related to function execution that is to be shared + /// across multiple kernels. + ExecContext* exec_context() { return exec_ctx_; } + + /// \brief The memory pool to use for allocations. For now, it uses the + /// MemoryPool contained in the ExecContext used to create the KernelContext. + MemoryPool* memory_pool() { return exec_ctx_->memory_pool(); } + + const Kernel* kernel() const { return kernel_; } + + private: + ExecContext* exec_ctx_; + KernelState* state_ = NULLPTR; + const Kernel* kernel_ = NULLPTR; +}; + +/// \brief An type-checking interface to permit customizable validation rules +/// for use with InputType and KernelSignature. This is for scenarios where the +/// acceptance is not an exact type instance, such as a TIMESTAMP type for a +/// specific TimeUnit, but permitting any time zone. +struct ARROW_EXPORT TypeMatcher { + virtual ~TypeMatcher() = default; + + /// \brief Return true if this matcher accepts the data type. + virtual bool Matches(const DataType& type) const = 0; + + /// \brief A human-interpretable string representation of what the type + /// matcher checks for, usable when printing KernelSignature or formatting + /// error messages. + virtual std::string ToString() const = 0; + + /// \brief Return true if this TypeMatcher contains the same matching rule as + /// the other. Currently depends on RTTI. + virtual bool Equals(const TypeMatcher& other) const = 0; +}; + +namespace match { + +/// \brief Match any DataType instance having the same DataType::id. +ARROW_EXPORT std::shared_ptr SameTypeId(Type::type type_id); + +/// \brief Match any TimestampType instance having the same unit, but the time +/// zones can be different. +ARROW_EXPORT std::shared_ptr TimestampTypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time32TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr Time64TypeUnit(TimeUnit::type unit); +ARROW_EXPORT std::shared_ptr DurationTypeUnit(TimeUnit::type unit); + +// \brief Match any integer type +ARROW_EXPORT std::shared_ptr Integer(); + +// Match types using 32-bit varbinary representation +ARROW_EXPORT std::shared_ptr BinaryLike(); + +// Match types using 64-bit varbinary representation +ARROW_EXPORT std::shared_ptr LargeBinaryLike(); + +// Match any fixed binary type +ARROW_EXPORT std::shared_ptr FixedSizeBinaryLike(); + +// \brief Match any primitive type (boolean or any type representable as a C +// Type) +ARROW_EXPORT std::shared_ptr Primitive(); + +// \brief Match any integer type that can be used as run-end in run-end encoded +// arrays +ARROW_EXPORT std::shared_ptr RunEndInteger(); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr value_type_matcher); + +/// \brief Match run-end encoded types that use any valid run-end type and +/// encode specific value types +/// +/// @param[in] value_type_id a type id that the type of the values field should match +ARROW_EXPORT std::shared_ptr RunEndEncoded(Type::type value_type_id); + +/// \brief Match run-end encoded types that encode specific run-end and value types +/// +/// @param[in] run_end_type_matcher a matcher that is applied to the run_ends field +/// @param[in] value_type_matcher a matcher that is applied to the values field +ARROW_EXPORT std::shared_ptr RunEndEncoded( + std::shared_ptr run_end_type_matcher, + std::shared_ptr value_type_matcher); + +} // namespace match + +/// \brief An object used for type-checking arguments to be passed to a kernel +/// and stored in a KernelSignature. The type-checking rule can be supplied +/// either with an exact DataType instance or a custom TypeMatcher. +class ARROW_EXPORT InputType { + public: + /// \brief The kind of type-checking rule that the InputType contains. + enum Kind { + /// \brief Accept any value type. + ANY_TYPE, + + /// \brief A fixed arrow::DataType and will only exact match having this + /// exact type (e.g. same TimestampType unit, same decimal scale and + /// precision, or same nested child types). + EXACT_TYPE, + + /// \brief Uses a TypeMatcher implementation to check the type. + USE_TYPE_MATCHER + }; + + /// \brief Accept any value type + InputType() : kind_(ANY_TYPE) {} + + /// \brief Accept an exact value type. + InputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(EXACT_TYPE), type_(std::move(type)) {} + + /// \brief Use the passed TypeMatcher to type check. + InputType(std::shared_ptr type_matcher) // NOLINT implicit construction + : kind_(USE_TYPE_MATCHER), type_matcher_(std::move(type_matcher)) {} + + /// \brief Match any type with the given Type::type. Uses a TypeMatcher for + /// its implementation. + InputType(Type::type type_id) // NOLINT implicit construction + : InputType(match::SameTypeId(type_id)) {} + + InputType(const InputType& other) { CopyInto(other); } + + void operator=(const InputType& other) { CopyInto(other); } + + InputType(InputType&& other) { MoveInto(std::forward(other)); } + + void operator=(InputType&& other) { MoveInto(std::forward(other)); } + + // \brief Match any input (array, scalar of any type) + static InputType Any() { return InputType(); } + + /// \brief Return true if this input type matches the same type cases as the + /// other. + bool Equals(const InputType& other) const; + + bool operator==(const InputType& other) const { return this->Equals(other); } + + bool operator!=(const InputType& other) const { return !(*this == other); } + + /// \brief Return hash code. + size_t Hash() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return true if the Datum matches this argument kind in + /// type (and only allows scalar or array-like Datums). + bool Matches(const Datum& value) const; + + /// \brief Return true if the type matches this InputType + bool Matches(const DataType& type) const; + + /// \brief The type matching rule that this InputType uses. + Kind kind() const { return kind_; } + + /// \brief For InputType::EXACT_TYPE kind, the exact type that this InputType + /// must match. Otherwise this function should not be used and will assert in + /// debug builds. + const std::shared_ptr& type() const; + + /// \brief For InputType::USE_TYPE_MATCHER, the TypeMatcher to be used for + /// checking the type of a value. Otherwise this function should not be used + /// and will assert in debug builds. + const TypeMatcher& type_matcher() const; + + private: + void CopyInto(const InputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->type_matcher_ = other.type_matcher_; + } + + void MoveInto(InputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->type_matcher_ = std::move(other.type_matcher_); + } + + Kind kind_; + + // For EXACT_TYPE Kind + std::shared_ptr type_; + + // For USE_TYPE_MATCHER Kind + std::shared_ptr type_matcher_; +}; + +/// \brief Container to capture both exact and input-dependent output types. +class ARROW_EXPORT OutputType { + public: + /// \brief An enum indicating whether the value type is an invariant fixed + /// value or one that's computed by a kernel-defined resolver function. + enum ResolveKind { FIXED, COMPUTED }; + + /// Type resolution function. Given input types, return output type. This + /// function MAY may use the kernel state to decide the output type based on + /// the FunctionOptions. + /// + /// This function SHOULD _not_ be used to check for arity, that is to be + /// performed one or more layers above. + using Resolver = + std::function(KernelContext*, const std::vector&)>; + + /// \brief Output an exact type + OutputType(std::shared_ptr type) // NOLINT implicit construction + : kind_(FIXED), type_(std::move(type)) {} + + /// \brief Output a computed type depending on actual input types + template + OutputType(Fn resolver) // NOLINT implicit construction + : kind_(COMPUTED), resolver_(std::move(resolver)) {} + + OutputType(const OutputType& other) { + this->kind_ = other.kind_; + this->type_ = other.type_; + this->resolver_ = other.resolver_; + } + + OutputType(OutputType&& other) { + this->kind_ = other.kind_; + this->type_ = std::move(other.type_); + this->resolver_ = other.resolver_; + } + + OutputType& operator=(const OutputType&) = default; + OutputType& operator=(OutputType&&) = default; + + /// \brief Return the type of the expected output value of the kernel given + /// the input argument types. The resolver may make use of state information + /// kept in the KernelContext. + Result Resolve(KernelContext* ctx, + const std::vector& args) const; + + /// \brief The exact output value type for the FIXED kind. + const std::shared_ptr& type() const; + + /// \brief For use with COMPUTED resolution strategy. It may be more + /// convenient to invoke this with OutputType::Resolve returned from this + /// method. + const Resolver& resolver() const; + + /// \brief Render a human-readable string representation. + std::string ToString() const; + + /// \brief Return the kind of type resolution of this output type, whether + /// fixed/invariant or computed by a resolver. + ResolveKind kind() const { return kind_; } + + private: + ResolveKind kind_; + + // For FIXED resolution + std::shared_ptr type_; + + // For COMPUTED resolution + Resolver resolver_ = NULLPTR; +}; + +/// \brief Holds the input types and output type of the kernel. +/// +/// VarArgs functions with minimum N arguments should pass up to N input types to be +/// used to validate the input types of a function invocation. The first N-1 types +/// will be matched against the first N-1 arguments, and the last type will be +/// matched against the remaining arguments. +class ARROW_EXPORT KernelSignature { + public: + KernelSignature(std::vector in_types, OutputType out_type, + bool is_varargs = false); + + /// \brief Convenience ctor since make_shared can be awkward + static std::shared_ptr Make(std::vector in_types, + OutputType out_type, + bool is_varargs = false); + + /// \brief Return true if the signature if compatible with the list of input + /// value descriptors. + bool MatchesInputs(const std::vector& types) const; + + /// \brief Returns true if the input types of each signature are + /// equal. Well-formed functions should have a deterministic output type + /// given input types, but currently it is the responsibility of the + /// developer to ensure this. + bool Equals(const KernelSignature& other) const; + + bool operator==(const KernelSignature& other) const { return this->Equals(other); } + + bool operator!=(const KernelSignature& other) const { return !(*this == other); } + + /// \brief Compute a hash code for the signature + size_t Hash() const; + + /// \brief The input types for the kernel. For VarArgs functions, this should + /// generally contain a single validator to use for validating all of the + /// function arguments. + const std::vector& in_types() const { return in_types_; } + + /// \brief The output type for the kernel. Use Resolve to return the + /// exact output given input argument types, since many kernels' + /// output types depend on their input types (or their type + /// metadata). + const OutputType& out_type() const { return out_type_; } + + /// \brief Render a human-readable string representation + std::string ToString() const; + + bool is_varargs() const { return is_varargs_; } + + private: + std::vector in_types_; + OutputType out_type_; + bool is_varargs_; + + // For caching the hash code after it's computed the first time + mutable uint64_t hash_code_; +}; + +/// \brief A function may contain multiple variants of a kernel for a given +/// type combination for different SIMD levels. Based on the active system's +/// CPU info or the user's preferences, we can elect to use one over the other. +struct SimdLevel { + enum type { NONE = 0, SSE4_2, AVX, AVX2, AVX512, NEON, MAX }; +}; + +/// \brief The strategy to use for propagating or otherwise populating the +/// validity bitmap of a kernel output. +struct NullHandling { + enum type { + /// Compute the output validity bitmap by intersecting the validity bitmaps + /// of the arguments using bitwise-and operations. This means that values + /// in the output are valid/non-null only if the corresponding values in + /// all input arguments were valid/non-null. Kernel generally need not + /// touch the bitmap thereafter, but a kernel's exec function is permitted + /// to alter the bitmap after the null intersection is computed if it needs + /// to. + INTERSECTION, + + /// Kernel expects a pre-allocated buffer to write the result bitmap + /// into. The preallocated memory is not zeroed (except for the last byte), + /// so the kernel should ensure to completely populate the bitmap. + COMPUTED_PREALLOCATE, + + /// Kernel allocates and sets the validity bitmap of the output. + COMPUTED_NO_PREALLOCATE, + + /// Kernel output is never null and a validity bitmap does not need to be + /// allocated. + OUTPUT_NOT_NULL + }; +}; + +/// \brief The preference for memory preallocation of fixed-width type outputs +/// in kernel execution. +struct MemAllocation { + enum type { + // For data types that support pre-allocation (i.e. fixed-width), the + // kernel expects to be provided a pre-allocated data buffer to write + // into. Non-fixed-width types must always allocate their own data + // buffers. The allocation made for the same length as the execution batch, + // so vector kernels yielding differently sized output should not use this. + // + // It is valid for the data to not be preallocated but the validity bitmap + // is (or is computed using the intersection/bitwise-and method). + // + // For variable-size output types like BinaryType or StringType, or for + // nested types, this option has no effect. + PREALLOCATE, + + // The kernel is responsible for allocating its own data buffer for + // fixed-width type outputs. + NO_PREALLOCATE + }; +}; + +struct Kernel; + +/// \brief Arguments to pass to an KernelInit function. A struct is used to help +/// avoid API breakage should the arguments passed need to be expanded. +struct KernelInitArgs { + /// \brief A pointer to the kernel being initialized. The init function may + /// depend on the kernel's KernelSignature or other data contained there. + const Kernel* kernel; + + /// \brief The types of the input arguments that the kernel is + /// about to be executed against. + const std::vector& inputs; + + /// \brief Opaque options specific to this kernel. May be nullptr for functions + /// that do not require options. + const FunctionOptions* options; +}; + +/// \brief Common initializer function for all kernel types. +using KernelInit = std::function>( + KernelContext*, const KernelInitArgs&)>; + +/// \brief Base type for kernels. Contains the function signature and +/// optionally the state initialization function, along with some common +/// attributes +struct ARROW_EXPORT Kernel { + Kernel() = default; + + Kernel(std::shared_ptr sig, KernelInit init) + : signature(std::move(sig)), init(std::move(init)) {} + + Kernel(std::vector in_types, OutputType out_type, KernelInit init) + : Kernel(KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init)) {} + + /// \brief The "signature" of the kernel containing the InputType input + /// argument validators and OutputType output type resolver. + std::shared_ptr signature; + + /// \brief Create a new KernelState for invocations of this kernel, e.g. to + /// set up any options or state relevant for execution. + KernelInit init; + + /// \brief Create a vector of new KernelState for invocations of this kernel. + static Status InitAll(KernelContext*, const KernelInitArgs&, + std::vector>*); + + /// \brief Indicates whether execution can benefit from parallelization + /// (splitting large chunks into smaller chunks and using multiple + /// threads). Some kernels may not support parallel execution at + /// all. Synchronization and concurrency-related issues are currently the + /// responsibility of the Kernel's implementation. + bool parallelizable = true; + + /// \brief Indicates the level of SIMD instruction support in the host CPU is + /// required to use the function. The intention is for functions to be able to + /// contain multiple kernels with the same signature but different levels of SIMD, + /// so that the most optimized kernel supported on a host's processor can be chosen. + SimdLevel::type simd_level = SimdLevel::NONE; + + // Additional kernel-specific data + std::shared_ptr data; +}; + +/// \brief The scalar kernel execution API that must be implemented for SCALAR +/// kernel types. This includes both stateless and stateful kernels. Kernels +/// depending on some execution state access that state via subclasses of +/// KernelState set on the KernelContext object. Implementations should +/// endeavor to write into pre-allocated memory if they are able, though for +/// some kernels (e.g. in cases when a builder like StringBuilder) must be +/// employed this may not be possible. +using ArrayKernelExec = Status (*)(KernelContext*, const ExecSpan&, ExecResult*); + +/// \brief Kernel data structure for implementations of ScalarFunction. In +/// addition to the members found in Kernel, contains the null handling +/// and memory pre-allocation preferences. +struct ARROW_EXPORT ScalarKernel : public Kernel { + ScalarKernel() = default; + + ScalarKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(sig), init), exec(exec) {} + + ScalarKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), exec(exec) {} + + /// \brief Perform a single invocation of this kernel. Depending on the + /// implementation, it may only write into preallocated memory, while in some + /// cases it will allocate its own memory. Any required state is managed + /// through the KernelContext. + ArrayKernelExec exec; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + // For scalar functions preallocated data and intersecting arg validity + // bitmaps is a reasonable default + NullHandling::type null_handling = NullHandling::INTERSECTION; + MemAllocation::type mem_allocation = MemAllocation::PREALLOCATE; +}; + +// ---------------------------------------------------------------------- +// VectorKernel (for VectorFunction) + +/// \brief Kernel data structure for implementations of VectorFunction. In +/// contains an optional finalizer function, the null handling and memory +/// pre-allocation preferences (which have different defaults from +/// ScalarKernel), and some other execution-related options. +struct ARROW_EXPORT VectorKernel : public Kernel { + /// \brief See VectorKernel::finalize member for usage + using FinalizeFunc = std::function*)>; + + /// \brief Function for executing a stateful VectorKernel against a + /// ChunkedArray input. Does not need to be defined for all VectorKernels + using ChunkedExec = Status (*)(KernelContext*, const ExecBatch&, Datum* out); + + VectorKernel() = default; + + VectorKernel(std::vector in_types, OutputType out_type, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(in_types), std::move(out_type), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + VectorKernel(std::shared_ptr sig, ArrayKernelExec exec, + KernelInit init = NULLPTR, FinalizeFunc finalize = NULLPTR) + : Kernel(std::move(sig), std::move(init)), + exec(exec), + finalize(std::move(finalize)) {} + + /// \brief Perform a single invocation of this kernel. Any required state is + /// managed through the KernelContext. + ArrayKernelExec exec; + + /// \brief Execute the kernel on a ChunkedArray. Does not need to be defined + ChunkedExec exec_chunked = NULLPTR; + + /// \brief For VectorKernel, convert intermediate results into finalized + /// results. Mutates input argument. Some kernels may accumulate state + /// (example: hashing-related functions) through processing chunked inputs, and + /// then need to attach some accumulated state to each of the outputs of + /// processing each chunk of data. + FinalizeFunc finalize; + + /// Since vector kernels generally are implemented rather differently from + /// scalar/elementwise kernels (and they may not even yield arrays of the same + /// size), so we make the developer opt-in to any memory preallocation rather + /// than having to turn it off. + NullHandling::type null_handling = NullHandling::COMPUTED_NO_PREALLOCATE; + MemAllocation::type mem_allocation = MemAllocation::NO_PREALLOCATE; + + /// \brief Writing execution results into larger contiguous allocations + /// requires that the kernel be able to write into sliced output ArrayData*, + /// including sliced output validity bitmaps. Some kernel implementations may + /// not be able to do this, so setting this to false disables this + /// functionality. + bool can_write_into_slices = true; + + /// Some vector kernels can do chunkwise execution using ExecSpanIterator, + /// in some cases accumulating some state. Other kernels (like Take) need to + /// be passed whole arrays and don't work on ChunkedArray inputs + bool can_execute_chunkwise = true; + + /// Some kernels (like unique and value_counts) yield non-chunked output from + /// chunked-array inputs. This option controls how the results are boxed when + /// returned from ExecVectorFunction + /// + /// true -> ChunkedArray + /// false -> Array + bool output_chunked = true; +}; + +// ---------------------------------------------------------------------- +// ScalarAggregateKernel (for ScalarAggregateFunction) + +using ScalarAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using ScalarAggregateMerge = Status (*)(KernelContext*, KernelState&&, KernelState*); +// Finalize returns Datum to permit multiple return values +using ScalarAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// ScalarAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * consume: processes an ExecSpan and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT ScalarAggregateKernel : public Kernel { + ScalarAggregateKernel(std::shared_ptr sig, KernelInit init, + ScalarAggregateConsume consume, ScalarAggregateMerge merge, + ScalarAggregateFinalize finalize, const bool ordered) + : Kernel(std::move(sig), std::move(init)), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + ScalarAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, ScalarAggregateConsume consume, + ScalarAggregateMerge merge, ScalarAggregateFinalize finalize, + const bool ordered) + : ScalarAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), consume, merge, finalize, ordered) {} + + /// \brief Merge a vector of KernelStates into a single KernelState. + /// The merged state will be returned and will be set on the KernelContext. + static Result> MergeAll( + const ScalarAggregateKernel* kernel, KernelContext* ctx, + std::vector> states); + + ScalarAggregateConsume consume; + ScalarAggregateMerge merge; + ScalarAggregateFinalize finalize; + /// \brief Whether this kernel requires ordering + /// Some aggregations, such as, "first", requires some kind of input order. The + /// order can be implicit, e.g., the order of the input data, or explicit, e.g. + /// the ordering specified with a window aggregation. + /// The caller of the aggregate kernel is responsible for passing data in some + /// defined order to the kernel. The flag here is a way for the kernel to tell + /// the caller that data passed to the kernel must be defined in some order. + bool ordered = false; +}; + +// ---------------------------------------------------------------------- +// HashAggregateKernel (for HashAggregateFunction) + +using HashAggregateResize = Status (*)(KernelContext*, int64_t); +using HashAggregateConsume = Status (*)(KernelContext*, const ExecSpan&); +using HashAggregateMerge = Status (*)(KernelContext*, KernelState&&, const ArrayData&); + +// Finalize returns Datum to permit multiple return values +using HashAggregateFinalize = Status (*)(KernelContext*, Datum*); + +/// \brief Kernel data structure for implementations of +/// HashAggregateFunction. The four necessary components of an aggregation +/// kernel are the init, consume, merge, and finalize functions. +/// +/// * init: creates a new KernelState for a kernel. +/// * resize: ensure that the KernelState can accommodate the specified number of groups. +/// * consume: processes an ExecSpan (which includes the argument as well +/// as an array of group identifiers) and updates the KernelState found in the +/// KernelContext. +/// * merge: combines one KernelState with another. +/// * finalize: produces the end result of the aggregation using the +/// KernelState in the KernelContext. +struct ARROW_EXPORT HashAggregateKernel : public Kernel { + HashAggregateKernel() = default; + + HashAggregateKernel(std::shared_ptr sig, KernelInit init, + HashAggregateResize resize, HashAggregateConsume consume, + HashAggregateMerge merge, HashAggregateFinalize finalize, + const bool ordered) + : Kernel(std::move(sig), std::move(init)), + resize(resize), + consume(consume), + merge(merge), + finalize(finalize), + ordered(ordered) {} + + HashAggregateKernel(std::vector in_types, OutputType out_type, + KernelInit init, HashAggregateConsume consume, + HashAggregateResize resize, HashAggregateMerge merge, + HashAggregateFinalize finalize, const bool ordered) + : HashAggregateKernel( + KernelSignature::Make(std::move(in_types), std::move(out_type)), + std::move(init), resize, consume, merge, finalize, ordered) {} + + HashAggregateResize resize; + HashAggregateConsume consume; + HashAggregateMerge merge; + HashAggregateFinalize finalize; + /// @brief whether the summarizer requires ordering + /// This is similar to ScalarAggregateKernel. See ScalarAggregateKernel + /// for detailed doc of this variable. + bool ordered = false; +}; + +} // namespace compute +} // namespace arrow diff --git a/shared/package-files/cb/cb0e51b821e805cd0b6c96e3399bc1c668c451709ffcd785ccec98f99449be3b/test_isocalendar.cpython-311.pyc b/shared/package-files/cb/cb0e51b821e805cd0b6c96e3399bc1c668c451709ffcd785ccec98f99449be3b/test_isocalendar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1124d459a431eacb356bdf19b9691a81d4d1602f Binary files /dev/null and b/shared/package-files/cb/cb0e51b821e805cd0b6c96e3399bc1c668c451709ffcd785ccec98f99449be3b/test_isocalendar.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb14bc169798f1e2b87238927349c13dd28017c0919eeedca51d155ff04263be/type.h b/shared/package-files/cb/cb14bc169798f1e2b87238927349c13dd28017c0919eeedca51d155ff04263be/type.h new file mode 100644 index 0000000000000000000000000000000000000000..53207bb9da8a6fddc32c94022b2142c6f6708ac2 --- /dev/null +++ b/shared/package-files/cb/cb14bc169798f1e2b87238927349c13dd28017c0919eeedca51d155ff04263be/type.h @@ -0,0 +1,2629 @@ +// 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. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/type_fwd.h" // IWYU pragma: export +#include "arrow/util/checked_cast.h" +#include "arrow/util/endian.h" +#include "arrow/util/macros.h" +#include "arrow/util/visibility.h" +#include "arrow/visitor.h" // IWYU pragma: keep + +namespace arrow { +namespace detail { + +/// \defgroup numeric-datatypes Datatypes for numeric data +/// @{ +/// @} + +/// \defgroup binary-datatypes Datatypes for binary/string data +/// @{ +/// @} + +/// \defgroup temporal-datatypes Datatypes for temporal data +/// @{ +/// @} + +/// \defgroup nested-datatypes Datatypes for nested data +/// @{ +/// @} + +class ARROW_EXPORT Fingerprintable { + public: + virtual ~Fingerprintable(); + + const std::string& fingerprint() const { + auto p = fingerprint_.load(); + if (ARROW_PREDICT_TRUE(p != NULLPTR)) { + return *p; + } + return LoadFingerprintSlow(); + } + + const std::string& metadata_fingerprint() const { + auto p = metadata_fingerprint_.load(); + if (ARROW_PREDICT_TRUE(p != NULLPTR)) { + return *p; + } + return LoadMetadataFingerprintSlow(); + } + + protected: + const std::string& LoadFingerprintSlow() const; + const std::string& LoadMetadataFingerprintSlow() const; + + virtual std::string ComputeFingerprint() const = 0; + virtual std::string ComputeMetadataFingerprint() const = 0; + + mutable std::atomic fingerprint_{NULLPTR}; + mutable std::atomic metadata_fingerprint_{NULLPTR}; +}; + +} // namespace detail + +/// EXPERIMENTAL: Layout specification for a data type +struct ARROW_EXPORT DataTypeLayout { + enum BufferKind { FIXED_WIDTH, VARIABLE_WIDTH, BITMAP, ALWAYS_NULL }; + + /// Layout specification for a single data type buffer + struct BufferSpec { + BufferKind kind; + int64_t byte_width; // For FIXED_WIDTH + + bool operator==(const BufferSpec& other) const { + return kind == other.kind && + (kind != FIXED_WIDTH || byte_width == other.byte_width); + } + bool operator!=(const BufferSpec& other) const { return !(*this == other); } + }; + + static BufferSpec FixedWidth(int64_t w) { return BufferSpec{FIXED_WIDTH, w}; } + static BufferSpec VariableWidth() { return BufferSpec{VARIABLE_WIDTH, -1}; } + static BufferSpec Bitmap() { return BufferSpec{BITMAP, -1}; } + static BufferSpec AlwaysNull() { return BufferSpec{ALWAYS_NULL, -1}; } + + /// A vector of buffer layout specifications, one for each expected buffer + std::vector buffers; + /// Whether this type expects an associated dictionary array. + bool has_dictionary = false; + /// If this is provided, the number of buffers expected is only lower-bounded by + /// buffers.size(). Buffers beyond this lower bound are expected to conform to + /// variadic_spec. + std::optional variadic_spec; + + explicit DataTypeLayout(std::vector buffers, + std::optional variadic_spec = {}) + : buffers(std::move(buffers)), variadic_spec(variadic_spec) {} +}; + +/// \brief Base class for all data types +/// +/// Data types in this library are all *logical*. They can be expressed as +/// either a primitive physical type (bytes or bits of some fixed size), a +/// nested type consisting of other data types, or another data type (e.g. a +/// timestamp encoded as an int64). +/// +/// Simple datatypes may be entirely described by their Type::type id, but +/// complex datatypes are usually parametric. +class ARROW_EXPORT DataType : public std::enable_shared_from_this, + public detail::Fingerprintable, + public util::EqualityComparable { + public: + explicit DataType(Type::type id) : detail::Fingerprintable(), id_(id) {} + ~DataType() override; + + /// \brief Return whether the types are equal + /// + /// Types that are logically convertible from one to another (e.g. List + /// and Binary) are NOT equal. + bool Equals(const DataType& other, bool check_metadata = false) const; + + /// \brief Return whether the types are equal + bool Equals(const std::shared_ptr& other, bool check_metadata = false) const; + + /// \brief Return the child field at index i. + const std::shared_ptr& field(int i) const { return children_[i]; } + + /// \brief Return the children fields associated with this type. + const FieldVector& fields() const { return children_; } + + /// \brief Return the number of children fields associated with this type. + int num_fields() const { return static_cast(children_.size()); } + + /// \brief Apply the TypeVisitor::Visit() method specialized to the data type + Status Accept(TypeVisitor* visitor) const; + + /// \brief A string representation of the type, including any children + virtual std::string ToString(bool show_metadata = false) const = 0; + + /// \brief Return hash value (excluding metadata in child fields) + size_t Hash() const; + + /// \brief A string name of the type, omitting any child fields + /// + /// \since 0.7.0 + virtual std::string name() const = 0; + + /// \brief Return the data type layout. Children are not included. + /// + /// \note Experimental API + virtual DataTypeLayout layout() const = 0; + + /// \brief Return the type category + Type::type id() const { return id_; } + + /// \brief Return the type category of the storage type + virtual Type::type storage_id() const { return id_; } + + /// \brief Returns the type's fixed byte width, if any. Returns -1 + /// for non-fixed-width types, and should only be used for + /// subclasses of FixedWidthType + virtual int32_t byte_width() const { + int32_t num_bits = this->bit_width(); + return num_bits > 0 ? num_bits / 8 : -1; + } + + /// \brief Returns the type's fixed bit width, if any. Returns -1 + /// for non-fixed-width types, and should only be used for + /// subclasses of FixedWidthType + virtual int bit_width() const { return -1; } + + // \brief EXPERIMENTAL: Enable retrieving shared_ptr from a const + // context. + std::shared_ptr GetSharedPtr() const { + return const_cast(this)->shared_from_this(); + } + + protected: + // Dummy version that returns a null string (indicating not implemented). + // Subclasses should override for fast equality checks. + std::string ComputeFingerprint() const override; + + // Generic versions that works for all regular types, nested or not. + std::string ComputeMetadataFingerprint() const override; + + Type::type id_; + FieldVector children_; + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(DataType); +}; + +/// \brief EXPERIMENTAL: Container for a type pointer which can hold a +/// dynamically created shared_ptr if it needs to. +struct ARROW_EXPORT TypeHolder { + const DataType* type = NULLPTR; + std::shared_ptr owned_type; + + TypeHolder() = default; + TypeHolder(const TypeHolder& other) = default; + TypeHolder& operator=(const TypeHolder& other) = default; + TypeHolder(TypeHolder&& other) = default; + TypeHolder& operator=(TypeHolder&& other) = default; + + TypeHolder(std::shared_ptr owned_type) // NOLINT implicit construction + : type(owned_type.get()), owned_type(std::move(owned_type)) {} + + TypeHolder(const DataType* type) // NOLINT implicit construction + : type(type) {} + + Type::type id() const { return this->type->id(); } + + std::shared_ptr GetSharedPtr() const { + return this->type != NULLPTR ? this->type->GetSharedPtr() : NULLPTR; + } + + const DataType& operator*() const { return *this->type; } + + operator bool() const { return this->type != NULLPTR; } + + bool operator==(const TypeHolder& other) const { + if (type == other.type) return true; + if (type == NULLPTR || other.type == NULLPTR) return false; + return type->Equals(*other.type); + } + + bool operator==(decltype(NULLPTR)) const { return this->type == NULLPTR; } + + bool operator==(const DataType& other) const { + if (this->type == NULLPTR) return false; + return other.Equals(*this->type); + } + + bool operator!=(const DataType& other) const { return !(*this == other); } + + bool operator==(const std::shared_ptr& other) const { + return *this == *other; + } + + bool operator!=(const TypeHolder& other) const { return !(*this == other); } + + std::string ToString(bool show_metadata = false) const { + return this->type ? this->type->ToString(show_metadata) : ""; + } + + static std::string ToString(const std::vector&, bool show_metadata = false); + + static std::vector FromTypes( + const std::vector>& types); +}; + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, const DataType& type); + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, const TypeHolder& type); + +/// \brief Return the compatible physical data type +/// +/// Some types may have distinct logical meanings but the exact same physical +/// representation. For example, TimestampType has Int64Type as a physical +/// type (defined as TimestampType::PhysicalType). +/// +/// The return value is as follows: +/// - if a `PhysicalType` alias exists in the concrete type class, return +/// an instance of `PhysicalType`. +/// - otherwise, return the input type itself. +std::shared_ptr GetPhysicalType(const std::shared_ptr& type); + +/// \brief Base class for all fixed-width data types +class ARROW_EXPORT FixedWidthType : public DataType { + public: + using DataType::DataType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~FixedWidthType() override; +}; + +/// \brief Base class for all data types representing primitive values +class ARROW_EXPORT PrimitiveCType : public FixedWidthType { + public: + using FixedWidthType::FixedWidthType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~PrimitiveCType() override; +}; + +/// \brief Base class for all numeric data types +class ARROW_EXPORT NumberType : public PrimitiveCType { + public: + using PrimitiveCType::PrimitiveCType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~NumberType() override; +}; + +/// \brief Base class for all integral data types +class ARROW_EXPORT IntegerType : public NumberType { + public: + using NumberType::NumberType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~IntegerType() override; + virtual bool is_signed() const = 0; +}; + +/// \brief Base class for all floating-point data types +class ARROW_EXPORT FloatingPointType : public NumberType { + public: + using NumberType::NumberType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~FloatingPointType() override; + enum Precision { HALF, SINGLE, DOUBLE }; + virtual Precision precision() const = 0; +}; + +/// \brief Base class for all parametric data types +class ParametricType {}; + +class ARROW_EXPORT NestedType : public DataType, public ParametricType { + public: + using DataType::DataType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~NestedType() override; +}; + +/// \brief The combination of a field name and data type, with optional metadata +/// +/// Fields are used to describe the individual constituents of a +/// nested DataType or a Schema. +/// +/// A field's metadata is represented by a KeyValueMetadata instance, +/// which holds arbitrary key-value pairs. +class ARROW_EXPORT Field : public detail::Fingerprintable, + public util::EqualityComparable { + public: + Field(std::string name, std::shared_ptr type, bool nullable = true, + std::shared_ptr metadata = NULLPTR) + : detail::Fingerprintable(), + name_(std::move(name)), + type_(std::move(type)), + nullable_(nullable), + metadata_(std::move(metadata)) {} + + ~Field() override; + + /// \brief Return the field's attached metadata + std::shared_ptr metadata() const { return metadata_; } + + /// \brief Return whether the field has non-empty metadata + bool HasMetadata() const; + + /// \brief Return a copy of this field with the given metadata attached to it + std::shared_ptr WithMetadata( + const std::shared_ptr& metadata) const; + + /// \brief EXPERIMENTAL: Return a copy of this field with the given metadata + /// merged with existing metadata (any colliding keys will be overridden by + /// the passed metadata) + std::shared_ptr WithMergedMetadata( + const std::shared_ptr& metadata) const; + + /// \brief Return a copy of this field without any metadata attached to it + std::shared_ptr RemoveMetadata() const; + + /// \brief Return a copy of this field with the replaced type. + std::shared_ptr WithType(const std::shared_ptr& type) const; + + /// \brief Return a copy of this field with the replaced name. + std::shared_ptr WithName(const std::string& name) const; + + /// \brief Return a copy of this field with the replaced nullability. + std::shared_ptr WithNullable(bool nullable) const; + + /// \brief Options that control the behavior of `MergeWith`. + /// Options are to be added to allow type conversions, including integer + /// widening, promotion from integer to float, or conversion to or from boolean. + struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable { + /// If true, a Field of NullType can be unified with a Field of another type. + /// The unified field will be of the other type and become nullable. + /// Nullability will be promoted to the looser option (nullable if one is not + /// nullable). + bool promote_nullability = true; + + /// Allow a decimal to be unified with another decimal of the same + /// width, adjusting scale and precision as appropriate. May fail + /// if the adjustment is not possible. + bool promote_decimal = false; + + /// Allow a decimal to be promoted to a float. The float type will + /// not itself be promoted (e.g. Decimal128 + Float32 = Float32). + bool promote_decimal_to_float = false; + + /// Allow an integer to be promoted to a decimal. + /// + /// May fail if the decimal has insufficient precision to + /// accommodate the integer (see promote_numeric_width). + bool promote_integer_to_decimal = false; + + /// Allow an integer of a given bit width to be promoted to a + /// float; the result will be a float of an equal or greater bit + /// width to both of the inputs. Examples: + /// - int8 + float32 = float32 + /// - int32 + float32 = float64 + /// - int32 + float64 = float64 + /// Because an int32 cannot always be represented exactly in the + /// 24 bits of a float32 mantissa. + bool promote_integer_to_float = false; + + /// Allow an unsigned integer of a given bit width to be promoted + /// to a signed integer that fits into the signed type: + /// uint + int16 = int16 + /// When widening is needed, set promote_numeric_width to true: + /// uint16 + int16 = int32 + bool promote_integer_sign = false; + + /// Allow an integer, float, or decimal of a given bit width to be + /// promoted to an equivalent type of a greater bit width. + bool promote_numeric_width = false; + + /// Allow strings to be promoted to binary types. Promotion of fixed size + /// binary types to variable sized formats, and binary to large binary, + /// and string to large string. + bool promote_binary = false; + + /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc + bool promote_temporal_unit = false; + + /// Allow promotion from a list to a large-list and from a fixed-size list to a + /// variable sized list + bool promote_list = false; + + /// Unify dictionary index types and dictionary value types. + bool promote_dictionary = false; + + /// Allow merging ordered and non-ordered dictionaries. + /// The result will be ordered if and only if both inputs + /// are ordered. + bool promote_dictionary_ordered = false; + + /// Get default options. Only NullType will be merged with other types. + static MergeOptions Defaults() { return MergeOptions(); } + /// Get permissive options. All options are enabled, except + /// promote_dictionary_ordered. + static MergeOptions Permissive(); + /// Get a human-readable representation of the options. + std::string ToString() const; + }; + + /// \brief Merge the current field with a field of the same name. + /// + /// The two fields must be compatible, i.e: + /// - have the same name + /// - have the same type, or of compatible types according to `options`. + /// + /// The metadata of the current field is preserved; the metadata of the other + /// field is discarded. + Result> MergeWith( + const Field& other, MergeOptions options = MergeOptions::Defaults()) const; + Result> MergeWith( + const std::shared_ptr& other, + MergeOptions options = MergeOptions::Defaults()) const; + + FieldVector Flatten() const; + + /// \brief Indicate if fields are equals. + /// + /// \param[in] other field to check equality with. + /// \param[in] check_metadata controls if it should check for metadata + /// equality. + /// + /// \return true if fields are equal, false otherwise. + bool Equals(const Field& other, bool check_metadata = false) const; + bool Equals(const std::shared_ptr& other, bool check_metadata = false) const; + + /// \brief Indicate if fields are compatibles. + /// + /// See the criteria of MergeWith. + /// + /// \return true if fields are compatible, false otherwise. + bool IsCompatibleWith(const Field& other) const; + bool IsCompatibleWith(const std::shared_ptr& other) const; + + /// \brief Return a string representation ot the field + /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty, + /// print keys and values in the output + std::string ToString(bool show_metadata = false) const; + + /// \brief Return the field name + const std::string& name() const { return name_; } + /// \brief Return the field data type + const std::shared_ptr& type() const { return type_; } + /// \brief Return whether the field is nullable + bool nullable() const { return nullable_; } + + std::shared_ptr Copy() const; + + private: + std::string ComputeFingerprint() const override; + std::string ComputeMetadataFingerprint() const override; + + // Field name + std::string name_; + + // The field's data type + std::shared_ptr type_; + + // Fields can be nullable + bool nullable_; + + // The field's metadata, if any + std::shared_ptr metadata_; + + ARROW_DISALLOW_COPY_AND_ASSIGN(Field); +}; + +ARROW_EXPORT void PrintTo(const Field& field, std::ostream* os); + +namespace detail { + +template +class CTypeImpl : public BASE { + public: + static constexpr Type::type type_id = TYPE_ID; + using c_type = C_TYPE; + using PhysicalType = DERIVED; + + CTypeImpl() : BASE(TYPE_ID) {} + + int bit_width() const override { return static_cast(sizeof(C_TYPE) * CHAR_BIT); } + + DataTypeLayout layout() const override { + return DataTypeLayout( + {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(C_TYPE))}); + } + + std::string name() const override { return DERIVED::type_name(); } + + std::string ToString(bool show_metadata = false) const override { return this->name(); } +}; + +template +constexpr Type::type CTypeImpl::type_id; + +template +class IntegerTypeImpl : public detail::CTypeImpl { + bool is_signed() const override { return std::is_signed::value; } +}; + +} // namespace detail + +/// Concrete type class for always-null data +class ARROW_EXPORT NullType : public DataType { + public: + static constexpr Type::type type_id = Type::NA; + + static constexpr const char* type_name() { return "null"; } + + NullType() : DataType(Type::NA) {} + + std::string ToString(bool show_metadata = false) const override; + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::AlwaysNull()}); + } + + std::string name() const override { return "null"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for boolean data +class ARROW_EXPORT BooleanType + : public detail::CTypeImpl { + public: + static constexpr const char* type_name() { return "bool"; } + + // BooleanType within arrow use a single bit instead of the C 8-bits layout. + int bit_width() const final { return 1; } + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::Bitmap()}); + } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \addtogroup numeric-datatypes +/// +/// @{ + +/// Concrete type class for unsigned 8-bit integer data +class ARROW_EXPORT UInt8Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 8-bit integer data +class ARROW_EXPORT Int8Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 16-bit integer data +class ARROW_EXPORT UInt16Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint16"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 16-bit integer data +class ARROW_EXPORT Int16Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int16"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 32-bit integer data +class ARROW_EXPORT UInt32Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint32"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 32-bit integer data +class ARROW_EXPORT Int32Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int32"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 64-bit integer data +class ARROW_EXPORT UInt64Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint64"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 64-bit integer data +class ARROW_EXPORT Int64Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int64"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for 16-bit floating-point data +class ARROW_EXPORT HalfFloatType + : public detail::CTypeImpl { + public: + Precision precision() const override; + static constexpr const char* type_name() { return "halffloat"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for 32-bit floating-point data (C "float") +class ARROW_EXPORT FloatType + : public detail::CTypeImpl { + public: + Precision precision() const override; + static constexpr const char* type_name() { return "float"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for 64-bit floating-point data (C "double") +class ARROW_EXPORT DoubleType + : public detail::CTypeImpl { + public: + Precision precision() const override; + static constexpr const char* type_name() { return "double"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// @} + +/// \brief Base class for all variable-size binary data types +class ARROW_EXPORT BaseBinaryType : public DataType { + public: + using DataType::DataType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~BaseBinaryType() override; +}; + +constexpr int64_t kBinaryMemoryLimit = std::numeric_limits::max() - 1; + +/// \addtogroup binary-datatypes +/// +/// @{ + +/// \brief Concrete type class for variable-size binary data +class ARROW_EXPORT BinaryType : public BaseBinaryType { + public: + static constexpr Type::type type_id = Type::BINARY; + static constexpr bool is_utf8 = false; + using offset_type = int32_t; + using PhysicalType = BinaryType; + + static constexpr const char* type_name() { return "binary"; } + + BinaryType() : BinaryType(Type::BINARY) {} + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), + DataTypeLayout::FixedWidth(sizeof(offset_type)), + DataTypeLayout::VariableWidth()}); + } + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "binary"; } + + protected: + std::string ComputeFingerprint() const override; + + // Allow subclasses like StringType to change the logical type. + explicit BinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {} +}; + +/// \brief Concrete type class for variable-size binary view data +class ARROW_EXPORT BinaryViewType : public DataType { + public: + static constexpr Type::type type_id = Type::BINARY_VIEW; + static constexpr bool is_utf8 = false; + using PhysicalType = BinaryViewType; + + static constexpr int kSize = 16; + static constexpr int kInlineSize = 12; + static constexpr int kPrefixSize = 4; + + /// Variable length string or binary with inline optimization for small values (12 bytes + /// or fewer). This is similar to std::string_view except limited in size to INT32_MAX + /// and at least the first four bytes of the string are copied inline (accessible + /// without pointer dereference). This inline prefix allows failing comparisons early. + /// Furthermore when dealing with short strings the CPU cache working set is reduced + /// since many can be inline. + /// + /// This union supports two states: + /// + /// - Entirely inlined string data + /// |----|--------------| + /// ^ ^ + /// | | + /// size in-line string data, zero padded + /// + /// - Reference into a buffer + /// |----|----|----|----| + /// ^ ^ ^ ^ + /// | | | | + /// size | | `------. + /// prefix | | + /// buffer index | + /// offset in buffer + /// + /// Adapted from TU Munich's UmbraDB [1], Velox, DuckDB. + /// + /// [1]: https://db.in.tum.de/~freitag/papers/p29-neumann-cidr20.pdf + /// + /// Alignment to 64 bits enables an aligned load of the size and prefix into + /// a single 64 bit integer, which is useful to the comparison fast path. + union alignas(int64_t) c_type { + struct { + int32_t size; + std::array data; + } inlined; + + struct { + int32_t size; + std::array prefix; + int32_t buffer_index; + int32_t offset; + } ref; + + /// The number of bytes viewed. + int32_t size() const { + // Size is in the common initial subsequence of each member of the union, + // so accessing `inlined.size` is legal even if another member is active. + return inlined.size; + } + + /// True if the view's data is entirely stored inline. + bool is_inline() const { return size() <= kInlineSize; } + + /// Return a pointer to the inline data of a view. + /// + /// For inline views, this points to the entire data of the view. + /// For other views, this points to the 4 byte prefix. + const uint8_t* inline_data() const& { + // Since `ref.prefix` has the same address as `inlined.data`, + // the branch will be trivially optimized out. + return is_inline() ? inlined.data.data() : ref.prefix.data(); + } + const uint8_t* inline_data() && = delete; + }; + static_assert(sizeof(c_type) == kSize); + static_assert(std::is_trivial_v); + + static constexpr const char* type_name() { return "binary_view"; } + + BinaryViewType() : BinaryViewType(Type::BINARY_VIEW) {} + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(kSize)}, + DataTypeLayout::VariableWidth()); + } + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "binary_view"; } + + protected: + std::string ComputeFingerprint() const override; + + // Allow subclasses like StringType to change the logical type. + explicit BinaryViewType(Type::type logical_type) : DataType(logical_type) {} +}; + +/// \brief Concrete type class for large variable-size binary data +class ARROW_EXPORT LargeBinaryType : public BaseBinaryType { + public: + static constexpr Type::type type_id = Type::LARGE_BINARY; + static constexpr bool is_utf8 = false; + using offset_type = int64_t; + using PhysicalType = LargeBinaryType; + + static constexpr const char* type_name() { return "large_binary"; } + + LargeBinaryType() : LargeBinaryType(Type::LARGE_BINARY) {} + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), + DataTypeLayout::FixedWidth(sizeof(offset_type)), + DataTypeLayout::VariableWidth()}); + } + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "large_binary"; } + + protected: + std::string ComputeFingerprint() const override; + + // Allow subclasses like LargeStringType to change the logical type. + explicit LargeBinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {} +}; + +/// \brief Concrete type class for variable-size string data, utf8-encoded +class ARROW_EXPORT StringType : public BinaryType { + public: + static constexpr Type::type type_id = Type::STRING; + static constexpr bool is_utf8 = true; + using PhysicalType = BinaryType; + + static constexpr const char* type_name() { return "utf8"; } + + StringType() : BinaryType(Type::STRING) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "utf8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for variable-size string data, utf8-encoded +class ARROW_EXPORT StringViewType : public BinaryViewType { + public: + static constexpr Type::type type_id = Type::STRING_VIEW; + static constexpr bool is_utf8 = true; + using PhysicalType = BinaryViewType; + + static constexpr const char* type_name() { return "utf8_view"; } + + StringViewType() : BinaryViewType(Type::STRING_VIEW) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "utf8_view"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for large variable-size string data, utf8-encoded +class ARROW_EXPORT LargeStringType : public LargeBinaryType { + public: + static constexpr Type::type type_id = Type::LARGE_STRING; + static constexpr bool is_utf8 = true; + using PhysicalType = LargeBinaryType; + + static constexpr const char* type_name() { return "large_utf8"; } + + LargeStringType() : LargeBinaryType(Type::LARGE_STRING) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "large_utf8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for fixed-size binary data +class ARROW_EXPORT FixedSizeBinaryType : public FixedWidthType, public ParametricType { + public: + static constexpr Type::type type_id = Type::FIXED_SIZE_BINARY; + static constexpr bool is_utf8 = false; + + static constexpr const char* type_name() { return "fixed_size_binary"; } + + explicit FixedSizeBinaryType(int32_t byte_width) + : FixedWidthType(Type::FIXED_SIZE_BINARY), byte_width_(byte_width) {} + explicit FixedSizeBinaryType(int32_t byte_width, Type::type override_type_id) + : FixedWidthType(override_type_id), byte_width_(byte_width) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "fixed_size_binary"; } + + DataTypeLayout layout() const override { + return DataTypeLayout( + {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(byte_width())}); + } + + int byte_width() const override { return byte_width_; } + + int bit_width() const override; + + // Validating constructor + static Result> Make(int32_t byte_width); + + protected: + std::string ComputeFingerprint() const override; + + int32_t byte_width_; +}; + +/// @} + +/// \addtogroup numeric-datatypes +/// +/// @{ + +/// \brief Base type class for (fixed-size) decimal data +class ARROW_EXPORT DecimalType : public FixedSizeBinaryType { + public: + explicit DecimalType(Type::type type_id, int32_t byte_width, int32_t precision, + int32_t scale) + : FixedSizeBinaryType(byte_width, type_id), precision_(precision), scale_(scale) {} + + /// Constructs concrete decimal types + static Result> Make(Type::type type_id, int32_t precision, + int32_t scale); + + int32_t precision() const { return precision_; } + int32_t scale() const { return scale_; } + + /// \brief Returns the number of bytes needed for precision. + /// + /// precision must be >= 1 + static int32_t DecimalSize(int32_t precision); + + protected: + std::string ComputeFingerprint() const override; + + int32_t precision_; + int32_t scale_; +}; + +/// \brief Concrete type class for 32-bit decimal data +/// +/// Arrow decimals are fixed-point decimal numbers encoded as a scaled +/// integer. The precision is the number of significant digits that the +/// decimal type can represent; the scale is the number of digits after +/// the decimal point (note the scale can be negative). +/// +/// As an example, `Decimal32Type(7, 3)` can exactly represent the numbers +/// 1234.567 and -1234.567 (encoded internally as the 32-bit integers +/// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. +/// +/// Decimal32Type has a maximum precision of 9 significant digits +/// (also available as Decimal32Type::kMaxPrecision). +/// If higher precision is needed, consider using Decimal64Type, +/// Decimal128Type or Decimal256Type. +class ARROW_EXPORT Decimal32Type : public DecimalType { + public: + static constexpr Type::type type_id = Type::DECIMAL32; + + static constexpr const char* type_name() { return "decimal32"; } + + /// Decimal32Type constructor that aborts on invalid input. + explicit Decimal32Type(int32_t precision, int32_t scale); + + /// Decimal32Type constructor that returns an error on invalid input + static Result> Make(int32_t precision, int32_t scale); + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "decimal32"; } + + static constexpr int32_t kMinPrecision = 1; + static constexpr int32_t kMaxPrecision = 9; + static constexpr int32_t kByteWidth = 4; +}; + +/// \brief Concrete type class for 64-bit decimal data +/// +/// Arrow decimals are fixed-point decimal numbers encoded as a scaled +/// integer. The precision is the number of significant digits that the +/// decimal type can represent; the scale is the number of digits after +/// the decimal point (note the scale can be negative). +/// +/// As an example, `Decimal64Type(7, 3)` can exactly represent the numbers +/// 1234.567 and -1234.567 (encoded internally as the 64-bit integers +/// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. +/// +/// Decimal64Type has a maximum precision of 18 significant digits +/// (also available as Decimal64Type::kMaxPrecision). +/// If higher precision is needed, consider using Decimal128Type or +/// Decimal256Type. +class ARROW_EXPORT Decimal64Type : public DecimalType { + public: + static constexpr Type::type type_id = Type::DECIMAL64; + + static constexpr const char* type_name() { return "decimal64"; } + + /// Decimal32Type constructor that aborts on invalid input. + explicit Decimal64Type(int32_t precision, int32_t scale); + + /// Decimal32Type constructor that returns an error on invalid input + static Result> Make(int32_t precision, int32_t scale); + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "decimal64"; } + + static constexpr int32_t kMinPrecision = 1; + static constexpr int32_t kMaxPrecision = 18; + static constexpr int32_t kByteWidth = 8; +}; + +/// \brief Concrete type class for 128-bit decimal data +/// +/// Arrow decimals are fixed-point decimal numbers encoded as a scaled +/// integer. The precision is the number of significant digits that the +/// decimal type can represent; the scale is the number of digits after +/// the decimal point (note the scale can be negative). +/// +/// As an example, `Decimal128Type(7, 3)` can exactly represent the numbers +/// 1234.567 and -1234.567 (encoded internally as the 128-bit integers +/// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567. +/// +/// Decimal128Type has a maximum precision of 38 significant digits +/// (also available as Decimal128Type::kMaxPrecision). +/// If higher precision is needed, consider using Decimal256Type. +class ARROW_EXPORT Decimal128Type : public DecimalType { + public: + static constexpr Type::type type_id = Type::DECIMAL128; + + static constexpr const char* type_name() { return "decimal128"; } + + /// Decimal128Type constructor that aborts on invalid input. + explicit Decimal128Type(int32_t precision, int32_t scale); + + /// Decimal128Type constructor that returns an error on invalid input. + static Result> Make(int32_t precision, int32_t scale); + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "decimal128"; } + + static constexpr int32_t kMinPrecision = 1; + static constexpr int32_t kMaxPrecision = 38; + static constexpr int32_t kByteWidth = 16; +}; + +/// \brief Concrete type class for 256-bit decimal data +/// +/// Arrow decimals are fixed-point decimal numbers encoded as a scaled +/// integer. The precision is the number of significant digits that the +/// decimal type can represent; the scale is the number of digits after +/// the decimal point (note the scale can be negative). +/// +/// Decimal256Type has a maximum precision of 76 significant digits. +/// (also available as Decimal256Type::kMaxPrecision). +/// +/// For most use cases, the maximum precision offered by Decimal128Type +/// is sufficient, and it will result in a more compact and more efficient +/// encoding. +class ARROW_EXPORT Decimal256Type : public DecimalType { + public: + static constexpr Type::type type_id = Type::DECIMAL256; + + static constexpr const char* type_name() { return "decimal256"; } + + /// Decimal256Type constructor that aborts on invalid input. + explicit Decimal256Type(int32_t precision, int32_t scale); + + /// Decimal256Type constructor that returns an error on invalid input. + static Result> Make(int32_t precision, int32_t scale); + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "decimal256"; } + + static constexpr int32_t kMinPrecision = 1; + static constexpr int32_t kMaxPrecision = 76; + static constexpr int32_t kByteWidth = 32; +}; + +/// @} + +/// \addtogroup nested-datatypes +/// +/// @{ + +/// \brief Base class for all variable-size list data types +class ARROW_EXPORT BaseListType : public NestedType { + public: + using NestedType::NestedType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~BaseListType() override; + const std::shared_ptr& value_field() const { return children_[0]; } + + const std::shared_ptr& value_type() const { return children_[0]->type(); } +}; + +/// \brief Concrete type class for list data +/// +/// List data is nested data where each value is a variable number of +/// child items. Lists can be recursively nested, for example +/// list(list(int32)). +class ARROW_EXPORT ListType : public BaseListType { + public: + static constexpr Type::type type_id = Type::LIST; + using offset_type = int32_t; + + static constexpr const char* type_name() { return "list"; } + + // List can contain any other logical value type + explicit ListType(std::shared_ptr value_type) + : ListType(std::make_shared("item", std::move(value_type))) {} + + explicit ListType(std::shared_ptr value_field) : BaseListType(type_id) { + children_ = {std::move(value_field)}; + } + + DataTypeLayout layout() const override { + return DataTypeLayout( + {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))}); + } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "list"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for large list data +/// +/// LargeListType is like ListType but with 64-bit rather than 32-bit offsets. +class ARROW_EXPORT LargeListType : public BaseListType { + public: + static constexpr Type::type type_id = Type::LARGE_LIST; + using offset_type = int64_t; + + static constexpr const char* type_name() { return "large_list"; } + + // List can contain any other logical value type + explicit LargeListType(std::shared_ptr value_type) + : LargeListType(std::make_shared("item", std::move(value_type))) {} + + explicit LargeListType(std::shared_ptr value_field) : BaseListType(type_id) { + children_ = {std::move(value_field)}; + } + + DataTypeLayout layout() const override { + return DataTypeLayout( + {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))}); + } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "large_list"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Type class for array of list views +class ARROW_EXPORT ListViewType : public BaseListType { + public: + static constexpr Type::type type_id = Type::LIST_VIEW; + using offset_type = int32_t; + + static constexpr const char* type_name() { return "list_view"; } + + // ListView can contain any other logical value type + explicit ListViewType(const std::shared_ptr& value_type) + : ListViewType(std::make_shared("item", value_type)) {} + + explicit ListViewType(const std::shared_ptr& value_field) + : BaseListType(type_id) { + children_ = {value_field}; + } + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), + DataTypeLayout::FixedWidth(sizeof(offset_type)), + DataTypeLayout::FixedWidth(sizeof(offset_type))}); + } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "list_view"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for large list-view data +/// +/// LargeListViewType is like ListViewType but with 64-bit rather than 32-bit offsets and +/// sizes. +class ARROW_EXPORT LargeListViewType : public BaseListType { + public: + static constexpr Type::type type_id = Type::LARGE_LIST_VIEW; + using offset_type = int64_t; + + static constexpr const char* type_name() { return "large_list_view"; } + + // LargeListView can contain any other logical value type + explicit LargeListViewType(const std::shared_ptr& value_type) + : LargeListViewType(std::make_shared("item", value_type)) {} + + explicit LargeListViewType(const std::shared_ptr& value_field) + : BaseListType(type_id) { + children_ = {value_field}; + } + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap(), + DataTypeLayout::FixedWidth(sizeof(offset_type)), + DataTypeLayout::FixedWidth(sizeof(offset_type))}); + } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "large_list_view"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// \brief Concrete type class for map data +/// +/// Map data is nested data where each value is a variable number of +/// key-item pairs. Its physical representation is the same as +/// a list of `{key, item}` structs. +/// +/// Maps can be recursively nested, for example map(utf8, map(utf8, int32)). +class ARROW_EXPORT MapType : public ListType { + public: + static constexpr Type::type type_id = Type::MAP; + + static constexpr const char* type_name() { return "map"; } + + MapType(std::shared_ptr key_type, std::shared_ptr item_type, + bool keys_sorted = false); + + MapType(std::shared_ptr key_type, std::shared_ptr item_field, + bool keys_sorted = false); + + MapType(std::shared_ptr key_field, std::shared_ptr item_field, + bool keys_sorted = false); + + explicit MapType(std::shared_ptr value_field, bool keys_sorted = false); + + // Validating constructor + static Result> Make(std::shared_ptr value_field, + bool keys_sorted = false); + + std::shared_ptr key_field() const { return value_type()->field(0); } + std::shared_ptr key_type() const { return key_field()->type(); } + + std::shared_ptr item_field() const { return value_type()->field(1); } + std::shared_ptr item_type() const { return item_field()->type(); } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "map"; } + + bool keys_sorted() const { return keys_sorted_; } + + private: + std::string ComputeFingerprint() const override; + + bool keys_sorted_; +}; + +/// \brief Concrete type class for fixed size list data +class ARROW_EXPORT FixedSizeListType : public BaseListType { + public: + static constexpr Type::type type_id = Type::FIXED_SIZE_LIST; + // While the individual item size is 32-bit, the overall data size + // (item size * list length) may not fit in a 32-bit int. + using offset_type = int64_t; + + static constexpr const char* type_name() { return "fixed_size_list"; } + + // List can contain any other logical value type + FixedSizeListType(std::shared_ptr value_type, int32_t list_size) + : FixedSizeListType(std::make_shared("item", std::move(value_type)), + list_size) {} + + FixedSizeListType(std::shared_ptr value_field, int32_t list_size) + : BaseListType(type_id), list_size_(list_size) { + children_ = {std::move(value_field)}; + } + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap()}); + } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "fixed_size_list"; } + + int32_t list_size() const { return list_size_; } + + protected: + std::string ComputeFingerprint() const override; + + int32_t list_size_; +}; + +/// \brief Concrete type class for struct data +class ARROW_EXPORT StructType : public NestedType { + public: + static constexpr Type::type type_id = Type::STRUCT; + + static constexpr const char* type_name() { return "struct"; } + + explicit StructType(const FieldVector& fields); + + ~StructType() override; + + DataTypeLayout layout() const override { + return DataTypeLayout({DataTypeLayout::Bitmap()}); + } + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "struct"; } + + /// Returns null if name not found + std::shared_ptr GetFieldByName(const std::string& name) const; + + /// Return all fields having this name + FieldVector GetAllFieldsByName(const std::string& name) const; + + /// Returns -1 if name not found or if there are multiple fields having the + /// same name + int GetFieldIndex(const std::string& name) const; + + /// \brief Return the indices of all fields having this name in sorted order + std::vector GetAllFieldIndices(const std::string& name) const; + + /// \brief Create a new StructType with field added at given index + Result> AddField(int i, + const std::shared_ptr& field) const; + /// \brief Create a new StructType by removing the field at given index + Result> RemoveField(int i) const; + /// \brief Create a new StructType by changing the field at given index + Result> SetField(int i, + const std::shared_ptr& field) const; + + private: + std::string ComputeFingerprint() const override; + + class Impl; + std::unique_ptr impl_; +}; + +/// \brief Base type class for union data +class ARROW_EXPORT UnionType : public NestedType { + public: + static constexpr int8_t kMaxTypeCode = 127; + static constexpr int kInvalidChildId = -1; + + static Result> Make( + const FieldVector& fields, const std::vector& type_codes, + UnionMode::type mode = UnionMode::SPARSE) { + if (mode == UnionMode::SPARSE) { + return sparse_union(fields, type_codes); + } else { + return dense_union(fields, type_codes); + } + } + + DataTypeLayout layout() const override; + + std::string ToString(bool show_metadata = false) const override; + + /// The array of logical type ids. + /// + /// For example, the first type in the union might be denoted by the id 5 + /// (instead of 0). + const std::vector& type_codes() const { return type_codes_; } + + /// An array mapping logical type ids to physical child ids. + const std::vector& child_ids() const { return child_ids_; } + + uint8_t max_type_code() const; + + UnionMode::type mode() const; + + protected: + UnionType(FieldVector fields, std::vector type_codes, Type::type id); + + static Status ValidateParameters(const FieldVector& fields, + const std::vector& type_codes, + UnionMode::type mode); + + private: + std::string ComputeFingerprint() const override; + + std::vector type_codes_; + std::vector child_ids_; +}; + +/// \brief Concrete type class for sparse union data +/// +/// A sparse union is a nested type where each logical value is taken from +/// a single child. A buffer of 8-bit type ids indicates which child +/// a given logical value is to be taken from. +/// +/// In a sparse union, each child array should have the same length as the +/// union array, regardless of the actual number of union values that +/// refer to it. +/// +/// Note that, unlike most other types, unions don't have a top-level validity bitmap. +class ARROW_EXPORT SparseUnionType : public UnionType { + public: + static constexpr Type::type type_id = Type::SPARSE_UNION; + + static constexpr const char* type_name() { return "sparse_union"; } + + SparseUnionType(FieldVector fields, std::vector type_codes); + + // A constructor variant that validates input parameters + static Result> Make(FieldVector fields, + std::vector type_codes); + + std::string name() const override { return "sparse_union"; } +}; + +/// \brief Concrete type class for dense union data +/// +/// A dense union is a nested type where each logical value is taken from +/// a single child, at a specific offset. A buffer of 8-bit type ids +/// indicates which child a given logical value is to be taken from, +/// and a buffer of 32-bit offsets indicates at which physical position +/// in the given child array the logical value is to be taken from. +/// +/// Unlike a sparse union, a dense union allows encoding only the child array +/// values which are actually referred to by the union array. This is +/// counterbalanced by the additional footprint of the offsets buffer, and +/// the additional indirection cost when looking up values. +/// +/// Note that, unlike most other types, unions don't have a top-level validity bitmap. +class ARROW_EXPORT DenseUnionType : public UnionType { + public: + static constexpr Type::type type_id = Type::DENSE_UNION; + + static constexpr const char* type_name() { return "dense_union"; } + + DenseUnionType(FieldVector fields, std::vector type_codes); + + // A constructor variant that validates input parameters + static Result> Make(FieldVector fields, + std::vector type_codes); + + std::string name() const override { return "dense_union"; } +}; + +/// \brief Type class for run-end encoded data +class ARROW_EXPORT RunEndEncodedType : public NestedType { + public: + static constexpr Type::type type_id = Type::RUN_END_ENCODED; + + static constexpr const char* type_name() { return "run_end_encoded"; } + + explicit RunEndEncodedType(std::shared_ptr run_end_type, + std::shared_ptr value_type); + ~RunEndEncodedType() override; + + DataTypeLayout layout() const override { + // A lot of existing code expects at least one buffer + return DataTypeLayout({DataTypeLayout::AlwaysNull()}); + } + + const std::shared_ptr& run_end_type() const { return fields()[0]->type(); } + const std::shared_ptr& value_type() const { return fields()[1]->type(); } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "run_end_encoded"; } + + static bool RunEndTypeValid(const DataType& run_end_type); + + private: + std::string ComputeFingerprint() const override; +}; + +/// @} + +// ---------------------------------------------------------------------- +// Date and time types + +/// \addtogroup temporal-datatypes +/// +/// @{ + +/// \brief Base type for all date and time types +class ARROW_EXPORT TemporalType : public FixedWidthType { + public: + using FixedWidthType::FixedWidthType; + // This is only for preventing defining this class in each + // translation unit to avoid one-definition-rule violation. + ~TemporalType() override; + + DataTypeLayout layout() const override { + return DataTypeLayout( + {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(bit_width() / 8)}); + } +}; + +/// \brief Base type class for date data +class ARROW_EXPORT DateType : public TemporalType { + public: + virtual DateUnit unit() const = 0; + + protected: + explicit DateType(Type::type type_id); +}; + +/// Concrete type class for 32-bit date data (as number of days since UNIX epoch) +class ARROW_EXPORT Date32Type : public DateType { + public: + static constexpr Type::type type_id = Type::DATE32; + static constexpr DateUnit UNIT = DateUnit::DAY; + using c_type = int32_t; + using PhysicalType = Int32Type; + + static constexpr const char* type_name() { return "date32"; } + + Date32Type(); + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "date32"; } + DateUnit unit() const override { return UNIT; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for 64-bit date data (as number of milliseconds since UNIX epoch) +class ARROW_EXPORT Date64Type : public DateType { + public: + static constexpr Type::type type_id = Type::DATE64; + static constexpr DateUnit UNIT = DateUnit::MILLI; + using c_type = int64_t; + using PhysicalType = Int64Type; + + static constexpr const char* type_name() { return "date64"; } + + Date64Type(); + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "date64"; } + DateUnit unit() const override { return UNIT; } + + protected: + std::string ComputeFingerprint() const override; +}; + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, TimeUnit::type unit); + +/// Base type class for time data +class ARROW_EXPORT TimeType : public TemporalType, public ParametricType { + public: + TimeUnit::type unit() const { return unit_; } + + protected: + TimeType(Type::type type_id, TimeUnit::type unit); + std::string ComputeFingerprint() const override; + + TimeUnit::type unit_; +}; + +/// Concrete type class for 32-bit time data (as number of seconds or milliseconds +/// since midnight) +class ARROW_EXPORT Time32Type : public TimeType { + public: + static constexpr Type::type type_id = Type::TIME32; + using c_type = int32_t; + using PhysicalType = Int32Type; + + static constexpr const char* type_name() { return "time32"; } + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + explicit Time32Type(TimeUnit::type unit = TimeUnit::MILLI); + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "time32"; } +}; + +/// Concrete type class for 64-bit time data (as number of microseconds or nanoseconds +/// since midnight) +class ARROW_EXPORT Time64Type : public TimeType { + public: + static constexpr Type::type type_id = Type::TIME64; + using c_type = int64_t; + using PhysicalType = Int64Type; + + static constexpr const char* type_name() { return "time64"; } + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + explicit Time64Type(TimeUnit::type unit = TimeUnit::NANO); + + std::string ToString(bool show_metadata = false) const override; + + std::string name() const override { return "time64"; } +}; + +/// \brief Concrete type class for datetime data (as number of seconds, milliseconds, +/// microseconds or nanoseconds since UNIX epoch) +/// +/// If supplied, the timezone string should take either the form (i) "Area/Location", +/// with values drawn from the names in the IANA Time Zone Database (such as +/// "Europe/Zurich"); or (ii) "(+|-)HH:MM" indicating an absolute offset from GMT +/// (such as "-08:00"). To indicate a native UTC timestamp, one of the strings "UTC", +/// "Etc/UTC" or "+00:00" should be used. +/// +/// If any non-empty string is supplied as the timezone for a TimestampType, then the +/// Arrow field containing that timestamp type (and by extension the column associated +/// with such a field) is considered "timezone-aware". The integer arrays that comprise +/// a timezone-aware column must contain UTC normalized datetime values, regardless of +/// the contents of their timezone string. More precisely, (i) the producer of a +/// timezone-aware column must populate its constituent arrays with valid UTC values +/// (performing offset conversions from non-UTC values if necessary); and (ii) the +/// consumer of a timezone-aware column may assume that the column's values are directly +/// comparable (that is, with no offset adjustment required) to the values of any other +/// timezone-aware column or to any other valid UTC datetime value (provided all values +/// are expressed in the same units). +/// +/// If a TimestampType is constructed without a timezone (or, equivalently, if the +/// timezone supplied is an empty string) then the resulting Arrow field (column) is +/// considered "timezone-naive". The producer of a timezone-naive column may populate +/// its constituent integer arrays with datetime values from any timezone; the consumer +/// of a timezone-naive column should make no assumptions about the interoperability or +/// comparability of the values of such a column with those of any other timestamp +/// column or datetime value. +/// +/// If a timezone-aware field contains a recognized timezone, its values may be +/// localized to that locale upon display; the values of timezone-naive fields must +/// always be displayed "as is", with no localization performed on them. +class ARROW_EXPORT TimestampType : public TemporalType, public ParametricType { + public: + using Unit = TimeUnit; + + static constexpr Type::type type_id = Type::TIMESTAMP; + using c_type = int64_t; + using PhysicalType = Int64Type; + + static constexpr const char* type_name() { return "timestamp"; } + + int bit_width() const override { return static_cast(sizeof(int64_t) * CHAR_BIT); } + + explicit TimestampType(TimeUnit::type unit = TimeUnit::MILLI) + : TemporalType(Type::TIMESTAMP), unit_(unit) {} + + explicit TimestampType(TimeUnit::type unit, const std::string& timezone) + : TemporalType(Type::TIMESTAMP), unit_(unit), timezone_(timezone) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "timestamp"; } + + TimeUnit::type unit() const { return unit_; } + const std::string& timezone() const { return timezone_; } + + protected: + std::string ComputeFingerprint() const override; + + private: + TimeUnit::type unit_; + std::string timezone_; +}; + +// Base class for the different kinds of calendar intervals. +class ARROW_EXPORT IntervalType : public TemporalType, public ParametricType { + public: + enum type { MONTHS, DAY_TIME, MONTH_DAY_NANO }; + + virtual type interval_type() const = 0; + + protected: + explicit IntervalType(Type::type subtype) : TemporalType(subtype) {} + std::string ComputeFingerprint() const override; +}; + +/// \brief Represents a number of months. +/// +/// Type representing a number of months. Corresponds to YearMonth type +/// in Schema.fbs (years are defined as 12 months). +class ARROW_EXPORT MonthIntervalType : public IntervalType { + public: + static constexpr Type::type type_id = Type::INTERVAL_MONTHS; + using c_type = int32_t; + using PhysicalType = Int32Type; + + static constexpr const char* type_name() { return "month_interval"; } + + IntervalType::type interval_type() const override { return IntervalType::MONTHS; } + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + MonthIntervalType() : IntervalType(type_id) {} + + std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { + return name(); + } + std::string name() const override { return "month_interval"; } +}; + +/// \brief Represents a number of days and milliseconds (fraction of day). +class ARROW_EXPORT DayTimeIntervalType : public IntervalType { + public: + struct DayMilliseconds { + int32_t days = 0; + int32_t milliseconds = 0; + constexpr DayMilliseconds() = default; + constexpr DayMilliseconds(int32_t days, int32_t milliseconds) + : days(days), milliseconds(milliseconds) {} + bool operator==(DayMilliseconds other) const { + return this->days == other.days && this->milliseconds == other.milliseconds; + } + bool operator!=(DayMilliseconds other) const { return !(*this == other); } + bool operator<(DayMilliseconds other) const { + return this->days < other.days || this->milliseconds < other.milliseconds; + } + }; + using c_type = DayMilliseconds; + using PhysicalType = DayTimeIntervalType; + + static_assert(sizeof(DayMilliseconds) == 8, + "DayMilliseconds struct assumed to be of size 8 bytes"); + static constexpr Type::type type_id = Type::INTERVAL_DAY_TIME; + + static constexpr const char* type_name() { return "day_time_interval"; } + + IntervalType::type interval_type() const override { return IntervalType::DAY_TIME; } + + DayTimeIntervalType() : IntervalType(type_id) {} + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { + return name(); + } + std::string name() const override { return "day_time_interval"; } +}; + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, DayTimeIntervalType::DayMilliseconds interval); + +/// \brief Represents a number of months, days and nanoseconds between +/// two dates. +/// +/// All fields are independent from one another. +class ARROW_EXPORT MonthDayNanoIntervalType : public IntervalType { + public: + struct MonthDayNanos { + int32_t months; + int32_t days; + int64_t nanoseconds; + bool operator==(MonthDayNanos other) const { + return this->months == other.months && this->days == other.days && + this->nanoseconds == other.nanoseconds; + } + bool operator!=(MonthDayNanos other) const { return !(*this == other); } + }; + using c_type = MonthDayNanos; + using PhysicalType = MonthDayNanoIntervalType; + + static_assert(sizeof(MonthDayNanos) == 16, + "MonthDayNanos struct assumed to be of size 16 bytes"); + static constexpr Type::type type_id = Type::INTERVAL_MONTH_DAY_NANO; + + static constexpr const char* type_name() { return "month_day_nano_interval"; } + + IntervalType::type interval_type() const override { + return IntervalType::MONTH_DAY_NANO; + } + + MonthDayNanoIntervalType() : IntervalType(type_id) {} + + int bit_width() const override { return static_cast(sizeof(c_type) * CHAR_BIT); } + + std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { + return name(); + } + std::string name() const override { return "month_day_nano_interval"; } +}; + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, + MonthDayNanoIntervalType::MonthDayNanos interval); + +/// \brief Represents an elapsed time without any relation to a calendar artifact. +class ARROW_EXPORT DurationType : public TemporalType, public ParametricType { + public: + using Unit = TimeUnit; + + static constexpr Type::type type_id = Type::DURATION; + using c_type = int64_t; + using PhysicalType = Int64Type; + + static constexpr const char* type_name() { return "duration"; } + + int bit_width() const override { return static_cast(sizeof(int64_t) * CHAR_BIT); } + + explicit DurationType(TimeUnit::type unit = TimeUnit::MILLI) + : TemporalType(Type::DURATION), unit_(unit) {} + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "duration"; } + + TimeUnit::type unit() const { return unit_; } + + protected: + std::string ComputeFingerprint() const override; + + private: + TimeUnit::type unit_; +}; + +/// @} + +// ---------------------------------------------------------------------- +// Dictionary type (for representing categorical or dictionary-encoded +// in memory) + +/// \brief Dictionary-encoded value type with data-dependent +/// dictionary. Indices are represented by any integer types. +class ARROW_EXPORT DictionaryType : public FixedWidthType { + public: + static constexpr Type::type type_id = Type::DICTIONARY; + + static constexpr const char* type_name() { return "dictionary"; } + + DictionaryType(const std::shared_ptr& index_type, + const std::shared_ptr& value_type, bool ordered = false); + + // A constructor variant that validates its input parameters + static Result> Make( + const std::shared_ptr& index_type, + const std::shared_ptr& value_type, bool ordered = false); + + std::string ToString(bool show_metadata = false) const override; + std::string name() const override { return "dictionary"; } + + int bit_width() const override; + + DataTypeLayout layout() const override; + + const std::shared_ptr& index_type() const { return index_type_; } + const std::shared_ptr& value_type() const { return value_type_; } + + bool ordered() const { return ordered_; } + + protected: + static Status ValidateParameters(const DataType& index_type, + const DataType& value_type); + + std::string ComputeFingerprint() const override; + + // Must be an integer type (not currently checked) + std::shared_ptr index_type_; + std::shared_ptr value_type_; + bool ordered_; +}; + +// ---------------------------------------------------------------------- +// FieldRef + +/// \class FieldPath +/// +/// Represents a path to a nested field using indices of child fields. +/// For example, given indices {5, 9, 3} the field would be retrieved with +/// schema->field(5)->type()->field(9)->type()->field(3) +/// +/// Attempting to retrieve a child field using a FieldPath which is not valid for +/// a given schema will raise an error. Invalid FieldPaths include: +/// - an index is out of range +/// - the path is empty (note: a default constructed FieldPath will be empty) +/// +/// FieldPaths provide a number of accessors for drilling down to potentially nested +/// children. They are overloaded for convenience to support Schema (returns a field), +/// DataType (returns a child field), Field (returns a child field of this field's type) +/// Array (returns a child array), RecordBatch (returns a column). +class ARROW_EXPORT FieldPath { + public: + FieldPath() = default; + + FieldPath(std::vector indices) // NOLINT runtime/explicit + : indices_(std::move(indices)) {} + + FieldPath(std::initializer_list indices) // NOLINT runtime/explicit + : indices_(std::move(indices)) {} + + std::string ToString() const; + + size_t hash() const; + struct Hash { + size_t operator()(const FieldPath& path) const { return path.hash(); } + }; + + bool empty() const { return indices_.empty(); } + bool operator==(const FieldPath& other) const { return indices() == other.indices(); } + bool operator!=(const FieldPath& other) const { return indices() != other.indices(); } + + const std::vector& indices() const { return indices_; } + int operator[](size_t i) const { return indices_[i]; } + std::vector::const_iterator begin() const { return indices_.begin(); } + std::vector::const_iterator end() const { return indices_.end(); } + + /// \brief Retrieve the referenced child Field from a Schema, Field, or DataType + Result> Get(const Schema& schema) const; + Result> Get(const Field& field) const; + Result> Get(const DataType& type) const; + Result> Get(const FieldVector& fields) const; + + static Result> GetAll(const Schema& schema, + const std::vector& paths); + + /// \brief Retrieve the referenced column from a RecordBatch or Table + Result> Get(const RecordBatch& batch) const; + Result> Get(const Table& table) const; + + /// \brief Retrieve the referenced child from an Array or ArrayData + Result> Get(const Array& array) const; + Result> Get(const ArrayData& data) const; + + /// \brief Retrieve the referenced child from a ChunkedArray + Result> Get(const ChunkedArray& chunked_array) const; + + /// \brief Retrieve the referenced child/column from an Array, ArrayData, ChunkedArray, + /// RecordBatch, or Table + /// + /// Unlike `FieldPath::Get`, these variants are not zero-copy and the retrieved child's + /// null bitmap is ANDed with its ancestors' + Result> GetFlattened(const Array& array, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const ArrayData& data, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const ChunkedArray& chunked_array, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const RecordBatch& batch, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const Table& table, + MemoryPool* pool = NULLPTR) const; + + private: + std::vector indices_; +}; + +/// \class FieldRef +/// \brief Descriptor of a (potentially nested) field within a schema. +/// +/// Unlike FieldPath (which exclusively uses indices of child fields), FieldRef may +/// reference a field by name. It is intended to replace parameters like `int field_index` +/// and `const std::string& field_name`; it can be implicitly constructed from either a +/// field index or a name. +/// +/// Nested fields can be referenced as well. Given +/// schema({field("a", struct_({field("n", null())})), field("b", int32())}) +/// +/// the following all indicate the nested field named "n": +/// FieldRef ref1(0, 0); +/// FieldRef ref2("a", 0); +/// FieldRef ref3("a", "n"); +/// FieldRef ref4(0, "n"); +/// ARROW_ASSIGN_OR_RAISE(FieldRef ref5, +/// FieldRef::FromDotPath(".a[0]")); +/// +/// FieldPaths matching a FieldRef are retrieved using the member function FindAll. +/// Multiple matches are possible because field names may be duplicated within a schema. +/// For example: +/// Schema a_is_ambiguous({field("a", int32()), field("a", float32())}); +/// auto matches = FieldRef("a").FindAll(a_is_ambiguous); +/// assert(matches.size() == 2); +/// assert(matches[0].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(0))); +/// assert(matches[1].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(1))); +/// +/// Convenience accessors are available which raise a helpful error if the field is not +/// found or ambiguous, and for immediately calling FieldPath::Get to retrieve any +/// matching children: +/// auto maybe_match = FieldRef("struct", "field_i32").FindOneOrNone(schema); +/// auto maybe_column = FieldRef("struct", "field_i32").GetOne(some_table); +class ARROW_EXPORT FieldRef : public util::EqualityComparable { + public: + FieldRef() = default; + + /// Construct a FieldRef using a string of indices. The reference will be retrieved as: + /// schema.fields[self.indices[0]].type.fields[self.indices[1]] ... + /// + /// Empty indices are not valid. + FieldRef(FieldPath indices); // NOLINT runtime/explicit + + /// Construct a by-name FieldRef. Multiple fields may match a by-name FieldRef: + /// [f for f in schema.fields where f.name == self.name] + FieldRef(std::string name) : impl_(std::move(name)) {} // NOLINT runtime/explicit + FieldRef(const char* name) : impl_(std::string(name)) {} // NOLINT runtime/explicit + + /// Equivalent to a single index string of indices. + FieldRef(int index) : impl_(FieldPath({index})) {} // NOLINT runtime/explicit + + /// Construct a nested FieldRef. + explicit FieldRef(std::vector refs) { Flatten(std::move(refs)); } + + /// Convenience constructor for nested FieldRefs: each argument will be used to + /// construct a FieldRef + template + FieldRef(A0&& a0, A1&& a1, A&&... a) { + Flatten({// cpplint thinks the following are constructor decls + FieldRef(std::forward(a0)), // NOLINT runtime/explicit + FieldRef(std::forward(a1)), // NOLINT runtime/explicit + FieldRef(std::forward(a))...}); // NOLINT runtime/explicit + } + + /// Parse a dot path into a FieldRef. + /// + /// dot_path = '.' name + /// | '[' digit+ ']' + /// | dot_path+ + /// + /// Examples: + /// ".alpha" => FieldRef("alpha") + /// "[2]" => FieldRef(2) + /// ".beta[3]" => FieldRef("beta", 3) + /// "[5].gamma.delta[7]" => FieldRef(5, "gamma", "delta", 7) + /// ".hello world" => FieldRef("hello world") + /// R"(.\[y\]\\tho\.\)" => FieldRef(R"([y]\tho.\)") + /// + /// Note: When parsing a name, a '\' preceding any other character will be dropped from + /// the resulting name. Therefore if a name must contain the characters '.', '\', or '[' + /// those must be escaped with a preceding '\'. + static Result FromDotPath(const std::string& dot_path); + std::string ToDotPath() const; + + bool Equals(const FieldRef& other) const { return impl_ == other.impl_; } + + std::string ToString() const; + + size_t hash() const; + struct Hash { + size_t operator()(const FieldRef& ref) const { return ref.hash(); } + }; + + explicit operator bool() const { return Equals(FieldPath{}); } + bool operator!() const { return !Equals(FieldPath{}); } + + bool IsFieldPath() const { return std::holds_alternative(impl_); } + bool IsName() const { return std::holds_alternative(impl_); } + bool IsNested() const { + if (IsName()) return false; + if (IsFieldPath()) return std::get(impl_).indices().size() > 1; + return true; + } + + /// \brief Return true if this ref is a name or a nested sequence of only names + /// + /// Useful for determining if iteration is possible without recursion or inner loops + bool IsNameSequence() const { + if (IsName()) return true; + if (const auto* nested = nested_refs()) { + for (const auto& ref : *nested) { + if (!ref.IsName()) return false; + } + return !nested->empty(); + } + return false; + } + + const FieldPath* field_path() const { + return IsFieldPath() ? &std::get(impl_) : NULLPTR; + } + const std::string* name() const { + return IsName() ? &std::get(impl_) : NULLPTR; + } + const std::vector* nested_refs() const { + return std::holds_alternative>(impl_) + ? &std::get>(impl_) + : NULLPTR; + } + + /// \brief Retrieve FieldPath of every child field which matches this FieldRef. + std::vector FindAll(const Schema& schema) const; + std::vector FindAll(const Field& field) const; + std::vector FindAll(const DataType& type) const; + std::vector FindAll(const FieldVector& fields) const; + + /// \brief Convenience function which applies FindAll to arg's type or schema. + std::vector FindAll(const ArrayData& array) const; + std::vector FindAll(const Array& array) const; + std::vector FindAll(const ChunkedArray& chunked_array) const; + std::vector FindAll(const RecordBatch& batch) const; + std::vector FindAll(const Table& table) const; + + /// \brief Convenience function: raise an error if matches is empty. + template + Status CheckNonEmpty(const std::vector& matches, const T& root) const { + if (matches.empty()) { + return Status::Invalid("No match for ", ToString(), " in ", root.ToString()); + } + return Status::OK(); + } + + /// \brief Convenience function: raise an error if matches contains multiple FieldPaths. + template + Status CheckNonMultiple(const std::vector& matches, const T& root) const { + if (matches.size() > 1) { + return Status::Invalid("Multiple matches for ", ToString(), " in ", + root.ToString()); + } + return Status::OK(); + } + + /// \brief Retrieve FieldPath of a single child field which matches this + /// FieldRef. Emit an error if none or multiple match. + template + Result FindOne(const T& root) const { + auto matches = FindAll(root); + ARROW_RETURN_NOT_OK(CheckNonEmpty(matches, root)); + ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root)); + return std::move(matches[0]); + } + + /// \brief Retrieve FieldPath of a single child field which matches this + /// FieldRef. Emit an error if multiple match. An empty (invalid) FieldPath + /// will be returned if none match. + template + Result FindOneOrNone(const T& root) const { + auto matches = FindAll(root); + ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root)); + if (matches.empty()) { + return FieldPath(); + } + return std::move(matches[0]); + } + + template + using GetType = decltype(std::declval().Get(std::declval()).ValueOrDie()); + + /// \brief Get all children matching this FieldRef. + template + std::vector> GetAll(const T& root) const { + std::vector> out; + for (const auto& match : FindAll(root)) { + out.push_back(match.Get(root).ValueOrDie()); + } + return out; + } + /// \brief Get all children matching this FieldRef. + /// + /// Unlike `FieldRef::GetAll`, this variant is not zero-copy and the retrieved + /// children's null bitmaps are ANDed with their ancestors' + template + Result>> GetAllFlattened(const T& root, + MemoryPool* pool = NULLPTR) const { + std::vector> out; + for (const auto& match : FindAll(root)) { + ARROW_ASSIGN_OR_RAISE(auto child, match.GetFlattened(root, pool)); + out.push_back(std::move(child)); + } + return out; + } + + /// \brief Get the single child matching this FieldRef. + /// Emit an error if none or multiple match. + template + Result> GetOne(const T& root) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root)); + return match.Get(root).ValueOrDie(); + } + /// \brief Get the single child matching this FieldRef. + /// + /// Unlike `FieldRef::GetOne`, this variant is not zero-copy and the retrieved + /// child's null bitmap is ANDed with its ancestors' + template + Result> GetOneFlattened(const T& root, MemoryPool* pool = NULLPTR) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root)); + return match.GetFlattened(root, pool); + } + + /// \brief Get the single child matching this FieldRef. + /// Return nullptr if none match, emit an error if multiple match. + template + Result> GetOneOrNone(const T& root) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); + if (match.empty()) { + return static_cast>(NULLPTR); + } + return match.Get(root).ValueOrDie(); + } + /// \brief Get the single child matching this FieldRef. + /// + /// Return nullptr if none match, emit an error if multiple match. + /// Unlike `FieldRef::GetOneOrNone`, this variant is not zero-copy and the + /// retrieved child's null bitmap is ANDed with its ancestors' + template + Result> GetOneOrNoneFlattened(const T& root, + MemoryPool* pool = NULLPTR) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); + if (match.empty()) { + return static_cast>(NULLPTR); + } + return match.GetFlattened(root, pool); + } + + private: + void Flatten(std::vector children); + + std::variant> impl_; +}; + +ARROW_EXPORT void PrintTo(const FieldRef& ref, std::ostream* os); + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, const FieldRef&); + +// ---------------------------------------------------------------------- +// Schema + +enum class Endianness { + Little = 0, + Big = 1, +#if ARROW_LITTLE_ENDIAN + Native = Little +#else + Native = Big +#endif +}; + +/// \class Schema +/// \brief Sequence of arrow::Field objects describing the columns of a record +/// batch or table data structure +class ARROW_EXPORT Schema : public detail::Fingerprintable, + public util::EqualityComparable, + public util::ToStringOstreamable { + public: + explicit Schema(FieldVector fields, Endianness endianness, + std::shared_ptr metadata = NULLPTR); + + explicit Schema(FieldVector fields, + std::shared_ptr metadata = NULLPTR); + + Schema(const Schema&); + + ~Schema() override; + + /// Returns true if all of the schema fields are equal + bool Equals(const Schema& other, bool check_metadata = false) const; + bool Equals(const std::shared_ptr& other, bool check_metadata = false) const; + + /// \brief Set endianness in the schema + /// + /// \return new Schema + std::shared_ptr WithEndianness(Endianness endianness) const; + + /// \brief Return endianness in the schema + Endianness endianness() const; + + /// \brief Indicate if endianness is equal to platform-native endianness + bool is_native_endian() const; + + /// \brief Return the number of fields (columns) in the schema + int num_fields() const; + + /// Return the ith schema element. Does not boundscheck + const std::shared_ptr& field(int i) const; + + const FieldVector& fields() const; + + std::vector field_names() const; + + /// Returns null if name not found + std::shared_ptr GetFieldByName(const std::string& name) const; + + /// \brief Return the indices of all fields having this name in sorted order + FieldVector GetAllFieldsByName(const std::string& name) const; + + /// Returns -1 if name not found + int GetFieldIndex(const std::string& name) const; + + /// Return the indices of all fields having this name + std::vector GetAllFieldIndices(const std::string& name) const; + + /// Indicate if field named `name` can be found unambiguously in the schema. + Status CanReferenceFieldByName(const std::string& name) const; + + /// Indicate if fields named `names` can be found unambiguously in the schema. + Status CanReferenceFieldsByNames(const std::vector& names) const; + + /// \brief The custom key-value metadata, if any + /// + /// \return metadata may be null + const std::shared_ptr& metadata() const; + + /// \brief Render a string representation of the schema suitable for debugging + /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty, + /// print keys and values in the output + std::string ToString(bool show_metadata = false) const; + + Result> AddField(int i, + const std::shared_ptr& field) const; + Result> RemoveField(int i) const; + Result> SetField(int i, + const std::shared_ptr& field) const; + + /// \brief Replace field names with new names + /// + /// \param[in] names new names + /// \return new Schema + Result> WithNames(const std::vector& names) const; + + /// \brief Replace key-value metadata with new metadata + /// + /// \param[in] metadata new KeyValueMetadata + /// \return new Schema + std::shared_ptr WithMetadata( + const std::shared_ptr& metadata) const; + + /// \brief Return copy of Schema without the KeyValueMetadata + std::shared_ptr RemoveMetadata() const; + + /// \brief Indicate that the Schema has non-empty KevValueMetadata + bool HasMetadata() const; + + /// \brief Indicate that the Schema has distinct field names. + bool HasDistinctFieldNames() const; + + protected: + std::string ComputeFingerprint() const override; + std::string ComputeMetadataFingerprint() const override; + + private: + class Impl; + std::unique_ptr impl_; +}; + +ARROW_EXPORT void PrintTo(const Schema& s, std::ostream* os); + +ARROW_EXPORT +std::string EndiannessToString(Endianness endianness); + +// ---------------------------------------------------------------------- + +/// \brief Convenience class to incrementally construct/merge schemas. +/// +/// This class amortizes the cost of validating field name conflicts by +/// maintaining the mapping. The caller also controls the conflict resolution +/// scheme. +class ARROW_EXPORT SchemaBuilder { + public: + // Indicate how field conflict(s) should be resolved when building a schema. A + // conflict arise when a field is added to the builder and one or more field(s) + // with the same name already exists. + enum ConflictPolicy { + // Ignore the conflict and append the field. This is the default behavior of the + // Schema constructor and the `arrow::schema` factory function. + CONFLICT_APPEND = 0, + // Keep the existing field and ignore the newer one. + CONFLICT_IGNORE, + // Replace the existing field with the newer one. + CONFLICT_REPLACE, + // Merge the fields. The merging behavior can be controlled by `Field::MergeOptions` + // specified at construction time. Also see documentation of `Field::MergeWith`. + CONFLICT_MERGE, + // Refuse the new field and error out. + CONFLICT_ERROR + }; + + /// \brief Construct an empty SchemaBuilder + /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. + SchemaBuilder( + ConflictPolicy conflict_policy = CONFLICT_APPEND, + Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); + /// \brief Construct a SchemaBuilder from a list of fields + /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. + SchemaBuilder( + FieldVector fields, ConflictPolicy conflict_policy = CONFLICT_APPEND, + Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); + /// \brief Construct a SchemaBuilder from a schema, preserving the metadata + /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. + SchemaBuilder( + const std::shared_ptr& schema, + ConflictPolicy conflict_policy = CONFLICT_APPEND, + Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); + + /// \brief Return the conflict resolution method. + ConflictPolicy policy() const; + + /// \brief Set the conflict resolution method. + void SetPolicy(ConflictPolicy resolution); + + /// \brief Add a field to the constructed schema. + /// + /// \param[in] field to add to the constructed Schema. + /// \return A failure if encountered. + Status AddField(const std::shared_ptr& field); + + /// \brief Add multiple fields to the constructed schema. + /// + /// \param[in] fields to add to the constructed Schema. + /// \return The first failure encountered, if any. + Status AddFields(const FieldVector& fields); + + /// \brief Add fields of a Schema to the constructed Schema. + /// + /// \param[in] schema to take fields to add to the constructed Schema. + /// \return The first failure encountered, if any. + Status AddSchema(const std::shared_ptr& schema); + + /// \brief Add fields of multiple Schemas to the constructed Schema. + /// + /// \param[in] schemas to take fields to add to the constructed Schema. + /// \return The first failure encountered, if any. + Status AddSchemas(const std::vector>& schemas); + + Status AddMetadata(const KeyValueMetadata& metadata); + + /// \brief Return the constructed Schema. + /// + /// The builder internal state is not affected by invoking this method, i.e. + /// a single builder can yield multiple incrementally constructed schemas. + /// + /// \return the constructed schema. + Result> Finish() const; + + /// \brief Merge schemas in a unified schema according to policy. + static Result> Merge( + const std::vector>& schemas, + ConflictPolicy policy = CONFLICT_MERGE); + + /// \brief Indicate if schemas are compatible to merge according to policy. + static Status AreCompatible(const std::vector>& schemas, + ConflictPolicy policy = CONFLICT_MERGE); + + /// \brief Reset internal state with an empty schema (and metadata). + void Reset(); + + ~SchemaBuilder(); + + private: + class Impl; + std::unique_ptr impl_; + + Status AppendField(const std::shared_ptr& field); +}; + +/// \brief Unifies schemas by merging fields by name. +/// +/// The behavior of field merging can be controlled via `Field::MergeOptions`. +/// +/// The resulting schema will contain the union of fields from all schemas. +/// Fields with the same name will be merged. See `Field::MergeOptions`. +/// - They are expected to be mergeable under provided `field_merge_options`. +/// - The unified field will inherit the metadata from the schema where +/// that field is first defined. +/// - The first N fields in the schema will be ordered the same as the +/// N fields in the first schema. +/// The resulting schema will inherit its metadata from the first input schema. +/// Returns an error if: +/// - Any input schema contains fields with duplicate names. +/// - Fields of the same name are not mergeable. +ARROW_EXPORT +Result> UnifySchemas( + const std::vector>& schemas, + Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); + +namespace internal { + +constexpr bool may_have_validity_bitmap(Type::type id) { + switch (id) { + case Type::NA: + case Type::DENSE_UNION: + case Type::SPARSE_UNION: + case Type::RUN_END_ENCODED: + return false; + default: + return true; + } +} + +ARROW_DEPRECATED("Deprecated in 17.0.0. Use may_have_validity_bitmap() instead.") +constexpr bool HasValidityBitmap(Type::type id) { return may_have_validity_bitmap(id); } + +ARROW_EXPORT +std::string ToString(Type::type id); + +ARROW_EXPORT +std::string ToTypeName(Type::type id); + +ARROW_EXPORT +std::string ToString(TimeUnit::type unit); + +} // namespace internal + +// Helpers to get instances of data types based on general categories + +/// \brief Signed integer types +ARROW_EXPORT +const std::vector>& SignedIntTypes(); +/// \brief Unsigned integer types +ARROW_EXPORT +const std::vector>& UnsignedIntTypes(); +/// \brief Signed and unsigned integer types +ARROW_EXPORT +const std::vector>& IntTypes(); +/// \brief Floating point types +ARROW_EXPORT +const std::vector>& FloatingPointTypes(); +/// \brief Number types without boolean - integer and floating point types +ARROW_EXPORT +const std::vector>& NumericTypes(); +/// \brief Binary and string-like types (except fixed-size binary) +ARROW_EXPORT +const std::vector>& BaseBinaryTypes(); +/// \brief Binary and large-binary types +ARROW_EXPORT +const std::vector>& BinaryTypes(); +/// \brief String and large-string types +ARROW_EXPORT +const std::vector>& StringTypes(); +/// \brief String-view and Binary-view +ARROW_EXPORT +const std::vector>& BinaryViewTypes(); +/// \brief Temporal types including date, time and timestamps for each unit +ARROW_EXPORT +const std::vector>& TemporalTypes(); +/// \brief Interval types +ARROW_EXPORT +const std::vector>& IntervalTypes(); +/// \brief Duration types for each unit +ARROW_EXPORT +const std::vector>& DurationTypes(); +/// \brief Numeric, base binary, date, boolean and null types +ARROW_EXPORT +const std::vector>& PrimitiveTypes(); + +} // namespace arrow diff --git a/shared/package-files/cb/cb19d6ad861c1395cf21910e6d4b492e72a6c2a87218f16032dc112f6e9ad409/rcode.cpython-311.pyc b/shared/package-files/cb/cb19d6ad861c1395cf21910e6d4b492e72a6c2a87218f16032dc112f6e9ad409/rcode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32a8be38b320e5a48c641d6832af654863a83d06 Binary files /dev/null and b/shared/package-files/cb/cb19d6ad861c1395cf21910e6d4b492e72a6c2a87218f16032dc112f6e9ad409/rcode.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb1da0b501e5228cb73e6ee9748850b6b9efb762550586bba2b67c573c6c2ec8/_foreach_atan.h b/shared/package-files/cb/cb1da0b501e5228cb73e6ee9748850b6b9efb762550586bba2b67c573c6c2ec8/_foreach_atan.h new file mode 100644 index 0000000000000000000000000000000000000000..1912f24d96a40badd3d73622766bf30915e7fc8e --- /dev/null +++ b/shared/package-files/cb/cb1da0b501e5228cb73e6ee9748850b6b9efb762550586bba2b67c573c6c2ec8/_foreach_atan.h @@ -0,0 +1,45 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_atan(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_atan(at::TensorList self) { + return at::_ops::_foreach_atan::call(self); +} + +// aten::_foreach_atan_(Tensor(a!)[] self) -> () +inline void _foreach_atan_(at::TensorList self) { + return at::_ops::_foreach_atan_::call(self); +} + +// aten::_foreach_atan.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_atan_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_atan_out::call(self, out); +} +// aten::_foreach_atan.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_atan_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_atan_out::call(self, out); +} + +} diff --git a/shared/package-files/cb/cb1e16d5d4d0b188fe7f5ea4704a6e0efc5ec37d7d76bd5ed92b5647dae1bff9/functions.cpython-311.pyc b/shared/package-files/cb/cb1e16d5d4d0b188fe7f5ea4704a6e0efc5ec37d7d76bd5ed92b5647dae1bff9/functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38617277703b1e957c1ef0906baacc0640f31f40 Binary files /dev/null and b/shared/package-files/cb/cb1e16d5d4d0b188fe7f5ea4704a6e0efc5ec37d7d76bd5ed92b5647dae1bff9/functions.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb1feeb6ba63df2a55304c7fb2f3b23efc1d7955771c1292f6f6a504c69a4875/normalization.h b/shared/package-files/cb/cb1feeb6ba63df2a55304c7fb2f3b23efc1d7955771c1292f6f6a504c69a4875/normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..3df0189890864f4b18eb7ae8321625733a7664e3 --- /dev/null +++ b/shared/package-files/cb/cb1feeb6ba63df2a55304c7fb2f3b23efc1d7955771c1292f6f6a504c69a4875/normalization.h @@ -0,0 +1,207 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::nn::functional { + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace detail { +inline Tensor normalize( + const Tensor& input, + double p, + int64_t dim, + double eps, + std::optional out) { + if (out == std::nullopt) { + auto denom = input.norm(p, dim, true).clamp_min(eps).expand_as(input); + return input / denom; + } else { + auto denom = input.norm(p, dim, true).clamp_min(eps).expand_as(input); + return torch::div_out(*out, input, denom); + } +} +} // namespace detail +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/// See +/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.normalize +/// about the exact behavior of this functional. +/// +/// See the documentation for `torch::nn::functional::NormalizeFuncOptions` +/// class to learn what optional arguments are supported for this functional. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::normalize(input, F::NormalizeFuncOptions().p(1).dim(-1)); +/// ``` +inline Tensor normalize( + const Tensor& input, + NormalizeFuncOptions options = {}) { + return detail::normalize( + input, options.p(), options.dim(), options.eps(), options.out()); +} + +// ============================================================================ + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace detail { +inline Tensor layer_norm( + const Tensor& input, + const std::vector& normalized_shape, + const Tensor& weight, + const Tensor& bias, + double eps) { + return torch::layer_norm(input, normalized_shape, weight, bias, eps); +} +} // namespace detail +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/// See +/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.layer_norm +/// about the exact behavior of this functional. +/// +/// See the documentation for `torch::nn::functional::LayerNormFuncOptions` +/// class to learn what optional arguments are supported for this functional. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::layer_norm(input, F::LayerNormFuncOptions({2, 2}).eps(2e-5)); +/// ``` +inline Tensor layer_norm( + const Tensor& input, + const LayerNormFuncOptions& options) { + return detail::layer_norm( + input, + options.normalized_shape(), + options.weight(), + options.bias(), + options.eps()); +} + +// ============================================================================ + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace detail { +inline Tensor local_response_norm( + const Tensor& input, + int64_t size, + double alpha, + double beta, + double k) { + auto dim = input.dim(); + TORCH_CHECK( + dim >= 3, + "Expected 3D or higher dimensionality input (got ", + dim, + " dimensions)"); + auto div = input.mul(input).unsqueeze(1); + if (dim == 3) { + div = detail::pad( + div, + /*pad=*/{0, 0, size / 2, (size - 1) / 2}, + /*mode=*/torch::kConstant, + /*value=*/0); + div = detail::avg_pool2d( + div, + /*kernel_size=*/{size, 1}, + /*stride=*/1, + /*padding=*/0, + /*ceil_mode=*/false, + /*count_include_pad=*/true, + /*divisor_override=*/std::nullopt) + .squeeze(1); + } else { + auto sizes = input.sizes(); + div = div.view({sizes[0], 1, sizes[1], sizes[2], -1}); + div = detail::pad( + div, + /*pad=*/{0, 0, 0, 0, size / 2, (size - 1) / 2}, + /*mode=*/torch::kConstant, + /*value=*/0); + div = detail::avg_pool3d( + div, + /*kernel_size=*/{size, 1, 1}, + /*stride=*/1, + /*padding=*/0, + /*ceil_mode=*/false, + /*count_include_pad=*/true, + /*divisor_override=*/std::nullopt) + .squeeze(1); + div = div.view(sizes); + } + div = div.mul(alpha).add(k).pow(beta); + return input / div; +} +} // namespace detail +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/// See +/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.local_response_norm +/// about the exact behavior of this functional. +/// +/// See the documentation for +/// `torch::nn::functional::LocalResponseNormFuncOptions` class to learn what +/// optional arguments are supported for this functional. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::local_response_norm(x, F::LocalResponseNormFuncOptions(2)); +/// ``` +inline Tensor local_response_norm( + const Tensor& input, + const LocalResponseNormFuncOptions& options) { + return detail::local_response_norm( + input, options.size(), options.alpha(), options.beta(), options.k()); +} + +// ============================================================================ + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace detail { +inline Tensor group_norm( + const Tensor& input, + int64_t num_groups, + const Tensor& weight, + const Tensor& bias, + double eps) { + return torch::group_norm( + input, + num_groups, + weight, + bias, + eps, + at::globalContext().userEnabledCuDNN()); +} +} // namespace detail +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/// See +/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.group_norm +/// about the exact behavior of this functional. +/// +/// See the documentation for `torch::nn::functional::GroupNormFuncOptions` +/// class to learn what optional arguments are supported for this functional. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::group_norm(input, F::GroupNormFuncOptions(2).eps(2e-5)); +/// ``` +inline Tensor group_norm( + const Tensor& input, + const GroupNormFuncOptions& options) { + return detail::group_norm( + input, + options.num_groups(), + options.weight(), + options.bias(), + options.eps()); +} + +} // namespace torch::nn::functional diff --git a/shared/package-files/cb/cb23fa55864bb73f7e8ed4085dcb6a142ba7ced65fc18515641974e0092cf4b6/test_where.cpython-311.pyc b/shared/package-files/cb/cb23fa55864bb73f7e8ed4085dcb6a142ba7ced65fc18515641974e0092cf4b6/test_where.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b9cf096afcb038a7254187ab70fe07c3c8aca1a Binary files /dev/null and b/shared/package-files/cb/cb23fa55864bb73f7e8ed4085dcb6a142ba7ced65fc18515641974e0092cf4b6/test_where.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb24d65398a2aab8d03289569d413f5d3afe12a90bf42deeb9f4e6edfd2c3027/instancenorm.h b/shared/package-files/cb/cb24d65398a2aab8d03289569d413f5d3afe12a90bf42deeb9f4e6edfd2c3027/instancenorm.h new file mode 100644 index 0000000000000000000000000000000000000000..92f96946503190e6fb075192b45227cf663ee305 --- /dev/null +++ b/shared/package-files/cb/cb24d65398a2aab8d03289569d413f5d3afe12a90bf42deeb9f4e6edfd2c3027/instancenorm.h @@ -0,0 +1,59 @@ +#pragma once + +#include + +namespace torch::nn::functional { + +#ifndef DOXYGEN_SHOULD_SKIP_THIS +namespace detail { +inline Tensor instance_norm( + const Tensor& input, + const Tensor& running_mean, + const Tensor& running_var, + const Tensor& weight, + const Tensor& bias, + bool use_input_stats, + double momentum, + double eps) { + return torch::instance_norm( + input, + weight, + bias, + running_mean, + running_var, + use_input_stats, + momentum, + eps, + at::globalContext().userEnabledCuDNN()); +} +} // namespace detail +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/// See +/// https://pytorch.org/docs/main/nn.functional.html#torch.nn.functional.instance_norm +/// about the exact behavior of this functional. +/// +/// See the documentation for `torch::nn::functional::InstanceNormFuncOptions` +/// class to learn what optional arguments are supported for this functional. +/// +/// Example: +/// ``` +/// namespace F = torch::nn::functional; +/// F::instance_norm(input, +/// F::InstanceNormFuncOptions().running_mean(mean).running_var(variance).weight(weight).bias(bias).momentum(0.1).eps(1e-5)); +/// ``` +inline Tensor instance_norm( + const Tensor& input, + const InstanceNormFuncOptions& options = {}) { + return detail::instance_norm( + input, + options.running_mean(), + options.running_var(), + options.weight(), + options.bias(), + options.use_input_stats(), + options.momentum(), + options.eps()); +} + +} // namespace torch::nn::functional diff --git a/shared/package-files/cb/cb2a7e695237aa8e71b89d14c817b29d9fa037ab9dac491905c75c9dab1d28e6/_linalg_svd_cuda_dispatch.h b/shared/package-files/cb/cb2a7e695237aa8e71b89d14c817b29d9fa037ab9dac491905c75c9dab1d28e6/_linalg_svd_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c41cfe31031e1f3f38dc31fe7ab8dcc2bdb4ecca --- /dev/null +++ b/shared/package-files/cb/cb2a7e695237aa8e71b89d14c817b29d9fa037ab9dac491905c75c9dab1d28e6/_linalg_svd_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple _linalg_svd(const at::Tensor & A, bool full_matrices=false, bool compute_uv=true, ::std::optional driver=::std::nullopt); +TORCH_API ::std::tuple _linalg_svd_out(at::Tensor & U, at::Tensor & S, at::Tensor & Vh, const at::Tensor & A, bool full_matrices=false, bool compute_uv=true, ::std::optional driver=::std::nullopt); +TORCH_API ::std::tuple _linalg_svd_outf(const at::Tensor & A, bool full_matrices, bool compute_uv, ::std::optional driver, at::Tensor & U, at::Tensor & S, at::Tensor & Vh); + +} // namespace cuda +} // namespace at diff --git a/shared/package-files/cb/cb2edcc6abe8916cbd087b012586f5b14be8fe85472d4246b8850f40dcf6fe89/addbmm_ops.h b/shared/package-files/cb/cb2edcc6abe8916cbd087b012586f5b14be8fe85472d4246b8850f40dcf6fe89/addbmm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..acf2d797bfd751deed32d30b8acb735ca4ac4015 --- /dev/null +++ b/shared/package-files/cb/cb2edcc6abe8916cbd087b012586f5b14be8fe85472d4246b8850f40dcf6fe89/addbmm_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API addbmm_ { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::addbmm_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); +}; + +struct TORCH_API addbmm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::addbmm"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "addbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +}; + +struct TORCH_API addbmm { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::addbmm"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor"; + static at::Tensor call(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cb/cb37e40ffab5671bb578c099ba9ae603757365785e717dcad3175995475895c6/gammasimp.py b/shared/package-files/cb/cb37e40ffab5671bb578c099ba9ae603757365785e717dcad3175995475895c6/gammasimp.py new file mode 100644 index 0000000000000000000000000000000000000000..aec20c56eb60efb8e1aadfb5bff3d1ba1ab51869 --- /dev/null +++ b/shared/package-files/cb/cb37e40ffab5671bb578c099ba9ae603757365785e717dcad3175995475895c6/gammasimp.py @@ -0,0 +1,493 @@ +from sympy.core import Function, S, Mul, Pow, Add +from sympy.core.sorting import ordered, default_sort_key +from sympy.core.function import expand_func +from sympy.core.symbol import Dummy +from sympy.functions import gamma, sqrt, sin +from sympy.polys import factor, cancel +from sympy.utilities.iterables import sift, uniq + + +def gammasimp(expr): + r""" + Simplify expressions with gamma functions. + + Explanation + =========== + + This function takes as input an expression containing gamma + functions or functions that can be rewritten in terms of gamma + functions and tries to minimize the number of those functions and + reduce the size of their arguments. + + The algorithm works by rewriting all gamma functions as expressions + involving rising factorials (Pochhammer symbols) and applies + recurrence relations and other transformations applicable to rising + factorials, to reduce their arguments, possibly letting the resulting + rising factorial to cancel. Rising factorials with the second argument + being an integer are expanded into polynomial forms and finally all + other rising factorial are rewritten in terms of gamma functions. + + Then the following two steps are performed. + + 1. Reduce the number of gammas by applying the reflection theorem + gamma(x)*gamma(1-x) == pi/sin(pi*x). + 2. Reduce the number of gammas by applying the multiplication theorem + gamma(x)*gamma(x+1/n)*...*gamma(x+(n-1)/n) == C*gamma(n*x). + + It then reduces the number of prefactors by absorbing them into gammas + where possible and expands gammas with rational argument. + + All transformation rules can be found (or were derived from) here: + + .. [1] https://functions.wolfram.com/GammaBetaErf/Pochhammer/17/01/02/ + .. [2] https://functions.wolfram.com/GammaBetaErf/Pochhammer/27/01/0005/ + + Examples + ======== + + >>> from sympy.simplify import gammasimp + >>> from sympy import gamma, Symbol + >>> from sympy.abc import x + >>> n = Symbol('n', integer = True) + + >>> gammasimp(gamma(x)/gamma(x - 3)) + (x - 3)*(x - 2)*(x - 1) + >>> gammasimp(gamma(n + 3)) + gamma(n + 3) + + """ + + expr = expr.rewrite(gamma) + + # compute_ST will be looking for Functions and we don't want + # it looking for non-gamma functions: issue 22606 + # so we mask free, non-gamma functions + f = expr.atoms(Function) + # take out gammas + gammas = {i for i in f if isinstance(i, gamma)} + if not gammas: + return expr # avoid side effects like factoring + f -= gammas + # keep only those without bound symbols + f = f & expr.as_dummy().atoms(Function) + if f: + dum, fun, simp = zip(*[ + (Dummy(), fi, fi.func(*[ + _gammasimp(a, as_comb=False) for a in fi.args])) + for fi in ordered(f)]) + d = expr.xreplace(dict(zip(fun, dum))) + return _gammasimp(d, as_comb=False).xreplace(dict(zip(dum, simp))) + + return _gammasimp(expr, as_comb=False) + + +def _gammasimp(expr, as_comb): + """ + Helper function for gammasimp and combsimp. + + Explanation + =========== + + Simplifies expressions written in terms of gamma function. If + as_comb is True, it tries to preserve integer arguments. See + docstring of gammasimp for more information. This was part of + combsimp() in combsimp.py. + """ + expr = expr.replace(gamma, + lambda n: _rf(1, (n - 1).expand())) + + if as_comb: + expr = expr.replace(_rf, + lambda a, b: gamma(b + 1)) + else: + expr = expr.replace(_rf, + lambda a, b: gamma(a + b)/gamma(a)) + + def rule_gamma(expr, level=0): + """ Simplify products of gamma functions further. """ + + if expr.is_Atom: + return expr + + def gamma_rat(x): + # helper to simplify ratios of gammas + was = x.count(gamma) + xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand() + ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a))) + if xx.count(gamma) < was: + x = xx + return x + + def gamma_factor(x): + # return True if there is a gamma factor in shallow args + if isinstance(x, gamma): + return True + if x.is_Add or x.is_Mul: + return any(gamma_factor(xi) for xi in x.args) + if x.is_Pow and (x.exp.is_integer or x.base.is_positive): + return gamma_factor(x.base) + return False + + # recursion step + if level == 0: + expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args]) + level += 1 + + if not expr.is_Mul: + return expr + + # non-commutative step + if level == 1: + args, nc = expr.args_cnc() + if not args: + return expr + if nc: + return rule_gamma(Mul._from_args(args), level + 1)*Mul._from_args(nc) + level += 1 + + # pure gamma handling, not factor absorption + if level == 2: + T, F = sift(expr.args, gamma_factor, binary=True) + gamma_ind = Mul(*F) + d = Mul(*T) + + nd, dd = d.as_numer_denom() + for ipass in range(2): + args = list(ordered(Mul.make_args(nd))) + for i, ni in enumerate(args): + if ni.is_Add: + ni, dd = Add(*[ + rule_gamma(gamma_rat(a/dd), level + 1) for a in ni.args] + ).as_numer_denom() + args[i] = ni + if not dd.has(gamma): + break + nd = Mul(*args) + if ipass == 0 and not gamma_factor(nd): + break + nd, dd = dd, nd # now process in reversed order + expr = gamma_ind*nd/dd + if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))): + return expr + level += 1 + + # iteration until constant + if level == 3: + while True: + was = expr + expr = rule_gamma(expr, 4) + if expr == was: + return expr + + numer_gammas = [] + denom_gammas = [] + numer_others = [] + denom_others = [] + def explicate(p): + if p is S.One: + return None, [] + b, e = p.as_base_exp() + if e.is_Integer: + if isinstance(b, gamma): + return True, [b.args[0]]*e + else: + return False, [b]*e + else: + return False, [p] + + newargs = list(ordered(expr.args)) + while newargs: + n, d = newargs.pop().as_numer_denom() + isg, l = explicate(n) + if isg: + numer_gammas.extend(l) + elif isg is False: + numer_others.extend(l) + isg, l = explicate(d) + if isg: + denom_gammas.extend(l) + elif isg is False: + denom_others.extend(l) + + # =========== level 2 work: pure gamma manipulation ========= + + if not as_comb: + # Try to reduce the number of gamma factors by applying the + # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x) + for gammas, numer, denom in [( + numer_gammas, numer_others, denom_others), + (denom_gammas, denom_others, numer_others)]: + new = [] + while gammas: + g1 = gammas.pop() + if g1.is_integer: + new.append(g1) + continue + for i, g2 in enumerate(gammas): + n = g1 + g2 - 1 + if not n.is_Integer: + continue + numer.append(S.Pi) + denom.append(sin(S.Pi*g1)) + gammas.pop(i) + if n > 0: + numer.extend(1 - g1 + k for k in range(n)) + elif n < 0: + denom.extend(-g1 - k for k in range(-n)) + break + else: + new.append(g1) + # /!\ updating IN PLACE + gammas[:] = new + + # Try to reduce the number of gammas by using the duplication + # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) = + # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could + # be done with higher argument ratios like gamma(3*x)/gamma(x), + # this would not reduce the number of gammas as in this case. + for ng, dg, no, do in [(numer_gammas, denom_gammas, numer_others, + denom_others), + (denom_gammas, numer_gammas, denom_others, + numer_others)]: + + while True: + for x in ng: + for y in dg: + n = x - 2*y + if n.is_Integer: + break + else: + continue + break + else: + break + ng.remove(x) + dg.remove(y) + if n > 0: + no.extend(2*y + k for k in range(n)) + elif n < 0: + do.extend(2*y - 1 - k for k in range(-n)) + ng.append(y + S.Half) + no.append(2**(2*y - 1)) + do.append(sqrt(S.Pi)) + + # Try to reduce the number of gamma factors by applying the + # multiplication theorem (used when n gammas with args differing + # by 1/n mod 1 are encountered). + # + # run of 2 with args differing by 1/2 + # + # >>> gammasimp(gamma(x)*gamma(x+S.Half)) + # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x) + # + # run of 3 args differing by 1/3 (mod 1) + # + # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3)) + # 6*3**(-3*x - 1/2)*pi*gamma(3*x) + # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3)) + # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x) + # + def _run(coeffs): + # find runs in coeffs such that the difference in terms (mod 1) + # of t1, t2, ..., tn is 1/n + u = list(uniq(coeffs)) + for i in range(len(u)): + dj = ([((u[j] - u[i]) % 1, j) for j in range(i + 1, len(u))]) + for one, j in dj: + if one.p == 1 and one.q != 1: + n = one.q + got = [i] + get = list(range(1, n)) + for d, j in dj: + m = n*d + if m.is_Integer and m in get: + get.remove(m) + got.append(j) + if not get: + break + else: + continue + for i, j in enumerate(got): + c = u[j] + coeffs.remove(c) + got[i] = c + return one.q, got[0], got[1:] + + def _mult_thm(gammas, numer, denom): + # pull off and analyze the leading coefficient from each gamma arg + # looking for runs in those Rationals + + # expr -> coeff + resid -> rats[resid] = coeff + rats = {} + for g in gammas: + c, resid = g.as_coeff_Add() + rats.setdefault(resid, []).append(c) + + # look for runs in Rationals for each resid + keys = sorted(rats, key=default_sort_key) + for resid in keys: + coeffs = sorted(rats[resid]) + new = [] + while True: + run = _run(coeffs) + if run is None: + break + + # process the sequence that was found: + # 1) convert all the gamma functions to have the right + # argument (could be off by an integer) + # 2) append the factors corresponding to the theorem + # 3) append the new gamma function + + n, ui, other = run + + # (1) + for u in other: + con = resid + u - 1 + for k in range(int(u - ui)): + numer.append(con - k) + + con = n*(resid + ui) # for (2) and (3) + + # (2) + numer.append((2*S.Pi)**(S(n - 1)/2)* + n**(S.Half - con)) + # (3) + new.append(con) + + # restore resid to coeffs + rats[resid] = [resid + c for c in coeffs] + new + + # rebuild the gamma arguments + g = [] + for resid in keys: + g += rats[resid] + # /!\ updating IN PLACE + gammas[:] = g + + for l, numer, denom in [(numer_gammas, numer_others, denom_others), + (denom_gammas, denom_others, numer_others)]: + _mult_thm(l, numer, denom) + + # =========== level >= 2 work: factor absorption ========= + + if level >= 2: + # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1) + # and gamma(x)/(x - 1) -> gamma(x - 1) + # This code (in particular repeated calls to find_fuzzy) can be very + # slow. + def find_fuzzy(l, x): + if not l: + return + S1, T1 = compute_ST(x) + for y in l: + S2, T2 = inv[y] + if T1 != T2 or (not S1.intersection(S2) and + (S1 != set() or S2 != set())): + continue + # XXX we want some simplification (e.g. cancel or + # simplify) but no matter what it's slow. + a = len(cancel(x/y).free_symbols) + b = len(x.free_symbols) + c = len(y.free_symbols) + # TODO is there a better heuristic? + if a == 0 and (b > 0 or c > 0): + return y + + # We thus try to avoid expensive calls by building the following + # "invariants": For every factor or gamma function argument + # - the set of free symbols S + # - the set of functional components T + # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset + # or S1 == S2 == emptyset) + inv = {} + + def compute_ST(expr): + if expr in inv: + return inv[expr] + return (expr.free_symbols, expr.atoms(Function).union( + {e.exp for e in expr.atoms(Pow)})) + + def update_ST(expr): + inv[expr] = compute_ST(expr) + for expr in numer_gammas + denom_gammas + numer_others + denom_others: + update_ST(expr) + + for gammas, numer, denom in [( + numer_gammas, numer_others, denom_others), + (denom_gammas, denom_others, numer_others)]: + new = [] + while gammas: + g = gammas.pop() + cont = True + while cont: + cont = False + y = find_fuzzy(numer, g) + if y is not None: + numer.remove(y) + if y != g: + numer.append(y/g) + update_ST(y/g) + g += 1 + cont = True + y = find_fuzzy(denom, g - 1) + if y is not None: + denom.remove(y) + if y != g - 1: + numer.append((g - 1)/y) + update_ST((g - 1)/y) + g -= 1 + cont = True + new.append(g) + # /!\ updating IN PLACE + gammas[:] = new + + # =========== rebuild expr ================================== + + return Mul(*[gamma(g) for g in numer_gammas]) \ + / Mul(*[gamma(g) for g in denom_gammas]) \ + * Mul(*numer_others) / Mul(*denom_others) + + was = factor(expr) + # (for some reason we cannot use Basic.replace in this case) + expr = rule_gamma(was) + if expr != was: + expr = factor(expr) + + expr = expr.replace(gamma, + lambda n: expand_func(gamma(n)) if n.is_Rational else gamma(n)) + + return expr + + +class _rf(Function): + @classmethod + def eval(cls, a, b): + if b.is_Integer: + if not b: + return S.One + + n = int(b) + + if n > 0: + return Mul(*[a + i for i in range(n)]) + elif n < 0: + return 1/Mul(*[a - i for i in range(1, -n + 1)]) + else: + if b.is_Add: + c, _b = b.as_coeff_Add() + + if c.is_Integer: + if c > 0: + return _rf(a, _b)*_rf(a + _b, c) + elif c < 0: + return _rf(a, _b)/_rf(a + _b + c, -c) + + if a.is_Add: + c, _a = a.as_coeff_Add() + + if c.is_Integer: + if c > 0: + return _rf(_a, b)*_rf(_a + b, c)/_rf(_a, c) + elif c < 0: + return _rf(_a, b)*_rf(_a + c, -c)/_rf(_a + b + c, -c) diff --git a/shared/package-files/cb/cb3886fb695bcd70a38989601d618c7ff1100718221298dd5a830bdb11f9939d/abs_ops.h b/shared/package-files/cb/cb3886fb695bcd70a38989601d618c7ff1100718221298dd5a830bdb11f9939d/abs_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c141cb15e6a51e1236593375a9986dea4a963914 --- /dev/null +++ b/shared/package-files/cb/cb3886fb695bcd70a38989601d618c7ff1100718221298dd5a830bdb11f9939d/abs_ops.h @@ -0,0 +1,51 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API abs { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::abs"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "abs(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API abs_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::abs_"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "abs_(Tensor(a!) self) -> Tensor(a!)"; + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API abs_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::abs"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cb/cb3dc35c81e596f4431877819a9cf8f4fcc3094f76a4a7b1836453297e0a8531/latex.lark b/shared/package-files/cb/cb3dc35c81e596f4431877819a9cf8f4fcc3094f76a4a7b1836453297e0a8531/latex.lark new file mode 100644 index 0000000000000000000000000000000000000000..43e8d0e9105fa4da9bcdd2c0fa6111f6d523c9a9 --- /dev/null +++ b/shared/package-files/cb/cb3dc35c81e596f4431877819a9cf8f4fcc3094f76a4a7b1836453297e0a8531/latex.lark @@ -0,0 +1,403 @@ +%ignore /[ \t\n\r]+/ + +%ignore "\\," | "\\thinspace" | "\\:" | "\\medspace" | "\\;" | "\\thickspace" +%ignore "\\quad" | "\\qquad" +%ignore "\\!" | "\\negthinspace" | "\\negmedspace" | "\\negthickspace" +%ignore "\\vrule" | "\\vcenter" | "\\vbox" | "\\vskip" | "\\vspace" | "\\hfill" +%ignore "\\*" | "\\-" | "\\." | "\\/" | "\\(" | "\\=" + +%ignore "\\left" | "\\right" +%ignore "\\limits" | "\\nolimits" +%ignore "\\displaystyle" + +///////////////////// tokens /////////////////////// + +// basic binary operators +ADD: "+" +SUB: "-" +MUL: "*" +DIV: "/" + +// tokens with distinct left and right symbols +L_BRACE: "{" +R_BRACE: "}" +L_BRACE_LITERAL: "\\{" +R_BRACE_LITERAL: "\\}" +L_BRACKET: "[" +R_BRACKET: "]" +L_CEIL: "\\lceil" +R_CEIL: "\\rceil" +L_FLOOR: "\\lfloor" +R_FLOOR: "\\rfloor" +L_PAREN: "(" +R_PAREN: ")" + +// limit, integral, sum, and product symbols +FUNC_LIM: "\\lim" +LIM_APPROACH_SYM: "\\to" | "\\rightarrow" | "\\Rightarrow" | "\\longrightarrow" | "\\Longrightarrow" +FUNC_INT: "\\int" | "\\intop" +FUNC_SUM: "\\sum" +FUNC_PROD: "\\prod" + +// common functions +FUNC_EXP: "\\exp" +FUNC_LOG: "\\log" +FUNC_LN: "\\ln" +FUNC_LG: "\\lg" +FUNC_MIN: "\\min" +FUNC_MAX: "\\max" + +// trigonometric functions +FUNC_SIN: "\\sin" +FUNC_COS: "\\cos" +FUNC_TAN: "\\tan" +FUNC_CSC: "\\csc" +FUNC_SEC: "\\sec" +FUNC_COT: "\\cot" + +// inverse trigonometric functions +FUNC_ARCSIN: "\\arcsin" +FUNC_ARCCOS: "\\arccos" +FUNC_ARCTAN: "\\arctan" +FUNC_ARCCSC: "\\arccsc" +FUNC_ARCSEC: "\\arcsec" +FUNC_ARCCOT: "\\arccot" + +// hyperbolic trigonometric functions +FUNC_SINH: "\\sinh" +FUNC_COSH: "\\cosh" +FUNC_TANH: "\\tanh" +FUNC_ARSINH: "\\arsinh" +FUNC_ARCOSH: "\\arcosh" +FUNC_ARTANH: "\\artanh" + +FUNC_SQRT: "\\sqrt" + +// miscellaneous symbols +CMD_TIMES: "\\times" +CMD_CDOT: "\\cdot" +CMD_DIV: "\\div" +CMD_FRAC: "\\frac" | "\\dfrac" | "\\tfrac" | "\\nicefrac" +CMD_BINOM: "\\binom" | "\\dbinom" | "\\tbinom" +CMD_OVERLINE: "\\overline" +CMD_LANGLE: "\\langle" +CMD_RANGLE: "\\rangle" + +CMD_MATHIT: "\\mathit" + +CMD_INFTY: "\\infty" + +BANG: "!" +BAR: "|" +CARET: "^" +COLON: ":" +UNDERSCORE: "_" + +// relational symbols +EQUAL: "=" +NOT_EQUAL: "\\neq" | "\\ne" +LT: "<" +LTE: "\\leq" | "\\le" | "\\leqslant" +GT: ">" +GTE: "\\geq" | "\\ge" | "\\geqslant" + +DIV_SYMBOL: CMD_DIV | DIV +MUL_SYMBOL: MUL | CMD_TIMES | CMD_CDOT + +%import .greek_symbols.GREEK_SYMBOL + +UPRIGHT_DIFFERENTIAL_SYMBOL: "\\text{d}" | "\\mathrm{d}" +DIFFERENTIAL_SYMBOL: "d" | UPRIGHT_DIFFERENTIAL_SYMBOL + +// disallow "d" as a variable name because we want to parse "d" as a differential symbol. +SYMBOL: /[a-zA-Z]'*/ +GREEK_SYMBOL_WITH_PRIMES: GREEK_SYMBOL "'"* +LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT: /([a-zA-Z]'*)_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/ +LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT: /([a-zA-Z]'*)_/ GREEK_SYMBOL | /([a-zA-Z]'*)_/ L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE +// best to define the variant with braces like that instead of shoving it all into one case like in +// /([a-zA-Z])_/ L_BRACE? GREEK_SYMBOL R_BRACE? because then we can easily error out on input like +// r"h_{\theta" +GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_(([A-Za-z0-9]|[a-zA-Z]+)|\{([A-Za-z0-9]|[a-zA-Z]+'*)\})/ +GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT: GREEK_SYMBOL_WITH_PRIMES /_/ (GREEK_SYMBOL | L_BRACE GREEK_SYMBOL_WITH_PRIMES R_BRACE) +MULTI_LETTER_SYMBOL: /[a-zA-Z]+(\s+[a-zA-Z]+)*'*/ + +%import common.DIGIT -> DIGIT + +CMD_PRIME: "\\prime" +CMD_ASTERISK: "\\ast" + +PRIMES: "'"+ +STARS: "*"+ +PRIMES_VIA_CMD: CMD_PRIME+ +STARS_VIA_CMD: CMD_ASTERISK+ + +CMD_IMAGINARY_UNIT: "\\imaginaryunit" + +CMD_BEGIN: "\\begin" +CMD_END: "\\end" + +// matrices +IGNORE_L: /[ \t\n\r]*/ L_BRACE* /[ \t\n\r]*/ +IGNORE_R: /[ \t\n\r]*/ R_BRACE* /[ \t\n\r]*/ +ARRAY_MATRIX_BEGIN: L_BRACE "array" R_BRACE L_BRACE /[^}]*/ R_BRACE +ARRAY_MATRIX_END: L_BRACE "array" R_BRACE +AMSMATH_MATRIX: L_BRACE "matrix" R_BRACE +AMSMATH_PMATRIX: L_BRACE "pmatrix" R_BRACE +AMSMATH_BMATRIX: L_BRACE "bmatrix" R_BRACE +// Without the (L|R)_PARENs and (L|R)_BRACKETs, a matrix defined using +// \begin{array}...\end{array} or \begin{matrix}...\end{matrix} must +// not qualify as a complete matrix expression; this is done so that +// if we have \begin{array}...\end{array} or \begin{matrix}...\end{matrix} +// between BAR pairs, then they should be interpreted as determinants as +// opposed to sympy.Abs (absolute value) applied to a matrix. +CMD_BEGIN_AMSPMATRIX_AMSBMATRIX: CMD_BEGIN (AMSMATH_PMATRIX | AMSMATH_BMATRIX) +CMD_BEGIN_ARRAY_AMSMATRIX: (L_PAREN | L_BRACKET) IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX) +CMD_MATRIX_BEGIN: CMD_BEGIN_AMSPMATRIX_AMSBMATRIX | CMD_BEGIN_ARRAY_AMSMATRIX +CMD_END_AMSPMATRIX_AMSBMATRIX: CMD_END (AMSMATH_PMATRIX | AMSMATH_BMATRIX) +CMD_END_ARRAY_AMSMATRIX: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? (R_PAREN | R_BRACKET) +CMD_MATRIX_END: CMD_END_AMSPMATRIX_AMSBMATRIX | CMD_END_ARRAY_AMSMATRIX +MATRIX_COL_DELIM: "&" +MATRIX_ROW_DELIM: "\\\\" +FUNC_MATRIX_TRACE: "\\trace" +FUNC_MATRIX_ADJUGATE: "\\adjugate" + +// determinants +AMSMATH_VMATRIX: L_BRACE "vmatrix" R_BRACE +CMD_DETERMINANT_BEGIN_SIMPLE: CMD_BEGIN AMSMATH_VMATRIX +CMD_DETERMINANT_BEGIN_VARIANT: BAR IGNORE_L CMD_BEGIN (ARRAY_MATRIX_BEGIN | AMSMATH_MATRIX) +CMD_DETERMINANT_BEGIN: CMD_DETERMINANT_BEGIN_SIMPLE | CMD_DETERMINANT_BEGIN_VARIANT +CMD_DETERMINANT_END_SIMPLE: CMD_END AMSMATH_VMATRIX +CMD_DETERMINANT_END_VARIANT: CMD_END (ARRAY_MATRIX_END | AMSMATH_MATRIX) IGNORE_R "\\right"? BAR +CMD_DETERMINANT_END: CMD_DETERMINANT_END_SIMPLE | CMD_DETERMINANT_END_VARIANT +FUNC_DETERMINANT: "\\det" + +//////////////////// grammar ////////////////////// + +latex_string: _relation | _expression + +_one_letter_symbol: SYMBOL + | LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT + | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT + | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT + | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT + | GREEK_SYMBOL_WITH_PRIMES +// LuaTeX-generated outputs of \mathit{foo'} and \mathit{foo}' +// seem to be the same on the surface. We allow both styles. +multi_letter_symbol: CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE + | CMD_MATHIT L_BRACE MULTI_LETTER_SYMBOL R_BRACE /'+/ +number: /\d+(\.\d*)?/ | CMD_IMAGINARY_UNIT + +_atomic_expr: _one_letter_symbol + | multi_letter_symbol + | number + | CMD_INFTY + +group_round_parentheses: L_PAREN _expression R_PAREN +group_square_brackets: L_BRACKET _expression R_BRACKET +group_curly_parentheses: L_BRACE _expression R_BRACE + +_relation: eq | ne | lt | lte | gt | gte + +eq: _expression EQUAL _expression +ne: _expression NOT_EQUAL _expression +lt: _expression LT _expression +lte: _expression LTE _expression +gt: _expression GT _expression +gte: _expression GTE _expression + +_expression_core: _atomic_expr | group_curly_parentheses + +add: _expression ADD _expression_mul + | ADD _expression_mul +sub: _expression SUB _expression_mul + | SUB _expression_mul +mul: _expression_mul MUL_SYMBOL _expression_power +div: _expression_mul DIV_SYMBOL _expression_power + +adjacent_expressions: (_one_letter_symbol | number) _expression_mul + | group_round_parentheses (group_round_parentheses | _one_letter_symbol) + | _function _function + | fraction _expression_mul + +_expression_func: _expression_core + | group_round_parentheses + | fraction + | binomial + | _function + | _integral// | derivative + | limit + | matrix + +_expression_power: _expression_func | superscript | matrix_prime | symbol_prime + +_expression_mul: _expression_power + | mul | div | adjacent_expressions + | summation | product + +_expression: _expression_mul | add | sub + +_limit_dir: "+" | "-" | L_BRACE ("+" | "-") R_BRACE + +limit_dir_expr: _expression CARET _limit_dir + +group_curly_parentheses_lim: L_BRACE _expression LIM_APPROACH_SYM (limit_dir_expr | _expression) R_BRACE + +limit: FUNC_LIM UNDERSCORE group_curly_parentheses_lim _expression + +differential: DIFFERENTIAL_SYMBOL _one_letter_symbol + +//_derivative_operator: CMD_FRAC L_BRACE DIFFERENTIAL_SYMBOL R_BRACE L_BRACE differential R_BRACE + +//derivative: _derivative_operator _expression + +_integral: normal_integral | integral_with_special_fraction + +normal_integral: FUNC_INT _expression DIFFERENTIAL_SYMBOL _one_letter_symbol + | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol + | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? _expression? DIFFERENTIAL_SYMBOL _one_letter_symbol + +group_curly_parentheses_int: L_BRACE _expression? differential R_BRACE + +special_fraction: CMD_FRAC group_curly_parentheses_int group_curly_parentheses + +integral_with_special_fraction: FUNC_INT special_fraction + | FUNC_INT (CARET _expression_core UNDERSCORE _expression_core)? special_fraction + | FUNC_INT (UNDERSCORE _expression_core CARET _expression_core)? special_fraction + +group_curly_parentheses_special: UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE CARET _expression_core + | CARET _expression_core UNDERSCORE L_BRACE _atomic_expr EQUAL _atomic_expr R_BRACE + +summation: FUNC_SUM group_curly_parentheses_special _expression + | FUNC_SUM group_curly_parentheses_special _expression + +product: FUNC_PROD group_curly_parentheses_special _expression + | FUNC_PROD group_curly_parentheses_special _expression + +superscript: _expression_func CARET (_expression_power | CMD_PRIME | CMD_ASTERISK) + | _expression_func CARET L_BRACE (PRIMES | STARS | PRIMES_VIA_CMD | STARS_VIA_CMD) R_BRACE + +matrix_prime: (matrix | group_round_parentheses) PRIMES + +symbol_prime: (LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT + | LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT + | GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT + | GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT) PRIMES + +fraction: _basic_fraction + | _simple_fraction + | _general_fraction + +_basic_fraction: CMD_FRAC DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES) + +_simple_fraction: CMD_FRAC DIGIT group_curly_parentheses + | CMD_FRAC group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES) + +_general_fraction: CMD_FRAC group_curly_parentheses group_curly_parentheses + +binomial: _basic_binomial + | _simple_binomial + | _general_binomial + +_basic_binomial: CMD_BINOM DIGIT (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES) + +_simple_binomial: CMD_BINOM DIGIT group_curly_parentheses + | CMD_BINOM group_curly_parentheses (DIGIT | SYMBOL | GREEK_SYMBOL_WITH_PRIMES) + +_general_binomial: CMD_BINOM group_curly_parentheses group_curly_parentheses + +list_of_expressions: _expression ("," _expression)* + +function_applied: _one_letter_symbol L_PAREN list_of_expressions R_PAREN + +min: FUNC_MIN L_PAREN list_of_expressions R_PAREN + +max: FUNC_MAX L_PAREN list_of_expressions R_PAREN + +bra: CMD_LANGLE _expression BAR + +ket: BAR _expression CMD_RANGLE + +inner_product: CMD_LANGLE _expression BAR _expression CMD_RANGLE + +_function: function_applied + | abs | floor | ceil + | _trigonometric_function | _inverse_trigonometric_function + | _trigonometric_function_power + | _hyperbolic_trigonometric_function | _inverse_hyperbolic_trigonometric_function + | exponential + | log + | square_root + | factorial + | conjugate + | max | min + | bra | ket | inner_product + | determinant + | trace + | adjugate + +exponential: FUNC_EXP _expression + +log: FUNC_LOG _expression + | FUNC_LN _expression + | FUNC_LG _expression + | FUNC_LOG UNDERSCORE (DIGIT | _one_letter_symbol) _expression + | FUNC_LOG UNDERSCORE group_curly_parentheses _expression + +square_root: FUNC_SQRT group_curly_parentheses + | FUNC_SQRT group_square_brackets group_curly_parentheses + +factorial: _expression_func BANG + +conjugate: CMD_OVERLINE group_curly_parentheses + | CMD_OVERLINE DIGIT + +_trigonometric_function: sin | cos | tan | csc | sec | cot + +sin: FUNC_SIN _expression +cos: FUNC_COS _expression +tan: FUNC_TAN _expression +csc: FUNC_CSC _expression +sec: FUNC_SEC _expression +cot: FUNC_COT _expression + +_trigonometric_function_power: sin_power | cos_power | tan_power | csc_power | sec_power | cot_power + +sin_power: FUNC_SIN CARET _expression_core _expression +cos_power: FUNC_COS CARET _expression_core _expression +tan_power: FUNC_TAN CARET _expression_core _expression +csc_power: FUNC_CSC CARET _expression_core _expression +sec_power: FUNC_SEC CARET _expression_core _expression +cot_power: FUNC_COT CARET _expression_core _expression + +_hyperbolic_trigonometric_function: sinh | cosh | tanh + +sinh: FUNC_SINH _expression +cosh: FUNC_COSH _expression +tanh: FUNC_TANH _expression + +_inverse_trigonometric_function: arcsin | arccos | arctan | arccsc | arcsec | arccot + +arcsin: FUNC_ARCSIN _expression +arccos: FUNC_ARCCOS _expression +arctan: FUNC_ARCTAN _expression +arccsc: FUNC_ARCCSC _expression +arcsec: FUNC_ARCSEC _expression +arccot: FUNC_ARCCOT _expression + +_inverse_hyperbolic_trigonometric_function: asinh | acosh | atanh + +asinh: FUNC_ARSINH _expression +acosh: FUNC_ARCOSH _expression +atanh: FUNC_ARTANH _expression + +abs: BAR _expression BAR +floor: L_FLOOR _expression R_FLOOR +ceil: L_CEIL _expression R_CEIL + +matrix: CMD_MATRIX_BEGIN matrix_body CMD_MATRIX_END +matrix_body: matrix_row (MATRIX_ROW_DELIM matrix_row)* (MATRIX_ROW_DELIM)? +matrix_row: _expression (MATRIX_COL_DELIM _expression)* +determinant: (CMD_DETERMINANT_BEGIN matrix_body CMD_DETERMINANT_END) + | FUNC_DETERMINANT _expression +trace: FUNC_MATRIX_TRACE _expression +adjugate: FUNC_MATRIX_ADJUGATE _expression diff --git a/shared/package-files/cb/cb3e8c0cba2598c744fa0a49c4acd9324b8e1e593efe29f6d20b2a9293ca5221/util.py b/shared/package-files/cb/cb3e8c0cba2598c744fa0a49c4acd9324b8e1e593efe29f6d20b2a9293ca5221/util.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c3249cab15b3464cbbad2e0162bd1e918f40d6 --- /dev/null +++ b/shared/package-files/cb/cb3e8c0cba2598c744fa0a49c4acd9324b8e1e593efe29f6d20b2a9293ca5221/util.py @@ -0,0 +1,120 @@ +import collections +import os +import tempfile +from typing import Any, Mapping, Sequence +from zarr.context import Context + +from zarr.storage import Store +from zarr._storage.v3 import StoreV3 + +import pytest + + +class CountingDict(Store): + def __init__(self): + self.wrapped = dict() + self.counter = collections.Counter() + + def __len__(self): + self.counter["__len__"] += 1 + return len(self.wrapped) + + def keys(self): + self.counter["keys"] += 1 + return self.wrapped.keys() + + def __iter__(self): + self.counter["__iter__"] += 1 + return iter(self.wrapped) + + def __contains__(self, item): + self.counter["__contains__", item] += 1 + return item in self.wrapped + + def __getitem__(self, item): + self.counter["__getitem__", item] += 1 + return self.wrapped[item] + + def __setitem__(self, key, value): + self.counter["__setitem__", key] += 1 + self.wrapped[key] = value + + def __delitem__(self, key): + self.counter["__delitem__", key] += 1 + del self.wrapped[key] + + def getitems( + self, keys: Sequence[str], *, contexts: Mapping[str, Context] + ) -> Mapping[str, Any]: + for key in keys: + self.counter["__getitem__", key] += 1 + return {k: self.wrapped[k] for k in keys if k in self.wrapped} + + +class CountingDictV3(CountingDict, StoreV3): + pass + + +def skip_test_env_var(name): + """Checks for environment variables indicating whether tests requiring services should be run""" + value = os.environ.get(name, "0") + return pytest.mark.skipif(value == "0", reason="Tests not enabled via environment variable") + + +try: + import fsspec # noqa: F401 + + have_fsspec = True +except ImportError: # pragma: no cover + have_fsspec = False + + +try: + import bsddb3 # noqa: F401 + + have_bsddb3 = True +except ImportError: # pragma: no cover + have_bsddb3 = False + + +try: + import lmdb # noqa: F401 + + have_lmdb = True +except ImportError: # pragma: no cover + have_lmdb = False + + +try: + import sqlite3 # noqa: F401 + + have_sqlite3 = True +except ImportError: # pragma: no cover + have_sqlite3 = False + + +def abs_container(): + from azure.core.exceptions import ResourceExistsError + import azure.storage.blob as asb + + URL = "http://127.0.0.1:10000" + ACCOUNT_NAME = "devstoreaccount1" + KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" + CONN_STR = ( + f"DefaultEndpointsProtocol=http;AccountName={ACCOUNT_NAME};" + f"AccountKey={KEY};BlobEndpoint={URL}/{ACCOUNT_NAME};" + ) + + blob_service_client = asb.BlobServiceClient.from_connection_string(CONN_STR) + try: + container_client = blob_service_client.create_container("test") + except ResourceExistsError: + container_client = blob_service_client.get_container_client("test") + + return container_client + + +def mktemp(**kwargs): + f = tempfile.NamedTemporaryFile(**kwargs) + f.close() + return f.name diff --git a/shared/package-files/cb/cb4b77528beee8aab9100a96e658d6bfab3218f40e906b426f9f76f8525ff482/convolution_native.h b/shared/package-files/cb/cb4b77528beee8aab9100a96e658d6bfab3218f40e906b426f9f76f8525ff482/convolution_native.h new file mode 100644 index 0000000000000000000000000000000000000000..846ea5ebebbbbc085c19926338488ef895d8ee02 --- /dev/null +++ b/shared/package-files/cb/cb4b77528beee8aab9100a96e658d6bfab3218f40e906b426f9f76f8525ff482/convolution_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor convolution(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups); +TORCH_API at::Tensor & convolution_out_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cb4bc47576940fcb613f75dab1956492882a5ce181d1cb362677c711ae033634/function.py b/shared/package-files/cb/cb4bc47576940fcb613f75dab1956492882a5ce181d1cb362677c711ae033634/function.py new file mode 100644 index 0000000000000000000000000000000000000000..ac850845e0bb2aaf9b535635567d6e2629527ad7 --- /dev/null +++ b/shared/package-files/cb/cb4bc47576940fcb613f75dab1956492882a5ce181d1cb362677c711ae033634/function.py @@ -0,0 +1,3423 @@ +""" +There are three types of functions implemented in SymPy: + + 1) defined functions (in the sense that they can be evaluated) like + exp or sin; they have a name and a body: + f = exp + 2) undefined function which have a name but no body. Undefined + functions can be defined using a Function class as follows: + f = Function('f') + (the result will be a Function instance) + 3) anonymous function (or lambda function) which have a body (defined + with dummy variables) but have no name: + f = Lambda(x, exp(x)*x) + f = Lambda((x, y), exp(x)*y) + The fourth type of functions are composites, like (sin + cos)(x); these work in + SymPy core, but are not yet part of SymPy. + + Examples + ======== + + >>> import sympy + >>> f = sympy.Function("f") + >>> from sympy.abc import x + >>> f(x) + f(x) + >>> print(sympy.srepr(f(x).func)) + Function('f') + >>> f(x).args + (x,) + +""" + +from __future__ import annotations + +from typing import Any +from collections.abc import Iterable +import copyreg + +from .add import Add +from .basic import Basic, _atomic +from .cache import cacheit +from .containers import Tuple, Dict +from .decorators import _sympifyit +from .evalf import pure_complex +from .expr import Expr, AtomicExpr +from .logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool +from .mul import Mul +from .numbers import Rational, Float, Integer +from .operations import LatticeOp +from .parameters import global_parameters +from .rules import Transform +from .singleton import S +from .sympify import sympify, _sympify + +from .sorting import default_sort_key, ordered +from sympy.utilities.exceptions import (sympy_deprecation_warning, + SymPyDeprecationWarning, ignore_warnings) +from sympy.utilities.iterables import (has_dups, sift, iterable, + is_sequence, uniq, topological_sort) +from sympy.utilities.lambdify import MPMATH_TRANSLATIONS +from sympy.utilities.misc import as_int, filldedent, func_name + +import mpmath +from mpmath.libmp.libmpf import prec_to_dps + +import inspect +from collections import Counter + +def _coeff_isneg(a): + """Return True if the leading Number is negative. + + Examples + ======== + + >>> from sympy.core.function import _coeff_isneg + >>> from sympy import S, Symbol, oo, pi + >>> _coeff_isneg(-3*pi) + True + >>> _coeff_isneg(S(3)) + False + >>> _coeff_isneg(-oo) + True + >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1 + False + + For matrix expressions: + + >>> from sympy import MatrixSymbol, sqrt + >>> A = MatrixSymbol("A", 3, 3) + >>> _coeff_isneg(-sqrt(2)*A) + True + >>> _coeff_isneg(sqrt(2)*A) + False + """ + + if a.is_MatMul: + a = a.args[0] + if a.is_Mul: + a = a.args[0] + return a.is_Number and a.is_extended_negative + + +class PoleError(Exception): + pass + + +class ArgumentIndexError(ValueError): + def __str__(self): + return ("Invalid operation with argument number %s for Function %s" % + (self.args[1], self.args[0])) + + +class BadSignatureError(TypeError): + '''Raised when a Lambda is created with an invalid signature''' + pass + + +class BadArgumentsError(TypeError): + '''Raised when a Lambda is called with an incorrect number of arguments''' + pass + + +# Python 3 version that does not raise a Deprecation warning +def arity(cls): + """Return the arity of the function if it is known, else None. + + Explanation + =========== + + When default values are specified for some arguments, they are + optional and the arity is reported as a tuple of possible values. + + Examples + ======== + + >>> from sympy import arity, log + >>> arity(lambda x: x) + 1 + >>> arity(log) + (1, 2) + >>> arity(lambda *x: sum(x)) is None + True + """ + eval_ = getattr(cls, 'eval', cls) + + parameters = inspect.signature(eval_).parameters.items() + if [p for _, p in parameters if p.kind == p.VAR_POSITIONAL]: + return + p_or_k = [p for _, p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD] + # how many have no default and how many have a default value + no, yes = map(len, sift(p_or_k, + lambda p:p.default == p.empty, binary=True)) + return no if not yes else tuple(range(no, no + yes + 1)) + +class FunctionClass(type): + """ + Base class for function classes. FunctionClass is a subclass of type. + + Use Function('' [ , signature ]) to create + undefined function classes. + """ + _new = type.__new__ + + def __init__(cls, *args, **kwargs): + # honor kwarg value or class-defined value before using + # the number of arguments in the eval function (if present) + nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', arity(cls))) + if nargs is None and 'nargs' not in cls.__dict__: + for supcls in cls.__mro__: + if hasattr(supcls, '_nargs'): + nargs = supcls._nargs + break + else: + continue + + # Canonicalize nargs here; change to set in nargs. + if is_sequence(nargs): + if not nargs: + raise ValueError(filldedent(''' + Incorrectly specified nargs as %s: + if there are no arguments, it should be + `nargs = 0`; + if there are any number of arguments, + it should be + `nargs = None`''' % str(nargs))) + nargs = tuple(ordered(set(nargs))) + elif nargs is not None: + nargs = (as_int(nargs),) + cls._nargs = nargs + + # When __init__ is called from UndefinedFunction it is called with + # just one arg but when it is called from subclassing Function it is + # called with the usual (name, bases, namespace) type() signature. + if len(args) == 3: + namespace = args[2] + if 'eval' in namespace and not isinstance(namespace['eval'], classmethod): + raise TypeError("eval on Function subclasses should be a class method (defined with @classmethod)") + + @property + def __signature__(self): + """ + Allow Python 3's inspect.signature to give a useful signature for + Function subclasses. + """ + # Python 3 only, but backports (like the one in IPython) still might + # call this. + try: + from inspect import signature + except ImportError: + return None + + # TODO: Look at nargs + return signature(self.eval) + + @property + def free_symbols(self): + return set() + + @property + def xreplace(self): + # Function needs args so we define a property that returns + # a function that takes args...and then use that function + # to return the right value + return lambda rule, **_: rule.get(self, self) + + @property + def nargs(self): + """Return a set of the allowed number of arguments for the function. + + Examples + ======== + + >>> from sympy import Function + >>> f = Function('f') + + If the function can take any number of arguments, the set of whole + numbers is returned: + + >>> Function('f').nargs + Naturals0 + + If the function was initialized to accept one or more arguments, a + corresponding set will be returned: + + >>> Function('f', nargs=1).nargs + {1} + >>> Function('f', nargs=(2, 1)).nargs + {1, 2} + + The undefined function, after application, also has the nargs + attribute; the actual number of arguments is always available by + checking the ``args`` attribute: + + >>> f = Function('f') + >>> f(1).nargs + Naturals0 + >>> len(f(1).args) + 1 + """ + from sympy.sets.sets import FiniteSet + # XXX it would be nice to handle this in __init__ but there are import + # problems with trying to import FiniteSet there + return FiniteSet(*self._nargs) if self._nargs else S.Naturals0 + + def _valid_nargs(self, n : int) -> bool: + """ Return True if the specified integer is a valid number of arguments + + The number of arguments n is guaranteed to be an integer and positive + + """ + if self._nargs: + return n in self._nargs + + nargs = self.nargs + return nargs is S.Naturals0 or n in nargs + + def __repr__(cls): + return cls.__name__ + + +class Application(Basic, metaclass=FunctionClass): + """ + Base class for applied functions. + + Explanation + =========== + + Instances of Application represent the result of applying an application of + any type to any object. + """ + + is_Function = True + + @cacheit + def __new__(cls, *args, **options): + from sympy.sets.fancysets import Naturals0 + from sympy.sets.sets import FiniteSet + + args = list(map(sympify, args)) + evaluate = options.pop('evaluate', global_parameters.evaluate) + # WildFunction (and anything else like it) may have nargs defined + # and we throw that value away here + options.pop('nargs', None) + + if options: + raise ValueError("Unknown options: %s" % options) + + if evaluate: + evaluated = cls.eval(*args) + if evaluated is not None: + return evaluated + + obj = super().__new__(cls, *args, **options) + + # make nargs uniform here + sentinel = object() + objnargs = getattr(obj, "nargs", sentinel) + if objnargs is not sentinel: + # things passing through here: + # - functions subclassed from Function (e.g. myfunc(1).nargs) + # - functions like cos(1).nargs + # - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs + # Canonicalize nargs here + if is_sequence(objnargs): + nargs = tuple(ordered(set(objnargs))) + elif objnargs is not None: + nargs = (as_int(objnargs),) + else: + nargs = None + else: + # things passing through here: + # - WildFunction('f').nargs + # - AppliedUndef with no nargs like Function('f')(1).nargs + nargs = obj._nargs # note the underscore here + # convert to FiniteSet + obj.nargs = FiniteSet(*nargs) if nargs else Naturals0() + return obj + + @classmethod + def eval(cls, *args): + """ + Returns a canonical form of cls applied to arguments args. + + Explanation + =========== + + The ``eval()`` method is called when the class ``cls`` is about to be + instantiated and it should return either some simplified instance + (possible of some other class), or if the class ``cls`` should be + unmodified, return None. + + Examples of ``eval()`` for the function "sign" + + .. code-block:: python + + @classmethod + def eval(cls, arg): + if arg is S.NaN: + return S.NaN + if arg.is_zero: return S.Zero + if arg.is_positive: return S.One + if arg.is_negative: return S.NegativeOne + if isinstance(arg, Mul): + coeff, terms = arg.as_coeff_Mul(rational=True) + if coeff is not S.One: + return cls(coeff) * cls(terms) + + """ + return + + @property + def func(self): + return self.__class__ + + def _eval_subs(self, old, new): + if (old.is_Function and new.is_Function and + callable(old) and callable(new) and + old == self.func and len(self.args) in new.nargs): + return new(*[i._subs(old, new) for i in self.args]) + + +class Function(Application, Expr): + r""" + Base class for applied mathematical functions. + + It also serves as a constructor for undefined function classes. + + See the :ref:`custom-functions` guide for details on how to subclass + ``Function`` and what methods can be defined. + + Examples + ======== + + **Undefined Functions** + + To create an undefined function, pass a string of the function name to + ``Function``. + + >>> from sympy import Function, Symbol + >>> x = Symbol('x') + >>> f = Function('f') + >>> g = Function('g')(x) + >>> f + f + >>> f(x) + f(x) + >>> g + g(x) + >>> f(x).diff(x) + Derivative(f(x), x) + >>> g.diff(x) + Derivative(g(x), x) + + Assumptions can be passed to ``Function`` the same as with a + :class:`~.Symbol`. Alternatively, you can use a ``Symbol`` with + assumptions for the function name and the function will inherit the name + and assumptions associated with the ``Symbol``: + + >>> f_real = Function('f', real=True) + >>> f_real(x).is_real + True + >>> f_real_inherit = Function(Symbol('f', real=True)) + >>> f_real_inherit(x).is_real + True + + Note that assumptions on a function are unrelated to the assumptions on + the variables it is called on. If you want to add a relationship, subclass + ``Function`` and define custom assumptions handler methods. See the + :ref:`custom-functions-assumptions` section of the :ref:`custom-functions` + guide for more details. + + **Custom Function Subclasses** + + The :ref:`custom-functions` guide has several + :ref:`custom-functions-complete-examples` of how to subclass ``Function`` + to create a custom function. + + """ + + @property + def _diff_wrt(self): + return False + + @cacheit + def __new__(cls, *args, **options) -> type[AppliedUndef]: # type: ignore + # Handle calls like Function('f') + if cls is Function: + return UndefinedFunction(*args, **options) # type: ignore + else: + return cls._new_(*args, **options) # type: ignore + + @classmethod + def _new_(cls, *args, **options) -> Expr: + n = len(args) + + if not cls._valid_nargs(n): + # XXX: exception message must be in exactly this format to + # make it work with NumPy's functions like vectorize(). See, + # for example, https://github.com/numpy/numpy/issues/1697. + # The ideal solution would be just to attach metadata to + # the exception and change NumPy to take advantage of this. + temp = ('%(name)s takes %(qual)s %(args)s ' + 'argument%(plural)s (%(given)s given)') + raise TypeError(temp % { + 'name': cls, + 'qual': 'exactly' if len(cls.nargs) == 1 else 'at least', + 'args': min(cls.nargs), + 'plural': 's'*(min(cls.nargs) != 1), + 'given': n}) + + evaluate = options.get('evaluate', global_parameters.evaluate) + result = super().__new__(cls, *args, **options) + if evaluate and isinstance(result, cls) and result.args: + _should_evalf = [cls._should_evalf(a) for a in result.args] + pr2 = min(_should_evalf) + if pr2 > 0: + pr = max(_should_evalf) + result = result.evalf(prec_to_dps(pr)) + + return _sympify(result) + + @classmethod + def _should_evalf(cls, arg): + """ + Decide if the function should automatically evalf(). + + Explanation + =========== + + By default (in this implementation), this happens if (and only if) the + ARG is a floating point number (including complex numbers). + This function is used by __new__. + + Returns the precision to evalf to, or -1 if it should not evalf. + """ + if arg.is_Float: + return arg._prec + if not arg.is_Add: + return -1 + m = pure_complex(arg) + if m is None: + return -1 + # the elements of m are of type Number, so have a _prec + return max(m[0]._prec, m[1]._prec) + + @classmethod + def class_key(cls): + from sympy.sets.fancysets import Naturals0 + funcs = { + 'exp': 10, + 'log': 11, + 'sin': 20, + 'cos': 21, + 'tan': 22, + 'cot': 23, + 'sinh': 30, + 'cosh': 31, + 'tanh': 32, + 'coth': 33, + 'conjugate': 40, + 're': 41, + 'im': 42, + 'arg': 43, + } + name = cls.__name__ + + try: + i = funcs[name] + except KeyError: + i = 0 if isinstance(cls.nargs, Naturals0) else 10000 + + return 4, i, name + + def _eval_evalf(self, prec): + + def _get_mpmath_func(fname): + """Lookup mpmath function based on name""" + if isinstance(self, AppliedUndef): + # Shouldn't lookup in mpmath but might have ._imp_ + return None + + if not hasattr(mpmath, fname): + fname = MPMATH_TRANSLATIONS.get(fname, None) + if fname is None: + return None + return getattr(mpmath, fname) + + _eval_mpmath = getattr(self, '_eval_mpmath', None) + if _eval_mpmath is None: + func = _get_mpmath_func(self.func.__name__) + args = self.args + else: + func, args = _eval_mpmath() + + # Fall-back evaluation + if func is None: + imp = getattr(self, '_imp_', None) + if imp is None: + return None + try: + return Float(imp(*[i.evalf(prec) for i in self.args]), prec) + except (TypeError, ValueError): + return None + + # Convert all args to mpf or mpc + # Convert the arguments to *higher* precision than requested for the + # final result. + # XXX + 5 is a guess, it is similar to what is used in evalf.py. Should + # we be more intelligent about it? + try: + args = [arg._to_mpmath(prec + 5) for arg in args] + def bad(m): + from mpmath import mpf, mpc + # the precision of an mpf value is the last element + # if that is 1 (and m[1] is not 1 which would indicate a + # power of 2), then the eval failed; so check that none of + # the arguments failed to compute to a finite precision. + # Note: An mpc value has two parts, the re and imag tuple; + # check each of those parts, too. Anything else is allowed to + # pass + if isinstance(m, mpf): + m = m._mpf_ + return m[1] !=1 and m[-1] == 1 + elif isinstance(m, mpc): + m, n = m._mpc_ + return m[1] !=1 and m[-1] == 1 and \ + n[1] !=1 and n[-1] == 1 + else: + return False + if any(bad(a) for a in args): + raise ValueError # one or more args failed to compute with significance + except ValueError: + return + + with mpmath.workprec(prec): + v = func(*args) + + return Expr._from_mpmath(v, prec) + + def _eval_derivative(self, s): + # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) + i = 0 + l = [] + for a in self.args: + i += 1 + da = a.diff(s) + if da.is_zero: + continue + try: + df = self.fdiff(i) + except ArgumentIndexError: + df = Function.fdiff(self, i) + l.append(df * da) + return Add(*l) + + def _eval_is_commutative(self): + return fuzzy_and(a.is_commutative for a in self.args) + + def _eval_is_meromorphic(self, x, a): + if not self.args: + return True + if any(arg.has(x) for arg in self.args[1:]): + return False + + arg = self.args[0] + if not arg._eval_is_meromorphic(x, a): + return None + + return fuzzy_not(type(self).is_singular(arg.subs(x, a))) + + _singularities: FuzzyBool | tuple[Expr, ...] = None + + @classmethod + def is_singular(cls, a): + """ + Tests whether the argument is an essential singularity + or a branch point, or the functions is non-holomorphic. + """ + ss = cls._singularities + if ss in (True, None, False): + return ss + + return fuzzy_or(a.is_infinite if s is S.ComplexInfinity + else (a - s).is_zero for s in ss) + + def _eval_aseries(self, n, args0, x, logx): + """ + Compute an asymptotic expansion around args0, in terms of self.args. + This function is only used internally by _eval_nseries and should not + be called directly; derived classes can overwrite this to implement + asymptotic expansions. + """ + raise PoleError(filldedent(''' + Asymptotic expansion of %s around %s is + not implemented.''' % (type(self), args0))) + + def _eval_nseries(self, x, n, logx, cdir=0): + """ + This function does compute series for multivariate functions, + but the expansion is always in terms of *one* variable. + + Examples + ======== + + >>> from sympy import atan2 + >>> from sympy.abc import x, y + >>> atan2(x, y).series(x, n=2) + atan2(0, y) + x/y + O(x**2) + >>> atan2(x, y).series(y, n=2) + -y/x + atan2(x, 0) + O(y**2) + + This function also computes asymptotic expansions, if necessary + and possible: + + >>> from sympy import loggamma + >>> loggamma(1/x)._eval_nseries(x,0,None) + -1/x - log(x)/x + log(x)/2 + O(1) + + """ + from .symbol import uniquely_named_symbol + from sympy.series.order import Order + from sympy.sets.sets import FiniteSet + args = self.args + args0 = [t.limit(x, 0) for t in args] + if any(t.is_finite is False for t in args0): + from .numbers import oo, zoo, nan + a = [t.as_leading_term(x, logx=logx) for t in args] + a0 = [t.limit(x, 0) for t in a] + if any(t.has(oo, -oo, zoo, nan) for t in a0): + return self._eval_aseries(n, args0, x, logx) + # Careful: the argument goes to oo, but only logarithmically so. We + # are supposed to do a power series expansion "around the + # logarithmic term". e.g. + # f(1+x+log(x)) + # -> f(1+logx) + x*f'(1+logx) + O(x**2) + # where 'logx' is given in the argument + a = [t._eval_nseries(x, n, logx) for t in args] + z = [r - r0 for (r, r0) in zip(a, a0)] + p = [Dummy() for _ in z] + q = [] + v = None + for ai, zi, pi in zip(a0, z, p): + if zi.has(x): + if v is not None: + raise NotImplementedError + q.append(ai + pi) + v = pi + else: + q.append(ai) + e1 = self.func(*q) + if v is None: + return e1 + s = e1._eval_nseries(v, n, logx) + o = s.getO() + s = s.removeO() + s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x) + return s + if (self.func.nargs is S.Naturals0 + or (self.func.nargs == FiniteSet(1) and args0[0]) + or any(c > 1 for c in self.func.nargs)): + e = self + e1 = e.expand() + if e == e1: + #for example when e = sin(x+1) or e = sin(cos(x)) + #let's try the general algorithm + if len(e.args) == 1: + # issue 14411 + e = e.func(e.args[0].cancel()) + term = e.subs(x, S.Zero) + if term.is_finite is False or term is S.NaN: + raise PoleError("Cannot expand %s around 0" % (self)) + series = term + fact = S.One + + _x = uniquely_named_symbol('xi', self) + e = e.subs(x, _x) + for i in range(1, n): + fact *= Rational(i) + e = e.diff(_x) + subs = e.subs(_x, S.Zero) + if subs is S.NaN: + # try to evaluate a limit if we have to + subs = e.limit(_x, S.Zero) + if subs.is_finite is False: + raise PoleError("Cannot expand %s around 0" % (self)) + term = subs*(x**i)/fact + term = term.expand() + series += term + return series + Order(x**n, x) + return e1.nseries(x, n=n, logx=logx) + arg = self.args[0] + l = [] + g = None + # try to predict a number of terms needed + nterms = n + 2 + cf = Order(arg.as_leading_term(x), x).getn() + if cf != 0: + nterms = (n/cf).ceiling() + for i in range(nterms): + g = self.taylor_term(i, arg, g) + g = g.nseries(x, n=n, logx=logx) + l.append(g) + return Add(*l) + Order(x**n, x) + + def fdiff(self, argindex=1): + """ + Returns the first derivative of the function. + """ + if not (1 <= argindex <= len(self.args)): + raise ArgumentIndexError(self, argindex) + ix = argindex - 1 + A = self.args[ix] + if A._diff_wrt: + if len(self.args) == 1 or not A.is_Symbol: + return _derivative_dispatch(self, A) + for i, v in enumerate(self.args): + if i != ix and A in v.free_symbols: + # it can't be in any other argument's free symbols + # issue 8510 + break + else: + return _derivative_dispatch(self, A) + + # See issue 4624 and issue 4719, 5600 and 8510 + D = Dummy('xi_%i' % argindex, dummy_index=hash(A)) + args = self.args[:ix] + (D,) + self.args[ix + 1:] + return Subs(Derivative(self.func(*args), D), D, A) + + def _eval_as_leading_term(self, x, logx, cdir): + """Stub that should be overridden by new Functions to return + the first non-zero term in a series if ever an x-dependent + argument whose leading term vanishes as x -> 0 might be encountered. + See, for example, cos._eval_as_leading_term. + """ + from sympy.series.order import Order + args = [a.as_leading_term(x, logx=logx) for a in self.args] + o = Order(1, x) + if any(x in a.free_symbols and o.contains(a) for a in args): + # Whereas x and any finite number are contained in O(1, x), + # expressions like 1/x are not. If any arg simplified to a + # vanishing expression as x -> 0 (like x or x**2, but not + # 3, 1/x, etc...) then the _eval_as_leading_term is needed + # to supply the first non-zero term of the series, + # + # e.g. expression leading term + # ---------- ------------ + # cos(1/x) cos(1/x) + # cos(cos(x)) cos(1) + # cos(x) 1 <- _eval_as_leading_term needed + # sin(x) x <- _eval_as_leading_term needed + # + raise NotImplementedError( + '%s has no _eval_as_leading_term routine' % self.func) + else: + return self + + +class DefinedFunction(Function): + """Base class for defined functions like ``sin``, ``cos``, ...""" + + @cacheit + def __new__(cls, *args, **options) -> Expr: # type: ignore + return cls._new_(*args, **options) + + +class AppliedUndef(Function): + """ + Base class for expressions resulting from the application of an undefined + function. + """ + + is_number = False + + name: str + + def __new__(cls, *args, **options) -> Expr: # type: ignore + args = tuple(map(sympify, args)) + u = [a.name for a in args if isinstance(a, UndefinedFunction)] + if u: + raise TypeError('Invalid argument: expecting an expression, not UndefinedFunction%s: %s' % ( + 's'*(len(u) > 1), ', '.join(u))) + obj: Expr = super().__new__(cls, *args, **options) # type: ignore + return obj + + def _eval_as_leading_term(self, x, logx, cdir): + return self + + @property + def _diff_wrt(self): + """ + Allow derivatives wrt to undefined functions. + + Examples + ======== + + >>> from sympy import Function, Symbol + >>> f = Function('f') + >>> x = Symbol('x') + >>> f(x)._diff_wrt + True + >>> f(x).diff(x) + Derivative(f(x), x) + """ + return True + + +class UndefSageHelper: + """ + Helper to facilitate Sage conversion. + """ + def __get__(self, ins, typ): + import sage.all as sage + if ins is None: + return lambda: sage.function(typ.__name__) + else: + args = [arg._sage_() for arg in ins.args] + return lambda : sage.function(ins.__class__.__name__)(*args) + +_undef_sage_helper = UndefSageHelper() + + +class UndefinedFunction(FunctionClass): + """ + The (meta)class of undefined functions. + """ + name: str + _sage_: UndefSageHelper + + def __new__(mcl, name, bases=(AppliedUndef,), __dict__=None, **kwargs) -> type[AppliedUndef]: + from .symbol import _filter_assumptions + # Allow Function('f', real=True) + # and/or Function(Symbol('f', real=True)) + assumptions, kwargs = _filter_assumptions(kwargs) + if isinstance(name, Symbol): + assumptions = name._merge(assumptions) + name = name.name + elif not isinstance(name, str): + raise TypeError('expecting string or Symbol for name') + else: + commutative = assumptions.get('commutative', None) + assumptions = Symbol(name, **assumptions).assumptions0 + if commutative is None: + assumptions.pop('commutative') + __dict__ = __dict__ or {} + # put the `is_*` for into __dict__ + __dict__.update({'is_%s' % k: v for k, v in assumptions.items()}) + # You can add other attributes, although they do have to be hashable + # (but seriously, if you want to add anything other than assumptions, + # just subclass Function) + __dict__.update(kwargs) + # add back the sanitized assumptions without the is_ prefix + kwargs.update(assumptions) + # Save these for __eq__ + __dict__.update({'_kwargs': kwargs}) + # do this for pickling + __dict__['__module__'] = None + obj = super().__new__(mcl, name, bases, __dict__) # type: ignore + obj.name = name + obj._sage_ = _undef_sage_helper + return obj # type: ignore + + def __instancecheck__(cls, instance): + return cls in type(instance).__mro__ + + _kwargs: dict[str, bool | None] = {} + + def __hash__(self): + return hash((self.class_key(), frozenset(self._kwargs.items()))) + + def __eq__(self, other): + return (isinstance(other, self.__class__) and + self.class_key() == other.class_key() and + self._kwargs == other._kwargs) + + def __ne__(self, other): + return not self == other + + @property + def _diff_wrt(self): + return False + + +# Using copyreg is the only way to make a dynamically generated instance of a +# metaclass picklable without using a custom pickler. It is not possible to +# define e.g. __reduce__ on the metaclass because obj.__reduce__ will retrieve +# the __reduce__ method for reducing instances of the type rather than for the +# type itself. +def _reduce_undef(f): + return (_rebuild_undef, (f.name, f._kwargs)) + +def _rebuild_undef(name, kwargs): + return Function(name, **kwargs) + +copyreg.pickle(UndefinedFunction, _reduce_undef) + + +# XXX: The type: ignore on WildFunction is because mypy complains: +# +# sympy/core/function.py:939: error: Cannot determine type of 'sort_key' in +# base class 'Expr' +# +# Somehow this is because of the @cacheit decorator but it is not clear how to +# fix it. + + +class WildFunction(Function, AtomicExpr): # type: ignore + """ + A WildFunction function matches any function (with its arguments). + + Examples + ======== + + >>> from sympy import WildFunction, Function, cos + >>> from sympy.abc import x, y + >>> F = WildFunction('F') + >>> f = Function('f') + >>> F.nargs + Naturals0 + >>> x.match(F) + >>> F.match(F) + {F_: F_} + >>> f(x).match(F) + {F_: f(x)} + >>> cos(x).match(F) + {F_: cos(x)} + >>> f(x, y).match(F) + {F_: f(x, y)} + + To match functions with a given number of arguments, set ``nargs`` to the + desired value at instantiation: + + >>> F = WildFunction('F', nargs=2) + >>> F.nargs + {2} + >>> f(x).match(F) + >>> f(x, y).match(F) + {F_: f(x, y)} + + To match functions with a range of arguments, set ``nargs`` to a tuple + containing the desired number of arguments, e.g. if ``nargs = (1, 2)`` + then functions with 1 or 2 arguments will be matched. + + >>> F = WildFunction('F', nargs=(1, 2)) + >>> F.nargs + {1, 2} + >>> f(x).match(F) + {F_: f(x)} + >>> f(x, y).match(F) + {F_: f(x, y)} + >>> f(x, y, 1).match(F) + + """ + + # XXX: What is this class attribute used for? + include: set[Any] = set() + + def __init__(cls, name, **assumptions): + from sympy.sets.sets import Set, FiniteSet + cls.name = name + nargs = assumptions.pop('nargs', S.Naturals0) + if not isinstance(nargs, Set): + # Canonicalize nargs here. See also FunctionClass. + if is_sequence(nargs): + nargs = tuple(ordered(set(nargs))) + elif nargs is not None: + nargs = (as_int(nargs),) + nargs = FiniteSet(*nargs) + cls.nargs = nargs + + def matches(self, expr, repl_dict=None, old=False): + if not isinstance(expr, (AppliedUndef, Function)): + return None + if len(expr.args) not in self.nargs: + return None + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + repl_dict[self] = expr + return repl_dict + + +class Derivative(Expr): + """ + Carries out differentiation of the given expression with respect to symbols. + + Examples + ======== + + >>> from sympy import Derivative, Function, symbols, Subs + >>> from sympy.abc import x, y + >>> f, g = symbols('f g', cls=Function) + + >>> Derivative(x**2, x, evaluate=True) + 2*x + + Denesting of derivatives retains the ordering of variables: + + >>> Derivative(Derivative(f(x, y), y), x) + Derivative(f(x, y), y, x) + + Contiguously identical symbols are merged into a tuple giving + the symbol and the count: + + >>> Derivative(f(x), x, x, y, x) + Derivative(f(x), (x, 2), y, x) + + If the derivative cannot be performed, and evaluate is True, the + order of the variables of differentiation will be made canonical: + + >>> Derivative(f(x, y), y, x, evaluate=True) + Derivative(f(x, y), x, y) + + Derivatives with respect to undefined functions can be calculated: + + >>> Derivative(f(x)**2, f(x), evaluate=True) + 2*f(x) + + Such derivatives will show up when the chain rule is used to + evaluate a derivative: + + >>> f(g(x)).diff(x) + Derivative(f(g(x)), g(x))*Derivative(g(x), x) + + Substitution is used to represent derivatives of functions with + arguments that are not symbols or functions: + + >>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3) + True + + Notes + ===== + + Simplification of high-order derivatives: + + Because there can be a significant amount of simplification that can be + done when multiple differentiations are performed, results will be + automatically simplified in a fairly conservative fashion unless the + keyword ``simplify`` is set to False. + + >>> from sympy import sqrt, diff, Function, symbols + >>> from sympy.abc import x, y, z + >>> f, g = symbols('f,g', cls=Function) + + >>> e = sqrt((x + 1)**2 + x) + >>> diff(e, (x, 5), simplify=False).count_ops() + 136 + >>> diff(e, (x, 5)).count_ops() + 30 + + Ordering of variables: + + If evaluate is set to True and the expression cannot be evaluated, the + list of differentiation symbols will be sorted, that is, the expression is + assumed to have continuous derivatives up to the order asked. + + Derivative wrt non-Symbols: + + For the most part, one may not differentiate wrt non-symbols. + For example, we do not allow differentiation wrt `x*y` because + there are multiple ways of structurally defining where x*y appears + in an expression: a very strict definition would make + (x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like + cos(x)) are not allowed, either: + + >>> (x*y*z).diff(x*y) + Traceback (most recent call last): + ... + ValueError: Can't calculate derivative wrt x*y. + + To make it easier to work with variational calculus, however, + derivatives wrt AppliedUndef and Derivatives are allowed. + For example, in the Euler-Lagrange method one may write + F(t, u, v) where u = f(t) and v = f'(t). These variables can be + written explicitly as functions of time:: + + >>> from sympy.abc import t + >>> F = Function('F') + >>> U = f(t) + >>> V = U.diff(t) + + The derivative wrt f(t) can be obtained directly: + + >>> direct = F(t, U, V).diff(U) + + When differentiation wrt a non-Symbol is attempted, the non-Symbol + is temporarily converted to a Symbol while the differentiation + is performed and the same answer is obtained: + + >>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U) + >>> assert direct == indirect + + The implication of this non-symbol replacement is that all + functions are treated as independent of other functions and the + symbols are independent of the functions that contain them:: + + >>> x.diff(f(x)) + 0 + >>> g(x).diff(f(x)) + 0 + + It also means that derivatives are assumed to depend only + on the variables of differentiation, not on anything contained + within the expression being differentiated:: + + >>> F = f(x) + >>> Fx = F.diff(x) + >>> Fx.diff(F) # derivative depends on x, not F + 0 + >>> Fxx = Fx.diff(x) + >>> Fxx.diff(Fx) # derivative depends on x, not Fx + 0 + + The last example can be made explicit by showing the replacement + of Fx in Fxx with y: + + >>> Fxx.subs(Fx, y) + Derivative(y, x) + + Since that in itself will evaluate to zero, differentiating + wrt Fx will also be zero: + + >>> _.doit() + 0 + + Replacing undefined functions with concrete expressions + + One must be careful to replace undefined functions with expressions + that contain variables consistent with the function definition and + the variables of differentiation or else insconsistent result will + be obtained. Consider the following example: + + >>> eq = f(x)*g(y) + >>> eq.subs(f(x), x*y).diff(x, y).doit() + y*Derivative(g(y), y) + g(y) + >>> eq.diff(x, y).subs(f(x), x*y).doit() + y*Derivative(g(y), y) + + The results differ because `f(x)` was replaced with an expression + that involved both variables of differentiation. In the abstract + case, differentiation of `f(x)` by `y` is 0; in the concrete case, + the presence of `y` made that derivative nonvanishing and produced + the extra `g(y)` term. + + Defining differentiation for an object + + An object must define ._eval_derivative(symbol) method that returns + the differentiation result. This function only needs to consider the + non-trivial case where expr contains symbol and it should call the diff() + method internally (not _eval_derivative); Derivative should be the only + one to call _eval_derivative. + + Any class can allow derivatives to be taken with respect to + itself (while indicating its scalar nature). See the + docstring of Expr._diff_wrt. + + See Also + ======== + _sort_variable_count + """ + + is_Derivative = True + + @property + def _diff_wrt(self): + """An expression may be differentiated wrt a Derivative if + it is in elementary form. + + Examples + ======== + + >>> from sympy import Function, Derivative, cos + >>> from sympy.abc import x + >>> f = Function('f') + + >>> Derivative(f(x), x)._diff_wrt + True + >>> Derivative(cos(x), x)._diff_wrt + False + >>> Derivative(x + 1, x)._diff_wrt + False + + A Derivative might be an unevaluated form of what will not be + a valid variable of differentiation if evaluated. For example, + + >>> Derivative(f(f(x)), x).doit() + Derivative(f(x), x)*Derivative(f(f(x)), f(x)) + + Such an expression will present the same ambiguities as arise + when dealing with any other product, like ``2*x``, so ``_diff_wrt`` + is False: + + >>> Derivative(f(f(x)), x)._diff_wrt + False + """ + return self.expr._diff_wrt and isinstance(self.doit(), Derivative) + + def __new__(cls, expr, *variables, **kwargs): + expr = sympify(expr) + if not isinstance(expr, Basic): + raise TypeError(f"Cannot represent derivative of {type(expr)}") + symbols_or_none = getattr(expr, "free_symbols", None) + has_symbol_set = isinstance(symbols_or_none, set) + + if not has_symbol_set: + raise ValueError(filldedent(''' + Since there are no variables in the expression %s, + it cannot be differentiated.''' % expr)) + + # determine value for variables if it wasn't given + if not variables: + variables = expr.free_symbols + if len(variables) != 1: + if expr.is_number: + return S.Zero + if len(variables) == 0: + raise ValueError(filldedent(''' + Since there are no variables in the expression, + the variable(s) of differentiation must be supplied + to differentiate %s''' % expr)) + else: + raise ValueError(filldedent(''' + Since there is more than one variable in the + expression, the variable(s) of differentiation + must be supplied to differentiate %s''' % expr)) + + # Split the list of variables into a list of the variables we are diff + # wrt, where each element of the list has the form (s, count) where + # s is the entity to diff wrt and count is the order of the + # derivative. + variable_count = [] + array_likes = (tuple, list, Tuple) + + from sympy.tensor.array import Array, NDimArray + + for i, v in enumerate(variables): + if isinstance(v, UndefinedFunction): + raise TypeError( + "cannot differentiate wrt " + "UndefinedFunction: %s" % v) + + if isinstance(v, array_likes): + if len(v) == 0: + # Ignore empty tuples: Derivative(expr, ... , (), ... ) + continue + if isinstance(v[0], array_likes): + # Derive by array: Derivative(expr, ... , [[x, y, z]], ... ) + if len(v) == 1: + v = Array(v[0]) + count = 1 + else: + v, count = v + v = Array(v) + else: + v, count = v + if count == 0: + continue + variable_count.append(Tuple(v, count)) + continue + + v = sympify(v) + if isinstance(v, Integer): + if i == 0: + raise ValueError("First variable cannot be a number: %i" % v) + count = v + prev, prevcount = variable_count[-1] + if prevcount != 1: + raise TypeError("tuple {} followed by number {}".format((prev, prevcount), v)) + if count == 0: + variable_count.pop() + else: + variable_count[-1] = Tuple(prev, count) + else: + count = 1 + variable_count.append(Tuple(v, count)) + + # light evaluation of contiguous, identical + # items: (x, 1), (x, 1) -> (x, 2) + merged = [] + for t in variable_count: + v, c = t + if c.is_negative: + raise ValueError( + 'order of differentiation must be nonnegative') + if merged and merged[-1][0] == v: + c += merged[-1][1] + if not c: + merged.pop() + else: + merged[-1] = Tuple(v, c) + else: + merged.append(t) + variable_count = merged + + # sanity check of variables of differentation; we waited + # until the counts were computed since some variables may + # have been removed because the count was 0 + for v, c in variable_count: + # v must have _diff_wrt True + if not v._diff_wrt: + __ = '' # filler to make error message neater + raise ValueError(filldedent(''' + Can't calculate derivative wrt %s.%s''' % (v, + __))) + + # We make a special case for 0th derivative, because there is no + # good way to unambiguously print this. + if len(variable_count) == 0: + return expr + + evaluate = kwargs.get('evaluate', False) + + if evaluate: + if isinstance(expr, Derivative): + expr = expr.canonical + variable_count = [ + (v.canonical if isinstance(v, Derivative) else v, c) + for v, c in variable_count] + + # Look for a quick exit if there are symbols that don't appear in + # expression at all. Note, this cannot check non-symbols like + # Derivatives as those can be created by intermediate + # derivatives. + zero = False + free = expr.free_symbols + from sympy.matrices.expressions.matexpr import MatrixExpr + + for v, c in variable_count: + vfree = v.free_symbols + if c.is_positive and vfree: + if isinstance(v, AppliedUndef): + # these match exactly since + # x.diff(f(x)) == g(x).diff(f(x)) == 0 + # and are not created by differentiation + D = Dummy() + if not expr.xreplace({v: D}).has(D): + zero = True + break + elif isinstance(v, MatrixExpr): + zero = False + break + elif isinstance(v, Symbol) and v not in free: + zero = True + break + else: + if not free & vfree: + # e.g. v is IndexedBase or Matrix + zero = True + break + if zero: + return cls._get_zero_with_shape_like(expr) + + # make the order of symbols canonical + #TODO: check if assumption of discontinuous derivatives exist + variable_count = cls._sort_variable_count(variable_count) + + # denest + if isinstance(expr, Derivative): + variable_count = list(expr.variable_count) + variable_count + expr = expr.expr + return _derivative_dispatch(expr, *variable_count, **kwargs) + + # we return here if evaluate is False or if there is no + # _eval_derivative method + if not evaluate or not hasattr(expr, '_eval_derivative'): + # return an unevaluated Derivative + if evaluate and variable_count == [(expr, 1)] and expr.is_scalar: + # special hack providing evaluation for classes + # that have defined is_scalar=True but have no + # _eval_derivative defined + return S.One + return Expr.__new__(cls, expr, *variable_count) + + # evaluate the derivative by calling _eval_derivative method + # of expr for each variable + # ------------------------------------------------------------- + nderivs = 0 # how many derivatives were performed + unhandled = [] + from sympy.matrices.matrixbase import MatrixBase + for i, (v, count) in enumerate(variable_count): + + old_expr = expr + old_v = None + + is_symbol = v.is_symbol or isinstance(v, + (Iterable, Tuple, MatrixBase, NDimArray)) + + if not is_symbol: + old_v = v + v = Dummy('xi') + expr = expr.xreplace({old_v: v}) + # Derivatives and UndefinedFunctions are independent + # of all others + clashing = not (isinstance(old_v, (Derivative, AppliedUndef))) + if v not in expr.free_symbols and not clashing: + return expr.diff(v) # expr's version of 0 + if not old_v.is_scalar and not hasattr( + old_v, '_eval_derivative'): + # special hack providing evaluation for classes + # that have defined is_scalar=True but have no + # _eval_derivative defined + expr *= old_v.diff(old_v) + + obj = cls._dispatch_eval_derivative_n_times(expr, v, count) + if obj is not None and obj.is_zero: + return obj + + nderivs += count + + if old_v is not None: + if obj is not None: + # remove the dummy that was used + obj = obj.subs(v, old_v) + # restore expr + expr = old_expr + + if obj is None: + # we've already checked for quick-exit conditions + # that give 0 so the remaining variables + # are contained in the expression but the expression + # did not compute a derivative so we stop taking + # derivatives + unhandled = variable_count[i:] + break + + expr = obj + + # what we have so far can be made canonical + expr = expr.replace( + lambda x: isinstance(x, Derivative), + lambda x: x.canonical) + + if unhandled: + if isinstance(expr, Derivative): + unhandled = list(expr.variable_count) + unhandled + expr = expr.expr + expr = Expr.__new__(cls, expr, *unhandled) + + if (nderivs > 1) == True and kwargs.get('simplify', True): + from .exprtools import factor_terms + from sympy.simplify.simplify import signsimp + expr = factor_terms(signsimp(expr)) + return expr + + @property + def canonical(cls): + return cls.func(cls.expr, + *Derivative._sort_variable_count(cls.variable_count)) + + @classmethod + def _sort_variable_count(cls, vc): + """ + Sort (variable, count) pairs into canonical order while + retaining order of variables that do not commute during + differentiation: + + * symbols and functions commute with each other + * derivatives commute with each other + * a derivative does not commute with anything it contains + * any other object is not allowed to commute if it has + free symbols in common with another object + + Examples + ======== + + >>> from sympy import Derivative, Function, symbols + >>> vsort = Derivative._sort_variable_count + >>> x, y, z = symbols('x y z') + >>> f, g, h = symbols('f g h', cls=Function) + + Contiguous items are collapsed into one pair: + + >>> vsort([(x, 1), (x, 1)]) + [(x, 2)] + >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) + [(y, 2), (f(x), 2)] + + Ordering is canonical. + + >>> def vsort0(*v): + ... # docstring helper to + ... # change vi -> (vi, 0), sort, and return vi vals + ... return [i[0] for i in vsort([(i, 0) for i in v])] + + >>> vsort0(y, x) + [x, y] + >>> vsort0(g(y), g(x), f(y)) + [f(y), g(x), g(y)] + + Symbols are sorted as far to the left as possible but never + move to the left of a derivative having the same symbol in + its variables; the same applies to AppliedUndef which are + always sorted after Symbols: + + >>> dfx = f(x).diff(x) + >>> assert vsort0(dfx, y) == [y, dfx] + >>> assert vsort0(dfx, x) == [dfx, x] + """ + if not vc: + return [] + vc = list(vc) + if len(vc) == 1: + return [Tuple(*vc[0])] + V = list(range(len(vc))) + E = [] + v = lambda i: vc[i][0] + D = Dummy() + def _block(d, v, wrt=False): + # return True if v should not come before d else False + if d == v: + return wrt + if d.is_Symbol: + return False + if isinstance(d, Derivative): + # a derivative blocks if any of it's variables contain + # v; the wrt flag will return True for an exact match + # and will cause an AppliedUndef to block if v is in + # the arguments + if any(_block(k, v, wrt=True) + for k in d._wrt_variables): + return True + return False + if not wrt and isinstance(d, AppliedUndef): + return False + if v.is_Symbol: + return v in d.free_symbols + if isinstance(v, AppliedUndef): + return _block(d.xreplace({v: D}), D) + return d.free_symbols & v.free_symbols + for i in range(len(vc)): + for j in range(i): + if _block(v(j), v(i)): + E.append((j,i)) + # this is the default ordering to use in case of ties + O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc)))) + ix = topological_sort((V, E), key=lambda i: O[v(i)]) + # merge counts of contiguously identical items + merged = [] + for v, c in [vc[i] for i in ix]: + if merged and merged[-1][0] == v: + merged[-1][1] += c + else: + merged.append([v, c]) + return [Tuple(*i) for i in merged] + + def _eval_is_commutative(self): + return self.expr.is_commutative + + def _eval_derivative(self, v): + # If v (the variable of differentiation) is not in + # self.variables, we might be able to take the derivative. + if v not in self._wrt_variables: + dedv = self.expr.diff(v) + if isinstance(dedv, Derivative): + return dedv.func(dedv.expr, *(self.variable_count + dedv.variable_count)) + # dedv (d(self.expr)/dv) could have simplified things such that the + # derivative wrt things in self.variables can now be done. Thus, + # we set evaluate=True to see if there are any other derivatives + # that can be done. The most common case is when dedv is a simple + # number so that the derivative wrt anything else will vanish. + return self.func(dedv, *self.variables, evaluate=True) + # In this case v was in self.variables so the derivative wrt v has + # already been attempted and was not computed, either because it + # couldn't be or evaluate=False originally. + variable_count = list(self.variable_count) + variable_count.append((v, 1)) + return self.func(self.expr, *variable_count, evaluate=False) + + def doit(self, **hints): + expr = self.expr + if hints.get('deep', True): + expr = expr.doit(**hints) + hints['evaluate'] = True + rv = self.func(expr, *self.variable_count, **hints) + if rv!= self and rv.has(Derivative): + rv = rv.doit(**hints) + return rv + + @_sympifyit('z0', NotImplementedError) + def doit_numerically(self, z0): + """ + Evaluate the derivative at z numerically. + + When we can represent derivatives at a point, this should be folded + into the normal evalf. For now, we need a special method. + """ + if len(self.free_symbols) != 1 or len(self.variables) != 1: + raise NotImplementedError('partials and higher order derivatives') + z = list(self.free_symbols)[0] + + def eval(x): + f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec)) + f0 = f0.evalf(prec_to_dps(mpmath.mp.prec)) + return f0._to_mpmath(mpmath.mp.prec) + return Expr._from_mpmath(mpmath.diff(eval, + z0._to_mpmath(mpmath.mp.prec)), + mpmath.mp.prec) + + @property + def expr(self): + return self._args[0] + + @property + def _wrt_variables(self): + # return the variables of differentiation without + # respect to the type of count (int or symbolic) + return [i[0] for i in self.variable_count] + + @property + def variables(self): + # TODO: deprecate? YES, make this 'enumerated_variables' and + # name _wrt_variables as variables + # TODO: support for `d^n`? + rv = [] + for v, count in self.variable_count: + if not count.is_Integer: + raise TypeError(filldedent(''' + Cannot give expansion for symbolic count. If you just + want a list of all variables of differentiation, use + _wrt_variables.''')) + rv.extend([v]*count) + return tuple(rv) + + @property + def variable_count(self): + return self._args[1:] + + @property + def derivative_count(self): + return sum([count for _, count in self.variable_count], 0) + + @property + def free_symbols(self): + ret = self.expr.free_symbols + # Add symbolic counts to free_symbols + for _, count in self.variable_count: + ret.update(count.free_symbols) + return ret + + @property + def kind(self): + return self.args[0].kind + + def _eval_subs(self, old, new): + # The substitution (old, new) cannot be done inside + # Derivative(expr, vars) for a variety of reasons + # as handled below. + if old in self._wrt_variables: + # first handle the counts + expr = self.func(self.expr, *[(v, c.subs(old, new)) + for v, c in self.variable_count]) + if expr != self: + return expr._eval_subs(old, new) + # quick exit case + if not getattr(new, '_diff_wrt', False): + # case (0): new is not a valid variable of + # differentiation + if isinstance(old, Symbol): + # don't introduce a new symbol if the old will do + return Subs(self, old, new) + else: + xi = Dummy('xi') + return Subs(self.xreplace({old: xi}), xi, new) + + # If both are Derivatives with the same expr, check if old is + # equivalent to self or if old is a subderivative of self. + if old.is_Derivative and old.expr == self.expr: + if self.canonical == old.canonical: + return new + + # collections.Counter doesn't have __le__ + def _subset(a, b): + return all((a[i] <= b[i]) == True for i in a) + + old_vars = Counter(dict(reversed(old.variable_count))) + self_vars = Counter(dict(reversed(self.variable_count))) + if _subset(old_vars, self_vars): + return _derivative_dispatch(new, *(self_vars - old_vars).items()).canonical + + args = list(self.args) + newargs = [x._subs(old, new) for x in args] + if args[0] == old: + # complete replacement of self.expr + # we already checked that the new is valid so we know + # it won't be a problem should it appear in variables + return _derivative_dispatch(*newargs) + + if newargs[0] != args[0]: + # case (1) can't change expr by introducing something that is in + # the _wrt_variables if it was already in the expr + # e.g. + # for Derivative(f(x, g(y)), y), x cannot be replaced with + # anything that has y in it; for f(g(x), g(y)).diff(g(y)) + # g(x) cannot be replaced with anything that has g(y) + syms = {vi: Dummy() for vi in self._wrt_variables + if not vi.is_Symbol} + wrt = {syms.get(vi, vi) for vi in self._wrt_variables} + forbidden = args[0].xreplace(syms).free_symbols & wrt + nfree = new.xreplace(syms).free_symbols + ofree = old.xreplace(syms).free_symbols + if (nfree - ofree) & forbidden: + return Subs(self, old, new) + + viter = ((i, j) for ((i, _), (j, _)) in zip(newargs[1:], args[1:])) + if any(i != j for i, j in viter): # a wrt-variable change + # case (2) can't change vars by introducing a variable + # that is contained in expr, e.g. + # for Derivative(f(z, g(h(x), y)), y), y cannot be changed to + # x, h(x), or g(h(x), y) + for a in _atomic(self.expr, recursive=True): + for i in range(1, len(newargs)): + vi, _ = newargs[i] + if a == vi and vi != args[i][0]: + return Subs(self, old, new) + # more arg-wise checks + vc = newargs[1:] + oldv = self._wrt_variables + newe = self.expr + subs = [] + for i, (vi, ci) in enumerate(vc): + if not vi._diff_wrt: + # case (3) invalid differentiation expression so + # create a replacement dummy + xi = Dummy('xi_%i' % i) + # replace the old valid variable with the dummy + # in the expression + newe = newe.xreplace({oldv[i]: xi}) + # and replace the bad variable with the dummy + vc[i] = (xi, ci) + # and record the dummy with the new (invalid) + # differentiation expression + subs.append((xi, vi)) + + if subs: + # handle any residual substitution in the expression + newe = newe._subs(old, new) + # return the Subs-wrapped derivative + return Subs(Derivative(newe, *vc), *zip(*subs)) + + # everything was ok + return _derivative_dispatch(*newargs) + + def _eval_lseries(self, x, logx, cdir=0): + dx = self.variables + for term in self.expr.lseries(x, logx=logx, cdir=cdir): + yield self.func(term, *dx) + + def _eval_nseries(self, x, n, logx, cdir=0): + arg = self.expr.nseries(x, n=n, logx=logx) + o = arg.getO() + dx = self.variables + rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())] + if o: + rv.append(o/x) + return Add(*rv) + + def _eval_as_leading_term(self, x, logx, cdir): + series_gen = self.expr.lseries(x) + d = S.Zero + for leading_term in series_gen: + d = diff(leading_term, *self.variables) + if d != 0: + break + return d + + def as_finite_difference(self, points=1, x0=None, wrt=None): + """ Expresses a Derivative instance as a finite difference. + + Parameters + ========== + + points : sequence or coefficient, optional + If sequence: discrete values (length >= order+1) of the + independent variable used for generating the finite + difference weights. + If it is a coefficient, it will be used as the step-size + for generating an equidistant sequence of length order+1 + centered around ``x0``. Default: 1 (step-size 1) + + x0 : number or Symbol, optional + the value of the independent variable (``wrt``) at which the + derivative is to be approximated. Default: same as ``wrt``. + + wrt : Symbol, optional + "with respect to" the variable for which the (partial) + derivative is to be approximated for. If not provided it + is required that the derivative is ordinary. Default: ``None``. + + + Examples + ======== + + >>> from sympy import symbols, Function, exp, sqrt, Symbol + >>> x, h = symbols('x h') + >>> f = Function('f') + >>> f(x).diff(x).as_finite_difference() + -f(x - 1/2) + f(x + 1/2) + + The default step size and number of points are 1 and + ``order + 1`` respectively. We can change the step size by + passing a symbol as a parameter: + + >>> f(x).diff(x).as_finite_difference(h) + -f(-h/2 + x)/h + f(h/2 + x)/h + + We can also specify the discretized values to be used in a + sequence: + + >>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h]) + -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) + + The algorithm is not restricted to use equidistant spacing, nor + do we need to make the approximation around ``x0``, but we can get + an expression estimating the derivative at an offset: + + >>> e, sq2 = exp(1), sqrt(2) + >>> xl = [x-h, x+h, x+e*h] + >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) # doctest: +ELLIPSIS + 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/... + + To approximate ``Derivative`` around ``x0`` using a non-equidistant + spacing step, the algorithm supports assignment of undefined + functions to ``points``: + + >>> dx = Function('dx') + >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h) + -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x) + + Partial derivatives are also supported: + + >>> y = Symbol('y') + >>> d2fdxdy=f(x,y).diff(x,y) + >>> d2fdxdy.as_finite_difference(wrt=x) + -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) + + We can apply ``as_finite_difference`` to ``Derivative`` instances in + compound expressions using ``replace``: + + >>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative, + ... lambda arg: arg.as_finite_difference()) + 42**(-f(x - 1/2) + f(x + 1/2)) + 1 + + + See also + ======== + + sympy.calculus.finite_diff.apply_finite_diff + sympy.calculus.finite_diff.differentiate_finite + sympy.calculus.finite_diff.finite_diff_weights + + """ + from sympy.calculus.finite_diff import _as_finite_diff + return _as_finite_diff(self, points, x0, wrt) + + @classmethod + def _get_zero_with_shape_like(cls, expr): + return S.Zero + + @classmethod + def _dispatch_eval_derivative_n_times(cls, expr, v, count): + # Evaluate the derivative `n` times. If + # `_eval_derivative_n_times` is not overridden by the current + # object, the default in `Basic` will call a loop over + # `_eval_derivative`: + return expr._eval_derivative_n_times(v, count) + + +def _derivative_dispatch(expr, *variables, **kwargs): + from sympy.matrices.matrixbase import MatrixBase + from sympy.matrices.expressions.matexpr import MatrixExpr + from sympy.tensor.array import NDimArray + array_types = (MatrixBase, MatrixExpr, NDimArray, list, tuple, Tuple) + if isinstance(expr, array_types) or any(isinstance(i[0], array_types) if isinstance(i, (tuple, list, Tuple)) else isinstance(i, array_types) for i in variables): + from sympy.tensor.array.array_derivatives import ArrayDerivative + return ArrayDerivative(expr, *variables, **kwargs) + return Derivative(expr, *variables, **kwargs) + + +class Lambda(Expr): + """ + Lambda(x, expr) represents a lambda function similar to Python's + 'lambda x: expr'. A function of several variables is written as + Lambda((x, y, ...), expr). + + Examples + ======== + + A simple example: + + >>> from sympy import Lambda + >>> from sympy.abc import x + >>> f = Lambda(x, x**2) + >>> f(4) + 16 + + For multivariate functions, use: + + >>> from sympy.abc import y, z, t + >>> f2 = Lambda((x, y, z, t), x + y**z + t**z) + >>> f2(1, 2, 3, 4) + 73 + + It is also possible to unpack tuple arguments: + + >>> f = Lambda(((x, y), z), x + y + z) + >>> f((1, 2), 3) + 6 + + A handy shortcut for lots of arguments: + + >>> p = x, y, z + >>> f = Lambda(p, x + y*z) + >>> f(*p) + x + y*z + + """ + is_Function = True + + def __new__(cls, signature, expr) -> Lambda: + if iterable(signature) and not isinstance(signature, (tuple, Tuple)): + sympy_deprecation_warning( + """ + Using a non-tuple iterable as the first argument to Lambda + is deprecated. Use Lambda(tuple(args), expr) instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-non-tuple-lambda", + ) + signature = tuple(signature) + _sig = signature if iterable(signature) else (signature,) + sig: Tuple = sympify(_sig) # type: ignore + cls._check_signature(sig) + + if len(sig) == 1 and sig[0] == expr: + return S.IdentityFunction + + return Expr.__new__(cls, sig, sympify(expr)) + + @classmethod + def _check_signature(cls, sig): + syms = set() + + def rcheck(args): + for a in args: + if a.is_symbol: + if a in syms: + raise BadSignatureError("Duplicate symbol %s" % a) + syms.add(a) + elif isinstance(a, Tuple): + rcheck(a) + else: + raise BadSignatureError("Lambda signature should be only tuples" + " and symbols, not %s" % a) + + if not isinstance(sig, Tuple): + raise BadSignatureError("Lambda signature should be a tuple not %s" % sig) + # Recurse through the signature: + rcheck(sig) + + @property + def signature(self): + """The expected form of the arguments to be unpacked into variables""" + return self._args[0] + + @property + def expr(self): + """The return value of the function""" + return self._args[1] + + @property + def variables(self): + """The variables used in the internal representation of the function""" + def _variables(args): + if isinstance(args, Tuple): + for arg in args: + yield from _variables(arg) + else: + yield args + return tuple(_variables(self.signature)) + + @property + def nargs(self): + from sympy.sets.sets import FiniteSet + return FiniteSet(len(self.signature)) + + bound_symbols = variables + + @property + def free_symbols(self): + return self.expr.free_symbols - set(self.variables) + + def __call__(self, *args): + n = len(args) + if n not in self.nargs: # Lambda only ever has 1 value in nargs + # XXX: exception message must be in exactly this format to + # make it work with NumPy's functions like vectorize(). See, + # for example, https://github.com/numpy/numpy/issues/1697. + # The ideal solution would be just to attach metadata to + # the exception and change NumPy to take advantage of this. + ## XXX does this apply to Lambda? If not, remove this comment. + temp = ('%(name)s takes exactly %(args)s ' + 'argument%(plural)s (%(given)s given)') + raise BadArgumentsError(temp % { + 'name': self, + 'args': list(self.nargs)[0], + 'plural': 's'*(list(self.nargs)[0] != 1), + 'given': n}) + + d = self._match_signature(self.signature, args) + + return self.expr.xreplace(d) + + def _match_signature(self, sig, args): + + symargmap = {} + + def rmatch(pars, args): + for par, arg in zip(pars, args): + if par.is_symbol: + symargmap[par] = arg + elif isinstance(par, Tuple): + if not isinstance(arg, (tuple, Tuple)) or len(args) != len(pars): + raise BadArgumentsError("Can't match %s and %s" % (args, pars)) + rmatch(par, arg) + + rmatch(sig, args) + + return symargmap + + @property + def is_identity(self): + """Return ``True`` if this ``Lambda`` is an identity function. """ + return self.signature == self.expr + + def _eval_evalf(self, prec): + return self.func(self.args[0], self.args[1].evalf(n=prec_to_dps(prec))) + + +class Subs(Expr): + """ + Represents unevaluated substitutions of an expression. + + ``Subs(expr, x, x0)`` represents the expression resulting + from substituting x with x0 in expr. + + Parameters + ========== + + expr : Expr + An expression. + + x : tuple, variable + A variable or list of distinct variables. + + x0 : tuple or list of tuples + A point or list of evaluation points + corresponding to those variables. + + Examples + ======== + + >>> from sympy import Subs, Function, sin, cos + >>> from sympy.abc import x, y, z + >>> f = Function('f') + + Subs are created when a particular substitution cannot be made. The + x in the derivative cannot be replaced with 0 because 0 is not a + valid variables of differentiation: + + >>> f(x).diff(x).subs(x, 0) + Subs(Derivative(f(x), x), x, 0) + + Once f is known, the derivative and evaluation at 0 can be done: + + >>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) + True + + Subs can also be created directly with one or more variables: + + >>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) + Subs(z + f(x)*sin(y), (x, y), (0, 1)) + >>> _.doit() + z + f(0)*sin(1) + + Notes + ===== + + ``Subs`` objects are generally useful to represent unevaluated derivatives + calculated at a point. + + The variables may be expressions, but they are subjected to the limitations + of subs(), so it is usually a good practice to use only symbols for + variables, since in that case there can be no ambiguity. + + There's no automatic expansion - use the method .doit() to effect all + possible substitutions of the object and also of objects inside the + expression. + + When evaluating derivatives at a point that is not a symbol, a Subs object + is returned. One is also able to calculate derivatives of Subs objects - in + this case the expression is always expanded (for the unevaluated form, use + Derivative()). + + In order to allow expressions to combine before doit is done, a + representation of the Subs expression is used internally to make + expressions that are superficially different compare the same: + + >>> a, b = Subs(x, x, 0), Subs(y, y, 0) + >>> a + b + 2*Subs(x, x, 0) + + This can lead to unexpected consequences when using methods + like `has` that are cached: + + >>> s = Subs(x, x, 0) + >>> s.has(x), s.has(y) + (True, False) + >>> ss = s.subs(x, y) + >>> ss.has(x), ss.has(y) + (True, False) + >>> s, ss + (Subs(x, x, 0), Subs(y, y, 0)) + """ + def __new__(cls, expr, variables, point, **assumptions): + if not is_sequence(variables, Tuple): + variables = [variables] + variables = Tuple(*variables) + + if has_dups(variables): + repeated = [str(v) for v, i in Counter(variables).items() if i > 1] + __ = ', '.join(repeated) + raise ValueError(filldedent(''' + The following expressions appear more than once: %s + ''' % __)) + + point = Tuple(*(point if is_sequence(point, Tuple) else [point])) + + if len(point) != len(variables): + raise ValueError('Number of point values must be the same as ' + 'the number of variables.') + + if not point: + return sympify(expr) + + # denest + if isinstance(expr, Subs): + variables = expr.variables + variables + point = expr.point + point + expr = expr.expr + else: + expr = sympify(expr) + + # use symbols with names equal to the point value (with prepended _) + # to give a variable-independent expression + pre = "_" + pts = sorted(set(point), key=default_sort_key) + from sympy.printing.str import StrPrinter + class CustomStrPrinter(StrPrinter): + def _print_Dummy(self, expr): + return str(expr) + str(expr.dummy_index) + def mystr(expr, **settings): + p = CustomStrPrinter(settings) + return p.doprint(expr) + while 1: + s_pts = {p: Symbol(pre + mystr(p)) for p in pts} + reps = [(v, s_pts[p]) + for v, p in zip(variables, point)] + # if any underscore-prepended symbol is already a free symbol + # and is a variable with a different point value, then there + # is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0)) + # because the new symbol that would be created is _1 but _1 + # is already mapped to 0 so __0 and __1 are used for the new + # symbols + if any(r in expr.free_symbols and + r in variables and + Symbol(pre + mystr(point[variables.index(r)])) != r + for _, r in reps): + pre += "_" + continue + break + + obj = Expr.__new__(cls, expr, Tuple(*variables), point) + obj._expr = expr.xreplace(dict(reps)) + return obj + + def _eval_is_commutative(self): + return self.expr.is_commutative + + def doit(self, **hints): + e, v, p = self.args + + # remove self mappings + for i, (vi, pi) in enumerate(zip(v, p)): + if vi == pi: + v = v[:i] + v[i + 1:] + p = p[:i] + p[i + 1:] + if not v: + return self.expr + + if isinstance(e, Derivative): + # apply functions first, e.g. f -> cos + undone = [] + for i, vi in enumerate(v): + if isinstance(vi, FunctionClass): + e = e.subs(vi, p[i]) + else: + undone.append((vi, p[i])) + if not isinstance(e, Derivative): + e = e.doit() + if isinstance(e, Derivative): + # do Subs that aren't related to differentiation + undone2 = [] + D = Dummy() + arg = e.args[0] + for vi, pi in undone: + if D not in e.xreplace({vi: D}).free_symbols: + if arg.has(vi): + e = e.subs(vi, pi) + else: + undone2.append((vi, pi)) + undone = undone2 + # differentiate wrt variables that are present + wrt = [] + D = Dummy() + expr = e.expr + free = expr.free_symbols + for vi, ci in e.variable_count: + if isinstance(vi, Symbol) and vi in free: + expr = expr.diff((vi, ci)) + elif D in expr.subs(vi, D).free_symbols: + expr = expr.diff((vi, ci)) + else: + wrt.append((vi, ci)) + # inject remaining subs + rv = expr.subs(undone) + # do remaining differentiation *in order given* + for vc in wrt: + rv = rv.diff(vc) + else: + # inject remaining subs + rv = e.subs(undone) + else: + rv = e.doit(**hints).subs(list(zip(v, p))) + + if hints.get('deep', True) and rv != self: + rv = rv.doit(**hints) + return rv + + def evalf(self, prec=None, **options): + return self.doit().evalf(prec, **options) + + n = evalf # type:ignore + + @property + def variables(self): + """The variables to be evaluated""" + return self._args[1] + + bound_symbols = variables + + @property + def expr(self): + """The expression on which the substitution operates""" + return self._args[0] + + @property + def point(self): + """The values for which the variables are to be substituted""" + return self._args[2] + + @property + def free_symbols(self): + return (self.expr.free_symbols - set(self.variables) | + set(self.point.free_symbols)) + + @property + def expr_free_symbols(self): + sympy_deprecation_warning(""" + The expr_free_symbols property is deprecated. Use free_symbols to get + the free symbols of an expression. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-expr-free-symbols") + # Don't show the warning twice from the recursive call + with ignore_warnings(SymPyDeprecationWarning): + return (self.expr.expr_free_symbols - set(self.variables) | + set(self.point.expr_free_symbols)) + + def __eq__(self, other): + if not isinstance(other, Subs): + return False + return self._hashable_content() == other._hashable_content() + + def __ne__(self, other): + return not(self == other) + + def __hash__(self): + return super().__hash__() + + def _hashable_content(self): + return (self._expr.xreplace(self.canonical_variables), + ) + tuple(ordered([(v, p) for v, p in + zip(self.variables, self.point) if not self.expr.has(v)])) + + def _eval_subs(self, old, new): + # Subs doit will do the variables in order; the semantics + # of subs for Subs is have the following invariant for + # Subs object foo: + # foo.doit().subs(reps) == foo.subs(reps).doit() + pt = list(self.point) + if old in self.variables: + if _atomic(new) == {new} and not any( + i.has(new) for i in self.args): + # the substitution is neutral + return self.xreplace({old: new}) + # any occurrence of old before this point will get + # handled by replacements from here on + i = self.variables.index(old) + for j in range(i, len(self.variables)): + pt[j] = pt[j]._subs(old, new) + return self.func(self.expr, self.variables, pt) + v = [i._subs(old, new) for i in self.variables] + if v != list(self.variables): + return self.func(self.expr, self.variables + (old,), pt + [new]) + expr = self.expr._subs(old, new) + pt = [i._subs(old, new) for i in self.point] + return self.func(expr, v, pt) + + def _eval_derivative(self, s): + # Apply the chain rule of the derivative on the substitution variables: + f = self.expr + vp = V, P = self.variables, self.point + val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit() + for v, p in zip(V, P)) + + # these are all the free symbols in the expr + efree = f.free_symbols + # some symbols like IndexedBase include themselves and args + # as free symbols + compound = {i for i in efree if len(i.free_symbols) > 1} + # hide them and see what independent free symbols remain + dums = {Dummy() for i in compound} + masked = f.xreplace(dict(zip(compound, dums))) + ifree = masked.free_symbols - dums + # include the compound symbols + free = ifree | compound + # remove the variables already handled + free -= set(V) + # add back any free symbols of remaining compound symbols + free |= {i for j in free & compound for i in j.free_symbols} + # if symbols of s are in free then there is more to do + if free & s.free_symbols: + val += Subs(f.diff(s), self.variables, self.point).doit() + return val + + def _eval_nseries(self, x, n, logx, cdir=0): + if x in self.point: + # x is the variable being substituted into + apos = self.point.index(x) + other = self.variables[apos] + else: + other = x + arg = self.expr.nseries(other, n=n, logx=logx) + o = arg.getO() + terms = Add.make_args(arg.removeO()) + rv = Add(*[self.func(a, *self.args[1:]) for a in terms]) + if o: + rv += o.subs(other, x) + return rv + + def _eval_as_leading_term(self, x, logx, cdir): + if x in self.point: + ipos = self.point.index(x) + xvar = self.variables[ipos] + return self.expr.as_leading_term(xvar) + if x in self.variables: + # if `x` is a dummy variable, it means it won't exist after the + # substitution has been performed: + return self + # The variable is independent of the substitution: + return self.expr.as_leading_term(x) + + +def diff(f, *symbols, **kwargs): + """ + Differentiate f with respect to symbols. + + Explanation + =========== + + This is just a wrapper to unify .diff() and the Derivative class; its + interface is similar to that of integrate(). You can use the same + shortcuts for multiple variables as with Derivative. For example, + diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative + of f(x). + + You can pass evaluate=False to get an unevaluated Derivative class. Note + that if there are 0 symbols (such as diff(f(x), x, 0), then the result will + be the function (the zeroth derivative), even if evaluate=False. + + Examples + ======== + + >>> from sympy import sin, cos, Function, diff + >>> from sympy.abc import x, y + >>> f = Function('f') + + >>> diff(sin(x), x) + cos(x) + >>> diff(f(x), x, x, x) + Derivative(f(x), (x, 3)) + >>> diff(f(x), x, 3) + Derivative(f(x), (x, 3)) + >>> diff(sin(x)*cos(y), x, 2, y, 2) + sin(x)*cos(y) + + >>> type(diff(sin(x), x)) + cos + >>> type(diff(sin(x), x, evaluate=False)) + + >>> type(diff(sin(x), x, 0)) + sin + >>> type(diff(sin(x), x, 0, evaluate=False)) + sin + + >>> diff(sin(x)) + cos(x) + >>> diff(sin(x*y)) + Traceback (most recent call last): + ... + ValueError: specify differentiation variables to differentiate sin(x*y) + + Note that ``diff(sin(x))`` syntax is meant only for convenience + in interactive sessions and should be avoided in library code. + + References + ========== + + .. [1] https://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html + + See Also + ======== + + Derivative + idiff: computes the derivative implicitly + + """ + if hasattr(f, 'diff'): + return f.diff(*symbols, **kwargs) + kwargs.setdefault('evaluate', True) + return _derivative_dispatch(f, *symbols, **kwargs) + + +def expand(e, deep=True, modulus=None, power_base=True, power_exp=True, + mul=True, log=True, multinomial=True, basic=True, **hints): + r""" + Expand an expression using methods given as hints. + + Explanation + =========== + + Hints evaluated unless explicitly set to False are: ``basic``, ``log``, + ``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following + hints are supported but not applied unless set to True: ``complex``, + ``func``, and ``trig``. In addition, the following meta-hints are + supported by some or all of the other hints: ``frac``, ``numer``, + ``denom``, ``modulus``, and ``force``. ``deep`` is supported by all + hints. Additionally, subclasses of Expr may define their own hints or + meta-hints. + + The ``basic`` hint is used for any special rewriting of an object that + should be done automatically (along with the other hints like ``mul``) + when expand is called. This is a catch-all hint to handle any sort of + expansion that may not be described by the existing hint names. To use + this hint an object should override the ``_eval_expand_basic`` method. + Objects may also define their own expand methods, which are not run by + default. See the API section below. + + If ``deep`` is set to ``True`` (the default), things like arguments of + functions are recursively expanded. Use ``deep=False`` to only expand on + the top level. + + If the ``force`` hint is used, assumptions about variables will be ignored + in making the expansion. + + Hints + ===== + + These hints are run by default + + mul + --- + + Distributes multiplication over addition: + + >>> from sympy import cos, exp, sin + >>> from sympy.abc import x, y, z + >>> (y*(x + z)).expand(mul=True) + x*y + y*z + + multinomial + ----------- + + Expand (x + y + ...)**n where n is a positive integer. + + >>> ((x + y + z)**2).expand(multinomial=True) + x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2 + + power_exp + --------- + + Expand addition in exponents into multiplied bases. + + >>> exp(x + y).expand(power_exp=True) + exp(x)*exp(y) + >>> (2**(x + y)).expand(power_exp=True) + 2**x*2**y + + power_base + ---------- + + Split powers of multiplied bases. + + This only happens by default if assumptions allow, or if the + ``force`` meta-hint is used: + + >>> ((x*y)**z).expand(power_base=True) + (x*y)**z + >>> ((x*y)**z).expand(power_base=True, force=True) + x**z*y**z + >>> ((2*y)**z).expand(power_base=True) + 2**z*y**z + + Note that in some cases where this expansion always holds, SymPy performs + it automatically: + + >>> (x*y)**2 + x**2*y**2 + + log + --- + + Pull out power of an argument as a coefficient and split logs products + into sums of logs. + + Note that these only work if the arguments of the log function have the + proper assumptions--the arguments must be positive and the exponents must + be real--or else the ``force`` hint must be True: + + >>> from sympy import log, symbols + >>> log(x**2*y).expand(log=True) + log(x**2*y) + >>> log(x**2*y).expand(log=True, force=True) + 2*log(x) + log(y) + >>> x, y = symbols('x,y', positive=True) + >>> log(x**2*y).expand(log=True) + 2*log(x) + log(y) + + basic + ----- + + This hint is intended primarily as a way for custom subclasses to enable + expansion by default. + + These hints are not run by default: + + complex + ------- + + Split an expression into real and imaginary parts. + + >>> x, y = symbols('x,y') + >>> (x + y).expand(complex=True) + re(x) + re(y) + I*im(x) + I*im(y) + >>> cos(x).expand(complex=True) + -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x)) + + Note that this is just a wrapper around ``as_real_imag()``. Most objects + that wish to redefine ``_eval_expand_complex()`` should consider + redefining ``as_real_imag()`` instead. + + func + ---- + + Expand other functions. + + >>> from sympy import gamma + >>> gamma(x + 1).expand(func=True) + x*gamma(x) + + trig + ---- + + Do trigonometric expansions. + + >>> cos(x + y).expand(trig=True) + -sin(x)*sin(y) + cos(x)*cos(y) + >>> sin(2*x).expand(trig=True) + 2*sin(x)*cos(x) + + Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)`` + and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x) + = 1`. The current implementation uses the form obtained from Chebyshev + polynomials, but this may change. See `this MathWorld article + `_ for more + information. + + Notes + ===== + + - You can shut off unwanted methods:: + + >>> (exp(x + y)*(x + y)).expand() + x*exp(x)*exp(y) + y*exp(x)*exp(y) + >>> (exp(x + y)*(x + y)).expand(power_exp=False) + x*exp(x + y) + y*exp(x + y) + >>> (exp(x + y)*(x + y)).expand(mul=False) + (x + y)*exp(x)*exp(y) + + - Use deep=False to only expand on the top level:: + + >>> exp(x + exp(x + y)).expand() + exp(x)*exp(exp(x)*exp(y)) + >>> exp(x + exp(x + y)).expand(deep=False) + exp(x)*exp(exp(x + y)) + + - Hints are applied in an arbitrary, but consistent order (in the current + implementation, they are applied in alphabetical order, except + multinomial comes before mul, but this may change). Because of this, + some hints may prevent expansion by other hints if they are applied + first. For example, ``mul`` may distribute multiplications and prevent + ``log`` and ``power_base`` from expanding them. Also, if ``mul`` is + applied before ``multinomial`, the expression might not be fully + distributed. The solution is to use the various ``expand_hint`` helper + functions or to use ``hint=False`` to this function to finely control + which hints are applied. Here are some examples:: + + >>> from sympy import expand, expand_mul, expand_power_base + >>> x, y, z = symbols('x,y,z', positive=True) + + >>> expand(log(x*(y + z))) + log(x) + log(y + z) + + Here, we see that ``log`` was applied before ``mul``. To get the mul + expanded form, either of the following will work:: + + >>> expand_mul(log(x*(y + z))) + log(x*y + x*z) + >>> expand(log(x*(y + z)), log=False) + log(x*y + x*z) + + A similar thing can happen with the ``power_base`` hint:: + + >>> expand((x*(y + z))**x) + (x*y + x*z)**x + + To get the ``power_base`` expanded form, either of the following will + work:: + + >>> expand((x*(y + z))**x, mul=False) + x**x*(y + z)**x + >>> expand_power_base((x*(y + z))**x) + x**x*(y + z)**x + + >>> expand((x + y)*y/x) + y + y**2/x + + The parts of a rational expression can be targeted:: + + >>> expand((x + y)*y/x/(x + 1), frac=True) + (x*y + y**2)/(x**2 + x) + >>> expand((x + y)*y/x/(x + 1), numer=True) + (x*y + y**2)/(x*(x + 1)) + >>> expand((x + y)*y/x/(x + 1), denom=True) + y*(x + y)/(x**2 + x) + + - The ``modulus`` meta-hint can be used to reduce the coefficients of an + expression post-expansion:: + + >>> expand((3*x + 1)**2) + 9*x**2 + 6*x + 1 + >>> expand((3*x + 1)**2, modulus=5) + 4*x**2 + x + 1 + + - Either ``expand()`` the function or ``.expand()`` the method can be + used. Both are equivalent:: + + >>> expand((x + 1)**2) + x**2 + 2*x + 1 + >>> ((x + 1)**2).expand() + x**2 + 2*x + 1 + + API + === + + Objects can define their own expand hints by defining + ``_eval_expand_hint()``. The function should take the form:: + + def _eval_expand_hint(self, **hints): + # Only apply the method to the top-level expression + ... + + See also the example below. Objects should define ``_eval_expand_hint()`` + methods only if ``hint`` applies to that specific object. The generic + ``_eval_expand_hint()`` method defined in Expr will handle the no-op case. + + Each hint should be responsible for expanding that hint only. + Furthermore, the expansion should be applied to the top-level expression + only. ``expand()`` takes care of the recursion that happens when + ``deep=True``. + + You should only call ``_eval_expand_hint()`` methods directly if you are + 100% sure that the object has the method, as otherwise you are liable to + get unexpected ``AttributeError``s. Note, again, that you do not need to + recursively apply the hint to args of your object: this is handled + automatically by ``expand()``. ``_eval_expand_hint()`` should + generally not be used at all outside of an ``_eval_expand_hint()`` method. + If you want to apply a specific expansion from within another method, use + the public ``expand()`` function, method, or ``expand_hint()`` functions. + + In order for expand to work, objects must be rebuildable by their args, + i.e., ``obj.func(*obj.args) == obj`` must hold. + + Expand methods are passed ``**hints`` so that expand hints may use + 'metahints'--hints that control how different expand methods are applied. + For example, the ``force=True`` hint described above that causes + ``expand(log=True)`` to ignore assumptions is such a metahint. The + ``deep`` meta-hint is handled exclusively by ``expand()`` and is not + passed to ``_eval_expand_hint()`` methods. + + Note that expansion hints should generally be methods that perform some + kind of 'expansion'. For hints that simply rewrite an expression, use the + .rewrite() API. + + Examples + ======== + + >>> from sympy import Expr, sympify + >>> class MyClass(Expr): + ... def __new__(cls, *args): + ... args = sympify(args) + ... return Expr.__new__(cls, *args) + ... + ... def _eval_expand_double(self, *, force=False, **hints): + ... ''' + ... Doubles the args of MyClass. + ... + ... If there more than four args, doubling is not performed, + ... unless force=True is also used (False by default). + ... ''' + ... if not force and len(self.args) > 4: + ... return self + ... return self.func(*(self.args + self.args)) + ... + >>> a = MyClass(1, 2, MyClass(3, 4)) + >>> a + MyClass(1, 2, MyClass(3, 4)) + >>> a.expand(double=True) + MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) + >>> a.expand(double=True, deep=False) + MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4)) + + >>> b = MyClass(1, 2, 3, 4, 5) + >>> b.expand(double=True) + MyClass(1, 2, 3, 4, 5) + >>> b.expand(double=True, force=True) + MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) + + See Also + ======== + + expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig, + expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand + + """ + # don't modify this; modify the Expr.expand method + hints['power_base'] = power_base + hints['power_exp'] = power_exp + hints['mul'] = mul + hints['log'] = log + hints['multinomial'] = multinomial + hints['basic'] = basic + return sympify(e).expand(deep=deep, modulus=modulus, **hints) + +# This is a special application of two hints + +def _mexpand(expr, recursive=False): + # expand multinomials and then expand products; this may not always + # be sufficient to give a fully expanded expression (see + # test_issue_8247_8354 in test_arit) + if expr is None: + return + was = None + while was != expr: + was, expr = expr, expand_mul(expand_multinomial(expr)) + if not recursive: + break + return expr + + +# These are simple wrappers around single hints. + + +def expand_mul(expr, deep=True): + """ + Wrapper around expand that only uses the mul hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import symbols, expand_mul, exp, log + >>> x, y = symbols('x,y', positive=True) + >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) + x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2) + + """ + return sympify(expr).expand(deep=deep, mul=True, power_exp=False, + power_base=False, basic=False, multinomial=False, log=False) + + +def expand_multinomial(expr, deep=True): + """ + Wrapper around expand that only uses the multinomial hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import symbols, expand_multinomial, exp + >>> x, y = symbols('x y', positive=True) + >>> expand_multinomial((x + exp(x + 1))**2) + x**2 + 2*x*exp(x + 1) + exp(2*x + 2) + + """ + return sympify(expr).expand(deep=deep, mul=False, power_exp=False, + power_base=False, basic=False, multinomial=True, log=False) + + +def expand_log(expr, deep=True, force=False, factor=False): + """ + Wrapper around expand that only uses the log hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import symbols, expand_log, exp, log + >>> x, y = symbols('x,y', positive=True) + >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) + (x + y)*(log(x) + 2*log(y))*exp(x + y) + + """ + from sympy.functions.elementary.exponential import log + from sympy.simplify.radsimp import fraction + if factor is False: + def _handleMul(x): + # look for the simple case of expanded log(b**a)/log(b) -> a in args + n, d = fraction(x) + n = [i for i in n.atoms(log) if i.args[0].is_Integer] + d = [i for i in d.atoms(log) if i.args[0].is_Integer] + if len(n) == 1 and len(d) == 1: + n = n[0] + d = d[0] + from sympy import multiplicity + m = multiplicity(d.args[0], n.args[0]) + if m: + r = m + log(n.args[0]//d.args[0]**m)/d + x = x.subs(n, d*r) + x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True)) + if x1.count(log) <= x.count(log): + return x1 + return x + + expr = expr.replace( + lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational + for i in Mul.make_args(j)) for j in x.as_numer_denom()), + _handleMul) + + return sympify(expr).expand(deep=deep, log=True, mul=False, + power_exp=False, power_base=False, multinomial=False, + basic=False, force=force, factor=factor) + + +def expand_func(expr, deep=True): + """ + Wrapper around expand that only uses the func hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import expand_func, gamma + >>> from sympy.abc import x + >>> expand_func(gamma(x + 2)) + x*(x + 1)*gamma(x) + + """ + return sympify(expr).expand(deep=deep, func=True, basic=False, + log=False, mul=False, power_exp=False, power_base=False, multinomial=False) + + +def expand_trig(expr, deep=True): + """ + Wrapper around expand that only uses the trig hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import expand_trig, sin + >>> from sympy.abc import x, y + >>> expand_trig(sin(x+y)*(x+y)) + (x + y)*(sin(x)*cos(y) + sin(y)*cos(x)) + + """ + return sympify(expr).expand(deep=deep, trig=True, basic=False, + log=False, mul=False, power_exp=False, power_base=False, multinomial=False) + + +def expand_complex(expr, deep=True): + """ + Wrapper around expand that only uses the complex hint. See the expand + docstring for more information. + + Examples + ======== + + >>> from sympy import expand_complex, exp, sqrt, I + >>> from sympy.abc import z + >>> expand_complex(exp(z)) + I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) + >>> expand_complex(sqrt(I)) + sqrt(2)/2 + sqrt(2)*I/2 + + See Also + ======== + + sympy.core.expr.Expr.as_real_imag + """ + return sympify(expr).expand(deep=deep, complex=True, basic=False, + log=False, mul=False, power_exp=False, power_base=False, multinomial=False) + + +def expand_power_base(expr, deep=True, force=False): + """ + Wrapper around expand that only uses the power_base hint. + + A wrapper to expand(power_base=True) which separates a power with a base + that is a Mul into a product of powers, without performing any other + expansions, provided that assumptions about the power's base and exponent + allow. + + deep=False (default is True) will only apply to the top-level expression. + + force=True (default is False) will cause the expansion to ignore + assumptions about the base and exponent. When False, the expansion will + only happen if the base is non-negative or the exponent is an integer. + + >>> from sympy.abc import x, y, z + >>> from sympy import expand_power_base, sin, cos, exp, Symbol + + >>> (x*y)**2 + x**2*y**2 + + >>> (2*x)**y + (2*x)**y + >>> expand_power_base(_) + 2**y*x**y + + >>> expand_power_base((x*y)**z) + (x*y)**z + >>> expand_power_base((x*y)**z, force=True) + x**z*y**z + >>> expand_power_base(sin((x*y)**z), deep=False) + sin((x*y)**z) + >>> expand_power_base(sin((x*y)**z), force=True) + sin(x**z*y**z) + + >>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) + 2**y*sin(x)**y + 2**y*cos(x)**y + + >>> expand_power_base((2*exp(y))**x) + 2**x*exp(y)**x + + >>> expand_power_base((2*cos(x))**y) + 2**y*cos(x)**y + + Notice that sums are left untouched. If this is not the desired behavior, + apply full ``expand()`` to the expression: + + >>> expand_power_base(((x+y)*z)**2) + z**2*(x + y)**2 + >>> (((x+y)*z)**2).expand() + x**2*z**2 + 2*x*y*z**2 + y**2*z**2 + + >>> expand_power_base((2*y)**(1+z)) + 2**(z + 1)*y**(z + 1) + >>> ((2*y)**(1+z)).expand() + 2*2**z*y**(z + 1) + + The power that is unexpanded can be expanded safely when + ``y != 0``, otherwise different values might be obtained for the expression: + + >>> prev = _ + + If we indicate that ``y`` is positive but then replace it with + a value of 0 after expansion, the expression becomes 0: + + >>> p = Symbol('p', positive=True) + >>> prev.subs(y, p).expand().subs(p, 0) + 0 + + But if ``z = -1`` the expression would not be zero: + + >>> prev.subs(y, 0).subs(z, -1) + 1 + + See Also + ======== + + expand + + """ + return sympify(expr).expand(deep=deep, log=False, mul=False, + power_exp=False, power_base=True, multinomial=False, + basic=False, force=force) + + +def expand_power_exp(expr, deep=True): + """ + Wrapper around expand that only uses the power_exp hint. + + See the expand docstring for more information. + + Examples + ======== + + >>> from sympy import expand_power_exp, Symbol + >>> from sympy.abc import x, y + >>> expand_power_exp(3**(y + 2)) + 9*3**y + >>> expand_power_exp(x**(y + 2)) + x**(y + 2) + + If ``x = 0`` the value of the expression depends on the + value of ``y``; if the expression were expanded the result + would be 0. So expansion is only done if ``x != 0``: + + >>> expand_power_exp(Symbol('x', zero=False)**(y + 2)) + x**2*x**y + """ + return sympify(expr).expand(deep=deep, complex=False, basic=False, + log=False, mul=False, power_exp=True, power_base=False, multinomial=False) + + +def count_ops(expr, visual=False): + """ + Return a representation (integer or expression) of the operations in expr. + + Parameters + ========== + + expr : Expr + If expr is an iterable, the sum of the op counts of the + items will be returned. + + visual : bool, optional + If ``False`` (default) then the sum of the coefficients of the + visual expression will be returned. + If ``True`` then the number of each type of operation is shown + with the core class types (or their virtual equivalent) multiplied by the + number of times they occur. + + Examples + ======== + + >>> from sympy.abc import a, b, x, y + >>> from sympy import sin, count_ops + + Although there is not a SUB object, minus signs are interpreted as + either negations or subtractions: + + >>> (x - y).count_ops(visual=True) + SUB + >>> (-x).count_ops(visual=True) + NEG + + Here, there are two Adds and a Pow: + + >>> (1 + a + b**2).count_ops(visual=True) + 2*ADD + POW + + In the following, an Add, Mul, Pow and two functions: + + >>> (sin(x)*x + sin(x)**2).count_ops(visual=True) + ADD + MUL + POW + 2*SIN + + for a total of 5: + + >>> (sin(x)*x + sin(x)**2).count_ops(visual=False) + 5 + + Note that "what you type" is not always what you get. The expression + 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather + than two DIVs: + + >>> (1/x/y).count_ops(visual=True) + DIV + MUL + + The visual option can be used to demonstrate the difference in + operations for expressions in different forms. Here, the Horner + representation is compared with the expanded form of a polynomial: + + >>> eq=x*(1 + x*(2 + x*(3 + x))) + >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) + -MUL + 3*POW + + The count_ops function also handles iterables: + + >>> count_ops([x, sin(x), None, True, x + 2], visual=False) + 2 + >>> count_ops([x, sin(x), None, True, x + 2], visual=True) + ADD + SIN + >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) + 2*ADD + SIN + + """ + from .relational import Relational + from sympy.concrete.summations import Sum + from sympy.integrals.integrals import Integral + from sympy.logic.boolalg import BooleanFunction + from sympy.simplify.radsimp import fraction + + expr = sympify(expr) + if isinstance(expr, Expr) and not expr.is_Relational: + + ops = [] + args = [expr] + NEG = Symbol('NEG') + DIV = Symbol('DIV') + SUB = Symbol('SUB') + ADD = Symbol('ADD') + EXP = Symbol('EXP') + while args: + a = args.pop() + + # if the following fails because the object is + # not Basic type, then the object should be fixed + # since it is the intention that all args of Basic + # should themselves be Basic + if a.is_Rational: + #-1/3 = NEG + DIV + if a is not S.One: + if a.p < 0: + ops.append(NEG) + if a.q != 1: + ops.append(DIV) + continue + elif a.is_Mul or a.is_MatMul: + if _coeff_isneg(a): + ops.append(NEG) + if a.args[0] is S.NegativeOne: + a = a.as_two_terms()[1] + else: + a = -a + n, d = fraction(a) + if n.is_Integer: + ops.append(DIV) + if n < 0: + ops.append(NEG) + args.append(d) + continue # won't be -Mul but could be Add + elif d is not S.One: + if not d.is_Integer: + args.append(d) + ops.append(DIV) + args.append(n) + continue # could be -Mul + elif a.is_Add or a.is_MatAdd: + aargs = list(a.args) + negs = 0 + for i, ai in enumerate(aargs): + if _coeff_isneg(ai): + negs += 1 + args.append(-ai) + if i > 0: + ops.append(SUB) + else: + args.append(ai) + if i > 0: + ops.append(ADD) + if negs == len(aargs): # -x - y = NEG + SUB + ops.append(NEG) + elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD + ops.append(SUB - ADD) + continue + if a.is_Pow and a.exp is S.NegativeOne: + ops.append(DIV) + args.append(a.base) # won't be -Mul but could be Add + continue + if a == S.Exp1: + ops.append(EXP) + continue + if a.is_Pow and a.base == S.Exp1: + ops.append(EXP) + args.append(a.exp) + continue + if a.is_Mul or isinstance(a, LatticeOp): + o = Symbol(a.func.__name__.upper()) + # count the args + ops.append(o*(len(a.args) - 1)) + elif a.args and ( + a.is_Pow or a.is_Function or isinstance(a, (Derivative, Integral, Sum))): + # if it's not in the list above we don't + # consider a.func something to count, e.g. + # Tuple, MatrixSymbol, etc... + if isinstance(a.func, UndefinedFunction): + o = Symbol("FUNC_" + a.func.__name__.upper()) + else: + o = Symbol(a.func.__name__.upper()) + ops.append(o) + + if not a.is_Symbol: + args.extend(a.args) + + elif isinstance(expr, Dict): + ops = [count_ops(k, visual=visual) + + count_ops(v, visual=visual) for k, v in expr.items()] + elif iterable(expr): + ops = [count_ops(i, visual=visual) for i in expr] + elif isinstance(expr, (Relational, BooleanFunction)): + ops = [] + for arg in expr.args: + ops.append(count_ops(arg, visual=True)) + o = Symbol(func_name(expr, short=True).upper()) + ops.append(o) + elif not isinstance(expr, Basic): + ops = [] + else: # it's Basic not isinstance(expr, Expr): + if not isinstance(expr, Basic): + raise TypeError("Invalid type of expr") + else: + ops = [] + args = [expr] + while args: + a = args.pop() + + if a.args: + o = Symbol(type(a).__name__.upper()) + if a.is_Boolean: + ops.append(o*(len(a.args)-1)) + else: + ops.append(o) + args.extend(a.args) + + if not ops: + if visual: + return S.Zero + return 0 + + ops = Add(*ops) + + if visual: + return ops + + if ops.is_Number: + return int(ops) + + return sum(int((a.args or [1])[0]) for a in Add.make_args(ops)) + + +def nfloat(expr, n=15, exponent=False, dkeys=False): + """Make all Rationals in expr Floats except those in exponents + (unless the exponents flag is set to True) and those in undefined + functions. When processing dictionaries, do not modify the keys + unless ``dkeys=True``. + + Examples + ======== + + >>> from sympy import nfloat, cos, pi, sqrt + >>> from sympy.abc import x, y + >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) + x**4 + 0.5*x + sqrt(y) + 1.5 + >>> nfloat(x**4 + sqrt(y), exponent=True) + x**4.0 + y**0.5 + + Container types are not modified: + + >>> type(nfloat((1, 2))) is tuple + True + """ + from sympy.matrices.matrixbase import MatrixBase + + kw = {"n": n, "exponent": exponent, "dkeys": dkeys} + + if isinstance(expr, MatrixBase): + return expr.applyfunc(lambda e: nfloat(e, **kw)) + + # handling of iterable containers + if iterable(expr, exclude=str): + if isinstance(expr, (dict, Dict)): + if dkeys: + args = [tuple((nfloat(i, **kw) for i in a)) + for a in expr.items()] + else: + args = [(k, nfloat(v, **kw)) for k, v in expr.items()] + if isinstance(expr, dict): + return type(expr)(args) + else: + return expr.func(*args) + elif isinstance(expr, Basic): + return expr.func(*[nfloat(a, **kw) for a in expr.args]) + return type(expr)([nfloat(a, **kw) for a in expr]) + + rv = sympify(expr) + + if rv.is_Number: + return Float(rv, n) + elif rv.is_number: + # evalf doesn't always set the precision + rv = rv.n(n) + if rv.is_Number: + rv = Float(rv.n(n), n) + else: + pass # pure_complex(rv) is likely True + return rv + elif rv.is_Atom: + return rv + elif rv.is_Relational: + args_nfloat = (nfloat(arg, **kw) for arg in rv.args) + return rv.func(*args_nfloat) + + + # watch out for RootOf instances that don't like to have + # their exponents replaced with Dummies and also sometimes have + # problems with evaluating at low precision (issue 6393) + from sympy.polys.rootoftools import RootOf + rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)}) + + from .power import Pow + if not exponent: + reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)] + rv = rv.xreplace(dict(reps)) + rv = rv.n(n) + if not exponent: + rv = rv.xreplace({d.exp: p.exp for p, d in reps}) + else: + # Pow._eval_evalf special cases Integer exponents so if + # exponent is suppose to be handled we have to do so here + rv = rv.xreplace(Transform( + lambda x: Pow(x.base, Float(x.exp, n)), + lambda x: x.is_Pow and x.exp.is_Integer)) + + return rv.xreplace(Transform( + lambda x: x.func(*nfloat(x.args, n, exponent)), + lambda x: isinstance(x, Function) and not isinstance(x, AppliedUndef))) + + +from .symbol import Dummy, Symbol diff --git a/shared/package-files/cb/cb513a6b12af4fe02f81f989ad5329b580d5279b2fb7bdb78cdb90608269fe48/mkl.cmake b/shared/package-files/cb/cb513a6b12af4fe02f81f989ad5329b580d5279b2fb7bdb78cdb90608269fe48/mkl.cmake new file mode 100644 index 0000000000000000000000000000000000000000..2f6d1fd905aa303cc240b058318acdfb2483e9ad --- /dev/null +++ b/shared/package-files/cb/cb513a6b12af4fe02f81f989ad5329b580d5279b2fb7bdb78cdb90608269fe48/mkl.cmake @@ -0,0 +1,40 @@ +find_package(MKL QUIET) + +if(TARGET caffe2::mkl) + return() +endif() + +add_library(caffe2::mkl INTERFACE IMPORTED) +target_include_directories(caffe2::mkl INTERFACE ${MKL_INCLUDE_DIR}) +target_link_libraries(caffe2::mkl INTERFACE ${MKL_LIBRARIES}) +foreach(MKL_LIB IN LISTS MKL_LIBRARIES) + if(EXISTS "${MKL_LIB}") + get_filename_component(MKL_LINK_DIR "${MKL_LIB}" DIRECTORY) + if(IS_DIRECTORY "${MKL_LINK_DIR}") + target_link_directories(caffe2::mkl INTERFACE "${MKL_LINK_DIR}") + endif() + endif() +endforeach() + +# TODO: This is a hack, it will not pick up architecture dependent +# MKL libraries correctly; see https://github.com/pytorch/pytorch/issues/73008 +set_property( + TARGET caffe2::mkl PROPERTY INTERFACE_LINK_DIRECTORIES + ${MKL_ROOT}/lib ${MKL_ROOT}/lib/intel64 ${MKL_ROOT}/lib/intel64_win ${MKL_ROOT}/lib/win-x64) + +if(UNIX) + if(USE_STATIC_MKL) + foreach(MKL_LIB_PATH IN LISTS MKL_LIBRARIES) + if(NOT EXISTS "${MKL_LIB_PATH}") + continue() + endif() + + get_filename_component(MKL_LIB_NAME "${MKL_LIB_PATH}" NAME) + + # Match archive libraries starting with "libmkl_" + if(MKL_LIB_NAME MATCHES "^libmkl_" AND MKL_LIB_NAME MATCHES ".a$") + target_link_options(caffe2::mkl INTERFACE "-Wl,--exclude-libs,${MKL_LIB_NAME}") + endif() + endforeach() + endif() +endif() diff --git a/shared/package-files/cb/cb52c599ac421496868ac746d3e321a1d0f398974a28ababe4ccb1e32d61842e/pybind.h b/shared/package-files/cb/cb52c599ac421496868ac746d3e321a1d0f398974a28ababe4ccb1e32d61842e/pybind.h new file mode 100644 index 0000000000000000000000000000000000000000..1eb7818c00e906b9069f64298b3901450bde88c1 --- /dev/null +++ b/shared/package-files/cb/cb52c599ac421496868ac746d3e321a1d0f398974a28ababe4ccb1e32d61842e/pybind.h @@ -0,0 +1,7 @@ +#include + +namespace torch::inductor { + +void initAOTIPackageBindings(PyObject* module); + +} // namespace torch::inductor diff --git a/shared/package-files/cb/cb572364dba65422d73b2c050760d1b29ed7396549b9854c6bf882997f6557b6/decomp_utils.cpython-311.pyc b/shared/package-files/cb/cb572364dba65422d73b2c050760d1b29ed7396549b9854c6bf882997f6557b6/decomp_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c949bb64a49746b8196f4b0543b78e06accf6a4e Binary files /dev/null and b/shared/package-files/cb/cb572364dba65422d73b2c050760d1b29ed7396549b9854c6bf882997f6557b6/decomp_utils.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb5764611c5c01eef8119ed1f7dc3b9c0eb802757c1ef3be7ae0e0a54478ad62/vander_native.h b/shared/package-files/cb/cb5764611c5c01eef8119ed1f7dc3b9c0eb802757c1ef3be7ae0e0a54478ad62/vander_native.h new file mode 100644 index 0000000000000000000000000000000000000000..96255830849d21a5c14b1651cdf37d4ff44a52ca --- /dev/null +++ b/shared/package-files/cb/cb5764611c5c01eef8119ed1f7dc3b9c0eb802757c1ef3be7ae0e0a54478ad62/vander_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor vander(const at::Tensor & x, ::std::optional N=::std::nullopt, bool increasing=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cb61cbd255dff3fdec44878f31166df2fb62c7ab21c407de3a4914e5690af5cf/gen_annotated_fn_args.cpython-311.pyc b/shared/package-files/cb/cb61cbd255dff3fdec44878f31166df2fb62c7ab21c407de3a4914e5690af5cf/gen_annotated_fn_args.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64fdb9e623e5c89cbc6511e8540c79e6d0279b8a Binary files /dev/null and b/shared/package-files/cb/cb61cbd255dff3fdec44878f31166df2fb62c7ab21c407de3a4914e5690af5cf/gen_annotated_fn_args.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb62108d0d84ce131e2db11aa0b2374200d9e6d4a889ce0420634ff7796fb236/test_indexing.cpython-311.pyc b/shared/package-files/cb/cb62108d0d84ce131e2db11aa0b2374200d9e6d4a889ce0420634ff7796fb236/test_indexing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8af51b307b85fbca2aca1d42c742b41f9d861c6 Binary files /dev/null and b/shared/package-files/cb/cb62108d0d84ce131e2db11aa0b2374200d9e6d4a889ce0420634ff7796fb236/test_indexing.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb6705c5ae9efac684140f5a5b6d99b93c22d30b9dede107abb5cddefdf42d3d/cooperative_groups.h b/shared/package-files/cb/cb6705c5ae9efac684140f5a5b6d99b93c22d30b9dede107abb5cddefdf42d3d/cooperative_groups.h new file mode 100644 index 0000000000000000000000000000000000000000..0532a97bbaba37b6aa8540426d9d89adef6f4612 --- /dev/null +++ b/shared/package-files/cb/cb6705c5ae9efac684140f5a5b6d99b93c22d30b9dede107abb5cddefdf42d3d/cooperative_groups.h @@ -0,0 +1,1743 @@ +/* + * Copyright 1993-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#ifndef _COOPERATIVE_GROUPS_H_ +#define _COOPERATIVE_GROUPS_H_ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#include "cooperative_groups/details/info.h" +#include "cooperative_groups/details/driver_abi.h" +#include "cooperative_groups/details/helpers.h" +#include "cooperative_groups/details/memory.h" + +#if defined(_CG_HAS_STL_ATOMICS) +#include +#define _CG_THREAD_SCOPE(scope) _CG_STATIC_CONST_DECL cuda::thread_scope thread_scope = scope; +#else +#define _CG_THREAD_SCOPE(scope) +#endif + +_CG_BEGIN_NAMESPACE + +namespace details { + _CG_CONST_DECL unsigned int coalesced_group_id = 1; + _CG_CONST_DECL unsigned int multi_grid_group_id = 2; + _CG_CONST_DECL unsigned int grid_group_id = 3; + _CG_CONST_DECL unsigned int thread_block_id = 4; + _CG_CONST_DECL unsigned int multi_tile_group_id = 5; + _CG_CONST_DECL unsigned int cluster_group_id = 6; +} + +/** + * class thread_group; + * + * Generic thread group type, into which all groups are convertible. + * It acts as a container for all storage necessary for the derived groups, + * and will dispatch the API calls to the correct derived group. This means + * that all derived groups must implement the same interface as thread_group. + */ +class thread_group +{ +protected: + struct group_data { + unsigned int _unused : 1; + unsigned int type : 7, : 0; + }; + + struct gg_data { + details::grid_workspace *gridWs; + }; + +#if defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) + struct mg_data { + unsigned long long _unused : 1; + unsigned long long type : 7; + unsigned long long handle : 56; + const details::multi_grid::multi_grid_functions *functions; + }; +#endif + + struct tg_data { + unsigned int is_tiled : 1; + unsigned int type : 7; + unsigned int size : 24; + // packed to 4b + unsigned int metaGroupSize : 16; + unsigned int metaGroupRank : 16; + // packed to 8b + unsigned int mask; + // packed to 12b + unsigned int _res; + }; + + friend _CG_QUALIFIER thread_group tiled_partition(const thread_group& parent, unsigned int tilesz); + friend class thread_block; + + union __align__(8) { + group_data group; + tg_data coalesced; + gg_data grid; +#if defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) + mg_data multi_grid; +#endif + } _data; + + _CG_QUALIFIER thread_group operator=(const thread_group& src); + + _CG_QUALIFIER thread_group(unsigned int type) { + _data.group.type = type; + _data.group._unused = false; + } + +#ifdef _CG_CPP11_FEATURES + static_assert(sizeof(tg_data) <= 16, "Failed size check"); + static_assert(sizeof(gg_data) <= 16, "Failed size check"); +# ifdef _CG_ABI_EXPERIMENTAL + static_assert(sizeof(mg_data) <= 16, "Failed size check"); +# endif +#endif + +public: + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_device) + + _CG_QUALIFIER unsigned long long size() const; + _CG_QUALIFIER unsigned long long num_threads() const; + _CG_QUALIFIER unsigned long long thread_rank() const; + _CG_QUALIFIER void sync() const; + _CG_QUALIFIER unsigned int get_type() const { + return _data.group.type; + } + +}; + +template +struct thread_group_base : public thread_group { + _CG_QUALIFIER thread_group_base() : thread_group(TyId) {} + _CG_STATIC_CONST_DECL unsigned int id = TyId; +}; + +#if defined(_CG_HAS_MULTI_GRID_GROUP) + +/** + * class multi_grid_group; + * + * Threads within this this group are guaranteed to be co-resident on the + * same system, on multiple devices within the same launched kernels. + * To use this group, the kernel must have been launched with + * cuLaunchCooperativeKernelMultiDevice (or the CUDA Runtime equivalent), + * and the device must support it (queryable device attribute). + * + * Constructed via this_multi_grid(); + */ + + +# if defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) +class multi_grid_group; + +// Multi grid group requires these functions to be templated to prevent ptxas from trying to use CG syscalls +template +__device__ _CG_DEPRECATED multi_grid_group this_multi_grid(); + +class multi_grid_group : public thread_group_base +{ +private: + template + _CG_QUALIFIER multi_grid_group() { + _data.multi_grid.functions = details::multi_grid::load_grid_intrinsics(); + _data.multi_grid.handle = _data.multi_grid.functions->get_intrinsic_handle(); + } + + friend multi_grid_group this_multi_grid(); + +public: + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_system) + + _CG_QUALIFIER bool is_valid() const { + return (_data.multi_grid.handle != 0); + } + + _CG_QUALIFIER void sync() const { + if (!is_valid()) { + _CG_ABORT(); + } + _data.multi_grid.functions->sync(_data.multi_grid.handle); + } + + _CG_QUALIFIER unsigned long long num_threads() const { + _CG_ASSERT(is_valid()); + return _data.multi_grid.functions->size(_data.multi_grid.handle); + } + + _CG_QUALIFIER unsigned long long size() const { + return num_threads(); + } + + _CG_QUALIFIER unsigned long long thread_rank() const { + _CG_ASSERT(is_valid()); + return _data.multi_grid.functions->thread_rank(_data.multi_grid.handle); + } + + _CG_QUALIFIER unsigned int grid_rank() const { + _CG_ASSERT(is_valid()); + return (_data.multi_grid.functions->grid_rank(_data.multi_grid.handle)); + } + + _CG_QUALIFIER unsigned int num_grids() const { + _CG_ASSERT(is_valid()); + return (_data.multi_grid.functions->num_grids(_data.multi_grid.handle)); + } +}; +# else +class multi_grid_group +{ +private: + unsigned long long _handle; + unsigned int _size; + unsigned int _rank; + + friend _CG_QUALIFIER multi_grid_group this_multi_grid(); + + _CG_QUALIFIER multi_grid_group() { + _handle = details::multi_grid::get_intrinsic_handle(); + _size = details::multi_grid::size(_handle); + _rank = details::multi_grid::thread_rank(_handle); + } + +public: + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_system) + + _CG_QUALIFIER _CG_DEPRECATED bool is_valid() const { + return (_handle != 0); + } + + _CG_QUALIFIER _CG_DEPRECATED void sync() const { + if (!is_valid()) { + _CG_ABORT(); + } + details::multi_grid::sync(_handle); + } + + _CG_QUALIFIER _CG_DEPRECATED unsigned long long num_threads() const { + _CG_ASSERT(is_valid()); + return _size; + } + + _CG_QUALIFIER _CG_DEPRECATED unsigned long long size() const { + return num_threads(); + } + + _CG_QUALIFIER _CG_DEPRECATED unsigned long long thread_rank() const { + _CG_ASSERT(is_valid()); + return _rank; + } + + _CG_QUALIFIER _CG_DEPRECATED unsigned int grid_rank() const { + _CG_ASSERT(is_valid()); + return (details::multi_grid::grid_rank(_handle)); + } + + _CG_QUALIFIER _CG_DEPRECATED unsigned int num_grids() const { + _CG_ASSERT(is_valid()); + return (details::multi_grid::num_grids(_handle)); + } +}; +# endif + +/** + * multi_grid_group this_multi_grid() + * + * Constructs a multi_grid_group + */ +# if defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) +template +__device__ +#else +_CG_QUALIFIER +# endif +_CG_DEPRECATED +multi_grid_group this_multi_grid() +{ + return multi_grid_group(); +} +#endif + +/** + * class grid_group; + * + * Threads within this this group are guaranteed to be co-resident on the + * same device within the same launched kernel. To use this group, the kernel + * must have been launched with cuLaunchCooperativeKernel (or the CUDA Runtime equivalent), + * and the device must support it (queryable device attribute). + * + * Constructed via this_grid(); + */ +class grid_group : public thread_group_base +{ + _CG_STATIC_CONST_DECL unsigned int _group_id = details::grid_group_id; + friend _CG_QUALIFIER grid_group this_grid(); + +private: + _CG_QUALIFIER grid_group(details::grid_workspace *gridWs) { + _data.grid.gridWs = gridWs; + } + + public: + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_device) + + _CG_QUALIFIER bool is_valid() const { + return (_data.grid.gridWs != NULL); + } + + _CG_QUALIFIER void sync() const { + if (!is_valid()) { + _CG_ABORT(); + } + details::grid::sync(&_data.grid.gridWs->barrier); + } + +#if defined(_CG_CPP11_FEATURES) + using arrival_token = unsigned int; + + _CG_QUALIFIER arrival_token barrier_arrive() const { + if (!is_valid()) { + _CG_ABORT(); + } + return details::grid::barrier_arrive(&_data.grid.gridWs->barrier); + } + + _CG_QUALIFIER void barrier_wait(arrival_token&& token) const { + details::grid::barrier_wait(token, &_data.grid.gridWs->barrier); + } +#endif + + _CG_STATIC_QUALIFIER unsigned long long size() { + return details::grid::size(); + } + + _CG_STATIC_QUALIFIER dim3 group_dim() { + return details::grid::grid_dim(); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() { + return details::grid::dim_threads(); + } + + _CG_STATIC_QUALIFIER unsigned long long num_threads() { + return details::grid::num_threads(); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() { + return details::grid::thread_index(); + } + + _CG_STATIC_QUALIFIER unsigned long long thread_rank() { + return details::grid::thread_rank(); + } + + _CG_STATIC_QUALIFIER dim3 dim_blocks() { + return details::grid::dim_blocks(); + } + + _CG_STATIC_QUALIFIER unsigned long long num_blocks() { + return details::grid::num_blocks(); + } + + _CG_STATIC_QUALIFIER dim3 block_index() { + return details::grid::block_index(); + } + + _CG_STATIC_QUALIFIER unsigned long long block_rank() { + return details::grid::block_rank(); + } + +# if defined(_CG_HAS_CLUSTER_GROUP) + _CG_STATIC_QUALIFIER dim3 dim_clusters() { + return details::grid::dim_clusters(); + } + + _CG_STATIC_QUALIFIER unsigned long long num_clusters() { + return details::grid::num_clusters(); + } + + _CG_STATIC_QUALIFIER dim3 cluster_index() { + return details::grid::cluster_index(); + } + + _CG_STATIC_QUALIFIER unsigned long long cluster_rank() { + return details::grid::cluster_rank(); + } +# endif +}; + +_CG_QUALIFIER grid_group this_grid() { + // Load a workspace from the driver + grid_group gg(details::get_grid_workspace()); +#ifdef _CG_DEBUG + // *all* threads must be available to synchronize + gg.sync(); +#endif // _CG_DEBUG + return gg; +} + +#if defined(_CG_HAS_CLUSTER_GROUP) +/** + * class cluster_group + * + * Every GPU kernel is executed by a grid of thread blocks. A grid can be evenly + * divided along all dimensions to form groups of blocks, each group of which is + * a block cluster. Clustered grids are subject to various restrictions and + * limitations. Primarily, a cluster consists of at most 8 blocks by default + * (although the user is allowed to opt-in to non-standard sizes,) and clustered + * grids are subject to additional occupancy limitations due to per-cluster + * hardware resource consumption. In exchange, a block cluster is guaranteed to + * be a cooperative group, with access to all cooperative group capabilities, as + * well as cluster specific capabilities and accelerations. A cluster_group + * represents a block cluster. + * + * Constructed via this_cluster_group(); + */ +class cluster_group : public thread_group_base +{ + // Friends + friend _CG_QUALIFIER cluster_group this_cluster(); + + // Disable constructor + _CG_QUALIFIER cluster_group() + { + } + + public: + //_CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_cluster) + + using arrival_token = struct {}; + + // Functionality exposed by the group + _CG_STATIC_QUALIFIER void sync() + { + return details::cluster::sync(); + } + + _CG_STATIC_QUALIFIER arrival_token barrier_arrive() + { + details::cluster::barrier_arrive(); + return arrival_token(); + } + + _CG_STATIC_QUALIFIER void barrier_wait() + { + return details::cluster::barrier_wait(); + } + + _CG_STATIC_QUALIFIER void barrier_wait(arrival_token&&) + { + return details::cluster::barrier_wait(); + } + + _CG_STATIC_QUALIFIER unsigned int query_shared_rank(const void *addr) + { + return details::cluster::query_shared_rank(addr); + } + + template + _CG_STATIC_QUALIFIER T* map_shared_rank(T *addr, int rank) + { + return details::cluster::map_shared_rank(addr, rank); + } + + _CG_STATIC_QUALIFIER dim3 block_index() + { + return details::cluster::block_index(); + } + + _CG_STATIC_QUALIFIER unsigned int block_rank() + { + return details::cluster::block_rank(); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() + { + return details::cluster::thread_index(); + } + + _CG_STATIC_QUALIFIER unsigned int thread_rank() + { + return details::cluster::thread_rank(); + } + + _CG_STATIC_QUALIFIER dim3 dim_blocks() + { + return details::cluster::dim_blocks(); + } + + _CG_STATIC_QUALIFIER unsigned int num_blocks() + { + return details::cluster::num_blocks(); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() + { + return details::cluster::dim_threads(); + } + + _CG_STATIC_QUALIFIER unsigned int num_threads() + { + return details::cluster::num_threads(); + } + + // Legacy aliases + _CG_STATIC_QUALIFIER unsigned int size() + { + return num_threads(); + } +}; + +/* + * cluster_group this_cluster() + * + * Constructs a cluster_group + */ +_CG_QUALIFIER cluster_group this_cluster() +{ + cluster_group cg; +#ifdef _CG_DEBUG + cg.sync(); +#endif + return cg; +} +#endif + +#if defined(_CG_CPP11_FEATURES) +class thread_block; +template +_CG_QUALIFIER thread_block this_thread_block(block_tile_memory& scratch); +#endif + +/** + * class thread_block + * + * Every GPU kernel is executed by a grid of thread blocks, and threads within + * each block are guaranteed to reside on the same streaming multiprocessor. + * A thread_block represents a thread block whose dimensions are not known until runtime. + * + * Constructed via this_thread_block(); + */ +class thread_block : public thread_group_base +{ + // Friends + friend _CG_QUALIFIER thread_block this_thread_block(); + friend _CG_QUALIFIER thread_group tiled_partition(const thread_group& parent, unsigned int tilesz); + friend _CG_QUALIFIER thread_group tiled_partition(const thread_block& parent, unsigned int tilesz); + +#if defined(_CG_CPP11_FEATURES) + template + friend _CG_QUALIFIER thread_block this_thread_block(block_tile_memory& scratch); + template + friend class __static_size_multi_warp_tile_base; + + details::multi_warp_scratch* const tile_memory; + + template + _CG_QUALIFIER thread_block(block_tile_memory& scratch) : + tile_memory(details::get_scratch_ptr(&scratch)) { +#ifdef _CG_DEBUG + if (num_threads() > MaxBlockSize) { + details::abort(); + } +#endif + + +#if defined(_CG_USER_PROVIDED_SHARED_MEMORY) +#define _CG_SKIP_BARRIER_INIT_TARGET NV_NO_TARGET +#else +#define _CG_SKIP_BARRIER_INIT_TARGET NV_PROVIDES_SM_80 +#endif + NV_IF_ELSE_TARGET( + _CG_SKIP_BARRIER_INIT_TARGET, + // skip if clause + , + (tile_memory->init_barriers(thread_rank()); + sync();) + ) + } +#endif +#undef _CG_SKIP_BARRIER_INIT_TARGET + + // Disable constructor + _CG_QUALIFIER thread_block() +#if defined(_CG_CPP11_FEATURES) + : tile_memory(details::get_scratch_ptr(NULL)) +#endif + { } + + // Internal Use + _CG_QUALIFIER thread_group _get_tiled_threads(unsigned int tilesz) const { + const bool pow2_tilesz = ((tilesz & (tilesz - 1)) == 0); + + // Invalid, immediately fail + if (tilesz == 0 || (tilesz > 32) || !pow2_tilesz) { + details::abort(); + return (thread_block()); + } + + unsigned int mask; + unsigned int base_offset = thread_rank() & (~(tilesz - 1)); + unsigned int masklength = min((unsigned int)size() - base_offset, tilesz); + + mask = (unsigned int)(-1) >> (32 - masklength); + mask <<= (details::laneid() & ~(tilesz - 1)); + thread_group tile = thread_group(details::coalesced_group_id); + tile._data.coalesced.mask = mask; + tile._data.coalesced.size = __popc(mask); + tile._data.coalesced.metaGroupSize = (details::cta::size() + tilesz - 1) / tilesz; + tile._data.coalesced.metaGroupRank = details::cta::thread_rank() / tilesz; + tile._data.coalesced.is_tiled = true; + return (tile); + } + + public: + _CG_STATIC_CONST_DECL unsigned int _group_id = details::thread_block_id; + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_block) + + _CG_STATIC_QUALIFIER void sync() { + details::cta::sync(); + } + +#if defined(_CG_CPP11_FEATURES) + struct arrival_token {}; + + _CG_QUALIFIER arrival_token barrier_arrive() const { + return arrival_token(); + } + + _CG_QUALIFIER void barrier_wait(arrival_token&&) const { + details::cta::sync(); + } +#endif + + _CG_STATIC_QUALIFIER unsigned int size() { + return details::cta::size(); + } + + _CG_STATIC_QUALIFIER unsigned int thread_rank() { + return details::cta::thread_rank(); + } + + // Additional functionality exposed by the group + _CG_STATIC_QUALIFIER dim3 group_index() { + return details::cta::group_index(); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() { + return details::cta::thread_index(); + } + + _CG_STATIC_QUALIFIER dim3 group_dim() { + return details::cta::block_dim(); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() { + return details::cta::dim_threads(); + } + + _CG_STATIC_QUALIFIER unsigned int num_threads() { + return details::cta::num_threads(); + } + +}; + +/** + * thread_block this_thread_block() + * + * Constructs a thread_block group + */ +_CG_QUALIFIER thread_block this_thread_block() +{ + return (thread_block()); +} + +#if defined(_CG_CPP11_FEATURES) +template +_CG_QUALIFIER thread_block this_thread_block(block_tile_memory& scratch) { + return (thread_block(scratch)); +} +#endif + +/** + * class coalesced_group + * + * A group representing the current set of converged threads in a warp. + * The size of the group is not guaranteed and it may return a group of + * only one thread (itself). + * + * This group exposes warp-synchronous builtins. + * Constructed via coalesced_threads(); + */ +class coalesced_group : public thread_group_base +{ +private: + friend _CG_QUALIFIER coalesced_group coalesced_threads(); + friend _CG_QUALIFIER thread_group tiled_partition(const thread_group& parent, unsigned int tilesz); + friend _CG_QUALIFIER coalesced_group tiled_partition(const coalesced_group& parent, unsigned int tilesz); + friend class details::_coalesced_group_data_access; + + _CG_QUALIFIER unsigned int _packLanes(unsigned laneMask) const { + unsigned int member_pack = 0; + unsigned int member_rank = 0; + for (int bit_idx = 0; bit_idx < 32; bit_idx++) { + unsigned int lane_bit = _data.coalesced.mask & (1 << bit_idx); + if (lane_bit) { + if (laneMask & lane_bit) + member_pack |= 1 << member_rank; + member_rank++; + } + } + return (member_pack); + } + + // Internal Use + _CG_QUALIFIER coalesced_group _get_tiled_threads(unsigned int tilesz) const { + const bool pow2_tilesz = ((tilesz & (tilesz - 1)) == 0); + + // Invalid, immediately fail + if (tilesz == 0 || (tilesz > 32) || !pow2_tilesz) { + details::abort(); + return (coalesced_group(0)); + } + if (size() <= tilesz) { + return (*this); + } + + if ((_data.coalesced.is_tiled == true) && pow2_tilesz) { + unsigned int base_offset = (thread_rank() & (~(tilesz - 1))); + unsigned int masklength = min((unsigned int)size() - base_offset, tilesz); + unsigned int mask = (unsigned int)(-1) >> (32 - masklength); + + mask <<= (details::laneid() & ~(tilesz - 1)); + coalesced_group coalesced_tile = coalesced_group(mask); + coalesced_tile._data.coalesced.metaGroupSize = size() / tilesz; + coalesced_tile._data.coalesced.metaGroupRank = thread_rank() / tilesz; + coalesced_tile._data.coalesced.is_tiled = true; + return (coalesced_tile); + } + else if ((_data.coalesced.is_tiled == false) && pow2_tilesz) { + unsigned int mask = 0; + unsigned int member_rank = 0; + int seen_lanes = (thread_rank() / tilesz) * tilesz; + for (unsigned int bit_idx = 0; bit_idx < 32; bit_idx++) { + unsigned int lane_bit = _data.coalesced.mask & (1 << bit_idx); + if (lane_bit) { + if (seen_lanes <= 0 && member_rank < tilesz) { + mask |= lane_bit; + member_rank++; + } + seen_lanes--; + } + } + coalesced_group coalesced_tile = coalesced_group(mask); + // Override parent with the size of this group + coalesced_tile._data.coalesced.metaGroupSize = (size() + tilesz - 1) / tilesz; + coalesced_tile._data.coalesced.metaGroupRank = thread_rank() / tilesz; + return coalesced_tile; + } + else { + // None in _CG_VERSION 1000 + details::abort(); + } + + return (coalesced_group(0)); + } + + protected: + _CG_QUALIFIER coalesced_group(unsigned int mask) { + _data.coalesced.mask = mask; + _data.coalesced.size = __popc(mask); + _data.coalesced.metaGroupRank = 0; + _data.coalesced.metaGroupSize = 1; + _data.coalesced.is_tiled = false; + } + + _CG_QUALIFIER unsigned int get_mask() const { + return (_data.coalesced.mask); + } + + public: + _CG_STATIC_CONST_DECL unsigned int _group_id = details::coalesced_group_id; + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_block) + + _CG_QUALIFIER unsigned int num_threads() const { + return _data.coalesced.size; + } + + _CG_QUALIFIER unsigned int size() const { + return num_threads(); + } + + _CG_QUALIFIER unsigned int thread_rank() const { + return (__popc(_data.coalesced.mask & details::lanemask32_lt())); + } + + // Rank of this group in the upper level of the hierarchy + _CG_QUALIFIER unsigned int meta_group_rank() const { + return _data.coalesced.metaGroupRank; + } + + // Total num partitions created out of all CTAs when the group was created + _CG_QUALIFIER unsigned int meta_group_size() const { + return _data.coalesced.metaGroupSize; + } + + _CG_QUALIFIER void sync() const { + __syncwarp(_data.coalesced.mask); + } + +#ifdef _CG_CPP11_FEATURES + template > + _CG_QUALIFIER TyRet shfl(TyElem&& elem, int srcRank) const { + unsigned int lane = (srcRank == 0) ? __ffs(_data.coalesced.mask) - 1 : + (size() == 32) ? srcRank : __fns(_data.coalesced.mask, 0, (srcRank + 1)); + + return details::tile::shuffle_dispatch::shfl( + _CG_STL_NAMESPACE::forward(elem), _data.coalesced.mask, lane, 32); + } + + template > + _CG_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int delta) const { + if (size() == 32) { + return details::tile::shuffle_dispatch::shfl_down( + _CG_STL_NAMESPACE::forward(elem), 0xFFFFFFFF, delta, 32); + } + + unsigned int lane = __fns(_data.coalesced.mask, details::laneid(), delta + 1); + + if (lane >= 32) + lane = details::laneid(); + + return details::tile::shuffle_dispatch::shfl( + _CG_STL_NAMESPACE::forward(elem), _data.coalesced.mask, lane, 32); + } + + template > + _CG_QUALIFIER TyRet shfl_up(TyElem&& elem, int delta) const { + if (size() == 32) { + return details::tile::shuffle_dispatch::shfl_up( + _CG_STL_NAMESPACE::forward(elem), 0xFFFFFFFF, delta, 32); + } + + unsigned lane = __fns(_data.coalesced.mask, details::laneid(), -(delta + 1)); + if (lane >= 32) + lane = details::laneid(); + + return details::tile::shuffle_dispatch::shfl( + _CG_STL_NAMESPACE::forward(elem), _data.coalesced.mask, lane, 32); + } +#else + template + _CG_QUALIFIER TyIntegral shfl(TyIntegral var, unsigned int src_rank) const { + details::assert_if_not_arithmetic(); + unsigned int lane = (src_rank == 0) ? __ffs(_data.coalesced.mask) - 1 : + (size() == 32) ? src_rank : __fns(_data.coalesced.mask, 0, (src_rank + 1)); + return (__shfl_sync(_data.coalesced.mask, var, lane, 32)); + } + + template + _CG_QUALIFIER TyIntegral shfl_up(TyIntegral var, int delta) const { + details::assert_if_not_arithmetic(); + if (size() == 32) { + return (__shfl_up_sync(0xFFFFFFFF, var, delta, 32)); + } + unsigned lane = __fns(_data.coalesced.mask, details::laneid(), -(delta + 1)); + if (lane >= 32) lane = details::laneid(); + return (__shfl_sync(_data.coalesced.mask, var, lane, 32)); + } + + template + _CG_QUALIFIER TyIntegral shfl_down(TyIntegral var, int delta) const { + details::assert_if_not_arithmetic(); + if (size() == 32) { + return (__shfl_down_sync(0xFFFFFFFF, var, delta, 32)); + } + unsigned int lane = __fns(_data.coalesced.mask, details::laneid(), delta + 1); + if (lane >= 32) lane = details::laneid(); + return (__shfl_sync(_data.coalesced.mask, var, lane, 32)); + } +#endif + + _CG_QUALIFIER int any(int predicate) const { + return (__ballot_sync(_data.coalesced.mask, predicate) != 0); + } + _CG_QUALIFIER int all(int predicate) const { + return (__ballot_sync(_data.coalesced.mask, predicate) == _data.coalesced.mask); + } + _CG_QUALIFIER unsigned int ballot(int predicate) const { + if (size() == 32) { + return (__ballot_sync(0xFFFFFFFF, predicate)); + } + unsigned int lane_ballot = __ballot_sync(_data.coalesced.mask, predicate); + return (_packLanes(lane_ballot)); + } + +#ifdef _CG_HAS_MATCH_COLLECTIVE + + template + _CG_QUALIFIER unsigned int match_any(TyIntegral val) const { + details::assert_if_not_arithmetic(); + if (size() == 32) { + return (__match_any_sync(0xFFFFFFFF, val)); + } + unsigned int lane_match = __match_any_sync(_data.coalesced.mask, val); + return (_packLanes(lane_match)); + } + + template + _CG_QUALIFIER unsigned int match_all(TyIntegral val, int &pred) const { + details::assert_if_not_arithmetic(); + if (size() == 32) { + return (__match_all_sync(0xFFFFFFFF, val, &pred)); + } + unsigned int lane_match = __match_all_sync(_data.coalesced.mask, val, &pred); + return (_packLanes(lane_match)); + } + +#endif /* !_CG_HAS_MATCH_COLLECTIVE */ + +}; + +_CG_QUALIFIER coalesced_group coalesced_threads() +{ + return (coalesced_group(__activemask())); +} + +namespace details { + template struct verify_thread_block_tile_size; + template <> struct verify_thread_block_tile_size<32> { typedef void OK; }; + template <> struct verify_thread_block_tile_size<16> { typedef void OK; }; + template <> struct verify_thread_block_tile_size<8> { typedef void OK; }; + template <> struct verify_thread_block_tile_size<4> { typedef void OK; }; + template <> struct verify_thread_block_tile_size<2> { typedef void OK; }; + template <> struct verify_thread_block_tile_size<1> { typedef void OK; }; + +#ifdef _CG_CPP11_FEATURES + template + using _is_power_of_2 = _CG_STL_NAMESPACE::integral_constant; + + template + using _is_single_warp = _CG_STL_NAMESPACE::integral_constant; + template + using _is_multi_warp = + _CG_STL_NAMESPACE::integral_constant 32) && (Size <= 1024)>; + + template + using _is_valid_single_warp_tile = + _CG_STL_NAMESPACE::integral_constant::value && _is_single_warp::value>; + template + using _is_valid_multi_warp_tile = + _CG_STL_NAMESPACE::integral_constant::value && _is_multi_warp::value>; +#else + template + struct _is_multi_warp { + static const bool value = false; + }; +#endif +} + +template +class __static_size_tile_base +{ +protected: + _CG_STATIC_CONST_DECL unsigned int numThreads = Size; + +public: + _CG_THREAD_SCOPE(cuda::thread_scope::thread_scope_block) + + // Rank of thread within tile + _CG_STATIC_QUALIFIER unsigned int thread_rank() { + return (details::cta::thread_rank() & (numThreads - 1)); + } + + // Number of threads within tile + _CG_STATIC_CONSTEXPR_QUALIFIER unsigned int num_threads() { + return numThreads; + } + + _CG_STATIC_CONSTEXPR_QUALIFIER unsigned int size() { + return num_threads(); + } +}; + +template +class __static_size_thread_block_tile_base : public __static_size_tile_base +{ + friend class details::_coalesced_group_data_access; + typedef details::tile::tile_helpers th; + +#ifdef _CG_CPP11_FEATURES + static_assert(details::_is_valid_single_warp_tile::value, "Size must be one of 1/2/4/8/16/32"); +#else + typedef typename details::verify_thread_block_tile_size::OK valid; +#endif + using __static_size_tile_base::numThreads; + _CG_STATIC_CONST_DECL unsigned int fullMask = 0xFFFFFFFF; + + protected: + _CG_STATIC_QUALIFIER unsigned int build_mask() { + unsigned int mask = fullMask; + if (numThreads != 32) { + // [0,31] representing the current active thread in the warp + unsigned int laneId = details::laneid(); + // shift mask according to the partition it belongs to + mask = th::tileMask << (laneId & ~(th::laneMask)); + } + return (mask); + } + +public: + _CG_STATIC_CONST_DECL unsigned int _group_id = details::coalesced_group_id; + + _CG_STATIC_QUALIFIER void sync() { + __syncwarp(build_mask()); + } + +#ifdef _CG_CPP11_FEATURES + // PTX supported collectives + template > + _CG_QUALIFIER TyRet shfl(TyElem&& elem, int srcRank) const { + return details::tile::shuffle_dispatch::shfl( + _CG_STL_NAMESPACE::forward(elem), build_mask(), srcRank, numThreads); + } + + template > + _CG_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int delta) const { + return details::tile::shuffle_dispatch::shfl_down( + _CG_STL_NAMESPACE::forward(elem), build_mask(), delta, numThreads); + } + + template > + _CG_QUALIFIER TyRet shfl_up(TyElem&& elem, unsigned int delta) const { + return details::tile::shuffle_dispatch::shfl_up( + _CG_STL_NAMESPACE::forward(elem), build_mask(), delta, numThreads); + } + + template > + _CG_QUALIFIER TyRet shfl_xor(TyElem&& elem, unsigned int laneMask) const { + return details::tile::shuffle_dispatch::shfl_xor( + _CG_STL_NAMESPACE::forward(elem), build_mask(), laneMask, numThreads); + } +#else + template + _CG_QUALIFIER TyIntegral shfl(TyIntegral var, int srcRank) const { + details::assert_if_not_arithmetic(); + return (__shfl_sync(build_mask(), var, srcRank, numThreads)); + } + + template + _CG_QUALIFIER TyIntegral shfl_down(TyIntegral var, unsigned int delta) const { + details::assert_if_not_arithmetic(); + return (__shfl_down_sync(build_mask(), var, delta, numThreads)); + } + + template + _CG_QUALIFIER TyIntegral shfl_up(TyIntegral var, unsigned int delta) const { + details::assert_if_not_arithmetic(); + return (__shfl_up_sync(build_mask(), var, delta, numThreads)); + } + + template + _CG_QUALIFIER TyIntegral shfl_xor(TyIntegral var, unsigned int laneMask) const { + details::assert_if_not_arithmetic(); + return (__shfl_xor_sync(build_mask(), var, laneMask, numThreads)); + } +#endif //_CG_CPP11_FEATURES + + _CG_QUALIFIER int any(int predicate) const { + unsigned int lane_ballot = __ballot_sync(build_mask(), predicate); + return (lane_ballot != 0); + } + _CG_QUALIFIER int all(int predicate) const { + unsigned int lane_ballot = __ballot_sync(build_mask(), predicate); + return (lane_ballot == build_mask()); + } + _CG_QUALIFIER unsigned int ballot(int predicate) const { + unsigned int lane_ballot = __ballot_sync(build_mask(), predicate); + return (lane_ballot >> (details::laneid() & (~(th::laneMask)))); + } + +#ifdef _CG_HAS_MATCH_COLLECTIVE + template + _CG_QUALIFIER unsigned int match_any(TyIntegral val) const { + details::assert_if_not_arithmetic(); + unsigned int lane_match = __match_any_sync(build_mask(), val); + return (lane_match >> (details::laneid() & (~(th::laneMask)))); + } + + template + _CG_QUALIFIER unsigned int match_all(TyIntegral val, int &pred) const { + details::assert_if_not_arithmetic(); + unsigned int lane_match = __match_all_sync(build_mask(), val, &pred); + return (lane_match >> (details::laneid() & (~(th::laneMask)))); + } +#endif + +}; + +template +class __static_parent_thread_block_tile_base +{ +public: + // Rank of this group in the upper level of the hierarchy + _CG_STATIC_QUALIFIER unsigned int meta_group_rank() { + return ParentT::thread_rank() / Size; + } + + // Total num partitions created out of all CTAs when the group was created + _CG_STATIC_QUALIFIER unsigned int meta_group_size() { + return (ParentT::size() + Size - 1) / Size; + } +}; + +/** + * class thread_block_tile + * + * Statically-sized group type, representing one tile of a thread block. + * The only specializations currently supported are those with native + * hardware support (1/2/4/8/16/32) + * + * This group exposes warp-synchronous builtins. + * Can only be constructed via tiled_partition(ParentT&) + */ + +template +class __single_warp_thread_block_tile : + public __static_size_thread_block_tile_base, + public __static_parent_thread_block_tile_base +{ + typedef __static_parent_thread_block_tile_base staticParentBaseT; + friend class details::_coalesced_group_data_access; + +protected: + _CG_QUALIFIER __single_warp_thread_block_tile() { }; + _CG_QUALIFIER __single_warp_thread_block_tile(unsigned int, unsigned int) { }; + + _CG_STATIC_QUALIFIER unsigned int get_mask() { + return __static_size_thread_block_tile_base::build_mask(); + } +}; + +template +class __single_warp_thread_block_tile : + public __static_size_thread_block_tile_base, + public thread_group_base +{ + _CG_STATIC_CONST_DECL unsigned int numThreads = Size; + + template friend class __single_warp_thread_block_tile; + friend class details::_coalesced_group_data_access; + + typedef __static_size_thread_block_tile_base staticSizeBaseT; + +protected: + _CG_QUALIFIER __single_warp_thread_block_tile(unsigned int meta_group_rank = 0, unsigned int meta_group_size = 1) { + _data.coalesced.mask = staticSizeBaseT::build_mask(); + _data.coalesced.size = numThreads; + _data.coalesced.metaGroupRank = meta_group_rank; + _data.coalesced.metaGroupSize = meta_group_size; + _data.coalesced.is_tiled = true; + } + + _CG_QUALIFIER unsigned int get_mask() const { + return (_data.coalesced.mask); + } + +public: + using staticSizeBaseT::sync; + using staticSizeBaseT::size; + using staticSizeBaseT::num_threads; + using staticSizeBaseT::thread_rank; + + _CG_QUALIFIER unsigned int meta_group_rank() const { + return _data.coalesced.metaGroupRank; + } + + _CG_QUALIFIER unsigned int meta_group_size() const { + return _data.coalesced.metaGroupSize; + } +}; + +/** + * Outer level API calls + * void sync(GroupT) - see .sync() + * void thread_rank(GroupT) - see .thread_rank() + * void group_size(GroupT) - see .size() + */ +template +_CG_QUALIFIER void sync(GroupT const &g) +{ + g.sync(); +} + +// TODO: Use a static dispatch to determine appropriate return type +// C++03 is stuck with unsigned long long for now +#ifdef _CG_CPP11_FEATURES +template +_CG_QUALIFIER auto thread_rank(GroupT const& g) -> decltype(g.thread_rank()) { + return g.thread_rank(); +} + + +template +_CG_QUALIFIER auto group_size(GroupT const &g) -> decltype(g.num_threads()) { + return g.num_threads(); +} +#else +template +_CG_QUALIFIER unsigned long long thread_rank(GroupT const& g) { + return static_cast(g.thread_rank()); +} + + +template +_CG_QUALIFIER unsigned long long group_size(GroupT const &g) { + return static_cast(g.num_threads()); +} +#endif + + +/** + * tiled_partition + * + * The tiled_partition(parent, tilesz) method is a collective operation that + * partitions the parent group into a one-dimensional, row-major, tiling of subgroups. + * + * A total of ((size(parent)+tilesz-1)/tilesz) subgroups will + * be created where threads having identical k = (thread_rank(parent)/tilesz) + * will be members of the same subgroup. + * + * The implementation may cause the calling thread to wait until all the members + * of the parent group have invoked the operation before resuming execution. + * + * Functionality is limited to power-of-two sized subgorup instances of at most + * 32 threads. Only thread_block, thread_block_tile<>, and their subgroups can be + * tiled_partition() in _CG_VERSION 1000. + */ +_CG_QUALIFIER thread_group tiled_partition(const thread_group& parent, unsigned int tilesz) +{ + if (parent.get_type() == details::coalesced_group_id) { + const coalesced_group *_cg = static_cast(&parent); + return _cg->_get_tiled_threads(tilesz); + } + else { + const thread_block *_tb = static_cast(&parent); + return _tb->_get_tiled_threads(tilesz); + } +} + +// Thread block type overload: returns a basic thread_group for now (may be specialized later) +_CG_QUALIFIER thread_group tiled_partition(const thread_block& parent, unsigned int tilesz) +{ + return (parent._get_tiled_threads(tilesz)); +} + +// Coalesced group type overload: retains its ability to stay coalesced +_CG_QUALIFIER coalesced_group tiled_partition(const coalesced_group& parent, unsigned int tilesz) +{ + return (parent._get_tiled_threads(tilesz)); +} + +namespace details { + template + class internal_thread_block_tile : public __single_warp_thread_block_tile {}; + + template + _CG_QUALIFIER internal_thread_block_tile tiled_partition_internal() { + return internal_thread_block_tile(); + } + + template + _CG_QUALIFIER TyVal multi_warp_collectives_helper( + const GroupT& group, + WarpLambda warp_lambda, + InterWarpLambda inter_warp_lambda) { + return group.template collectives_scheme(warp_lambda, inter_warp_lambda); + } + + template + _CG_QUALIFIER T* multi_warp_scratch_location_getter(const GroupT& group, unsigned int warp_id) { + return group.template get_scratch_location(warp_id); + } + + template + _CG_QUALIFIER details::barrier_t* multi_warp_sync_location_getter(const GroupT& group) { + return group.get_sync_location(); + } + +} +/** + * tiled_partition + * + * The tiled_partition(parent) method is a collective operation that + * partitions the parent group into a one-dimensional, row-major, tiling of subgroups. + * + * A total of ((size(parent)/tilesz) subgroups will be created, + * therefore the parent group size must be evenly divisible by the tilesz. + * The allow parent groups are thread_block or thread_block_tile. + * + * The implementation may cause the calling thread to wait until all the members + * of the parent group have invoked the operation before resuming execution. + * + * Functionality is limited to native hardware sizes, 1/2/4/8/16/32. + * The size(parent) must be greater than the template Size parameter + * otherwise the results are undefined. + */ + +#if defined(_CG_CPP11_FEATURES) +template +class __static_size_multi_warp_tile_base : public __static_size_tile_base +{ + static_assert(details::_is_valid_multi_warp_tile::value, "Size must be one of 64/128/256/512"); + + template + friend __device__ TyVal details::multi_warp_collectives_helper( + const GroupT& group, + WarpLambda warp_lambda, + InterWarpLambda inter_warp_lambda); + template + friend __device__ T* details::multi_warp_scratch_location_getter(const GroupT& group, unsigned int warp_id); + template + friend __device__ details::barrier_t* details::multi_warp_sync_location_getter(const GroupT& group); + template + friend class __static_size_multi_warp_tile_base; + using WarpType = details::internal_thread_block_tile<32, __static_size_multi_warp_tile_base>; + using ThisType = __static_size_multi_warp_tile_base; + _CG_STATIC_CONST_DECL int numWarps = Size / 32; + +protected: + details::multi_warp_scratch* const tile_memory; + + template + _CG_QUALIFIER __static_size_multi_warp_tile_base(const GroupT& g) : tile_memory(g.tile_memory) { +#if !defined(_CG_USER_PROVIDED_SHARED_MEMORY) + NV_IF_TARGET(NV_PROVIDES_SM_80, + details::sync_warps_reset(get_sync_location(), details::cta::thread_rank()); + g.sync(); + ) +#endif + } + + +private: + _CG_QUALIFIER details::barrier_t* get_sync_location() const { + // Different group sizes use different barriers, all groups of a given size share one barrier. + unsigned int sync_id = details::log2(Size / 64); + return &tile_memory->barriers[sync_id]; + } + + template + _CG_QUALIFIER T* get_scratch_location(unsigned int warp_id) const { + unsigned int scratch_id = (details::cta::thread_rank() - thread_rank()) / 32 + warp_id; + return reinterpret_cast(&tile_memory->communication_memory[scratch_id]); + } + + template + _CG_QUALIFIER T* get_scratch_location() const { + unsigned int scratch_id = details::cta::thread_rank() / 32; + return reinterpret_cast(&tile_memory->communication_memory[scratch_id]); + } + + template + _CG_QUALIFIER TyVal shfl_impl(TyVal val, unsigned int src) const { + unsigned int src_warp = src / 32; + auto warp = details::tiled_partition_internal<32, ThisType>(); + details::barrier_t* sync_location = get_sync_location(); + + // Get warp slot of the source threads warp. + TyVal* warp_scratch_location = get_scratch_location(src_warp); + + if (warp.meta_group_rank() == src_warp) { + warp.sync(); + // Put shuffled value into my warp slot and let my warp arrive at the barrier. + if (thread_rank() == src) { + *warp_scratch_location = val; + } + details::sync_warps_arrive(sync_location, details::cta::thread_rank(), numWarps); + TyVal result = *warp_scratch_location; + details::sync_warps_wait(sync_location, details::cta::thread_rank()); + return result; + } + else { + // Wait for the source warp to arrive on the barrier. + details::sync_warps_wait_for_specific_warp(sync_location, + (details::cta::thread_rank() / 32 - warp.meta_group_rank() + src_warp)); + TyVal result = *warp_scratch_location; + details::sync_warps(sync_location, details::cta::thread_rank(), numWarps); + return result; + } + } + + template + _CG_QUALIFIER TyVal collectives_scheme(const WarpLambda& warp_lambda, const InterWarpLambda& inter_warp_lambda) const { + static_assert(sizeof(TyVal) <= details::multi_warp_scratch::communication_size, + "Collectives with tiles larger than 32 threads are limited to types smaller then 8 bytes"); + auto warp = details::tiled_partition_internal<32, ThisType>(); + details::barrier_t* sync_location = get_sync_location(); + TyVal* warp_scratch_location = get_scratch_location(); + + warp_lambda(warp, warp_scratch_location); + + if (details::sync_warps_last_releases(sync_location, details::cta::thread_rank(), numWarps)) { + auto subwarp = details::tiled_partition_internal(); + if (subwarp.meta_group_rank() == 0) { + TyVal* thread_scratch_location = get_scratch_location(subwarp.thread_rank()); + inter_warp_lambda(subwarp, thread_scratch_location); + } + warp.sync(); + details::sync_warps_release(sync_location, warp.thread_rank() == 0, details::cta::thread_rank(), numWarps); + } + TyVal result = *warp_scratch_location; + return result; + } + +public: + _CG_STATIC_CONST_DECL unsigned int _group_id = details::multi_tile_group_id; + + using __static_size_tile_base::thread_rank; + + template + _CG_QUALIFIER TyVal shfl(TyVal val, unsigned int src) const { + static_assert(sizeof(TyVal) <= details::multi_warp_scratch::communication_size, + "Collectives with tiles larger than 32 threads are limited to types smaller then 8 bytes"); + return shfl_impl(val, src); + } + + _CG_QUALIFIER void sync() const { + details::sync_warps(get_sync_location(), details::cta::thread_rank(), numWarps); + } + + _CG_QUALIFIER int any(int predicate) const { + auto warp_lambda = [=] (WarpType& warp, int* warp_scratch_location) { + *warp_scratch_location = __any_sync(0xFFFFFFFF, predicate); + }; + auto inter_warp_lambda = + [] (details::internal_thread_block_tile& subwarp, int* thread_scratch_location) { + *thread_scratch_location = __any_sync(0xFFFFFFFFU >> (32 - numWarps), *thread_scratch_location); + }; + return collectives_scheme(warp_lambda, inter_warp_lambda); + } + + _CG_QUALIFIER int all(int predicate) const { + auto warp_lambda = [=] (WarpType& warp, int* warp_scratch_location) { + *warp_scratch_location = __all_sync(0xFFFFFFFF, predicate); + }; + auto inter_warp_lambda = + [] (details::internal_thread_block_tile& subwarp, int* thread_scratch_location) { + *thread_scratch_location = __all_sync(0xFFFFFFFFU >> (32 - numWarps), *thread_scratch_location); + }; + return collectives_scheme(warp_lambda, inter_warp_lambda); + } +}; + + +template +class __multi_warp_thread_block_tile : + public __static_size_multi_warp_tile_base, + public __static_parent_thread_block_tile_base +{ + typedef __static_parent_thread_block_tile_base staticParentBaseT; + typedef __static_size_multi_warp_tile_base staticTileBaseT; +protected: + _CG_QUALIFIER __multi_warp_thread_block_tile(const ParentT& g) : + __static_size_multi_warp_tile_base(g) {} +}; + +template +class __multi_warp_thread_block_tile : public __static_size_multi_warp_tile_base +{ + const unsigned int metaGroupRank; + const unsigned int metaGroupSize; + +protected: + template + _CG_QUALIFIER __multi_warp_thread_block_tile(const __multi_warp_thread_block_tile& g) : + __static_size_multi_warp_tile_base(g), metaGroupRank(g.meta_group_rank()), metaGroupSize(g.meta_group_size()) {} + +public: + _CG_QUALIFIER unsigned int meta_group_rank() const { + return metaGroupRank; + } + + _CG_QUALIFIER unsigned int meta_group_size() const { + return metaGroupSize; + } +}; +#endif + +template +class thread_block_tile; + +namespace details { + template + class thread_block_tile_impl; + + template + class thread_block_tile_impl: public __single_warp_thread_block_tile + { + protected: + template + _CG_QUALIFIER thread_block_tile_impl(const thread_block_tile_impl& g) : + __single_warp_thread_block_tile(g.meta_group_rank(), g.meta_group_size()) {} + + _CG_QUALIFIER thread_block_tile_impl(const thread_block& g) : + __single_warp_thread_block_tile() {} + }; + +#if defined(_CG_CPP11_FEATURES) + template + class thread_block_tile_impl : public __multi_warp_thread_block_tile + { + protected: + template + _CG_QUALIFIER thread_block_tile_impl(const GroupT& g) : + __multi_warp_thread_block_tile(g) {} + }; +#else + template + class thread_block_tile_impl + { + protected: + template + _CG_QUALIFIER thread_block_tile_impl(const GroupT& g) {} + }; +#endif +} + +template +class thread_block_tile : public details::thread_block_tile_impl::value> +{ + friend _CG_QUALIFIER thread_block_tile<1, void> this_thread(); + +protected: + _CG_QUALIFIER thread_block_tile(const ParentT& g) : + details::thread_block_tile_impl::value>(g) {} + +public: + _CG_QUALIFIER operator thread_block_tile() const { + return thread_block_tile(*this); + } +}; + +template +class thread_block_tile : public details::thread_block_tile_impl::value> +{ + template + friend class thread_block_tile; + +protected: + template + _CG_QUALIFIER thread_block_tile(const thread_block_tile& g) : + details::thread_block_tile_impl::value>(g) {} + +public: + template + _CG_QUALIFIER thread_block_tile(const thread_block_tile& g) : + details::thread_block_tile_impl::value>(g) {} +}; + +namespace details { + template + struct tiled_partition_impl; + + template + struct tiled_partition_impl : public thread_block_tile { + _CG_QUALIFIER tiled_partition_impl(const thread_block& g) : + thread_block_tile(g) {} + }; + + // ParentT = static thread_block_tile specialization + template + struct tiled_partition_impl > : + public thread_block_tile > { +#ifdef _CG_CPP11_FEATURES + static_assert(Size < ParentSize, "Tile size bigger or equal to the parent group size"); +#endif + _CG_QUALIFIER tiled_partition_impl(const thread_block_tile& g) : + thread_block_tile >(g) {} + }; + +} + +template +_CG_QUALIFIER thread_block_tile tiled_partition(const ParentT& g) +{ + return details::tiled_partition_impl(g); +} + +/** + * thread_group this_thread() + * + * Constructs a generic thread_group containing only the calling thread + */ +_CG_QUALIFIER thread_block_tile<1, void> this_thread() +{ + // Make thread_block_tile<1, thread_block> parent of the returned group, so it will have its + // meta group rank and size set to 0 and 1 respectively. + return thread_block_tile<1, thread_block_tile<1, thread_block> >(this_thread_block()); +} + +/** + * .sync() + * + * Executes a barrier across the group + * + * Implements both a compiler fence and an architectural fence to prevent, + * memory reordering around the barrier. + */ +_CG_QUALIFIER void thread_group::sync() const +{ + switch (_data.group.type) { + case details::coalesced_group_id: + cooperative_groups::sync(*static_cast(this)); + break; + case details::thread_block_id: + cooperative_groups::sync(*static_cast(this)); + break; + case details::grid_group_id: + cooperative_groups::sync(*static_cast(this)); + break; +#if defined(_CG_HAS_MULTI_GRID_GROUP) && defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) + case details::multi_grid_group_id: + cooperative_groups::sync(*static_cast(this)); + break; +#endif +#if defined(_CG_HAS_CLUSTER_GROUP) + case details::cluster_group_id: + cooperative_groups::sync(*static_cast(this)); + break; +#endif + default: + break; + } +} + +/** + * .size() + * + * Returns the total number of threads in the group. + */ +_CG_QUALIFIER unsigned long long thread_group::size() const +{ + unsigned long long size = 0; + switch (_data.group.type) { + case details::coalesced_group_id: + size = cooperative_groups::group_size(*static_cast(this)); + break; + case details::thread_block_id: + size = cooperative_groups::group_size(*static_cast(this)); + break; + case details::grid_group_id: + size = cooperative_groups::group_size(*static_cast(this)); + break; +#if defined(_CG_HAS_MULTI_GRID_GROUP) && defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) + case details::multi_grid_group_id: + size = cooperative_groups::group_size(*static_cast(this)); + break; +#endif +#if defined(_CG_HAS_CLUSTER_GROUP) + case details::cluster_group_id: + size = cooperative_groups::group_size(*static_cast(this)); + break; +#endif + default: + break; + } + return size; +} + +/** + * .thread_rank() + * + * Returns the linearized rank of the calling thread along the interval [0, size()). + */ +_CG_QUALIFIER unsigned long long thread_group::thread_rank() const +{ + unsigned long long rank = 0; + switch (_data.group.type) { + case details::coalesced_group_id: + rank = cooperative_groups::thread_rank(*static_cast(this)); + break; + case details::thread_block_id: + rank = cooperative_groups::thread_rank(*static_cast(this)); + break; + case details::grid_group_id: + rank = cooperative_groups::thread_rank(*static_cast(this)); + break; +#if defined(_CG_HAS_MULTI_GRID_GROUP) && defined(_CG_CPP11_FEATURES) && defined(_CG_ABI_EXPERIMENTAL) + case details::multi_grid_group_id: + rank = cooperative_groups::thread_rank(*static_cast(this)); + break; +#endif +#if defined(_CG_HAS_CLUSTER_GROUP) + case details::cluster_group_id: + rank = cooperative_groups::thread_rank(*static_cast(this)); + break; +#endif + default: + break; + } + return rank; +} + +_CG_END_NAMESPACE + +#include +#if (!defined(_MSC_VER) || defined(_WIN64)) +# include +#endif + +# endif /* ! (__cplusplus, __CUDACC__) */ + +#endif /* !_COOPERATIVE_GROUPS_H_ */ diff --git a/shared/package-files/cb/cb684549a280899856986c65c2fa577cc196a20425c5f1700a759cb3b70c4658/LocalDispatchKeySet.h b/shared/package-files/cb/cb684549a280899856986c65c2fa577cc196a20425c5f1700a759cb3b70c4658/LocalDispatchKeySet.h new file mode 100644 index 0000000000000000000000000000000000000000..1232bd25eb3bd41b01655751e3ddf5f8a0fd5b5e --- /dev/null +++ b/shared/package-files/cb/cb684549a280899856986c65c2fa577cc196a20425c5f1700a759cb3b70c4658/LocalDispatchKeySet.h @@ -0,0 +1,169 @@ +#pragma once + +#include +#include + +// TLS management for DispatchKeySet (the "local" DispatchKeySet(s)) +// +// This manages two thread-local DispatchKeySets: +// +// - The included type set, which adds a tensor type for consideration +// in dispatch. (For example, you might add Profiling to +// the included type set to turn on profiling on all tensor operations.) +// +// - The excluded type set, which disqualifies a tensor type from dispatch. +// (For example, after redispatching on variable, we disqualify +// Autograd so we don't attempt to handle variable again.) +// (Exclusion wins over inclusion.) +// +// NB: Originally, I implemented the excluded type set as storing the inverted +// set, but TLS is defined to be zero-initialized, so this doesn't actually work +// (if it's inverted, you want the set to be -1 initialized). + +namespace c10::impl { + +// POD version of LocalDispatchKeySet. Declared here just so that +// we can put it in the guards. +// This struct encapsulates special handling for TLS initialization +// in set_included()/included() API so that they reflect the truth. +// If you want to create PODLocalDispatchKeySet with non-zero state, +// use set_included() instead of default constructor. +struct C10_API PODLocalDispatchKeySet { + uint64_t included_; + uint64_t excluded_; + + // See Note [TLS Initialization] + DispatchKeySet included() const { + return DispatchKeySet(DispatchKeySet::RAW, included_) ^ + c10::default_included_set; + } + DispatchKeySet excluded() const { + return DispatchKeySet(DispatchKeySet::RAW, excluded_) ^ + c10::default_excluded_set; + } + + void set_included(DispatchKeySet x) { + included_ = (x ^ c10::default_included_set).raw_repr(); + } + void set_excluded(DispatchKeySet x) { + excluded_ = (x ^ c10::default_excluded_set).raw_repr(); + } +}; +static_assert( + std::is_trivial_v, + "PODLocalDispatchKeySet must be a POD type."); + +struct C10_API LocalDispatchKeySet { + /* implicit */ LocalDispatchKeySet(PODLocalDispatchKeySet x) + : included_(x.included()), excluded_(x.excluded()) {} + DispatchKeySet included_; + DispatchKeySet excluded_; +}; + +// thread_local variables cannot be C10_API on Windows. +// Inlining this seems to break AutoDispatchBelowAutograd on Android. +#if defined(_MSC_VER) || defined(C10_ANDROID) || defined(C10_IPHONE) +C10_API LocalDispatchKeySet tls_local_dispatch_key_set(); +#else // defined(_MSC_VER) || defined(C10_ANDROID) || defined(C10_IPHONE) +extern C10_API thread_local PODLocalDispatchKeySet raw_local_dispatch_key_set; + +inline C10_API LocalDispatchKeySet tls_local_dispatch_key_set() { + // Don't let people fiddle with the thread_local directly just + // because they include this header. + return raw_local_dispatch_key_set; +} +#endif // defined(_MSC_VER) || defined(C10_ANDROID) || defined(C10_IPHONE) + +// Internal, use ThreadLocalStateGuard +C10_API void _force_tls_local_dispatch_key_set(LocalDispatchKeySet key_set); + +// RAII API for manipulating the thread-local dispatch state. + +class C10_API IncludeDispatchKeyGuard { + public: + IncludeDispatchKeyGuard(DispatchKeySet); + IncludeDispatchKeyGuard(DispatchKey k) + : IncludeDispatchKeyGuard(DispatchKeySet(k)) {} + IncludeDispatchKeyGuard(const IncludeDispatchKeyGuard&) = delete; + IncludeDispatchKeyGuard operator=(const IncludeDispatchKeyGuard&) = delete; + IncludeDispatchKeyGuard(IncludeDispatchKeyGuard&&) = delete; + IncludeDispatchKeyGuard operator=(IncludeDispatchKeyGuard&&) = delete; + ~IncludeDispatchKeyGuard(); + + private: + // A little micro-optimization to save us from tls_get_addr call + // on destruction + PODLocalDispatchKeySet* tls_; + DispatchKeySet include_; +}; + +class C10_API ExcludeDispatchKeyGuard { + public: + ExcludeDispatchKeyGuard(DispatchKeySet); + ExcludeDispatchKeyGuard(DispatchKey k) + : ExcludeDispatchKeyGuard(DispatchKeySet(k)) {} + ExcludeDispatchKeyGuard(const ExcludeDispatchKeyGuard&) = delete; + ExcludeDispatchKeyGuard operator=(const ExcludeDispatchKeyGuard&) = delete; + ExcludeDispatchKeyGuard(ExcludeDispatchKeyGuard&&) = delete; + ExcludeDispatchKeyGuard operator=(ExcludeDispatchKeyGuard&&) = delete; + ~ExcludeDispatchKeyGuard(); + + private: + // A little micro-optimization to save us from tls_get_addr call + // on destruction + PODLocalDispatchKeySet* tls_; + DispatchKeySet exclude_; +}; + +struct C10_API ForceDispatchKeyGuard { + public: + ForceDispatchKeyGuard() + : saved_keyset_(c10::impl::tls_local_dispatch_key_set()) {} + ForceDispatchKeyGuard(c10::impl::LocalDispatchKeySet key_set) + : ForceDispatchKeyGuard() { + c10::impl::_force_tls_local_dispatch_key_set(key_set); + } + ForceDispatchKeyGuard( + c10::DispatchKeySet include, + c10::DispatchKeySet exclude) + : ForceDispatchKeyGuard() { + auto updated_set = saved_keyset_; + updated_set.included_ = include; + updated_set.excluded_ = exclude; + c10::impl::_force_tls_local_dispatch_key_set(updated_set); + } + + ForceDispatchKeyGuard(ForceDispatchKeyGuard&&) noexcept = delete; + ForceDispatchKeyGuard(const ForceDispatchKeyGuard&) = delete; + ForceDispatchKeyGuard& operator=(const ForceDispatchKeyGuard&) = delete; + ForceDispatchKeyGuard& operator=(ForceDispatchKeyGuard&&) = delete; + ~ForceDispatchKeyGuard() { + c10::impl::_force_tls_local_dispatch_key_set(saved_keyset_); + } + + private: + c10::impl::LocalDispatchKeySet saved_keyset_; +}; + +// Non-RAII API for manipulating the thread-local dispatch state. +// Please prefer the RAII API. The non-RAII API may be useful when +// the included/excluded state of a given DispatchKey must span +// many calls from the Python to the C++, so you cannot conveniently +// use an RAII guard. +// +// Example use case: a Python context manager that includes a certain +// DispatchKey, to ensure ops running under the context manager dispatch +// through that DispatchKey's registered overrides. +// +// The non-RAII API is less efficient than the RAII guards because both the +// getter and setter will do a tls_getaddr lookup (the RAII struct only needs +// one!) + +C10_API bool tls_is_dispatch_key_excluded(DispatchKey x); +C10_API void tls_set_dispatch_key_excluded(DispatchKey x, bool desired_state); +C10_API bool tls_is_dispatch_key_included(DispatchKey x); +C10_API void tls_set_dispatch_key_included(DispatchKey x, bool desired_state); +C10_API bool tls_is_dispatch_keyset_excluded(DispatchKeySet ks); +C10_API bool tls_is_dispatch_keyset_included(DispatchKeySet ks); + +} // namespace c10::impl diff --git a/shared/package-files/cb/cb6e10898c3beb627568fdbed2c9a80808fbefcee639506b91405223faebaefd/zero_native.h b/shared/package-files/cb/cb6e10898c3beb627568fdbed2c9a80808fbefcee639506b91405223faebaefd/zero_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ac496a1e0cda39be848270d5dc325afe602e9f71 --- /dev/null +++ b/shared/package-files/cb/cb6e10898c3beb627568fdbed2c9a80808fbefcee639506b91405223faebaefd/zero_native.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor zero(const at::Tensor & self); +TORCH_API at::Tensor & zero_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & zero_(at::Tensor & self); +TORCH_API at::Tensor & zero_meta_(at::Tensor & self); +TORCH_API at::Tensor & zero_nested_(at::Tensor & self); +TORCH_API at::Tensor & zero_sparse_(at::Tensor & self); +TORCH_API at::Tensor & zero_sparse_csr_(at::Tensor & self); +TORCH_API at::Tensor & mkldnn_zero_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cb729b1264a0c43fcec4091f211a0550118d2513d618c86c4ec93b4956882304/test_innerproduct.cpython-311.pyc b/shared/package-files/cb/cb729b1264a0c43fcec4091f211a0550118d2513d618c86c4ec93b4956882304/test_innerproduct.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde58693e6d4898eb35a167da1ddcb75b35d1c07 Binary files /dev/null and b/shared/package-files/cb/cb729b1264a0c43fcec4091f211a0550118d2513d618c86c4ec93b4956882304/test_innerproduct.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb797177ded4675064aeb65ed2bda5e8c33cccd0014c4fcbe0ab7117099dcde4/test_hyperexpand.py b/shared/package-files/cb/cb797177ded4675064aeb65ed2bda5e8c33cccd0014c4fcbe0ab7117099dcde4/test_hyperexpand.py new file mode 100644 index 0000000000000000000000000000000000000000..c703c228a13201de13cfd4c3413fc75a2cf5bdb6 --- /dev/null +++ b/shared/package-files/cb/cb797177ded4675064aeb65ed2bda5e8c33cccd0014c4fcbe0ab7117099dcde4/test_hyperexpand.py @@ -0,0 +1,1063 @@ +from sympy.core.random import randrange + +from sympy.simplify.hyperexpand import (ShiftA, ShiftB, UnShiftA, UnShiftB, + MeijerShiftA, MeijerShiftB, MeijerShiftC, MeijerShiftD, + MeijerUnShiftA, MeijerUnShiftB, MeijerUnShiftC, + MeijerUnShiftD, + ReduceOrder, reduce_order, apply_operators, + devise_plan, make_derivative_operator, Formula, + hyperexpand, Hyper_Function, G_Function, + reduce_order_meijer, + build_hypergeometric_formula) +from sympy.concrete.summations import Sum +from sympy.core.containers import Tuple +from sympy.core.expr import Expr +from sympy.core.numbers import I +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import binomial +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.hyper import (hyper, meijerg) +from sympy.abc import z, a, b, c +from sympy.testing.pytest import XFAIL, raises, slow, tooslow +from sympy.core.random import verify_numerically as tn + +from sympy.core.numbers import (Rational, pi) +from sympy.functions.elementary.exponential import (exp, exp_polar, log) +from sympy.functions.elementary.hyperbolic import atanh +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (asin, cos, sin) +from sympy.functions.special.bessel import besseli +from sympy.functions.special.error_functions import erf +from sympy.functions.special.gamma_functions import (gamma, lowergamma) + + +def test_branch_bug(): + assert hyperexpand(hyper((Rational(-1, 3), S.Half), (Rational(2, 3), Rational(3, 2)), -z)) == \ + -z**S('1/3')*lowergamma(exp_polar(I*pi)/3, z)/5 \ + + sqrt(pi)*erf(sqrt(z))/(5*sqrt(z)) + assert hyperexpand(meijerg([Rational(7, 6), 1], [], [Rational(2, 3)], [Rational(1, 6), 0], z)) == \ + 2*z**S('2/3')*(2*sqrt(pi)*erf(sqrt(z))/sqrt(z) - 2*lowergamma( + Rational(2, 3), z)/z**S('2/3'))*gamma(Rational(2, 3))/gamma(Rational(5, 3)) + + +def test_hyperexpand(): + # Luke, Y. L. (1969), The Special Functions and Their Approximations, + # Volume 1, section 6.2 + + assert hyperexpand(hyper([], [], z)) == exp(z) + assert hyperexpand(hyper([1, 1], [2], -z)*z) == log(1 + z) + assert hyperexpand(hyper([], [S.Half], -z**2/4)) == cos(z) + assert hyperexpand(z*hyper([], [S('3/2')], -z**2/4)) == sin(z) + assert hyperexpand(hyper([S('1/2'), S('1/2')], [S('3/2')], z**2)*z) \ + == asin(z) + assert isinstance(Sum(binomial(2, z)*z**2, (z, 0, a)).doit(), Expr) + + +def can_do(ap, bq, numerical=True, div=1, lowerplane=False): + r = hyperexpand(hyper(ap, bq, z)) + if r.has(hyper): + return False + if not numerical: + return True + repl = {} + randsyms = r.free_symbols - {z} + while randsyms: + # Only randomly generated parameters are checked. + for n, ai in enumerate(randsyms): + repl[ai] = randcplx(n)/div + if not any(b.is_Integer and b <= 0 for b in Tuple(*bq).subs(repl)): + break + [a, b, c, d] = [2, -1, 3, 1] + if lowerplane: + [a, b, c, d] = [2, -2, 3, -1] + return tn( + hyper(ap, bq, z).subs(repl), + r.replace(exp_polar, exp).subs(repl), + z, a=a, b=b, c=c, d=d) + + +def test_roach(): + # Kelly B. Roach. Meijer G Function Representations. + # Section "Gallery" + assert can_do([S.Half], [Rational(9, 2)]) + assert can_do([], [1, Rational(5, 2), 4]) + assert can_do([Rational(-1, 2), 1, 2], [3, 4]) + assert can_do([Rational(1, 3)], [Rational(-2, 3), Rational(-1, 2), S.Half, 1]) + assert can_do([Rational(-3, 2), Rational(-1, 2)], [Rational(-5, 2), 1]) + assert can_do([Rational(-3, 2), ], [Rational(-1, 2), S.Half]) # shine-integral + assert can_do([Rational(-3, 2), Rational(-1, 2)], [2]) # elliptic integrals + + +@XFAIL +def test_roach_fail(): + assert can_do([Rational(-1, 2), 1], [Rational(1, 4), S.Half, Rational(3, 4)]) # PFDD + assert can_do([Rational(3, 2)], [Rational(5, 2), 5]) # struve function + assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(5, 2)]) # polylog, pfdd + assert can_do([1, 2, 3], [S.Half, 4]) # XXX ? + assert can_do([S.Half], [Rational(-1, 3), Rational(-1, 2), Rational(-2, 3)]) # PFDD ? + +# For the long table tests, see end of file + + +def test_polynomial(): + from sympy.core.numbers import oo + assert hyperexpand(hyper([], [-1], z)) is oo + assert hyperexpand(hyper([-2], [-1], z)) is oo + assert hyperexpand(hyper([0, 0], [-1], z)) == 1 + assert can_do([-5, -2, randcplx(), randcplx()], [-10, randcplx()]) + assert hyperexpand(hyper((-1, 1), (-2,), z)) == 1 + z/2 + + +def test_hyperexpand_bases(): + assert hyperexpand(hyper([2], [a], z)) == \ + a + z**(-a + 1)*(-a**2 + 3*a + z*(a - 1) - 2)*exp(z)* \ + lowergamma(a - 1, z) - 1 + # TODO [a+1, aRational(-1, 2)], [2*a] + assert hyperexpand(hyper([1, 2], [3], z)) == -2/z - 2*log(-z + 1)/z**2 + assert hyperexpand(hyper([S.Half, 2], [Rational(3, 2)], z)) == \ + -1/(2*z - 2) + atanh(sqrt(z))/sqrt(z)/2 + assert hyperexpand(hyper([S.Half, S.Half], [Rational(5, 2)], z)) == \ + (-3*z + 3)/4/(z*sqrt(-z + 1)) \ + + (6*z - 3)*asin(sqrt(z))/(4*z**Rational(3, 2)) + assert hyperexpand(hyper([1, 2], [Rational(3, 2)], z)) == -1/(2*z - 2) \ + - asin(sqrt(z))/(sqrt(z)*(2*z - 2)*sqrt(-z + 1)) + assert hyperexpand(hyper([Rational(-1, 2) - 1, 1, 2], [S.Half, 3], z)) == \ + sqrt(z)*(z*Rational(6, 7) - Rational(6, 5))*atanh(sqrt(z)) \ + + (-30*z**2 + 32*z - 6)/35/z - 6*log(-z + 1)/(35*z**2) + assert hyperexpand(hyper([1 + S.Half, 1, 1], [2, 2], z)) == \ + -4*log(sqrt(-z + 1)/2 + S.Half)/z + # TODO hyperexpand(hyper([a], [2*a + 1], z)) + # TODO [S.Half, a], [Rational(3, 2), a+1] + assert hyperexpand(hyper([2], [b, 1], z)) == \ + z**(-b/2 + S.Half)*besseli(b - 1, 2*sqrt(z))*gamma(b) \ + + z**(-b/2 + 1)*besseli(b, 2*sqrt(z))*gamma(b) + # TODO [a], [a - S.Half, 2*a] + + +def test_hyperexpand_parametric(): + assert hyperexpand(hyper([a, S.Half + a], [S.Half], z)) \ + == (1 + sqrt(z))**(-2*a)/2 + (1 - sqrt(z))**(-2*a)/2 + assert hyperexpand(hyper([a, Rational(-1, 2) + a], [2*a], z)) \ + == 2**(2*a - 1)*((-z + 1)**S.Half + 1)**(-2*a + 1) + + +def test_shifted_sum(): + from sympy.simplify.simplify import simplify + assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \ + == z*sin(2*z) + (-z**2 + S.Half)*cos(2*z) - S.Half + + +def _randrat(): + """ Steer clear of integers. """ + return S(randrange(25) + 10)/50 + + +def randcplx(offset=-1): + """ Polys is not good with real coefficients. """ + return _randrat() + I*_randrat() + I*(1 + offset) + + +@slow +def test_formulae(): + from sympy.simplify.hyperexpand import FormulaCollection + formulae = FormulaCollection().formulae + for formula in formulae: + h = formula.func(formula.z) + rep = {} + for n, sym in enumerate(formula.symbols): + rep[sym] = randcplx(n) + + # NOTE hyperexpand returns truly branched functions. We know we are + # on the main sheet, but numerical evaluation can still go wrong + # (e.g. if exp_polar cannot be evalf'd). + # Just replace all exp_polar by exp, this usually works. + + # first test if the closed-form is actually correct + h = h.subs(rep) + closed_form = formula.closed_form.subs(rep).rewrite('nonrepsmall') + z = formula.z + assert tn(h, closed_form.replace(exp_polar, exp), z) + + # now test the computed matrix + cl = (formula.C * formula.B)[0].subs(rep).rewrite('nonrepsmall') + assert tn(closed_form.replace( + exp_polar, exp), cl.replace(exp_polar, exp), z) + deriv1 = z*formula.B.applyfunc(lambda t: t.rewrite( + 'nonrepsmall')).diff(z) + deriv2 = formula.M * formula.B + for d1, d2 in zip(deriv1, deriv2): + assert tn(d1.subs(rep).replace(exp_polar, exp), + d2.subs(rep).rewrite('nonrepsmall').replace(exp_polar, exp), z) + + +def test_meijerg_formulae(): + from sympy.simplify.hyperexpand import MeijerFormulaCollection + formulae = MeijerFormulaCollection().formulae + for sig in formulae: + for formula in formulae[sig]: + g = meijerg(formula.func.an, formula.func.ap, + formula.func.bm, formula.func.bq, + formula.z) + rep = {} + for sym in formula.symbols: + rep[sym] = randcplx() + + # first test if the closed-form is actually correct + g = g.subs(rep) + closed_form = formula.closed_form.subs(rep) + z = formula.z + assert tn(g, closed_form, z) + + # now test the computed matrix + cl = (formula.C * formula.B)[0].subs(rep) + assert tn(closed_form, cl, z) + deriv1 = z*formula.B.diff(z) + deriv2 = formula.M * formula.B + for d1, d2 in zip(deriv1, deriv2): + assert tn(d1.subs(rep), d2.subs(rep), z) + + +def op(f): + return z*f.diff(z) + + +def test_plan(): + assert devise_plan(Hyper_Function([0], ()), + Hyper_Function([0], ()), z) == [] + with raises(ValueError): + devise_plan(Hyper_Function([1], ()), Hyper_Function((), ()), z) + with raises(ValueError): + devise_plan(Hyper_Function([2], [1]), Hyper_Function([2], [2]), z) + with raises(ValueError): + devise_plan(Hyper_Function([2], []), Hyper_Function([S("1/2")], []), z) + + # We cannot use pi/(10000 + n) because polys is insanely slow. + a1, a2, b1 = (randcplx(n) for n in range(3)) + b1 += 2*I + h = hyper([a1, a2], [b1], z) + + h2 = hyper((a1 + 1, a2), [b1], z) + assert tn(apply_operators(h, + devise_plan(Hyper_Function((a1 + 1, a2), [b1]), + Hyper_Function((a1, a2), [b1]), z), op), + h2, z) + + h2 = hyper((a1 + 1, a2 - 1), [b1], z) + assert tn(apply_operators(h, + devise_plan(Hyper_Function((a1 + 1, a2 - 1), [b1]), + Hyper_Function((a1, a2), [b1]), z), op), + h2, z) + + +def test_plan_derivatives(): + a1, a2, a3 = 1, 2, S('1/2') + b1, b2 = 3, S('5/2') + h = Hyper_Function((a1, a2, a3), (b1, b2)) + h2 = Hyper_Function((a1 + 1, a2 + 1, a3 + 2), (b1 + 1, b2 + 1)) + ops = devise_plan(h2, h, z) + f = Formula(h, z, h(z), []) + deriv = make_derivative_operator(f.M, z) + assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) + + h2 = Hyper_Function((a1, a2 - 1, a3 - 2), (b1 - 1, b2 - 1)) + ops = devise_plan(h2, h, z) + assert tn((apply_operators(f.C, ops, deriv)*f.B)[0], h2(z), z) + + +def test_reduction_operators(): + a1, a2, b1 = (randcplx(n) for n in range(3)) + h = hyper([a1], [b1], z) + + assert ReduceOrder(2, 0) is None + assert ReduceOrder(2, -1) is None + assert ReduceOrder(1, S('1/2')) is None + + h2 = hyper((a1, a2), (b1, a2), z) + assert tn(ReduceOrder(a2, a2).apply(h, op), h2, z) + + h2 = hyper((a1, a2 + 1), (b1, a2), z) + assert tn(ReduceOrder(a2 + 1, a2).apply(h, op), h2, z) + + h2 = hyper((a2 + 4, a1), (b1, a2), z) + assert tn(ReduceOrder(a2 + 4, a2).apply(h, op), h2, z) + + # test several step order reduction + ap = (a2 + 4, a1, b1 + 1) + bq = (a2, b1, b1) + func, ops = reduce_order(Hyper_Function(ap, bq)) + assert func.ap == (a1,) + assert func.bq == (b1,) + assert tn(apply_operators(h, ops, op), hyper(ap, bq, z), z) + + +def test_shift_operators(): + a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) + h = hyper((a1, a2), (b1, b2, b3), z) + + raises(ValueError, lambda: ShiftA(0)) + raises(ValueError, lambda: ShiftB(1)) + + assert tn(ShiftA(a1).apply(h, op), hyper((a1 + 1, a2), (b1, b2, b3), z), z) + assert tn(ShiftA(a2).apply(h, op), hyper((a1, a2 + 1), (b1, b2, b3), z), z) + assert tn(ShiftB(b1).apply(h, op), hyper((a1, a2), (b1 - 1, b2, b3), z), z) + assert tn(ShiftB(b2).apply(h, op), hyper((a1, a2), (b1, b2 - 1, b3), z), z) + assert tn(ShiftB(b3).apply(h, op), hyper((a1, a2), (b1, b2, b3 - 1), z), z) + + +def test_ushift_operators(): + a1, a2, b1, b2, b3 = (randcplx(n) for n in range(5)) + h = hyper((a1, a2), (b1, b2, b3), z) + + raises(ValueError, lambda: UnShiftA((1,), (), 0, z)) + raises(ValueError, lambda: UnShiftB((), (-1,), 0, z)) + raises(ValueError, lambda: UnShiftA((1,), (0, -1, 1), 0, z)) + raises(ValueError, lambda: UnShiftB((0, 1), (1,), 0, z)) + + s = UnShiftA((a1, a2), (b1, b2, b3), 0, z) + assert tn(s.apply(h, op), hyper((a1 - 1, a2), (b1, b2, b3), z), z) + s = UnShiftA((a1, a2), (b1, b2, b3), 1, z) + assert tn(s.apply(h, op), hyper((a1, a2 - 1), (b1, b2, b3), z), z) + + s = UnShiftB((a1, a2), (b1, b2, b3), 0, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1 + 1, b2, b3), z), z) + s = UnShiftB((a1, a2), (b1, b2, b3), 1, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2 + 1, b3), z), z) + s = UnShiftB((a1, a2), (b1, b2, b3), 2, z) + assert tn(s.apply(h, op), hyper((a1, a2), (b1, b2, b3 + 1), z), z) + + +def can_do_meijer(a1, a2, b1, b2, numeric=True): + """ + This helper function tries to hyperexpand() the meijer g-function + corresponding to the parameters a1, a2, b1, b2. + It returns False if this expansion still contains g-functions. + If numeric is True, it also tests the so-obtained formula numerically + (at random values) and returns False if the test fails. + Else it returns True. + """ + from sympy.core.function import expand + from sympy.functions.elementary.complexes import unpolarify + r = hyperexpand(meijerg(a1, a2, b1, b2, z)) + if r.has(meijerg): + return False + # NOTE hyperexpand() returns a truly branched function, whereas numerical + # evaluation only works on the main branch. Since we are evaluating on + # the main branch, this should not be a problem, but expressions like + # exp_polar(I*pi/2*x)**a are evaluated incorrectly. We thus have to get + # rid of them. The expand heuristically does this... + r = unpolarify(expand(r, force=True, power_base=True, power_exp=False, + mul=False, log=False, multinomial=False, basic=False)) + + if not numeric: + return True + + repl = {} + for n, ai in enumerate(meijerg(a1, a2, b1, b2, z).free_symbols - {z}): + repl[ai] = randcplx(n) + return tn(meijerg(a1, a2, b1, b2, z).subs(repl), r.subs(repl), z) + + +@slow +def test_meijerg_expand(): + from sympy.simplify.gammasimp import gammasimp + from sympy.simplify.simplify import simplify + # from mpmath docs + assert hyperexpand(meijerg([[], []], [[0], []], -z)) == exp(z) + + assert hyperexpand(meijerg([[1, 1], []], [[1], [0]], z)) == \ + log(z + 1) + assert hyperexpand(meijerg([[1, 1], []], [[1], [1]], z)) == \ + z/(z + 1) + assert hyperexpand(meijerg([[], []], [[S.Half], [0]], (z/2)**2)) \ + == sin(z)/sqrt(pi) + assert hyperexpand(meijerg([[], []], [[0], [S.Half]], (z/2)**2)) \ + == cos(z)/sqrt(pi) + assert can_do_meijer([], [a], [a - 1, a - S.Half], []) + assert can_do_meijer([], [], [a/2], [-a/2], False) # branches... + assert can_do_meijer([a], [b], [a], [b, a - 1]) + + # wikipedia + assert hyperexpand(meijerg([1], [], [], [0], z)) == \ + Piecewise((0, abs(z) < 1), (1, abs(1/z) < 1), + (meijerg([1], [], [], [0], z), True)) + assert hyperexpand(meijerg([], [1], [0], [], z)) == \ + Piecewise((1, abs(z) < 1), (0, abs(1/z) < 1), + (meijerg([], [1], [0], [], z), True)) + + # The Special Functions and their Approximations + assert can_do_meijer([], [], [a + b/2], [a, a - b/2, a + S.Half]) + assert can_do_meijer( + [], [], [a], [b], False) # branches only agree for small z + assert can_do_meijer([], [S.Half], [a], [-a]) + assert can_do_meijer([], [], [a, b], []) + assert can_do_meijer([], [], [a, b], []) + assert can_do_meijer([], [], [a, a + S.Half], [b, b + S.Half]) + assert can_do_meijer([], [], [a, -a], [0, S.Half], False) # dito + assert can_do_meijer([], [], [a, a + S.Half, b, b + S.Half], []) + assert can_do_meijer([S.Half], [], [0], [a, -a]) + assert can_do_meijer([S.Half], [], [a], [0, -a], False) # dito + assert can_do_meijer([], [a - S.Half], [a, b], [a - S.Half], False) + assert can_do_meijer([], [a + S.Half], [a + b, a - b, a], [], False) + assert can_do_meijer([a + S.Half], [], [b, 2*a - b, a], [], False) + + # This for example is actually zero. + assert can_do_meijer([], [], [], [a, b]) + + # Testing a bug: + assert hyperexpand(meijerg([0, 2], [], [], [-1, 1], z)) == \ + Piecewise((0, abs(z) < 1), + (z*(1 - 1/z**2)/2, abs(1/z) < 1), + (meijerg([0, 2], [], [], [-1, 1], z), True)) + + # Test that the simplest possible answer is returned: + assert gammasimp(simplify(hyperexpand( + meijerg([1], [1 - a], [-a/2, -a/2 + S.Half], [], 1/z)))) == \ + -2*sqrt(pi)*(sqrt(z + 1) + 1)**a/a + + # Test that hyper is returned + assert hyperexpand(meijerg([1], [], [a], [0, 0], z)) == hyper( + (a,), (a + 1, a + 1), z*exp_polar(I*pi))*z**a*gamma(a)/gamma(a + 1)**2 + + # Test place option + f = meijerg(((0, 1), ()), ((S.Half,), (0,)), z**2) + assert hyperexpand(f) == sqrt(pi)/sqrt(1 + z**(-2)) + assert hyperexpand(f, place=0) == sqrt(pi)*z/sqrt(z**2 + 1) + + +def test_meijerg_lookup(): + from sympy.functions.special.error_functions import (Ci, Si) + from sympy.functions.special.gamma_functions import uppergamma + assert hyperexpand(meijerg([a], [], [b, a], [], z)) == \ + z**b*exp(z)*gamma(-a + b + 1)*uppergamma(a - b, z) + assert hyperexpand(meijerg([0], [], [0, 0], [], z)) == \ + exp(z)*uppergamma(0, z) + assert can_do_meijer([a], [], [b, a + 1], []) + assert can_do_meijer([a], [], [b + 2, a], []) + assert can_do_meijer([a], [], [b - 2, a], []) + + assert hyperexpand(meijerg([a], [], [a, a, a - S.Half], [], z)) == \ + -sqrt(pi)*z**(a - S.Half)*(2*cos(2*sqrt(z))*(Si(2*sqrt(z)) - pi/2) + - 2*sin(2*sqrt(z))*Ci(2*sqrt(z))) == \ + hyperexpand(meijerg([a], [], [a, a - S.Half, a], [], z)) == \ + hyperexpand(meijerg([a], [], [a - S.Half, a, a], [], z)) + assert can_do_meijer([a - 1], [], [a + 2, a - Rational(3, 2), a + 1], []) + + +@XFAIL +def test_meijerg_expand_fail(): + # These basically test hyper([], [1/2 - a, 1/2 + 1, 1/2], z), + # which is *very* messy. But since the meijer g actually yields a + # sum of bessel functions, things can sometimes be simplified a lot and + # are then put into tables... + assert can_do_meijer([], [], [a + S.Half], [a, a - b/2, a + b/2]) + assert can_do_meijer([], [], [0, S.Half], [a, -a]) + assert can_do_meijer([], [], [3*a - S.Half, a, -a - S.Half], [a - S.Half]) + assert can_do_meijer([], [], [0, a - S.Half, -a - S.Half], [S.Half]) + assert can_do_meijer([], [], [a, b + S.Half, b], [2*b - a]) + assert can_do_meijer([], [], [a, b + S.Half, b, 2*b - a]) + assert can_do_meijer([S.Half], [], [-a, a], [0]) + + +@slow +def test_meijerg(): + # carefully set up the parameters. + # NOTE: this used to fail sometimes. I believe it is fixed, but if you + # hit an inexplicable test failure here, please let me know the seed. + a1, a2 = (randcplx(n) - 5*I - n*I for n in range(2)) + b1, b2 = (randcplx(n) + 5*I + n*I for n in range(2)) + b3, b4, b5, a3, a4, a5 = (randcplx() for n in range(6)) + g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) + + assert ReduceOrder.meijer_minus(3, 4) is None + assert ReduceOrder.meijer_plus(4, 3) is None + + g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2], z) + assert tn(ReduceOrder.meijer_plus(a2, a2).apply(g, op), g2, z) + + g2 = meijerg([a1, a2], [a3, a4], [b1], [b3, b4, a2 + 1], z) + assert tn(ReduceOrder.meijer_plus(a2, a2 + 1).apply(g, op), g2, z) + + g2 = meijerg([a1, a2 - 1], [a3, a4], [b1], [b3, b4, a2 + 2], z) + assert tn(ReduceOrder.meijer_plus(a2 - 1, a2 + 2).apply(g, op), g2, z) + + g2 = meijerg([a1], [a3, a4, b2 - 1], [b1, b2 + 2], [b3, b4], z) + assert tn(ReduceOrder.meijer_minus( + b2 + 2, b2 - 1).apply(g, op), g2, z, tol=1e-6) + + # test several-step reduction + an = [a1, a2] + bq = [b3, b4, a2 + 1] + ap = [a3, a4, b2 - 1] + bm = [b1, b2 + 1] + niq, ops = reduce_order_meijer(G_Function(an, ap, bm, bq)) + assert niq.an == (a1,) + assert set(niq.ap) == {a3, a4} + assert niq.bm == (b1,) + assert set(niq.bq) == {b3, b4} + assert tn(apply_operators(g, ops, op), meijerg(an, ap, bm, bq, z), z) + + +def test_meijerg_shift_operators(): + # carefully set up the parameters. XXX this still fails sometimes + a1, a2, a3, a4, a5, b1, b2, b3, b4, b5 = (randcplx(n) for n in range(10)) + g = meijerg([a1], [a3, a4], [b1], [b3, b4], z) + + assert tn(MeijerShiftA(b1).apply(g, op), + meijerg([a1], [a3, a4], [b1 + 1], [b3, b4], z), z) + assert tn(MeijerShiftB(a1).apply(g, op), + meijerg([a1 - 1], [a3, a4], [b1], [b3, b4], z), z) + assert tn(MeijerShiftC(b3).apply(g, op), + meijerg([a1], [a3, a4], [b1], [b3 + 1, b4], z), z) + assert tn(MeijerShiftD(a3).apply(g, op), + meijerg([a1], [a3 - 1, a4], [b1], [b3, b4], z), z) + + s = MeijerUnShiftA([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3, a4], [b1 - 1], [b3, b4], z), z) + + s = MeijerUnShiftC([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3, a4], [b1], [b3 - 1, b4], z), z) + + s = MeijerUnShiftB([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1 + 1], [a3, a4], [b1], [b3, b4], z), z) + + s = MeijerUnShiftD([a1], [a3, a4], [b1], [b3, b4], 0, z) + assert tn( + s.apply(g, op), meijerg([a1], [a3 + 1, a4], [b1], [b3, b4], z), z) + + +@slow +def test_meijerg_confluence(): + def t(m, a, b): + from sympy.core.sympify import sympify + a, b = sympify([a, b]) + m_ = m + m = hyperexpand(m) + if not m == Piecewise((a, abs(z) < 1), (b, abs(1/z) < 1), (m_, True)): + return False + if not (m.args[0].args[0] == a and m.args[1].args[0] == b): + return False + z0 = randcplx()/10 + if abs(m.subs(z, z0).n() - a.subs(z, z0).n()).n() > 1e-10: + return False + if abs(m.subs(z, 1/z0).n() - b.subs(z, 1/z0).n()).n() > 1e-10: + return False + return True + + assert t(meijerg([], [1, 1], [0, 0], [], z), -log(z), 0) + assert t(meijerg( + [], [3, 1], [0, 0], [], z), -z**2/4 + z - log(z)/2 - Rational(3, 4), 0) + assert t(meijerg([], [3, 1], [-1, 0], [], z), + z**2/12 - z/2 + log(z)/2 + Rational(1, 4) + 1/(6*z), 0) + assert t(meijerg([], [1, 1, 1, 1], [0, 0, 0, 0], [], z), -log(z)**3/6, 0) + assert t(meijerg([1, 1], [], [], [0, 0], z), 0, -log(1/z)) + assert t(meijerg([1, 1], [2, 2], [1, 1], [0, 0], z), + -z*log(z) + 2*z, -log(1/z) + 2) + assert t(meijerg([S.Half], [1, 1], [0, 0], [Rational(3, 2)], z), log(z)/2 - 1, 0) + + def u(an, ap, bm, bq): + m = meijerg(an, ap, bm, bq, z) + m2 = hyperexpand(m, allow_hyper=True) + if m2.has(meijerg) and not (m2.is_Piecewise and len(m2.args) == 3): + return False + return tn(m, m2, z) + assert u([], [1], [0, 0], []) + assert u([1, 1], [], [], [0]) + assert u([1, 1], [2, 2, 5], [1, 1, 6], [0, 0]) + assert u([1, 1], [2, 2, 5], [1, 1, 6], [0]) + + +def test_meijerg_with_Floats(): + # see issue #10681 + from sympy.polys.domains.realfield import RR + f = meijerg(((3.0, 1), ()), ((Rational(3, 2),), (0,)), z) + a = -2.3632718012073 + g = a*z**Rational(3, 2)*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),), z*exp_polar(I*pi)) + assert RR.almosteq((hyperexpand(f)/g).n(), 1.0, 1e-12) + + +def test_lerchphi(): + from sympy.functions.special.zeta_functions import (lerchphi, polylog) + from sympy.simplify.gammasimp import gammasimp + assert hyperexpand(hyper([1, a], [a + 1], z)/a) == lerchphi(z, 1, a) + assert hyperexpand( + hyper([1, a, a], [a + 1, a + 1], z)/a**2) == lerchphi(z, 2, a) + assert hyperexpand(hyper([1, a, a, a], [a + 1, a + 1, a + 1], z)/a**3) == \ + lerchphi(z, 3, a) + assert hyperexpand(hyper([1] + [a]*10, [a + 1]*10, z)/a**10) == \ + lerchphi(z, 10, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a], [], [0], + [-a], exp_polar(-I*pi)*z))) == lerchphi(z, 1, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a], [], [0], + [-a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 2, a) + assert gammasimp(hyperexpand(meijerg([0, 1 - a, 1 - a, 1 - a], [], [0], + [-a, -a, -a], exp_polar(-I*pi)*z))) == lerchphi(z, 3, a) + + assert hyperexpand(z*hyper([1, 1], [2], z)) == -log(1 + -z) + assert hyperexpand(z*hyper([1, 1, 1], [2, 2], z)) == polylog(2, z) + assert hyperexpand(z*hyper([1, 1, 1, 1], [2, 2, 2], z)) == polylog(3, z) + + assert hyperexpand(hyper([1, a, 1 + S.Half], [a + 1, S.Half], z)) == \ + -2*a/(z - 1) + (-2*a**2 + a)*lerchphi(z, 1, a) + + # Now numerical tests. These make sure reductions etc are carried out + # correctly + + # a rational function (polylog at negative integer order) + assert can_do([2, 2, 2], [1, 1]) + + # NOTE these contain log(1-x) etc ... better make sure we have |z| < 1 + # reduction of order for polylog + assert can_do([1, 1, 1, b + 5], [2, 2, b], div=10) + + # reduction of order for lerchphi + # XXX lerchphi in mpmath is flaky + assert can_do( + [1, a, a, a, b + 5], [a + 1, a + 1, a + 1, b], numerical=False) + + # test a bug + from sympy.functions.elementary.complexes import Abs + assert hyperexpand(hyper([S.Half, S.Half, S.Half, 1], + [Rational(3, 2), Rational(3, 2), Rational(3, 2)], Rational(1, 4))) == \ + Abs(-polylog(3, exp_polar(I*pi)/2) + polylog(3, S.Half)) + + +def test_partial_simp(): + # First test that hypergeometric function formulae work. + a, b, c, d, e = (randcplx() for _ in range(5)) + for func in [Hyper_Function([a, b, c], [d, e]), + Hyper_Function([], [a, b, c, d, e])]: + f = build_hypergeometric_formula(func) + z = f.z + assert f.closed_form == func(z) + deriv1 = f.B.diff(z)*z + deriv2 = f.M*f.B + for func1, func2 in zip(deriv1, deriv2): + assert tn(func1, func2, z) + + # Now test that formulae are partially simplified. + a, b, z = symbols('a b z') + assert hyperexpand(hyper([3, a], [1, b], z)) == \ + (-a*b/2 + a*z/2 + 2*a)*hyper([a + 1], [b], z) \ + + (a*b/2 - 2*a + 1)*hyper([a], [b], z) + assert tn( + hyperexpand(hyper([3, d], [1, e], z)), hyper([3, d], [1, e], z), z) + assert hyperexpand(hyper([3], [1, a, b], z)) == \ + hyper((), (a, b), z) \ + + z*hyper((), (a + 1, b), z)/(2*a) \ + - z*(b - 4)*hyper((), (a + 1, b + 1), z)/(2*a*b) + assert tn( + hyperexpand(hyper([3], [1, d, e], z)), hyper([3], [1, d, e], z), z) + + +def test_hyperexpand_special(): + assert hyperexpand(hyper([a, b], [c], 1)) == \ + gamma(c)*gamma(c - a - b)/gamma(c - a)/gamma(c - b) + assert hyperexpand(hyper([a, b], [1 + a - b], -1)) == \ + gamma(1 + a/2)*gamma(1 + a - b)/gamma(1 + a)/gamma(1 + a/2 - b) + assert hyperexpand(hyper([a, b], [1 + b - a], -1)) == \ + gamma(1 + b/2)*gamma(1 + b - a)/gamma(1 + b)/gamma(1 + b/2 - a) + assert hyperexpand(meijerg([1 - z - a/2], [1 - z + a/2], [b/2], [-b/2], 1)) == \ + gamma(1 - 2*z)*gamma(z + a/2 + b/2)/gamma(1 - z + a/2 - b/2) \ + /gamma(1 - z - a/2 + b/2)/gamma(1 - z + a/2 + b/2) + assert hyperexpand(hyper([a], [b], 0)) == 1 + assert hyper([a], [b], 0) != 0 + + +def test_Mod1_behavior(): + from sympy.core.symbol import Symbol + from sympy.simplify.simplify import simplify + n = Symbol('n', integer=True) + # Note: this should not hang. + assert simplify(hyperexpand(meijerg([1], [], [n + 1], [0], z))) == \ + lowergamma(n + 1, z) + + +@slow +def test_prudnikov_misc(): + assert can_do([1, (3 + I)/2, (3 - I)/2], [Rational(3, 2), 2]) + assert can_do([S.Half, a - 1], [Rational(3, 2), a + 1], lowerplane=True) + assert can_do([], [b + 1]) + assert can_do([a], [a - 1, b + 1]) + + assert can_do([a], [a - S.Half, 2*a]) + assert can_do([a], [a - S.Half, 2*a + 1]) + assert can_do([a], [a - S.Half, 2*a - 1]) + assert can_do([a], [a + S.Half, 2*a]) + assert can_do([a], [a + S.Half, 2*a + 1]) + assert can_do([a], [a + S.Half, 2*a - 1]) + assert can_do([S.Half], [b, 2 - b]) + assert can_do([S.Half], [b, 3 - b]) + assert can_do([1], [2, b]) + + assert can_do([a, a + S.Half], [2*a, b, 2*a - b + 1]) + assert can_do([a, a + S.Half], [S.Half, 2*a, 2*a + S.Half]) + assert can_do([a], [a + 1], lowerplane=True) # lowergamma + + +def test_prudnikov_1(): + # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). + # Integrals and Series: More Special Functions, Vol. 3,. + # Gordon and Breach Science Publisher + + # 7.3.1 + assert can_do([a, -a], [S.Half]) + assert can_do([a, 1 - a], [S.Half]) + assert can_do([a, 1 - a], [Rational(3, 2)]) + assert can_do([a, 2 - a], [S.Half]) + assert can_do([a, 2 - a], [Rational(3, 2)]) + assert can_do([a, 2 - a], [Rational(3, 2)]) + assert can_do([a, a + S.Half], [2*a - 1]) + assert can_do([a, a + S.Half], [2*a]) + assert can_do([a, a + S.Half], [2*a + 1]) + assert can_do([a, a + S.Half], [S.Half]) + assert can_do([a, a + S.Half], [Rational(3, 2)]) + assert can_do([a, a/2 + 1], [a/2]) + assert can_do([1, b], [2]) + assert can_do([1, b], [b + 1], numerical=False) # Lerch Phi + # NOTE: branches are complicated for |z| > 1 + + assert can_do([a], [2*a]) + assert can_do([a], [2*a + 1]) + assert can_do([a], [2*a - 1]) + + +@slow +def test_prudnikov_2(): + h = S.Half + assert can_do([-h, -h], [h]) + assert can_do([-h, h], [3*h]) + assert can_do([-h, h], [5*h]) + assert can_do([-h, h], [7*h]) + assert can_do([-h, 1], [h]) + + for p in [-h, h]: + for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: + for m in [-h, h, 3*h, 5*h, 7*h]: + assert can_do([p, n], [m]) + for n in [1, 2, 3, 4]: + for m in [1, 2, 3, 4]: + assert can_do([p, n], [m]) + + +def test_prudnikov_3(): + h = S.Half + assert can_do([Rational(1, 4), Rational(3, 4)], [h]) + assert can_do([Rational(1, 4), Rational(3, 4)], [3*h]) + assert can_do([Rational(1, 3), Rational(2, 3)], [3*h]) + assert can_do([Rational(3, 4), Rational(5, 4)], [h]) + assert can_do([Rational(3, 4), Rational(5, 4)], [3*h]) + + +@tooslow +def test_prudnikov_3_slow(): + # XXX: This is marked as tooslow and hence skipped in CI. None of the + # individual cases below fails or hangs. Some cases are slow and the loops + # below generate 280 different cases. Is it really necessary to test all + # 280 cases here? + h = S.Half + for p in [1, 2, 3, 4]: + for n in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4, 9*h]: + for m in [1, 3*h, 2, 5*h, 3, 7*h, 4]: + assert can_do([p, m], [n]) + + +@slow +def test_prudnikov_4(): + h = S.Half + for p in [3*h, 5*h, 7*h]: + for n in [-h, h, 3*h, 5*h, 7*h]: + for m in [3*h, 2, 5*h, 3, 7*h, 4]: + assert can_do([p, m], [n]) + for n in [1, 2, 3, 4]: + for m in [2, 3, 4]: + assert can_do([p, m], [n]) + + +@slow +def test_prudnikov_5(): + h = S.Half + + for p in [1, 2, 3]: + for q in range(p, 4): + for r in [1, 2, 3]: + for s in range(r, 4): + assert can_do([-h, p, q], [r, s]) + + for p in [h, 1, 3*h, 2, 5*h, 3]: + for q in [h, 3*h, 5*h]: + for r in [h, 3*h, 5*h]: + for s in [h, 3*h, 5*h]: + if s <= q and s <= r: + assert can_do([-h, p, q], [r, s]) + + for p in [h, 1, 3*h, 2, 5*h, 3]: + for q in [1, 2, 3]: + for r in [h, 3*h, 5*h]: + for s in [1, 2, 3]: + assert can_do([-h, p, q], [r, s]) + + +@slow +def test_prudnikov_6(): + h = S.Half + + for m in [3*h, 5*h]: + for n in [1, 2, 3]: + for q in [h, 1, 2]: + for p in [1, 2, 3]: + assert can_do([h, q, p], [m, n]) + for q in [1, 2, 3]: + for p in [3*h, 5*h]: + assert can_do([h, q, p], [m, n]) + + for q in [1, 2]: + for p in [1, 2, 3]: + for m in [1, 2, 3]: + for n in [1, 2, 3]: + assert can_do([h, q, p], [m, n]) + + assert can_do([h, h, 5*h], [3*h, 3*h]) + assert can_do([h, 1, 5*h], [3*h, 3*h]) + assert can_do([h, 2, 2], [1, 3]) + + # pages 435 to 457 contain more PFDD and stuff like this + + +@slow +def test_prudnikov_7(): + assert can_do([3], [6]) + + h = S.Half + for n in [h, 3*h, 5*h, 7*h]: + assert can_do([-h], [n]) + for m in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: # HERE + for n in [-h, h, 3*h, 5*h, 7*h, 1, 2, 3, 4]: + assert can_do([m], [n]) + + +@slow +def test_prudnikov_8(): + h = S.Half + + # 7.12.2 + for ai in [1, 2, 3]: + for bi in [1, 2, 3]: + for ci in range(1, ai + 1): + for di in [h, 1, 3*h, 2, 5*h, 3]: + assert can_do([ai, bi], [ci, di]) + for bi in [3*h, 5*h]: + for ci in [h, 1, 3*h, 2, 5*h, 3]: + for di in [1, 2, 3]: + assert can_do([ai, bi], [ci, di]) + + for ai in [-h, h, 3*h, 5*h]: + for bi in [1, 2, 3]: + for ci in [h, 1, 3*h, 2, 5*h, 3]: + for di in [1, 2, 3]: + assert can_do([ai, bi], [ci, di]) + for bi in [h, 3*h, 5*h]: + for ci in [h, 3*h, 5*h, 3]: + for di in [h, 1, 3*h, 2, 5*h, 3]: + if ci <= bi: + assert can_do([ai, bi], [ci, di]) + + +def test_prudnikov_9(): + # 7.13.1 [we have a general formula ... so this is a bit pointless] + for i in range(9): + assert can_do([], [(S(i) + 1)/2]) + for i in range(5): + assert can_do([], [-(2*S(i) + 1)/2]) + + +@slow +def test_prudnikov_10(): + # 7.14.2 + h = S.Half + for p in [-h, h, 1, 3*h, 2, 5*h, 3, 7*h, 4]: + for m in [1, 2, 3, 4]: + for n in range(m, 5): + assert can_do([p], [m, n]) + + for p in [1, 2, 3, 4]: + for n in [h, 3*h, 5*h, 7*h]: + for m in [1, 2, 3, 4]: + assert can_do([p], [n, m]) + + for p in [3*h, 5*h, 7*h]: + for m in [h, 1, 2, 5*h, 3, 7*h, 4]: + assert can_do([p], [h, m]) + assert can_do([p], [3*h, m]) + + for m in [h, 1, 2, 5*h, 3, 7*h, 4]: + assert can_do([7*h], [5*h, m]) + + assert can_do([Rational(-1, 2)], [S.Half, S.Half]) # shine-integral shi + + +def test_prudnikov_11(): + # 7.15 + assert can_do([a, a + S.Half], [2*a, b, 2*a - b]) + assert can_do([a, a + S.Half], [Rational(3, 2), 2*a, 2*a - S.Half]) + + assert can_do([Rational(1, 4), Rational(3, 4)], [S.Half, S.Half, 1]) + assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), S.Half, 2]) + assert can_do([Rational(5, 4), Rational(3, 4)], [Rational(3, 2), Rational(3, 2), 1]) + assert can_do([Rational(5, 4), Rational(7, 4)], [Rational(3, 2), Rational(5, 2), 2]) + + assert can_do([1, 1], [Rational(3, 2), 2, 2]) # cosh-integral chi + + +def test_prudnikov_12(): + # 7.16 + assert can_do( + [], [a, a + S.Half, 2*a], False) # branches only agree for some z! + assert can_do([], [a, a + S.Half, 2*a + 1], False) # dito + assert can_do([], [S.Half, a, a + S.Half]) + assert can_do([], [Rational(3, 2), a, a + S.Half]) + + assert can_do([], [Rational(1, 4), S.Half, Rational(3, 4)]) + assert can_do([], [S.Half, S.Half, 1]) + assert can_do([], [S.Half, Rational(3, 2), 1]) + assert can_do([], [Rational(3, 4), Rational(3, 2), Rational(5, 4)]) + assert can_do([], [1, 1, Rational(3, 2)]) + assert can_do([], [1, 2, Rational(3, 2)]) + assert can_do([], [1, Rational(3, 2), Rational(3, 2)]) + assert can_do([], [Rational(5, 4), Rational(3, 2), Rational(7, 4)]) + assert can_do([], [2, Rational(3, 2), Rational(3, 2)]) + + +@slow +def test_prudnikov_2F1(): + h = S.Half + # Elliptic integrals + for p in [-h, h]: + for m in [h, 3*h, 5*h, 7*h]: + for n in [1, 2, 3, 4]: + assert can_do([p, m], [n]) + + +@XFAIL +def test_prudnikov_fail_2F1(): + assert can_do([a, b], [b + 1]) # incomplete beta function + assert can_do([-1, b], [c]) # Poly. also -2, -3 etc + + # TODO polys + + # Legendre functions: + assert can_do([a, b], [a + b + S.Half]) + assert can_do([a, b], [a + b - S.Half]) + assert can_do([a, b], [a + b + Rational(3, 2)]) + assert can_do([a, b], [(a + b + 1)/2]) + assert can_do([a, b], [(a + b)/2 + 1]) + assert can_do([a, b], [a - b + 1]) + assert can_do([a, b], [a - b + 2]) + assert can_do([a, b], [2*b]) + assert can_do([a, b], [S.Half]) + assert can_do([a, b], [Rational(3, 2)]) + assert can_do([a, 1 - a], [c]) + assert can_do([a, 2 - a], [c]) + assert can_do([a, 3 - a], [c]) + assert can_do([a, a + S.Half], [c]) + assert can_do([1, b], [c]) + assert can_do([1, b], [Rational(3, 2)]) + + assert can_do([Rational(1, 4), Rational(3, 4)], [1]) + + # PFDD + o = S.One + assert can_do([o/8, 1], [o/8*9]) + assert can_do([o/6, 1], [o/6*7]) + assert can_do([o/6, 1], [o/6*13]) + assert can_do([o/5, 1], [o/5*6]) + assert can_do([o/5, 1], [o/5*11]) + assert can_do([o/4, 1], [o/4*5]) + assert can_do([o/4, 1], [o/4*9]) + assert can_do([o/3, 1], [o/3*4]) + assert can_do([o/3, 1], [o/3*7]) + assert can_do([o/8*3, 1], [o/8*11]) + assert can_do([o/5*2, 1], [o/5*7]) + assert can_do([o/5*2, 1], [o/5*12]) + assert can_do([o/5*3, 1], [o/5*8]) + assert can_do([o/5*3, 1], [o/5*13]) + assert can_do([o/8*5, 1], [o/8*13]) + assert can_do([o/4*3, 1], [o/4*7]) + assert can_do([o/4*3, 1], [o/4*11]) + assert can_do([o/3*2, 1], [o/3*5]) + assert can_do([o/3*2, 1], [o/3*8]) + assert can_do([o/5*4, 1], [o/5*9]) + assert can_do([o/5*4, 1], [o/5*14]) + assert can_do([o/6*5, 1], [o/6*11]) + assert can_do([o/6*5, 1], [o/6*17]) + assert can_do([o/8*7, 1], [o/8*15]) + + +@XFAIL +def test_prudnikov_fail_3F2(): + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(1, 3), Rational(2, 3)]) + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(2, 3), Rational(4, 3)]) + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [Rational(4, 3), Rational(5, 3)]) + + # page 421 + assert can_do([a, a + Rational(1, 3), a + Rational(2, 3)], [a*Rational(3, 2), (3*a + 1)/2]) + + # pages 422 ... + assert can_do([Rational(-1, 2), S.Half, S.Half], [1, 1]) # elliptic integrals + assert can_do([Rational(-1, 2), S.Half, 1], [Rational(3, 2), Rational(3, 2)]) + # TODO LOTS more + + # PFDD + assert can_do([Rational(1, 8), Rational(3, 8), 1], [Rational(9, 8), Rational(11, 8)]) + assert can_do([Rational(1, 8), Rational(5, 8), 1], [Rational(9, 8), Rational(13, 8)]) + assert can_do([Rational(1, 8), Rational(7, 8), 1], [Rational(9, 8), Rational(15, 8)]) + assert can_do([Rational(1, 6), Rational(1, 3), 1], [Rational(7, 6), Rational(4, 3)]) + assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(7, 6), Rational(5, 3)]) + assert can_do([Rational(1, 6), Rational(2, 3), 1], [Rational(5, 3), Rational(13, 6)]) + assert can_do([S.Half, 1, 1], [Rational(1, 4), Rational(3, 4)]) + # LOTS more + + +@XFAIL +def test_prudnikov_fail_other(): + # 7.11.2 + + # 7.12.1 + assert can_do([1, a], [b, 1 - 2*a + b]) # ??? + + # 7.14.2 + assert can_do([Rational(-1, 2)], [S.Half, 1]) # struve + assert can_do([1], [S.Half, S.Half]) # struve + assert can_do([Rational(1, 4)], [S.Half, Rational(5, 4)]) # PFDD + assert can_do([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)]) # PFDD + assert can_do([1], [Rational(1, 4), Rational(3, 4)]) # PFDD + assert can_do([1], [Rational(3, 4), Rational(5, 4)]) # PFDD + assert can_do([1], [Rational(5, 4), Rational(7, 4)]) # PFDD + # TODO LOTS more + + # 7.15.2 + assert can_do([S.Half, 1], [Rational(3, 4), Rational(5, 4), Rational(3, 2)]) # PFDD + assert can_do([S.Half, 1], [Rational(7, 4), Rational(5, 4), Rational(3, 2)]) # PFDD + + # 7.16.1 + assert can_do([], [Rational(1, 3), S(2/3)]) # PFDD + assert can_do([], [Rational(2, 3), S(4/3)]) # PFDD + assert can_do([], [Rational(5, 3), S(4/3)]) # PFDD + + # XXX this does not *evaluate* right?? + assert can_do([], [a, a + S.Half, 2*a - 1]) + + +def test_bug(): + h = hyper([-1, 1], [z], -1) + assert hyperexpand(h) == (z + 1)/z + + +def test_omgissue_203(): + h = hyper((-5, -3, -4), (-6, -6), 1) + assert hyperexpand(h) == Rational(1, 30) + h = hyper((-6, -7, -5), (-6, -6), 1) + assert hyperexpand(h) == Rational(-1, 6) diff --git a/shared/package-files/cb/cb808ba6ecbf22ebbdb46136bdc362db23577f23a848571e97467521f42a7dcc/_foreach_log10_native.h b/shared/package-files/cb/cb808ba6ecbf22ebbdb46136bdc362db23577f23a848571e97467521f42a7dcc/_foreach_log10_native.h new file mode 100644 index 0000000000000000000000000000000000000000..26edf334ef599f2f3d20c6274175ee7a5c39cbdc --- /dev/null +++ b/shared/package-files/cb/cb808ba6ecbf22ebbdb46136bdc362db23577f23a848571e97467521f42a7dcc/_foreach_log10_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector foreach_tensor_log10_slow(at::TensorList self); +TORCH_API void _foreach_log10_out(at::TensorList self, at::TensorList out); +TORCH_API void foreach_tensor_log10_slow_(at::TensorList self); +TORCH_API ::std::vector foreach_tensor_log10_cuda(at::TensorList self); +TORCH_API void foreach_tensor_log10_cuda_(at::TensorList self); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cb82a64dab3605a9486816913827b9e55623ade3baa79d2ebcc82279c2a82cb8/_foreach_tan_native.h b/shared/package-files/cb/cb82a64dab3605a9486816913827b9e55623ade3baa79d2ebcc82279c2a82cb8/_foreach_tan_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e37501adc3ae7ed36a9e707fe7915fe45087b774 --- /dev/null +++ b/shared/package-files/cb/cb82a64dab3605a9486816913827b9e55623ade3baa79d2ebcc82279c2a82cb8/_foreach_tan_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::vector foreach_tensor_tan_slow(at::TensorList self); +TORCH_API void _foreach_tan_out(at::TensorList self, at::TensorList out); +TORCH_API void foreach_tensor_tan_slow_(at::TensorList self); +TORCH_API ::std::vector foreach_tensor_tan_cuda(at::TensorList self); +TORCH_API void foreach_tensor_tan_cuda_(at::TensorList self); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cb830cd89a92017b39b9102e67015da84639a7a1220f4d320a827c0595b12b15/test_cuda.cpython-311.pyc b/shared/package-files/cb/cb830cd89a92017b39b9102e67015da84639a7a1220f4d320a827c0595b12b15/test_cuda.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..518dedc5e0dcf6e0f16ff044bb318c59028df626 Binary files /dev/null and b/shared/package-files/cb/cb830cd89a92017b39b9102e67015da84639a7a1220f4d320a827c0595b12b15/test_cuda.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb8725d97453aaed80f7b83f91eec104aed568c693b012472ea45ef7667505b5/planet_and_moon.cpython-311.pyc b/shared/package-files/cb/cb8725d97453aaed80f7b83f91eec104aed568c693b012472ea45ef7667505b5/planet_and_moon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3a945d56a14c70099cb76f14f049ff591781883 Binary files /dev/null and b/shared/package-files/cb/cb8725d97453aaed80f7b83f91eec104aed568c693b012472ea45ef7667505b5/planet_and_moon.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb8997f92397e1f6089289ec0060393743b2fbcfe0238157c391cd235c6abd68/WHEEL b/shared/package-files/cb/cb8997f92397e1f6089289ec0060393743b2fbcfe0238157c391cd235c6abd68/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..564c6724e4bdf48d3dc10e804a73f100414c6533 --- /dev/null +++ b/shared/package-files/cb/cb8997f92397e1f6089289ec0060393743b2fbcfe0238157c391cd235c6abd68/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (70.2.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/shared/package-files/cb/cb91e6cdd3f53f00e3e1fdeec46bb6a4c39a12d037ad336d91a25176fe81b3dc/test_drop_duplicates.cpython-311.pyc b/shared/package-files/cb/cb91e6cdd3f53f00e3e1fdeec46bb6a4c39a12d037ad336d91a25176fe81b3dc/test_drop_duplicates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eac962fec35e335d93b17d9ed9a74d0a11c75835 Binary files /dev/null and b/shared/package-files/cb/cb91e6cdd3f53f00e3e1fdeec46bb6a4c39a12d037ad336d91a25176fe81b3dc/test_drop_duplicates.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb9371677fe736d73e3444d85b0e2285aecb4d533d3a4f4d58fb663145ed6708/laplace.py b/shared/package-files/cb/cb9371677fe736d73e3444d85b0e2285aecb4d533d3a4f4d58fb663145ed6708/laplace.py new file mode 100644 index 0000000000000000000000000000000000000000..604c4a2711440f13c62f0d778e382e4daaf33148 --- /dev/null +++ b/shared/package-files/cb/cb9371677fe736d73e3444d85b0e2285aecb4d533d3a4f4d58fb663145ed6708/laplace.py @@ -0,0 +1,2377 @@ +"""Laplace Transforms""" +import sys +import sympy +from sympy.core import S, pi, I +from sympy.core.add import Add +from sympy.core.cache import cacheit +from sympy.core.expr import Expr +from sympy.core.function import ( + AppliedUndef, Derivative, expand, expand_complex, expand_mul, expand_trig, + Lambda, WildFunction, diff, Subs) +from sympy.core.mul import Mul, prod +from sympy.core.relational import ( + _canonical, Ge, Gt, Lt, Unequality, Eq, Ne, Relational) +from sympy.core.sorting import ordered +from sympy.core.symbol import Dummy, symbols, Wild +from sympy.functions.elementary.complexes import ( + re, im, arg, Abs, polar_lift, periodic_argument) +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, asinh +from sympy.functions.elementary.miscellaneous import Max, Min, sqrt +from sympy.functions.elementary.piecewise import ( + Piecewise, piecewise_exclusive) +from sympy.functions.elementary.trigonometric import cos, sin, atan, sinc +from sympy.functions.special.bessel import besseli, besselj, besselk, bessely +from sympy.functions.special.delta_functions import DiracDelta, Heaviside +from sympy.functions.special.error_functions import erf, erfc, Ei +from sympy.functions.special.gamma_functions import ( + digamma, gamma, lowergamma, uppergamma) +from sympy.functions.special.singularity_functions import SingularityFunction +from sympy.integrals import integrate, Integral +from sympy.integrals.transforms import ( + _simplify, IntegralTransform, IntegralTransformError) +from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And +from sympy.matrices.matrixbase import MatrixBase +from sympy.polys.matrices.linsolve import _lin_eq2dict +from sympy.polys.polyerrors import PolynomialError +from sympy.polys.polyroots import roots +from sympy.polys.polytools import Poly +from sympy.polys.rationaltools import together +from sympy.polys.rootoftools import RootSum +from sympy.utilities.exceptions import ( + sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) +from sympy.utilities.misc import debugf + +_LT_level = 0 + + +def DEBUG_WRAP(func): + def wrap(*args, **kwargs): + from sympy import SYMPY_DEBUG + global _LT_level + + if not SYMPY_DEBUG: + return func(*args, **kwargs) + + if _LT_level == 0: + print('\n' + '-'*78, file=sys.stderr) + print('-LT- %s%s%s' % (' '*_LT_level, func.__name__, args), + file=sys.stderr) + _LT_level += 1 + if ( + func.__name__ == '_laplace_transform_integration' or + func.__name__ == '_inverse_laplace_transform_integration'): + sympy.SYMPY_DEBUG = False + print('**** %sIntegrating ...' % (' '*_LT_level), file=sys.stderr) + result = func(*args, **kwargs) + sympy.SYMPY_DEBUG = True + else: + result = func(*args, **kwargs) + _LT_level -= 1 + print('-LT- %s---> %s' % (' '*_LT_level, result), file=sys.stderr) + if _LT_level == 0: + print('-'*78 + '\n', file=sys.stderr) + return result + return wrap + + +def _debug(text): + from sympy import SYMPY_DEBUG + + if SYMPY_DEBUG: + print('-LT- %s%s' % (' '*_LT_level, text), file=sys.stderr) + + +def _simplifyconds(expr, s, a): + r""" + Naively simplify some conditions occurring in ``expr``, + given that `\operatorname{Re}(s) > a`. + + Examples + ======== + + >>> from sympy.integrals.laplace import _simplifyconds + >>> from sympy.abc import x + >>> from sympy import sympify as S + >>> _simplifyconds(abs(x**2) < 1, x, 1) + False + >>> _simplifyconds(abs(x**2) < 1, x, 2) + False + >>> _simplifyconds(abs(x**2) < 1, x, 0) + Abs(x**2) < 1 + >>> _simplifyconds(abs(1/x**2) < 1, x, 1) + True + >>> _simplifyconds(S(1) < abs(x), x, 1) + True + >>> _simplifyconds(S(1) < abs(1/x), x, 1) + False + + >>> from sympy import Ne + >>> _simplifyconds(Ne(1, x**3), x, 1) + True + >>> _simplifyconds(Ne(1, x**3), x, 2) + True + >>> _simplifyconds(Ne(1, x**3), x, 0) + Ne(1, x**3) + """ + + def power(ex): + if ex == s: + return 1 + if ex.is_Pow and ex.base == s: + return ex.exp + return None + + def bigger(ex1, ex2): + """ Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|. + Else return None. """ + if ex1.has(s) and ex2.has(s): + return None + if isinstance(ex1, Abs): + ex1 = ex1.args[0] + if isinstance(ex2, Abs): + ex2 = ex2.args[0] + if ex1.has(s): + return bigger(1/ex2, 1/ex1) + n = power(ex2) + if n is None: + return None + try: + if n > 0 and (Abs(ex1) <= Abs(a)**n) == S.true: + return False + if n < 0 and (Abs(ex1) >= Abs(a)**n) == S.true: + return True + except TypeError: + return None + + def replie(x, y): + """ simplify x < y """ + if (not (x.is_positive or isinstance(x, Abs)) + or not (y.is_positive or isinstance(y, Abs))): + return (x < y) + r = bigger(x, y) + if r is not None: + return not r + return (x < y) + + def replue(x, y): + b = bigger(x, y) + if b in (True, False): + return True + return Unequality(x, y) + + def repl(ex, *args): + if ex in (True, False): + return bool(ex) + return ex.replace(*args) + + from sympy.simplify.radsimp import collect_abs + expr = collect_abs(expr) + expr = repl(expr, Lt, replie) + expr = repl(expr, Gt, lambda x, y: replie(y, x)) + expr = repl(expr, Unequality, replue) + return S(expr) + + +@DEBUG_WRAP +def expand_dirac_delta(expr): + """ + Expand an expression involving DiractDelta to get it as a linear + combination of DiracDelta functions. + """ + return _lin_eq2dict(expr, expr.atoms(DiracDelta)) + + +@DEBUG_WRAP +def _laplace_transform_integration(f, t, s_, *, simplify): + """ The backend function for doing Laplace transforms by integration. + + This backend assumes that the frontend has already split sums + such that `f` is to an addition anymore. + """ + s = Dummy('s') + + if f.has(DiracDelta): + return None + + F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity)) + + if not F.has(Integral): + return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true + + if not F.is_Piecewise: + return None + + F, cond = F.args[0] + if F.has(Integral): + return None + + def process_conds(conds): + """ Turn ``conds`` into a strip and auxiliary conditions. """ + from sympy.solvers.inequalities import _solve_inequality + a = S.NegativeInfinity + aux = S.true + conds = conjuncts(to_cnf(conds)) + p, q, w1, w2, w3, w4, w5 = symbols( + 'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s]) + patterns = ( + p*Abs(arg((s + w3)*q)) < w2, + p*Abs(arg((s + w3)*q)) <= w2, + Abs(periodic_argument((s + w3)**p*q, w1)) < w2, + Abs(periodic_argument((s + w3)**p*q, w1)) <= w2, + Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2, + Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2) + for c in conds: + a_ = S.Infinity + aux_ = [] + for d in disjuncts(c): + if d.is_Relational and s in d.rhs.free_symbols: + d = d.reversed + if d.is_Relational and isinstance(d, (Ge, Gt)): + d = d.reversedsign + for pat in patterns: + m = d.match(pat) + if m: + break + if m and m[q].is_positive and m[w2]/m[p] == pi/2: + d = -re(s + m[w3]) < 0 + m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0) + if not m: + m = d.match( + cos(p - Abs(periodic_argument(s**w1*w5, q))*w2) * + Abs(s**w3)**w4 < 0) + if not m: + m = d.match( + p - cos( + Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2 + )*Abs(s**w3)**w4 < 0) + if m and all(m[wild].is_positive for wild in [ + w1, w2, w3, w4, w5]): + d = re(s) > m[p] + d_ = d.replace( + re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t) + if ( + not d.is_Relational or d.rel_op in ('==', '!=') + or d_.has(s) or not d_.has(t)): + aux_ += [d] + continue + soln = _solve_inequality(d_, t) + if not soln.is_Relational or soln.rel_op in ('==', '!='): + aux_ += [d] + continue + if soln.lts == t: + return None + else: + a_ = Min(soln.lts, a_) + if a_ is not S.Infinity: + a = Max(a_, a) + else: + aux = And(aux, Or(*aux_)) + return a, aux.canonical if aux.is_Relational else aux + + conds = [process_conds(c) for c in disjuncts(cond)] + conds2 = [x for x in conds if x[1] != + S.false and x[0] is not S.NegativeInfinity] + if not conds2: + conds2 = [x for x in conds if x[1] != S.false] + conds = list(ordered(conds2)) + + def cnt(expr): + if expr in (True, False): + return 0 + return expr.count_ops() + conds.sort(key=lambda x: (-x[0], cnt(x[1]))) + + if not conds: + return None + a, aux = conds[0] # XXX is [0] always the right one? + + def sbs(expr): + return expr.subs(s, s_) + if simplify: + F = _simplifyconds(F, s, a) + aux = _simplifyconds(aux, s, a) + return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux)) + + +@DEBUG_WRAP +def _laplace_deep_collect(f, t): + """ + This is an internal helper function that traverses through the expression + tree of `f(t)` and collects arguments. The purpose of it is that + anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that + it can match `f(a*t+b)`. + """ + if not isinstance(f, Expr): + return f + if (p := f.as_poly(t)) is not None: + return p.as_expr() + func = f.func + args = [_laplace_deep_collect(arg, t) for arg in f.args] + return func(*args) + + +@cacheit +def _laplace_build_rules(): + """ + This is an internal helper function that returns the table of Laplace + transform rules in terms of the time variable `t` and the frequency + variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a + tuple containing: + + (time domain pattern, + frequency-domain replacement, + condition for the rule to be applied, + convergence plane, + preparation function) + + The preparation function is a function with one argument that is applied + to the expression before matching. For most rules it should be + ``_laplace_deep_collect``. + """ + t = Dummy('t') + s = Dummy('s') + a = Wild('a', exclude=[t]) + b = Wild('b', exclude=[t]) + n = Wild('n', exclude=[t]) + tau = Wild('tau', exclude=[t]) + omega = Wild('omega', exclude=[t]) + def dco(f): return _laplace_deep_collect(f, t) + _debug('_laplace_build_rules is building rules') + + laplace_transform_rules = [ + (a, a/s, + S.true, S.Zero, dco), # 4.2.1 + (DiracDelta(a*t-b), exp(-s*b/a)/Abs(a), + Or(And(a > 0, b >= 0), And(a < 0, b <= 0)), + S.NegativeInfinity, dco), # Not in Bateman54 + (DiracDelta(a*t-b), S(0), + Or(And(a < 0, b >= 0), And(a > 0, b <= 0)), + S.NegativeInfinity, dco), # Not in Bateman54 + (Heaviside(a*t-b), exp(-s*b/a)/s, + And(a > 0, b > 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), (1-exp(-s*b/a))/s, + And(a < 0, b < 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), 1/s, + And(a > 0, b <= 0), S.Zero, dco), # 4.4.1 + (Heaviside(a*t-b), 0, + And(a < 0, b > 0), S.Zero, dco), # 4.4.1 + (t, 1/s**2, + S.true, S.Zero, dco), # 4.2.3 + (1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.6 + (1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.18 + ((a*t+b)**(-S(3)/2), + 2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s) * erfc(sqrt(b/a*s))/a, + Abs(arg(b/a)) < pi, S.Zero, dco), # 4.2.20 + (sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)), + Abs(arg(b)) < pi, S.Zero, dco), # 4.2.22 + (1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), + S.true, S.Zero, dco), # Not in Bateman54 + (t**n, gamma(n+1)/s**(n+1), + n > -1, S.Zero, dco), # 4.3.1 + ((a*t+b)**n, uppergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a, + And(n > -1, Abs(arg(b/a)) < pi), S.Zero, dco), # 4.3.4 + (t**n/(t+a), a**n*gamma(n+1)*uppergamma(-n, a*s), + And(n > -1, Abs(arg(a)) < pi), S.Zero, dco), # 4.3.7 + (exp(a*t-tau), exp(-tau)/(s-a), + S.true, re(a), dco), # 4.5.1 + (t*exp(a*t-tau), exp(-tau)/(s-a)**2, + S.true, re(a), dco), # 4.5.2 + (t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1), + re(n) > -1, re(a), dco), # 4.5.3 + (exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)), + re(a) > 0, S.Zero, dco), # 4.5.21 + (t*exp(-a*t**2), + 1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)), + re(a) > 0, S.Zero, dco), # 4.5.22 + (exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.25 + (sqrt(t)*exp(-a/t), + S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.26 + (exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)), + re(a) >= 0, S.Zero, dco), # 4.5.27 + (exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)), + re(a) > 0, S.Zero, dco), # 4.5.28 + (t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)), + re(a) > 0, S.Zero, dco), # 4.5.29 + # TODO: rules with sqrt(a*t) and sqrt(a/t) have stopped working after + # changes to as_base_exp + # (exp(-2*sqrt(a*t)), + # s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s) * erfc(sqrt(a/s)), + # Abs(arg(a)) < pi, S.Zero, dco), # 4.5.31 + # (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)), + # Abs(arg(a)) < pi, S.Zero, dco), # 4.5.33 + (exp(-a*exp(-t)), a**(-s)*lowergamma(s, a), + S.true, S.Zero, dco), # 4.5.36 + (exp(-a*exp(t)), a**s*uppergamma(-s, a), + re(a) > 0, S.Zero, dco), # 4.5.37 + (log(a*t), -log(exp(S.EulerGamma)*s/a)/s, + a > 0, S.Zero, dco), # 4.6.1 + (log(1+a*t), -exp(s/a)/s*Ei(-s/a), + Abs(arg(a)) < pi, S.Zero, dco), # 4.6.4 + (log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a, + And(a > 0, Abs(arg(b)) < pi), S.Zero, dco), # 4.6.5 + (log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)), + S.true, S.Zero, dco), # 4.6.9 + (t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)), + re(n) > -1, S.Zero, dco), # 4.6.11 + (log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s, + a > 0, S.Zero, dco), # 4.6.13 + (sin(omega*t), omega/(s**2+omega**2), + S.true, Abs(im(omega)), dco), # 4,7,1 + (Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega), + omega > 0, S.Zero, dco), # 4.7.2 + (sin(omega*t)/t, atan(omega/s), + S.true, Abs(im(omega)), dco), # 4.7.16 + (sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4, + S.true, 2*Abs(im(omega)), dco), # 4.7.17 + (sin(omega*t)**2/t**2, + omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4, + S.true, 2*Abs(im(omega)), dco), # 4.7.20 + # (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s), + # S.true, S.Zero, dco), # 4.7.32 + # (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)), + # S.true, S.Zero, dco), # 4.7.34 + (cos(omega*t), s/(s**2+omega**2), + S.true, Abs(im(omega)), dco), # 4.7.43 + (cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s, + S.true, 2*Abs(im(omega)), dco), # 4.7.45 + # (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s), + # S.true, S.Zero, dco), # 4.7.66 + # (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s), + # S.true, S.Zero, dco), # 4.7.67 + (sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78 + (cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79 + (cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), + S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80 + (sinh(a*t), a/(s**2-a**2), + S.true, Abs(re(a)), dco), # 4.9.1 + (cosh(a*t), s/(s**2-a**2), + S.true, Abs(re(a)), dco), # 4.9.2 + (sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s), + S.true, 2*Abs(re(a)), dco), # 4.9.3 + (cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s), + S.true, 2*Abs(re(a)), dco), # 4.9.4 + (sinh(a*t)/t, log((s+a)/(s-a))/2, + S.true, Abs(re(a)), dco), # 4.9.12 + (t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)), + n > -2, Abs(a), dco), # 4.9.18 + (t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)), + n > -1, Abs(a), dco), # 4.9.19 + # TODO + # (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s), + # S.true, S.Zero, dco), # 4.9.34 + # (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)), + # S.true, S.Zero, dco), # 4.9.35 + # ( + # sqrt(t)*sinh(2*sqrt(a*t)), + # pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a) * + # exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2), + # S.true, S.Zero, dco), # 4.9.36 + # (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s), + # S.true, S.Zero, dco), # 4.9.37 + # (sinh(2*sqrt(a*t))/sqrt(t), + # pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s) * erf(sqrt(a/s)), + # S.true, S.Zero, dco), # 4.9.38 + # (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s), + # S.true, S.Zero, dco), # 4.9.39 + # (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1), + # S.true, S.Zero, dco), # 4.9.40 + # (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1), + # S.true, S.Zero, dco), # 4.9.41 + (erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s, + 4*Abs(arg(a)) < pi, S.Zero, dco), # 4.12.2 + # (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s, + # S.true, Max(S.Zero, -re(a)), dco), # 4.12.4 + # (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a), + # S.true, Max(S.Zero, re(a)), dco), # 4.12.5 + # (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s, + # re(a) > 0, S.Zero, dco), # 4.12.6 + # (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s, + # S.true, -re(a), dco), # 4.12.9 + # (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)), + # S.true, S.Zero, dco), # 4.12.10 + # (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s, + # re(a) > 0, S.Zero, dco), # 4.2.11 + (besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n), + re(n) > -1, Abs(im(a)), dco), # 4.14.1 + (t**b*besselj(n, a*t), + 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half), + And(re(n) > -S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7 + (t**b*besselj(n, a*t), + 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2), + And(re(n) > -1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8 + # (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s, + # S.true, S.Zero, dco), # 4.14.25 + # (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s), + # And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30 + (besselj(0, a*sqrt(t**2+b*t)), + exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2), + Abs(arg(b)) < pi, Abs(im(a)), dco), # 4.15.19 + (besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n), + re(n) > -1, Abs(re(a)), dco), # 4.16.1 + (t**b*besseli(n, a*t), + 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half), + And(re(n) > -S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6 + (t**b*besseli(n, a*t), + 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2), + And(re(n) > -1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7 + # (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s), + # And(re(n) > -1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18 + (bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2), + S.true, Abs(im(a)), dco), # 4.15.44 + (besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)), + S.true, -re(a), dco) # 4.16.23 + ] + return laplace_transform_rules, t, s + + +@DEBUG_WRAP +def _laplace_rule_timescale(f, t, s): + """ + This function applies the time-scaling rule of the Laplace transform in + a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will + compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``. + """ + + a = Wild('a', exclude=[t]) + g = WildFunction('g', nargs=1) + ma1 = f.match(g) + if ma1: + arg = ma1[g].args[0].collect(t) + ma2 = arg.match(a*t) + if ma2 and ma2[a].is_positive and ma2[a] != 1: + _debug(' rule: time scaling (4.1.4)') + r, pr, cr = _laplace_transform( + 1/ma2[a]*ma1[g].func(t), t, s/ma2[a], simplify=False) + return (r, pr, cr) + return None + + +@DEBUG_WRAP +def _laplace_rule_heaviside(f, t, s): + """ + This function deals with time-shifted Heaviside step functions. If the time + shift is positive, it applies the time-shift rule of the Laplace transform. + For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute + ``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``. + + If the time shift is negative, the Heaviside function is simply removed + as it means nothing to the Laplace transform. + + The function does not remove a factor ``Heaviside(t)``; this is done by + the simple rules. + """ + + a = Wild('a', exclude=[t]) + y = Wild('y') + g = Wild('g') + if ma1 := f.match(Heaviside(y) * g): + if ma2 := ma1[y].match(t - a): + if ma2[a].is_positive: + _debug(' rule: time shift (4.1.4)') + r, pr, cr = _laplace_transform( + ma1[g].subs(t, t + ma2[a]), t, s, simplify=False) + return (exp(-ma2[a] * s) * r, pr, cr) + if ma2[a].is_negative: + _debug( + ' rule: Heaviside factor; negative time shift (4.1.4)') + r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) + return (r, pr, cr) + if ma2 := ma1[y].match(a - t): + if ma2[a].is_positive: + _debug(' rule: Heaviside window open') + r, pr, cr = _laplace_transform( + (1 - Heaviside(t - ma2[a])) * ma1[g], t, s, simplify=False) + return (r, pr, cr) + if ma2[a].is_negative: + _debug(' rule: Heaviside window closed') + return (0, 0, S.true) + return None + + +@DEBUG_WRAP +def _laplace_rule_exp(f, t, s): + """ + If this function finds a factor ``exp(a*t)``, it applies the + frequency-shift rule of the Laplace transform and adjusts the convergence + plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it + will compute ``LaplaceTransform(f(t), t, s+a)``. + """ + + a = Wild('a', exclude=[t]) + y = Wild('y') + z = Wild('z') + ma1 = f.match(exp(y)*z) + if ma1: + ma2 = ma1[y].collect(t).match(a*t) + if ma2: + _debug(' rule: multiply with exp (4.1.5)') + r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a], + simplify=False) + return (r, pr+re(ma2[a]), cr) + return None + + +@DEBUG_WRAP +def _laplace_rule_delta(f, t, s): + """ + If this function finds a factor ``DiracDelta(b*t-a)``, it applies the + masking property of the delta distribution. For example, if it gets + ``(DiracDelta(t-a)*f(t), t, s)``, it will return + ``(f(a)*exp(-a*s), -a, True)``. + """ + # This rule is not in Bateman54 + + a = Wild('a', exclude=[t]) + b = Wild('b', exclude=[t]) + + y = Wild('y') + z = Wild('z') + ma1 = f.match(DiracDelta(y)*z) + if ma1 and not ma1[z].has(DiracDelta): + ma2 = ma1[y].collect(t).match(b*t-a) + if ma2: + _debug(' rule: multiply with DiracDelta') + loc = ma2[a]/ma2[b] + if re(loc) >= 0 and im(loc) == 0: + fn = exp(-ma2[a]/ma2[b]*s)*ma1[z] + if fn.has(sin, cos): + # Then it may be possible that a sinc() is present in the + # term; let's try this: + fn = fn.rewrite(sinc).ratsimp() + n, d = [x.subs(t, ma2[a]/ma2[b]) for x in fn.as_numer_denom()] + if d != 0: + return (n/d/ma2[b], S.NegativeInfinity, S.true) + else: + return None + else: + return (0, S.NegativeInfinity, S.true) + if ma1[y].is_polynomial(t): + ro = roots(ma1[y], t) + if ro != {} and set(ro.values()) == {1}: + slope = diff(ma1[y], t) + r = Add( + *[exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x) + for x in list(ro.keys()) if im(x) == 0 and re(x) >= 0]) + return (r, S.NegativeInfinity, S.true) + return None + + +@DEBUG_WRAP +def _laplace_trig_split(fn): + """ + Helper function for `_laplace_rule_trig`. This function returns two terms + `f` and `g`. `f` contains all product terms with sin, cos, sinh, cosh in + them; `g` contains everything else. + """ + trigs = [S.One] + other = [S.One] + for term in Mul.make_args(fn): + if term.has(sin, cos, sinh, cosh, exp): + trigs.append(term) + else: + other.append(term) + f = Mul(*trigs) + g = Mul(*other) + return f, g + + +@DEBUG_WRAP +def _laplace_trig_expsum(f, t): + """ + Helper function for `_laplace_rule_trig`. This function expects the `f` + from `_laplace_trig_split`. It returns two lists `xm` and `xn`. `xm` is + a list of dictionaries with keys `k` and `a` representing a function + `k*exp(a*t)`. `xn` is a list of all terms that cannot be brought into + that form, which may happen, e.g., when a trigonometric function has + another function in its argument. + """ + c1 = Wild('c1', exclude=[t]) + c0 = Wild('c0', exclude=[t]) + p = Wild('p', exclude=[t]) + xm = [] + xn = [] + + x1 = f.rewrite(exp).expand() + + for term in Add.make_args(x1): + if not term.has(t): + xm.append({'k': term, 'a': 0, re: 0, im: 0}) + continue + term = _laplace_deep_collect(term.powsimp(combine='exp'), t) + + if (r := term.match(p*exp(c1*t+c0))) is not None: + xm.append({ + 'k': r[p]*exp(r[c0]), 'a': r[c1], + re: re(r[c1]), im: im(r[c1])}) + else: + xn.append(term) + return xm, xn + + +@DEBUG_WRAP +def _laplace_trig_ltex(xm, t, s): + """ + Helper function for `_laplace_rule_trig`. This function takes the list of + exponentials `xm` from `_laplace_trig_expsum` and simplifies complex + conjugate and real symmetric poles. It returns the result as a sum and + the convergence plane. + """ + results = [] + planes = [] + + def _simpc(coeffs): + nc = coeffs.copy() + for k in range(len(nc)): + ri = nc[k].as_real_imag() + if ri[0].has(im): + nc[k] = nc[k].rewrite(cos) + else: + nc[k] = (ri[0] + I*ri[1]).rewrite(cos) + return nc + + def _quadpole(t1, k1, k2, k3, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [ + k0 + k1 + k2 + k3, + a*(k0 + k1 - k2 - k3) - 2*I*a_i*k1 + 2*I*a_i*k2, + ( + a**2*(-k0 - k1 - k2 - k3) + + a*(4*I*a_i*k0 + 4*I*a_i*k3) + + 4*a_i**2*k0 + 4*a_i**2*k3), + ( + a**3*(-k0 - k1 + k2 + k3) + + a**2*(4*I*a_i*k0 + 2*I*a_i*k1 - 2*I*a_i*k2 - 4*I*a_i*k3) + + a*(4*a_i**2*k0 - 4*a_i**2*k3)) + ] + dc = [ + S.One, S.Zero, 2*a_i**2 - 2*a_r**2, + S.Zero, a_i**4 + 2*a_i**2*a_r**2 + a_r**4] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + return n/d + + def _ccpole(t1, k1, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [k0 + k1, -a*k0 - a*k1 + 2*I*a_i*k0] + dc = [S.One, -2*a_r, a_i**2 + a_r**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + return n/d + + def _rspole(t1, k2, s): + a, k0, a_r, a_i = t1['a'], t1['k'], t1[re], t1[im] + nc = [k0 + k2, a*k0 - a*k2 - 2*I*a_i*k0] + dc = [S.One, -2*I*a_i, -a_i**2 - a_r**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + return n/d + + def _sypole(t1, k3, s): + a, k0 = t1['a'], t1['k'] + nc = [k0 + k3, a*(k0 - k3)] + dc = [S.One, S.Zero, -a**2] + n = Add( + *[x*s**y for x, y in zip(_simpc(nc), range(len(nc))[::-1])]) + d = Add( + *[x*s**y for x, y in zip(dc, range(len(dc))[::-1])]) + return n/d + + def _simplepole(t1, s): + a, k0 = t1['a'], t1['k'] + n = k0 + d = s - a + return n/d + + while len(xm) > 0: + t1 = xm.pop() + i_imagsym = None + i_realsym = None + i_pointsym = None + # The following code checks all remaining poles. If t1 is a pole at + # a+b*I, then we check for a-b*I, -a+b*I, and -a-b*I, and + # assign the respective indices to i_imagsym, i_realsym, i_pointsym. + # -a-b*I / i_pointsym only applies if both a and b are != 0. + for i in range(len(xm)): + real_eq = t1[re] == xm[i][re] + realsym = t1[re] == -xm[i][re] + imag_eq = t1[im] == xm[i][im] + imagsym = t1[im] == -xm[i][im] + if realsym and imagsym and t1[re] != 0 and t1[im] != 0: + i_pointsym = i + elif realsym and imag_eq and t1[re] != 0: + i_realsym = i + elif real_eq and imagsym and t1[im] != 0: + i_imagsym = i + + # The next part looks for four possible pole constellations: + # quad: a+b*I, a-b*I, -a+b*I, -a-b*I + # cc: a+b*I, a-b*I (a may be zero) + # quad: a+b*I, -a+b*I (b may be zero) + # point: a+b*I, -a-b*I (a!=0 and b!=0 is needed, but that has been + # asserted when finding i_pointsym above.) + # If none apply, then t1 is a simple pole. + if ( + i_imagsym is not None and i_realsym is not None + and i_pointsym is not None): + results.append( + _quadpole(t1, + xm[i_imagsym]['k'], xm[i_realsym]['k'], + xm[i_pointsym]['k'], s)) + planes.append(Abs(re(t1['a']))) + # The three additional poles have now been used; to pop them + # easily we have to do it from the back. + indices_to_pop = [i_imagsym, i_realsym, i_pointsym] + indices_to_pop.sort(reverse=True) + for i in indices_to_pop: + xm.pop(i) + elif i_imagsym is not None: + results.append(_ccpole(t1, xm[i_imagsym]['k'], s)) + planes.append(t1[re]) + xm.pop(i_imagsym) + elif i_realsym is not None: + results.append(_rspole(t1, xm[i_realsym]['k'], s)) + planes.append(Abs(t1[re])) + xm.pop(i_realsym) + elif i_pointsym is not None: + results.append(_sypole(t1, xm[i_pointsym]['k'], s)) + planes.append(Abs(t1[re])) + xm.pop(i_pointsym) + else: + results.append(_simplepole(t1, s)) + planes.append(t1[re]) + + return Add(*results), Max(*planes) + + +@DEBUG_WRAP +def _laplace_rule_trig(fn, t_, s): + """ + This rule covers trigonometric factors by splitting everything into a + sum of exponential functions and collecting complex conjugate poles and + real symmetric poles. + """ + t = Dummy('t', real=True) + + if not fn.has(sin, cos, sinh, cosh): + return None + + f, g = _laplace_trig_split(fn.subs(t_, t)) + xm, xn = _laplace_trig_expsum(f, t) + + if len(xn) > 0: + # TODO not implemented yet, but also not important + return None + + if not g.has(t): + r, p = _laplace_trig_ltex(xm, t, s) + return g*r, p, S.true + else: + # Just transform `g` and make frequency-shifted copies + planes = [] + results = [] + G, G_plane, G_cond = _laplace_transform(g, t, s, simplify=False) + for x1 in xm: + results.append(x1['k']*G.subs(s, s-x1['a'])) + planes.append(G_plane+re(x1['a'])) + return Add(*results).subs(t, t_), Max(*planes), G_cond + + +@DEBUG_WRAP +def _laplace_rule_diff(f, t, s): + """ + This function looks for derivatives in the time domain and replaces it + by factors of `s` and initial conditions in the frequency domain. For + example, if it gets ``(diff(f(t), t), t, s)``, it will compute + ``s*LaplaceTransform(f(t), t, s) - f(0)``. + """ + + a = Wild('a', exclude=[t]) + n = Wild('n', exclude=[t]) + g = WildFunction('g') + ma1 = f.match(a*Derivative(g, (t, n))) + if ma1 and ma1[n].is_integer: + m = [z.has(t) for z in ma1[g].args] + if sum(m) == 1: + _debug(' rule: time derivative (4.1.8)') + d = [] + for k in range(ma1[n]): + if k == 0: + y = ma1[g].subs(t, 0) + else: + y = Derivative(ma1[g], (t, k)).subs(t, 0) + d.append(s**(ma1[n]-k-1)*y) + r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) + return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr) + return None + + +@DEBUG_WRAP +def _laplace_rule_sdiff(f, t, s): + """ + This function looks for multiplications with polynoimials in `t` as they + correspond to differentiation in the frequency domain. For example, if it + gets ``(t*f(t), t, s)``, it will compute + ``-Derivative(LaplaceTransform(f(t), t, s), s)``. + """ + + if f.is_Mul: + pfac = [1] + ofac = [1] + for fac in Mul.make_args(f): + if fac.is_polynomial(t): + pfac.append(fac) + else: + ofac.append(fac) + if len(pfac) > 1: + pex = prod(pfac) + pc = Poly(pex, t).all_coeffs() + N = len(pc) + if N > 1: + oex = prod(ofac) + r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False) + deri = [r_] + d1 = False + try: + d1 = -diff(deri[-1], s) + except ValueError: + d1 = False + if r_.has(LaplaceTransform): + for k in range(N-1): + deri.append((-1)**(k+1)*Derivative(r_, s, k+1)) + elif d1: + deri.append(d1) + for k in range(N-2): + deri.append(-diff(deri[-1], s)) + if d1: + r = Add(*[pc[N-n-1]*deri[n] for n in range(N)]) + return (r, p_, c_) + # We still have to cover the possibility that there is a symbolic positive + # integer exponent. + n = Wild('n', exclude=[t]) + g = Wild('g') + if ma1 := f.match(t**n*g): + if ma1[n].is_integer and ma1[n].is_positive: + r_, p_, c_ = _laplace_transform(ma1[g], t, s, simplify=False) + return (-1)**ma1[n]*diff(r_, (s, ma1[n])), p_, c_ + return None + + +@DEBUG_WRAP +def _laplace_expand(f, t, s): + """ + This function tries to expand its argument with successively stronger + methods: first it will expand on the top level, then it will expand any + multiplications in depth, then it will try all available expansion methods, + and finally it will try to expand trigonometric functions. + + If it can expand, it will then compute the Laplace transform of the + expanded term. + """ + + r = expand(f, deep=False) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + r = expand_mul(f) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + r = expand(f) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + if r != f: + return _laplace_transform(r, t, s, simplify=False) + r = expand(expand_trig(f)) + if r.is_Add: + return _laplace_transform(r, t, s, simplify=False) + return None + + +@DEBUG_WRAP +def _laplace_apply_prog_rules(f, t, s): + """ + This function applies all program rules and returns the result if one + of them gives a result. + """ + + prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta, + _laplace_rule_timescale, _laplace_rule_exp, + _laplace_rule_trig, + _laplace_rule_diff, _laplace_rule_sdiff] + + for p_rule in prog_rules: + if (L := p_rule(f, t, s)) is not None: + return L + return None + + +@DEBUG_WRAP +def _laplace_apply_simple_rules(f, t, s): + """ + This function applies all simple rules and returns the result if one + of them gives a result. + """ + simple_rules, t_, s_ = _laplace_build_rules() + prep_old = '' + prep_f = '' + for t_dom, s_dom, check, plane, prep in simple_rules: + if prep_old != prep: + prep_f = prep(f.subs({t: t_})) + prep_old = prep + ma = prep_f.match(t_dom) + if ma: + try: + c = check.xreplace(ma) + except TypeError: + # This may happen if the time function has imaginary + # numbers in it. Then we give up. + continue + if c == S.true: + return (s_dom.xreplace(ma).subs({s_: s}), + plane.xreplace(ma), S.true) + return None + + +@DEBUG_WRAP +def _piecewise_to_heaviside(f, t): + """ + This function converts a Piecewise expression to an expression written + with Heaviside. It is not exact, but valid in the context of the Laplace + transform. + """ + if not t.is_real: + r = Dummy('r', real=True) + return _piecewise_to_heaviside(f.xreplace({t: r}), r).xreplace({r: t}) + x = piecewise_exclusive(f) + r = [] + for fn, cond in x.args: + # Here we do not need to do many checks because piecewise_exclusive + # has a clearly predictable output. However, if any of the conditions + # is not relative to t, this function just returns the input argument. + if isinstance(cond, Relational) and t in cond.args: + if isinstance(cond, (Eq, Ne)): + # We do not cover this case; these would be single-point + # exceptions that do not play a role in Laplace practice, + # except if they contain Dirac impulses, and then we can + # expect users to not try to use Piecewise for writing it. + return f + else: + r.append(Heaviside(cond.gts - cond.lts)*fn) + elif isinstance(cond, Or) and len(cond.args) == 2: + # Or(t<2, t>4), Or(t>4, t<=2), ... in any order with any <= >= + for c2 in cond.args: + if c2.lhs == t: + r.append(Heaviside(c2.gts - c2.lts)*fn) + else: + return f + elif isinstance(cond, And) and len(cond.args) == 2: + # And(t>2, t<4), And(t>4, t<=2), ... in any order with any <= >= + c0, c1 = cond.args + if c0.lhs == t and c1.lhs == t: + if '>' in c0.rel_op: + c0, c1 = c1, c0 + r.append( + (Heaviside(c1.gts - c1.lts) - + Heaviside(c0.lts - c0.gts))*fn) + else: + return f + else: + return f + return Add(*r) + + +def laplace_correspondence(f, fdict, /): + """ + This helper function takes a function `f` that is the result of a + ``laplace_transform`` or an ``inverse_laplace_transform``. It replaces all + unevaluated ``LaplaceTransform(y(t), t, s)`` by `Y(s)` for any `s` and + all ``InverseLaplaceTransform(Y(s), s, t)`` by `y(t)` for any `t` if + ``fdict`` contains a correspondence ``{y: Y}``. + + Parameters + ========== + + f : sympy expression + Expression containing unevaluated ``LaplaceTransform`` or + ``LaplaceTransform`` objects. + fdict : dictionary + Dictionary containing one or more function correspondences, + e.g., ``{x: X, y: Y}`` meaning that ``X`` and ``Y`` are the + Laplace transforms of ``x`` and ``y``, respectively. + + Examples + ======== + + >>> from sympy import laplace_transform, diff, Function + >>> from sympy import laplace_correspondence, inverse_laplace_transform + >>> from sympy.abc import t, s + >>> y = Function("y") + >>> Y = Function("Y") + >>> z = Function("z") + >>> Z = Function("Z") + >>> f = laplace_transform(diff(y(t), t, 1) + z(t), t, s, noconds=True) + >>> laplace_correspondence(f, {y: Y, z: Z}) + s*Y(s) + Z(s) - y(0) + >>> f = inverse_laplace_transform(Y(s), s, t) + >>> laplace_correspondence(f, {y: Y}) + y(t) + """ + p = Wild('p') + s = Wild('s') + t = Wild('t') + a = Wild('a') + if ( + not isinstance(f, Expr) + or (not f.has(LaplaceTransform) + and not f.has(InverseLaplaceTransform))): + return f + for y, Y in fdict.items(): + if ( + (m := f.match(LaplaceTransform(y(a), t, s))) is not None + and m[a] == m[t]): + return Y(m[s]) + if ( + (m := f.match(InverseLaplaceTransform(Y(a), s, t, p))) + is not None + and m[a] == m[s]): + return y(m[t]) + func = f.func + args = [laplace_correspondence(arg, fdict) for arg in f.args] + return func(*args) + + +def laplace_initial_conds(f, t, fdict, /): + """ + This helper function takes a function `f` that is the result of a + ``laplace_transform``. It takes an fdict of the form ``{y: [1, 4, 2]}``, + where the values in the list are the initial value, the initial slope, the + initial second derivative, etc., of the function `y(t)`, and replaces all + unevaluated initial conditions. + + Parameters + ========== + + f : sympy expression + Expression containing initial conditions of unevaluated functions. + t : sympy expression + Variable for which the initial conditions are to be applied. + fdict : dictionary + Dictionary containing a list of initial conditions for every + function, e.g., ``{y: [0, 1, 2], x: [3, 4, 5]}``. The order + of derivatives is ascending, so `0`, `1`, `2` are `y(0)`, `y'(0)`, + and `y''(0)`, respectively. + + Examples + ======== + + >>> from sympy import laplace_transform, diff, Function + >>> from sympy import laplace_correspondence, laplace_initial_conds + >>> from sympy.abc import t, s + >>> y = Function("y") + >>> Y = Function("Y") + >>> f = laplace_transform(diff(y(t), t, 3), t, s, noconds=True) + >>> g = laplace_correspondence(f, {y: Y}) + >>> laplace_initial_conds(g, t, {y: [2, 4, 8, 16, 32]}) + s**3*Y(s) - 2*s**2 - 4*s - 8 + """ + for y, ic in fdict.items(): + for k in range(len(ic)): + if k == 0: + f = f.replace(y(0), ic[0]) + elif k == 1: + f = f.replace(Subs(Derivative(y(t), t), t, 0), ic[1]) + else: + f = f.replace(Subs(Derivative(y(t), (t, k)), t, 0), ic[k]) + return f + + +@DEBUG_WRAP +def _laplace_transform(fn, t_, s_, *, simplify): + """ + Front-end function of the Laplace transform. It tries to apply all known + rules recursively, and if everything else fails, it tries to integrate. + """ + + terms_t = Add.make_args(fn) + terms_s = [] + terms = [] + planes = [] + conditions = [] + + for ff in terms_t: + k, ft = ff.as_independent(t_, as_Add=False) + if ft.has(SingularityFunction): + _terms = Add.make_args(ft.rewrite(Heaviside)) + for _term in _terms: + k1, f1 = _term.as_independent(t_, as_Add=False) + terms.append((k*k1, f1)) + elif ft.func == Piecewise and not ft.has(DiracDelta(t_)): + _terms = Add.make_args(_piecewise_to_heaviside(ft, t_)) + for _term in _terms: + k1, f1 = _term.as_independent(t_, as_Add=False) + terms.append((k*k1, f1)) + else: + terms.append((k, ft)) + + for k, ft in terms: + if ft.has(SingularityFunction): + r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) + else: + if ft.has(Heaviside(t_)) and not ft.has(DiracDelta(t_)): + # For t>=0, Heaviside(t)=1 can be used, except if there is also + # a DiracDelta(t) present, in which case removing Heaviside(t) + # is unnecessary because _laplace_rule_delta can deal with it. + ft = ft.subs(Heaviside(t_), 1) + if ( + (r := _laplace_apply_simple_rules(ft, t_, s_)) + is not None or + (r := _laplace_apply_prog_rules(ft, t_, s_)) + is not None or + (r := _laplace_expand(ft, t_, s_)) is not None): + pass + elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)): + # If there are undefined functions f(t) then integration is + # unlikely to do anything useful so we skip it and given an + # unevaluated LaplaceTransform. + r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) + elif (r := _laplace_transform_integration( + ft, t_, s_, simplify=simplify)) is not None: + pass + else: + r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) + (ri_, pi_, ci_) = r + terms_s.append(k*ri_) + planes.append(pi_) + conditions.append(ci_) + + result = Add(*terms_s) + if simplify: + result = result.simplify(doit=False) + plane = Max(*planes) + condition = And(*conditions) + + return result, plane, condition + + +class LaplaceTransform(IntegralTransform): + """ + Class representing unevaluated Laplace transforms. + + For usage of this class, see the :class:`IntegralTransform` docstring. + + For how to compute Laplace transforms, see the :func:`laplace_transform` + docstring. + + If this is called with ``.doit()``, it returns the Laplace transform as an + expression. If it is called with ``.doit(noconds=False)``, it returns a + tuple containing the same expression, a convergence plane, and conditions. + """ + + _name = 'Laplace' + + def _compute_transform(self, f, t, s, **hints): + _simplify = hints.get('simplify', False) + LT = _laplace_transform_integration(f, t, s, simplify=_simplify) + return LT + + def _as_integral(self, f, t, s): + return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity)) + + def doit(self, **hints): + """ + Try to evaluate the transform in closed form. + + Explanation + =========== + + Standard hints are the following: + - ``noconds``: if True, do not return convergence conditions. The + default setting is `True`. + - ``simplify``: if True, it simplifies the final result. The + default setting is `False`. + """ + _noconds = hints.get('noconds', True) + _simplify = hints.get('simplify', False) + + debugf('[LT doit] (%s, %s, %s)', (self.function, + self.function_variable, + self.transform_variable)) + + t_ = self.function_variable + s_ = self.transform_variable + fn = self.function + + r = _laplace_transform(fn, t_, s_, simplify=_simplify) + + if _noconds: + return r[0] + else: + return r + + +def laplace_transform(f, t, s, legacy_matrix=True, **hints): + r""" + Compute the Laplace Transform `F(s)` of `f(t)`, + + .. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t. + + Explanation + =========== + + For all sensible functions, this converges absolutely in a + half-plane + + .. math :: a < \operatorname{Re}(s) + + This function returns ``(F, a, cond)`` where ``F`` is the Laplace + transform of ``f``, `a` is the half-plane of convergence, and `cond` are + auxiliary convergence conditions. + + The implementation is rule-based, and if you are interested in which + rules are applied, and whether integration is attempted, you can switch + debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers + of the rules in the debug information (and the code) refer to Bateman's + Tables of Integral Transforms [1]. + + The lower bound is `0-`, meaning that this bound should be approached + from the lower side. This is only necessary if distributions are involved. + At present, it is only done if `f(t)` contains ``DiracDelta``, in which + case the Laplace transform is computed implicitly as + + .. math :: + F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} + f(t) \mathrm{d}t + + by applying rules. + + If the Laplace transform cannot be fully computed in closed form, this + function returns expressions containing unevaluated + :class:`LaplaceTransform` objects. + + For a description of possible hints, refer to the docstring of + :func:`sympy.integrals.transforms.IntegralTransform.doit`. If + ``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also + not the plane ``a``). + + .. deprecated:: 1.9 + Legacy behavior for matrices where ``laplace_transform`` with + ``noconds=False`` (the default) returns a Matrix whose elements are + tuples. The behavior of ``laplace_transform`` for matrices will change + in a future release of SymPy to return a tuple of the transformed + Matrix and the convergence conditions for the matrix as a whole. Use + ``legacy_matrix=False`` to enable the new behavior. + + Examples + ======== + + >>> from sympy import DiracDelta, exp, laplace_transform + >>> from sympy.abc import t, s, a + >>> laplace_transform(t**4, t, s) + (24/s**5, 0, True) + >>> laplace_transform(t**a, t, s) + (gamma(a + 1)/(s*s**a), 0, re(a) > -1) + >>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) + (s/(a + s), -re(a), True) + + There are also helper functions that make it easy to solve differential + equations by Laplace transform. For example, to solve + + .. math :: m x''(t) + d x'(t) + k x(t) = 0 + + with initial value `0` and initial derivative `v`: + + >>> from sympy import Function, laplace_correspondence, diff, solve + >>> from sympy import laplace_initial_conds, inverse_laplace_transform + >>> from sympy.abc import d, k, m, v + >>> x = Function('x') + >>> X = Function('X') + >>> f = m*diff(x(t), t, 2) + d*diff(x(t), t) + k*x(t) + >>> F = laplace_transform(f, t, s, noconds=True) + >>> F = laplace_correspondence(F, {x: X}) + >>> F = laplace_initial_conds(F, t, {x: [0, v]}) + >>> F + d*s*X(s) + k*X(s) + m*(s**2*X(s) - v) + >>> Xs = solve(F, X(s))[0] + >>> Xs + m*v/(d*s + k + m*s**2) + >>> inverse_laplace_transform(Xs, s, t) + 2*v*exp(-d*t/(2*m))*sin(t*sqrt((-d**2 + 4*k*m)/m**2)/2)*Heaviside(t)/sqrt((-d**2 + 4*k*m)/m**2) + + References + ========== + + .. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1, + Bateman Manuscript Prooject, McGraw-Hill (1954), available: + https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353 + + See Also + ======== + + inverse_laplace_transform, mellin_transform, fourier_transform + hankel_transform, inverse_hankel_transform + + """ + + _noconds = hints.get('noconds', False) + _simplify = hints.get('simplify', False) + + if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'): + + conds = not hints.get('noconds', False) + + if conds and legacy_matrix: + adt = 'deprecated-laplace-transform-matrix' + sympy_deprecation_warning( + """ +Calling laplace_transform() on a Matrix with noconds=False (the default) is +deprecated. Either noconds=True or use legacy_matrix=False to get the new +behavior. + """, + deprecated_since_version='1.9', + active_deprecations_target=adt, + ) + # Temporarily disable the deprecation warning for non-Expr objects + # in Matrix + with ignore_warnings(SymPyDeprecationWarning): + return f.applyfunc( + lambda fij: laplace_transform(fij, t, s, **hints)) + else: + elements_trans = [laplace_transform( + fij, t, s, **hints) for fij in f] + if conds: + elements, avals, conditions = zip(*elements_trans) + f_laplace = type(f)(*f.shape, elements) + return f_laplace, Max(*avals), And(*conditions) + else: + return type(f)(*f.shape, elements_trans) + + LT, p, c = LaplaceTransform(f, t, s).doit(noconds=False, + simplify=_simplify) + + if not _noconds: + return LT, p, c + else: + return LT + + +@DEBUG_WRAP +def _inverse_laplace_transform_integration(F, s, t_, plane, *, simplify): + """ The backend function for inverse Laplace transforms. """ + from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp + from sympy.integrals.transforms import inverse_mellin_transform + + # There are two strategies we can try: + # 1) Use inverse mellin transform, related by a simple change of variables. + # 2) Use the inversion integral. + + t = Dummy('t', real=True) + + def pw_simp(*args): + """ Simplify a piecewise expression from hyperexpand. """ + if len(args) != 3: + return Piecewise(*args) + arg = args[2].args[0].argument + coeff, exponent = _get_coeff_exp(arg, t) + e1 = args[0].args[0] + e2 = args[1].args[0] + return ( + Heaviside(1/Abs(coeff) - t**exponent)*e1 + + Heaviside(t**exponent - 1/Abs(coeff))*e2) + + if F.is_rational_function(s): + F = F.apart(s) + + if F.is_Add: + f = Add( + *[_inverse_laplace_transform_integration(X, s, t, plane, simplify) + for X in F.args]) + return _simplify(f.subs(t, t_), simplify), True + + try: + f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity), + needeval=True, noconds=False) + except IntegralTransformError: + f = None + + if f is None: + f = meijerint_inversion(F, s, t) + if f is None: + return None + if f.is_Piecewise: + f, cond = f.args[0] + if f.has(Integral): + return None + else: + cond = S.true + f = f.replace(Piecewise, pw_simp) + + if f.is_Piecewise: + # many of the functions called below can't work with piecewise + # (b/c it has a bool in args) + return f.subs(t, t_), cond + + u = Dummy('u') + + def simp_heaviside(arg, H0=S.Half): + a = arg.subs(exp(-t), u) + if a.has(t): + return Heaviside(arg, H0) + from sympy.solvers.inequalities import _solve_inequality + rel = _solve_inequality(a > 0, u) + if rel.lts == u: + k = log(rel.gts) + return Heaviside(t + k, H0) + else: + k = log(rel.lts) + return Heaviside(-(t + k), H0) + + f = f.replace(Heaviside, simp_heaviside) + + def simp_exp(arg): + return expand_complex(exp(arg)) + + f = f.replace(exp, simp_exp) + + return _simplify(f.subs(t, t_), simplify), cond + + +@DEBUG_WRAP +def _complete_the_square_in_denom(f, s): + from sympy.simplify.radsimp import fraction + [n, d] = fraction(f) + if d.is_polynomial(s): + cf = d.as_poly(s).all_coeffs() + if len(cf) == 3: + a, b, c = cf + d = a*((s+b/(2*a))**2+c/a-(b/(2*a))**2) + return n/d + + +@cacheit +def _inverse_laplace_build_rules(): + """ + This is an internal helper function that returns the table of inverse + Laplace transform rules in terms of the time variable `t` and the + frequency variable `s`. It is used by `_inverse_laplace_apply_rules`. + """ + s = Dummy('s') + t = Dummy('t') + a = Wild('a', exclude=[s]) + b = Wild('b', exclude=[s]) + c = Wild('c', exclude=[s]) + + _debug('_inverse_laplace_build_rules is building rules') + + def _frac(f, s): + try: + return f.factor(s) + except PolynomialError: + return f + + def same(f): return f + # This list is sorted according to the prep function needed. + _ILT_rules = [ + (a/s, a, S.true, same, 1), + ( + b*(s+a)**(-c), t**(c-1)*exp(-a*t)/gamma(c), + S.true, same, 1), + (1/(s**2+a**2)**2, (sin(a*t) - a*t*cos(a*t))/(2*a**3), + S.true, same, 1), + # The next two rules must be there in that order. For the second + # one, the condition would be a != 0 or, respectively, to take the + # limit a -> 0 after the transform if a == 0. It is much simpler if + # the case a == 0 has its own rule. + (1/(s**b), t**(b - 1)/gamma(b), S.true, same, 1), + (1/(s*(s+a)**b), lowergamma(b, a*t)/(a**b*gamma(b)), + S.true, same, 1) + ] + return _ILT_rules, s, t + + +@DEBUG_WRAP +def _inverse_laplace_apply_simple_rules(f, s, t): + """ + Helper function for the class InverseLaplaceTransform. + """ + if f == 1: + _debug(' rule: 1 o---o DiracDelta()') + return DiracDelta(t), S.true + + _ILT_rules, s_, t_ = _inverse_laplace_build_rules() + _prep = '' + fsubs = f.subs({s: s_}) + + for s_dom, t_dom, check, prep, fac in _ILT_rules: + if _prep != (prep, fac): + _F = prep(fsubs*fac) + _prep = (prep, fac) + ma = _F.match(s_dom) + if ma: + c = check + if c is not S.true: + args = [x.xreplace(ma) for x in c[0]] + c = c[1](*args) + if c == S.true: + return Heaviside(t)*t_dom.xreplace(ma).subs({t_: t}), S.true + + return None + + +@DEBUG_WRAP +def _inverse_laplace_diff(f, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + a = Wild('a', exclude=[s]) + n = Wild('n', exclude=[s]) + g = Wild('g') + ma = f.match(a*Derivative(g, (s, n))) + if ma and ma[n].is_integer: + _debug(' rule: t**n*f(t) o---o (-1)**n*diff(F(s), s, n)') + r, c = _inverse_laplace_transform( + ma[g], s, t, plane, simplify=False, dorational=False) + return (-t)**ma[n]*r, c + return None + + +@DEBUG_WRAP +def _inverse_laplace_time_shift(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + a = Wild('a', exclude=[s]) + g = Wild('g') + + if not F.has(s): + return F*DiracDelta(t), S.true + if not F.has(exp): + return None + + ma1 = F.match(exp(a*s)) + if ma1: + if ma1[a].is_negative: + _debug(' rule: exp(-a*s) o---o DiracDelta(t-a)') + return DiracDelta(t+ma1[a]), S.true + else: + return InverseLaplaceTransform(F, s, t, plane), S.true + + ma1 = F.match(exp(a*s)*g) + if ma1: + if ma1[a].is_negative: + _debug(' rule: exp(-a*s)*F(s) o---o Heaviside(t-a)*f(t-a)') + return _inverse_laplace_transform( + ma1[g], s, t+ma1[a], plane, simplify=False, dorational=True) + else: + return InverseLaplaceTransform(F, s, t, plane), S.true + return None + + +@DEBUG_WRAP +def _inverse_laplace_freq_shift(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + if not F.has(s): + return F*DiracDelta(t), S.true + if len(args := F.args) == 1: + a = Wild('a', exclude=[s]) + if (ma := args[0].match(s-a)) and re(ma[a]).is_positive: + _debug(' rule: F(s-a) o---o exp(-a*t)*f(t)') + return ( + exp(-ma[a]*t) * + InverseLaplaceTransform(F.func(s), s, t, plane), S.true) + return None + + +@DEBUG_WRAP +def _inverse_laplace_time_diff(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + n = Wild('n', exclude=[s]) + g = Wild('g') + + ma1 = F.match(s**n*g) + if ma1 and ma1[n].is_integer and ma1[n].is_positive: + _debug(' rule: s**n*F(s) o---o diff(f(t), t, n)') + r, c = _inverse_laplace_transform( + ma1[g], s, t, plane, simplify=False, dorational=True) + r = r.replace(Heaviside(t), 1) + if r.has(InverseLaplaceTransform): + return diff(r, t, ma1[n]), c + else: + return Heaviside(t)*diff(r, t, ma1[n]), c + return None + + +@DEBUG_WRAP +def _inverse_laplace_irrational(fn, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + + a = Wild('a', exclude=[s]) + b = Wild('b', exclude=[s]) + m = Wild('m', exclude=[s]) + n = Wild('n', exclude=[s]) + + result = None + condition = S.true + + fa = fn.as_ordered_factors() + + ma = [x.match((a*s**m+b)**n) for x in fa] + + if None in ma: + return None + + constants = S.One + zeros = [] + poles = [] + rest = [] + + for term in ma: + if term[a] == 0: + constants = constants*term + elif term[n].is_positive: + zeros.append(term) + elif term[n].is_negative: + poles.append(term) + else: + rest.append(term) + + # The code below assumes that the poles are sorted in a specific way: + poles = sorted(poles, key=lambda x: (x[n], x[b] != 0, x[b])) + zeros = sorted(zeros, key=lambda x: (x[n], x[b] != 0, x[b])) + + if len(rest) != 0: + return None + + if len(poles) == 1 and len(zeros) == 0: + if poles[0][n] == -1 and poles[0][m] == S.Half: + # 1/(a0*sqrt(s)+b0) == 1/a0 * 1/(sqrt(s)+b0/a0) + a_ = poles[0][b]/poles[0][a] + k_ = 1/poles[0][a]*constants + if a_.is_positive: + result = ( + k_/sqrt(pi)/sqrt(t) - + k_*a_*exp(a_**2*t)*erfc(a_*sqrt(t))) + _debug(' rule 5.3.4') + elif poles[0][n] == -2 and poles[0][m] == S.Half: + # 1/(a0*sqrt(s)+b0)**2 == 1/a0**2 * 1/(sqrt(s)+b0/a0)**2 + a_sq = poles[0][b]/poles[0][a] + a_ = a_sq**2 + k_ = 1/poles[0][a]**2*constants + if a_sq.is_positive: + result = ( + k_*(1 - 2/sqrt(pi)*sqrt(a_)*sqrt(t) + + (1-2*a_*t)*exp(a_*t)*(erf(sqrt(a_)*sqrt(t))-1))) + _debug(' rule 5.3.10') + elif poles[0][n] == -3 and poles[0][m] == S.Half: + # 1/(a0*sqrt(s)+b0)**3 == 1/a0**3 * 1/(sqrt(s)+b0/a0)**3 + a_ = poles[0][b]/poles[0][a] + k_ = 1/poles[0][a]**3*constants + if a_.is_positive: + result = ( + k_*(2/sqrt(pi)*(a_**2*t+1)*sqrt(t) - + a_*t*exp(a_**2*t)*(2*a_**2*t+3)*erfc(a_*sqrt(t)))) + _debug(' rule 5.3.13') + elif poles[0][n] == -4 and poles[0][m] == S.Half: + # 1/(a0*sqrt(s)+b0)**4 == 1/a0**4 * 1/(sqrt(s)+b0/a0)**4 + a_ = poles[0][b]/poles[0][a] + k_ = 1/poles[0][a]**4*constants/3 + if a_.is_positive: + result = ( + k_*(t*(4*a_**4*t**2+12*a_**2*t+3)*exp(a_**2*t) * + erfc(a_*sqrt(t)) - + 2/sqrt(pi)*a_**3*t**(S(5)/2)*(2*a_**2*t+5))) + _debug(' rule 5.3.16') + elif poles[0][n] == -S.Half and poles[0][m] == 2: + # 1/sqrt(a0*s**2+b0) == 1/sqrt(a0) * 1/sqrt(s**2+b0/a0) + a_ = sqrt(poles[0][b]/poles[0][a]) + k_ = 1/sqrt(poles[0][a])*constants + result = (k_*(besselj(0, a_*t))) + _debug(' rule 5.3.35/44') + + elif len(poles) == 1 and len(zeros) == 1: + if ( + poles[0][n] == -3 and poles[0][m] == S.Half and + zeros[0][n] == S.Half and zeros[0][b] == 0): + # sqrt(az*s)/(ap*sqrt(s+bp)**3) + # == sqrt(az)/ap * sqrt(s)/(sqrt(s+bp)**3) + a_ = poles[0][b] + k_ = sqrt(zeros[0][a])/poles[0][a]*constants + result = ( + k_*(2*a_**4*t**2+5*a_**2*t+1)*exp(a_**2*t) * + erfc(a_*sqrt(t)) - 2/sqrt(pi)*a_*(a_**2*t+2)*sqrt(t)) + _debug(' rule 5.3.14') + if ( + poles[0][n] == -1 and poles[0][m] == 1 and + zeros[0][n] == S.Half and zeros[0][m] == 1): + # sqrt(az*s+bz)/(ap*s+bp) + # == sqrt(az)/ap * (sqrt(s+bz/az)/(s+bp/ap)) + a_ = zeros[0][b]/zeros[0][a] + b_ = poles[0][b]/poles[0][a] + k_ = sqrt(zeros[0][a])/poles[0][a]*constants + result = ( + k_*(exp(-a_*t)/sqrt(t)/sqrt(pi)+sqrt(a_-b_) * + exp(-b_*t)*erf(sqrt(a_-b_)*sqrt(t)))) + _debug(' rule 5.3.22') + + elif len(poles) == 2 and len(zeros) == 0: + if ( + poles[0][n] == -1 and poles[0][m] == 1 and + poles[1][n] == -S.Half and poles[1][m] == 1 and + poles[1][b] == 0): + # 1/((a0*s+b0)*sqrt(a1*s)) + # == 1/(a0*sqrt(a1)) * 1/((s+b0/a0)*sqrt(s)) + a_ = -poles[0][b]/poles[0][a] + k_ = 1/sqrt(poles[1][a])/poles[0][a]*constants + if a_.is_positive: + result = (k_/sqrt(a_)*exp(a_*t)*erf(sqrt(a_)*sqrt(t))) + _debug(' rule 5.3.1') + elif ( + poles[0][n] == -1 and poles[0][m] == 1 and poles[0][b] == 0 and + poles[1][n] == -1 and poles[1][m] == S.Half): + # 1/(a0*s*(a1*sqrt(s)+b1)) + # == 1/(a0*a1) * 1/(s*(sqrt(s)+b1/a1)) + a_ = poles[1][b]/poles[1][a] + k_ = 1/poles[0][a]/poles[1][a]/a_*constants + if a_.is_positive: + result = k_*(1-exp(a_**2*t)*erfc(a_*sqrt(t))) + _debug(' rule 5.3.5') + elif ( + poles[0][n] == -1 and poles[0][m] == S.Half and + poles[1][n] == -S.Half and poles[1][m] == 1 and + poles[1][b] == 0): + # 1/((a0*sqrt(s)+b0)*(sqrt(a1*s)) + # == 1/(a0*sqrt(a1)) * 1/((sqrt(s)+b0/a0)"sqrt(s)) + a_ = poles[0][b]/poles[0][a] + k_ = 1/(poles[0][a]*sqrt(poles[1][a]))*constants + if a_.is_positive: + result = k_*exp(a_**2*t)*erfc(a_*sqrt(t)) + _debug(' rule 5.3.7') + elif ( + poles[0][n] == -S(3)/2 and poles[0][m] == 1 and + poles[0][b] == 0 and poles[1][n] == -1 and + poles[1][m] == S.Half): + # 1/((a0**(3/2)*s**(3/2))*(a1*sqrt(s)+b1)) + # == 1/(a0**(3/2)*a1) 1/((s**(3/2))*(sqrt(s)+b1/a1)) + # Note that Bateman54 5.3 (8) is incorrect; there (sqrt(p)+a) + # should be (sqrt(p)+a)**(-1). + a_ = poles[1][b]/poles[1][a] + k_ = 1/(poles[0][a]**(S(3)/2)*poles[1][a])/a_**2*constants + if a_.is_positive: + result = ( + k_*(2/sqrt(pi)*a_*sqrt(t)+exp(a_**2*t)*erfc(a_*sqrt(t))-1)) + _debug(' rule 5.3.8') + elif ( + poles[0][n] == -2 and poles[0][m] == S.Half and + poles[1][n] == -1 and poles[1][m] == 1 and + poles[1][b] == 0): + # 1/((a0*sqrt(s)+b0)**2*a1*s) + # == 1/a0**2/a1 * 1/(sqrt(s)+b0/a0)**2/s + a_sq = poles[0][b]/poles[0][a] + a_ = a_sq**2 + k_ = 1/poles[0][a]**2/poles[1][a]*constants + if a_sq.is_positive: + result = ( + k_*(1/a_ + (2*t-1/a_)*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) - + 2/sqrt(pi)/sqrt(a_)*sqrt(t))) + _debug(' rule 5.3.11') + elif ( + poles[0][n] == -2 and poles[0][m] == S.Half and + poles[1][n] == -S.Half and poles[1][m] == 1 and + poles[1][b] == 0): + # 1/((a0*sqrt(s)+b0)**2*sqrt(a1*s)) + # == 1/a0**2/sqrt(a1) * 1/(sqrt(s)+b0/a0)**2/sqrt(s) + a_ = poles[0][b]/poles[0][a] + k_ = 1/poles[0][a]**2/sqrt(poles[1][a])*constants + if a_.is_positive: + result = ( + k_*(2/sqrt(pi)*sqrt(t) - + 2*a_*t*exp(a_**2*t)*erfc(a_*sqrt(t)))) + _debug(' rule 5.3.12') + elif ( + poles[0][n] == -3 and poles[0][m] == S.Half and + poles[1][n] == -S.Half and poles[1][m] == 1 and + poles[1][b] == 0): + # 1 / (sqrt(a1*s)*(a0*sqrt(s+b0)**3)) + # == 1/(sqrt(a1)*a0) * 1/(sqrt(s)*(sqrt(s+b0)**3)) + a_ = poles[0][b] + k_ = constants/sqrt(poles[1][a])/poles[0][a] + result = k_*( + (2*a_**2*t+1)*t*exp(a_**2*t)*erfc(a_*sqrt(t)) - + 2/sqrt(pi)*a_*t**(S(3)/2)) + _debug(' rule 5.3.15') + elif ( + poles[0][n] == -1 and poles[0][m] == 1 and + poles[1][n] == -S.Half and poles[1][m] == 1): + # 1 / ( (a0*s+b0)* sqrt(a1*s+b1) ) + # == 1/(sqrt(a1)*a0) * 1 / ( (s+b0/a0)* sqrt(s+b1/a1) ) + a_ = poles[0][b]/poles[0][a] + b_ = poles[1][b]/poles[1][a] + k_ = constants/sqrt(poles[1][a])/poles[0][a] + result = k_*( + 1/sqrt(b_-a_)*exp(-a_*t)*erf(sqrt(b_-a_)*sqrt(t))) + _debug(' rule 5.3.23') + + elif len(poles) == 2 and len(zeros) == 1: + if ( + poles[0][n] == -1 and poles[0][m] == 1 and + poles[1][n] == -1 and poles[1][m] == S.Half and + zeros[0][n] == S.Half and zeros[0][m] == 1 and + zeros[0][b] == 0): + # sqrt(za0*s)/((a0*s+b0)*(a1*sqrt(s)+b1)) + # == sqrt(za0)/(a0*a1) * s/((s+b0/a0)*(sqrt(s)+b1/a1)) + a_sq = poles[1][b]/poles[1][a] + a_ = a_sq**2 + b_ = -poles[0][b]/poles[0][a] + k_ = sqrt(zeros[0][a])/poles[0][a]/poles[1][a]/(a_-b_)*constants + if a_sq.is_positive and b_.is_positive: + result = k_*( + a_*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) + + sqrt(a_)*sqrt(b_)*exp(b_*t)*erfc(sqrt(b_)*sqrt(t)) - + b_*exp(b_*t)) + _debug(' rule 5.3.6') + elif ( + poles[0][n] == -1 and poles[0][m] == 1 and + poles[0][b] == 0 and poles[1][n] == -1 and + poles[1][m] == S.Half and zeros[0][n] == 1 and + zeros[0][m] == S.Half): + # (az*sqrt(s)+bz)/(a0*s*(a1*sqrt(s)+b1)) + # == az/a0/a1 * (sqrt(z)+bz/az)/(s*(sqrt(s)+b1/a1)) + a_num = zeros[0][b]/zeros[0][a] + a_ = poles[1][b]/poles[1][a] + if a_+a_num == 0: + k_ = zeros[0][a]/poles[0][a]/poles[1][a]*constants + result = k_*( + 2*exp(a_**2*t)*erfc(a_*sqrt(t))-1) + _debug(' rule 5.3.17') + elif ( + poles[1][n] == -1 and poles[1][m] == 1 and + poles[1][b] == 0 and poles[0][n] == -2 and + poles[0][m] == S.Half and zeros[0][n] == 2 and + zeros[0][m] == S.Half): + # (az*sqrt(s)+bz)**2/(a1*s*(a0*sqrt(s)+b0)**2) + # == az**2/a1/a0**2 * (sqrt(z)+bz/az)**2/(s*(sqrt(s)+b0/a0)**2) + a_num = zeros[0][b]/zeros[0][a] + a_ = poles[0][b]/poles[0][a] + if a_+a_num == 0: + k_ = zeros[0][a]**2/poles[1][a]/poles[0][a]**2*constants + result = k_*( + 1 + 8*a_**2*t*exp(a_**2*t)*erfc(a_*sqrt(t)) - + 8/sqrt(pi)*a_*sqrt(t)) + _debug(' rule 5.3.18') + elif ( + poles[1][n] == -1 and poles[1][m] == 1 and + poles[1][b] == 0 and poles[0][n] == -3 and + poles[0][m] == S.Half and zeros[0][n] == 3 and + zeros[0][m] == S.Half): + # (az*sqrt(s)+bz)**3/(a1*s*(a0*sqrt(s)+b0)**3) + # == az**3/a1/a0**3 * (sqrt(z)+bz/az)**3/(s*(sqrt(s)+b0/a0)**3) + a_num = zeros[0][b]/zeros[0][a] + a_ = poles[0][b]/poles[0][a] + if a_+a_num == 0: + k_ = zeros[0][a]**3/poles[1][a]/poles[0][a]**3*constants + result = k_*( + 2*(8*a_**4*t**2+8*a_**2*t+1)*exp(a_**2*t) * + erfc(a_*sqrt(t))-8/sqrt(pi)*a_*sqrt(t)*(2*a_**2*t+1)-1) + _debug(' rule 5.3.19') + + elif len(poles) == 3 and len(zeros) == 0: + if ( + poles[0][n] == -1 and poles[0][b] == 0 and poles[0][m] == 1 and + poles[1][n] == -1 and poles[1][m] == 1 and + poles[2][n] == -S.Half and poles[2][m] == 1): + # 1/((a0*s)*(a1*s+b1)*sqrt(a2*s)) + # == 1/(a0*a1*sqrt(a2)) * 1/((s)*(s+b1/a1)*sqrt(s)) + a_ = -poles[1][b]/poles[1][a] + k_ = 1/poles[0][a]/poles[1][a]/sqrt(poles[2][a])*constants + if a_.is_positive: + result = k_ * ( + a_**(-S(3)/2) * exp(a_*t) * erf(sqrt(a_)*sqrt(t)) - + 2/a_/sqrt(pi)*sqrt(t)) + _debug(' rule 5.3.2') + elif ( + poles[0][n] == -1 and poles[0][m] == 1 and + poles[1][n] == -1 and poles[1][m] == S.Half and + poles[2][n] == -S.Half and poles[2][m] == 1 and + poles[2][b] == 0): + # 1/((a0*s+b0)*(a1*sqrt(s)+b1)*(sqrt(a2)*sqrt(s))) + # == 1/(a0*a1*sqrt(a2)) * 1/((s+b0/a0)*(sqrt(s)+b1/a1)*sqrt(s)) + a_sq = poles[1][b]/poles[1][a] + a_ = a_sq**2 + b_ = -poles[0][b]/poles[0][a] + k_ = ( + 1/poles[0][a]/poles[1][a]/sqrt(poles[2][a]) / + (sqrt(b_)*(a_-b_))) + if a_sq.is_positive and b_.is_positive: + result = k_ * ( + sqrt(b_)*exp(a_*t)*erfc(sqrt(a_)*sqrt(t)) + + sqrt(a_)*exp(b_*t)*erf(sqrt(b_)*sqrt(t)) - + sqrt(b_)*exp(b_*t)) + _debug(' rule 5.3.9') + + if result is None: + return None + else: + return Heaviside(t)*result, condition + + +@DEBUG_WRAP +def _inverse_laplace_early_prog_rules(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + prog_rules = [_inverse_laplace_irrational] + + for p_rule in prog_rules: + if (r := p_rule(F, s, t, plane)) is not None: + return r + return None + + +@DEBUG_WRAP +def _inverse_laplace_apply_prog_rules(F, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + prog_rules = [_inverse_laplace_time_shift, _inverse_laplace_freq_shift, + _inverse_laplace_time_diff, _inverse_laplace_diff, + _inverse_laplace_irrational] + + for p_rule in prog_rules: + if (r := p_rule(F, s, t, plane)) is not None: + return r + return None + + +@DEBUG_WRAP +def _inverse_laplace_expand(fn, s, t, plane): + """ + Helper function for the class InverseLaplaceTransform. + """ + if fn.is_Add: + return None + r = expand(fn, deep=False) + if r.is_Add: + return _inverse_laplace_transform( + r, s, t, plane, simplify=False, dorational=True) + r = expand_mul(fn) + if r.is_Add: + return _inverse_laplace_transform( + r, s, t, plane, simplify=False, dorational=True) + r = expand(fn) + if r.is_Add: + return _inverse_laplace_transform( + r, s, t, plane, simplify=False, dorational=True) + if fn.is_rational_function(s): + r = fn.apart(s).doit() + if r.is_Add: + return _inverse_laplace_transform( + r, s, t, plane, simplify=False, dorational=True) + return None + + +@DEBUG_WRAP +def _inverse_laplace_rational(fn, s, t, plane, *, simplify): + """ + Helper function for the class InverseLaplaceTransform. + """ + x_ = symbols('x_') + f = fn.apart(s) + terms = Add.make_args(f) + terms_t = [] + conditions = [S.true] + for term in terms: + [n, d] = term.as_numer_denom() + dc = d.as_poly(s).all_coeffs() + dc_lead = dc[0] + dc = [x/dc_lead for x in dc] + nc = [x/dc_lead for x in n.as_poly(s).all_coeffs()] + if len(dc) == 1: + N = len(nc)-1 + for c in enumerate(nc): + r = c[1]*DiracDelta(t, N-c[0]) + terms_t.append(r) + elif len(dc) == 2: + r = nc[0]*exp(-dc[1]*t) + terms_t.append(Heaviside(t)*r) + elif len(dc) == 3: + a = dc[1]/2 + b = (dc[2]-a**2).factor() + if len(nc) == 1: + nc = [S.Zero] + nc + l, m = tuple(nc) + if b == 0: + r = (m*t+l*(1-a*t))*exp(-a*t) + else: + hyp = False + if b.is_negative: + b = -b + hyp = True + b2 = list(roots(x_**2-b, x_).keys())[0] + bs = sqrt(b).simplify() + if hyp: + r = ( + l*exp(-a*t)*cosh(b2*t) + (m-a*l) / + bs*exp(-a*t)*sinh(bs*t)) + else: + r = l*exp(-a*t)*cos(b2*t) + (m-a*l)/bs*exp(-a*t)*sin(bs*t) + terms_t.append(Heaviside(t)*r) + else: + ft, cond = _inverse_laplace_transform( + term, s, t, plane, simplify=simplify, dorational=False) + terms_t.append(ft) + conditions.append(cond) + + result = Add(*terms_t) + if simplify: + result = result.simplify(doit=False) + return result, And(*conditions) + + +@DEBUG_WRAP +def _inverse_laplace_transform(fn, s_, t_, plane, *, simplify, dorational): + """ + Front-end function of the inverse Laplace transform. It tries to apply all + known rules recursively. If everything else fails, it tries to integrate. + """ + terms = Add.make_args(fn) + terms_t = [] + conditions = [] + + for term in terms: + if term.has(exp): + # Simplify expressions with exp() such that time-shifted + # expressions have negative exponents in the numerator instead of + # positive exponents in the numerator and denominator; this is a + # (necessary) trick. It will, for example, convert + # (s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1)) into + # (s**2 + 4*exp(-s) - 4*exp(-2*s))/(s*(s**2 + 1)) + term = term.subs(s_, -s_).together().subs(s_, -s_) + k, f = term.as_independent(s_, as_Add=False) + if ( + dorational and term.is_rational_function(s_) and + (r := _inverse_laplace_rational( + f, s_, t_, plane, simplify=simplify)) + is not None or + (r := _inverse_laplace_apply_simple_rules(f, s_, t_)) + is not None or + (r := _inverse_laplace_early_prog_rules(f, s_, t_, plane)) + is not None or + (r := _inverse_laplace_expand(f, s_, t_, plane)) + is not None or + (r := _inverse_laplace_apply_prog_rules(f, s_, t_, plane)) + is not None): + pass + elif any(undef.has(s_) for undef in f.atoms(AppliedUndef)): + # If there are undefined functions f(t) then integration is + # unlikely to do anything useful so we skip it and given an + # unevaluated LaplaceTransform. + r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) + elif ( + r := _inverse_laplace_transform_integration( + f, s_, t_, plane, simplify=simplify)) is not None: + pass + else: + r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) + (ri_, ci_) = r + terms_t.append(k*ri_) + conditions.append(ci_) + + result = Add(*terms_t) + if simplify: + result = result.simplify(doit=False) + condition = And(*conditions) + + return result, condition + + +class InverseLaplaceTransform(IntegralTransform): + """ + Class representing unevaluated inverse Laplace transforms. + + For usage of this class, see the :class:`IntegralTransform` docstring. + + For how to compute inverse Laplace transforms, see the + :func:`inverse_laplace_transform` docstring. + """ + + _name = 'Inverse Laplace' + _none_sentinel = Dummy('None') + _c = Dummy('c') + + def __new__(cls, F, s, x, plane, **opts): + if plane is None: + plane = InverseLaplaceTransform._none_sentinel + return IntegralTransform.__new__(cls, F, s, x, plane, **opts) + + @property + def fundamental_plane(self): + plane = self.args[3] + if plane is InverseLaplaceTransform._none_sentinel: + plane = None + return plane + + def _compute_transform(self, F, s, t, **hints): + return _inverse_laplace_transform_integration( + F, s, t, self.fundamental_plane, **hints) + + def _as_integral(self, F, s, t): + c = self.__class__._c + return ( + Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity, + c + S.ImaginaryUnit*S.Infinity)) / + (2*S.Pi*S.ImaginaryUnit)) + + def doit(self, **hints): + """ + Try to evaluate the transform in closed form. + + Explanation + =========== + + Standard hints are the following: + - ``noconds``: if True, do not return convergence conditions. The + default setting is `True`. + - ``simplify``: if True, it simplifies the final result. The + default setting is `False`. + """ + _noconds = hints.get('noconds', True) + _simplify = hints.get('simplify', False) + + debugf('[ILT doit] (%s, %s, %s)', (self.function, + self.function_variable, + self.transform_variable)) + + s_ = self.function_variable + t_ = self.transform_variable + fn = self.function + plane = self.fundamental_plane + + r = _inverse_laplace_transform( + fn, s_, t_, plane, simplify=_simplify, dorational=True) + + if _noconds: + return r[0] + else: + return r + + +def inverse_laplace_transform(F, s, t, plane=None, **hints): + r""" + Compute the inverse Laplace transform of `F(s)`, defined as + + .. math :: + f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} + F(s) \mathrm{d}s, + + for `c` so large that `F(s)` has no singularites in the + half-plane `\operatorname{Re}(s) > c-\epsilon`. + + Explanation + =========== + + The plane can be specified by + argument ``plane``, but will be inferred if passed as None. + + Under certain regularity conditions, this recovers `f(t)` from its + Laplace Transform `F(s)`, for non-negative `t`, and vice + versa. + + If the integral cannot be computed in closed form, this function returns + an unevaluated :class:`InverseLaplaceTransform` object. + + Note that this function will always assume `t` to be real, + regardless of the SymPy assumption on `t`. + + For a description of possible hints, refer to the docstring of + :func:`sympy.integrals.transforms.IntegralTransform.doit`. + + Examples + ======== + + >>> from sympy import inverse_laplace_transform, exp, Symbol + >>> from sympy.abc import s, t + >>> a = Symbol('a', positive=True) + >>> inverse_laplace_transform(exp(-a*s)/s, s, t) + Heaviside(-a + t) + + See Also + ======== + + laplace_transform + hankel_transform, inverse_hankel_transform + """ + _noconds = hints.get('noconds', True) + _simplify = hints.get('simplify', False) + + if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'): + return F.applyfunc( + lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)) + + r, c = InverseLaplaceTransform(F, s, t, plane).doit( + noconds=False, simplify=_simplify) + + if _noconds: + return r + else: + return r, c + + +def _fast_inverse_laplace(e, s, t): + """Fast inverse Laplace transform of rational function including RootSum""" + a, b, n = symbols('a, b, n', cls=Wild, exclude=[s]) + + def _ilt(e): + if not e.has(s): + return e + elif e.is_Add: + return _ilt_add(e) + elif e.is_Mul: + return _ilt_mul(e) + elif e.is_Pow: + return _ilt_pow(e) + elif isinstance(e, RootSum): + return _ilt_rootsum(e) + else: + raise NotImplementedError + + def _ilt_add(e): + return e.func(*map(_ilt, e.args)) + + def _ilt_mul(e): + coeff, expr = e.as_independent(s) + if expr.is_Mul: + raise NotImplementedError + return coeff * _ilt(expr) + + def _ilt_pow(e): + match = e.match((a*s + b)**n) + if match is not None: + nm, am, bm = match[n], match[a], match[b] + if nm.is_Integer and nm < 0: + return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm)) + if nm == 1: + return exp(-(bm/am)*t) / am + raise NotImplementedError + + def _ilt_rootsum(e): + expr = e.fun.expr + [variable] = e.fun.variables + return RootSum(e.poly, Lambda(variable, together(_ilt(expr)))) + + return _ilt(e) diff --git a/shared/package-files/cb/cb9398c2738482a710fe8b50ac9acbd7b3e6bd53efc83cb2a9b85742c57ef9c9/test_jscode.cpython-311.pyc b/shared/package-files/cb/cb9398c2738482a710fe8b50ac9acbd7b3e6bd53efc83cb2a9b85742c57ef9c9/test_jscode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbbf5fc7970b091e598d642fd06cbfede4fb4d13 Binary files /dev/null and b/shared/package-files/cb/cb9398c2738482a710fe8b50ac9acbd7b3e6bd53efc83cb2a9b85742c57ef9c9/test_jscode.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb93f6ec10b193cd883d354ece8bf8f8e8ebdffb7290838694b952130584bffc/rpc_agent_test_fixture.py b/shared/package-files/cb/cb93f6ec10b193cd883d354ece8bf8f8e8ebdffb7290838694b952130584bffc/rpc_agent_test_fixture.py new file mode 100644 index 0000000000000000000000000000000000000000..3a684b73d2f315a00465371fad3050a795251ddb --- /dev/null +++ b/shared/package-files/cb/cb93f6ec10b193cd883d354ece8bf8f8e8ebdffb7290838694b952130584bffc/rpc_agent_test_fixture.py @@ -0,0 +1,63 @@ +# mypy: allow-untyped-defs + +import os +from abc import ABC, abstractmethod + +import torch.testing._internal.dist_utils + + +class RpcAgentTestFixture(ABC): + @property + def world_size(self) -> int: + return 4 + + @property + def init_method(self): + use_tcp_init = os.environ.get("RPC_INIT_WITH_TCP", None) + if use_tcp_init == "1": + master_addr = os.environ["MASTER_ADDR"] + master_port = os.environ["MASTER_PORT"] + return f"tcp://{master_addr}:{master_port}" + else: + return self.file_init_method + + @property + def file_init_method(self): + return torch.testing._internal.dist_utils.INIT_METHOD_TEMPLATE.format( + file_name=self.file_name + ) + + @property + @abstractmethod + def rpc_backend(self): + pass + + @property + @abstractmethod + def rpc_backend_options(self): + pass + + def setup_fault_injection(self, faulty_messages, messages_to_delay): # noqa: B027 + """Method used by dist_init to prepare the faulty agent. + + Does nothing for other agents. + """ + + # Shutdown sequence is not well defined, so we may see any of the following + # errors when running tests that simulate errors via a shutdown on the + # remote end. + @abstractmethod + def get_shutdown_error_regex(self): + """ + Return various error message we may see from RPC agents while running + tests that check for failures. This function is used to match against + possible errors to ensure failures were raised properly. + """ + + @abstractmethod + def get_timeout_error_regex(self): + """ + Returns a partial string indicating the error we should receive when an + RPC has timed out. Useful for use with assertRaisesRegex() to ensure we + have the right errors during timeout. + """ diff --git a/shared/package-files/cb/cb997d015658815f4f771b60b8d0b05a4e012a8b3ac70dea681c19e2d05671ce/variadic.cpython-311.pyc b/shared/package-files/cb/cb997d015658815f4f771b60b8d0b05a4e012a8b3ac70dea681c19e2d05671ce/variadic.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..476df49b3393a2653d1c59e45bc44cf3f78ba019 Binary files /dev/null and b/shared/package-files/cb/cb997d015658815f4f771b60b8d0b05a4e012a8b3ac70dea681c19e2d05671ce/variadic.cpython-311.pyc differ diff --git a/shared/package-files/cb/cb9cc6c5b1735f5cc5b87e1ee4b5cec92eb48642909df20ae7de810a88ebde53/vcfconvert.c.pysam.c b/shared/package-files/cb/cb9cc6c5b1735f5cc5b87e1ee4b5cec92eb48642909df20ae7de810a88ebde53/vcfconvert.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..f8921bf6381625f4bc2ed5012da66fc707eec5fe --- /dev/null +++ b/shared/package-files/cb/cb9cc6c5b1735f5cc5b87e1ee4b5cec92eb48642909df20ae7de810a88ebde53/vcfconvert.c.pysam.c @@ -0,0 +1,1813 @@ +#include "bcftools.pysam.h" + +/* vcfconvert.c -- convert between VCF/BCF and related formats. + + Copyright (C) 2013-2023 Genome Research Ltd. + + Author: Petr Danecek + +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. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "bcftools.h" +#include "filter.h" +#include "convert.h" +#include "tsv2vcf.h" + +// Logic of the filters: include or exclude sites which match the filters? +#define FLT_INCLUDE 1 +#define FLT_EXCLUDE 2 + +typedef struct _args_t args_t; +struct _args_t +{ + faidx_t *ref; + filter_t *filter; + char *filter_str; + int filter_logic; // include or exclude sites which match the filters? One of FLT_INCLUDE/FLT_EXCLUDE + convert_t *convert; + bcf_srs_t *files; + bcf_hdr_t *header; + void (*convert_func)(struct _args_t *); + struct { + int total, skipped, hom_rr, het_ra, hom_aa, het_aa, missing, written; + } n; + kstring_t str; + int32_t *gts; + float *flt; + int rev_als, output_vcf_ids, hap2dip, gen_3N6; + int nsamples, *samples, sample_is_file, targets_is_file, regions_is_file, output_type; + int regions_overlap, targets_overlap; + char **argv, *sample_list, *targets_list, *regions_list, *tag, *columns; + char *outfname, *infname, *ref_fname, *sex_fname; + int argc, n_threads, record_cmd_line, keep_duplicates, clevel; + char *index_fn; + int write_index; + struct { + kstring_t ref,alt,refalt; + } tsv; +}; + +static void destroy_data(args_t *args) +{ + if ( args->ref ) fai_destroy(args->ref); + if ( args->convert) convert_destroy(args->convert); + if ( args->filter ) filter_destroy(args->filter); + free(args->samples); + if ( args->files ) bcf_sr_destroy(args->files); +} + +static void open_vcf(args_t *args, const char *format_str) +{ + args->files = bcf_sr_init(); + if ( args->n_threads && bcf_sr_set_threads(args->files, args->n_threads)!=0 ) + error("Could not initialize --threads %d\n", args->n_threads); + + if ( args->regions_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap); + if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 ) + error("Failed to read the regions: %s\n", args->regions_list); + } + if ( args->targets_list ) + { + bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,args->targets_overlap); + if ( bcf_sr_set_targets(args->files, args->targets_list, args->targets_is_file, 0)<0 ) + error("Failed to read the targets: %s\n", args->targets_list); + } + if ( !bcf_sr_add_reader(args->files, args->infname) ) + error("Failed to open %s: %s\n", args->infname,bcf_sr_strerror(args->files->errnum)); + + args->header = args->files->readers[0].header; + + if ( args->filter_str ) + args->filter = filter_init(args->header, args->filter_str); + + int i, nsamples = 0, *samples = NULL; + if ( args->sample_list && strcmp("-",args->sample_list) ) + { + for (i=0; ifiles->nreaders; i++) + { + int ret = bcf_hdr_set_samples(args->files->readers[i].header,args->sample_list,args->sample_is_file); + if ( ret<0 ) error("Error parsing the sample list\n"); + else if ( ret>0 ) error("Sample name mismatch: sample #%d not found in the header\n", ret); + } + + if ( args->sample_list[0]!='^' ) + { + // the sample ordering may be different if not negated + int n; + char **smpls = hts_readlist(args->sample_list, args->sample_is_file, &n); + if ( !smpls ) error("Could not parse %s\n", args->sample_list); + if ( n!=bcf_hdr_nsamples(args->files->readers[0].header) ) + error("The number of samples does not match, perhaps some are present multiple times?\n"); + nsamples = bcf_hdr_nsamples(args->files->readers[0].header); + samples = (int*) malloc(sizeof(int)*nsamples); + for (i=0; ifiles->readers[0].header, BCF_DT_SAMPLE,smpls[i]); + free(smpls[i]); + } + free(smpls); + } + } + if ( format_str ) args->convert = convert_init(args->header, samples, nsamples, format_str); + free(samples); +} + +static int _set_ref_alt(args_t *args, bcf1_t *rec) +{ + args->tsv.refalt.l = 0; + kputs(args->tsv.ref.s, &args->tsv.refalt); + if ( strcmp(".",args->tsv.alt.s) && strcmp(args->tsv.ref.s,args->tsv.alt.s) ) + { + kputc(',', &args->tsv.refalt); + kputs(args->tsv.alt.s, &args->tsv.refalt); + } + bcf_update_alleles_str(args->header, rec, args->tsv.refalt.s); + args->tsv.ref.l = 0; + args->tsv.alt.l = 0; + args->tsv.refalt.l = 0; + return 0; +} +static int tsv_setter_ref(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.ref); + if ( args->tsv.alt.l ) return _set_ref_alt(args,rec); + return 0; +} +static int tsv_setter_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + kputsn(tsv->ss,tsv->se - tsv->ss,&args->tsv.alt); + if ( args->tsv.ref.l ) return _set_ref_alt(args,rec); + return 0; +} + +// Try to set CHROM:POS_REF_ALT[_END]. Return 0 on success, -1 on error +static int _set_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + + char tmp, *se = tsv->ss, *ss = tsv->ss; + while ( se < tsv->se && *se!=':' ) se++; + if ( *se!=':' ) return -1; + tmp = *se; *se = 0; + int rid = bcf_hdr_name2id(args->header,ss); + *se = tmp; + if ( rid<0 ) return -1; + + // POS + hts_pos_t pos = strtol(se+1,&ss,10); + if ( ss==se+1 ) return -1; + pos--; + + // REF,ALT + args->str.l = 0; + se = ++ss; + while ( se < tsv->se && *se!='_' ) se++; + if ( *se!='_' ) return -1; + kputsn(ss,se-ss,&args->str); + ss = ++se; + while ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) se++; + if ( se < tsv->se && *se!='_' && isspace(*tsv->se) ) return -1; + kputc(',',&args->str); + kputsn(ss,se-ss,&args->str); + + // END - optional + if (*se && *se=='_') + { + long end = strtol(se+1,&ss,10); + if ( ss==se+1 ) return -1; + if (end < 1 || end > INT32_MAX) + return -1; + int32_t e = end; // bcf_update_info_int32 needs an int32_t pointer + bcf_update_info_int32(args->header, rec, "END", &e, 1); + } + + rec->rid = rid; + rec->pos = pos; + bcf_update_alleles_str(args->header, rec, args->str.s); + + return 0; +} +static int tsv_setter_chrom_pos_ref_alt_or_chrom(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + int ret = _set_chrom_pos_ref_alt(tsv,rec,usr); + if ( !ret ) return ret; + return tsv_setter_chrom(tsv,rec,args->header); +} +static int tsv_setter_chrom_pos_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + int ret = _set_chrom_pos_ref_alt(tsv,rec,usr); + if ( ret!=0 ) error("Could not parse the CHROM:POS_REF_ALT[_END] string: %s\n", tsv->ss); + return ret; +} +// This function must be called first, then tsv_setter_chrom_pos_ref_alt_id_or_die. +// One of them is expected to find the CHROM:POS_REF_ALT[_END] string, if not, die. +static int tsv_setter_chrom_pos_ref_alt_or_id(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + if ( _set_chrom_pos_ref_alt(tsv,rec,usr)==0 ) return 0; + rec->pos = -1; // mark the record as unset + if ( !args->output_vcf_ids) return 0; + return tsv_setter_id(tsv,rec,usr); +} +static int tsv_setter_chrom_pos_ref_alt_id_or_die(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*)usr; + if ( rec->pos!=-1 ) + { + if ( !args->output_vcf_ids ) return 0; + return tsv_setter_id(tsv,rec,usr); + } + return tsv_setter_chrom_pos_ref_alt(tsv,rec,usr); +} +static int tsv_setter_verify_pos(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + char *se; + int pos = strtol(tsv->ss,&se,10); + if ( tsv->ss==se ) error("Could not parse POS: %s\n", tsv->ss); + if ( rec->pos != pos-1 ) error("POS mismatch: %s\n", tsv->ss); + return 0; +} +static int tsv_setter_verify_ref_alt(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + args->rev_als = 0; + char tmp = *tsv->se; *tsv->se = 0; + if ( strcmp(tsv->ss,rec->d.allele[0]) ) + { + if ( strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); } + args->rev_als = 1; + } + *tsv->se = tmp; + while ( *tsv->se && isspace(*tsv->se) ) tsv->se++; + tsv->ss = tsv->se; + while ( *tsv->se && !isspace(*tsv->se) ) tsv->se++; + tmp = *tsv->se; *tsv->se = 0; + if ( !args->rev_als && strcmp(tsv->ss,rec->d.allele[1]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[1]); } + else if ( args->rev_als && strcmp(tsv->ss,rec->d.allele[0]) ) { *tsv->se = tmp; error("REF/ALT mismatch: [%s][%s]\n", tsv->ss,rec->d.allele[0]); } + *tsv->se = tmp; + return 0; +} +static int tsv_setter_gt_gp(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + int i, nsamples = bcf_hdr_nsamples(args->header); + for (i=0; iss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(bcftools_stderr,"Could not parse first value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + ab = strtod(tsv->ss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(bcftools_stderr,"Could not parse second value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + bb = strtod(tsv->ss, &tsv->se); + if ( tsv->ss==tsv->se ) { fprintf(bcftools_stderr,"Could not parse third value of %d-th sample\n", i+1); return -1; } + tsv->ss = tsv->se+1; + + if ( args->rev_als ) { float tmp = bb; bb = aa; aa = tmp; } + args->flt[3*i+0] = aa; + args->flt[3*i+1] = ab; + args->flt[3*i+2] = bb; + + if ( aa >= ab ) + { + if ( aa >= bb ) args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(0); + else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1); + } + else if ( ab >= bb ) + { + args->gts[2*i+0] = bcf_gt_unphased(0); + args->gts[2*i+1] = bcf_gt_unphased(1); + } + else args->gts[2*i+0] = args->gts[2*i+1] = bcf_gt_unphased(1); + } + if ( *tsv->se ) error("Could not parse: %s\n", tsv->ss); + if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n"); + if ( bcf_update_format_float(args->header,rec,"GP",args->flt,nsamples*3) ) error("Could not update GP field\n"); + return 0; +} +static int tsv_setter_haps(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + int i, nsamples = bcf_hdr_nsamples(args->header); + + int32_t a0, a1; + if ( args->rev_als ) { a0 = bcf_gt_phased(1); a1 = bcf_gt_phased(0); } + else { a0 = bcf_gt_phased(0); a1 = bcf_gt_phased(1); } + + // up is short for "unphased" + int nup = 0; + for (i=0; iss + 4*i + nup; + int up = 0, all; + + for (all=0; all < 2; all++){ + // checking for premature ending + if ( !ss[0] || !ss[1] || !ss[2] || + (up && (!ss[3] || !ss[4]) ) ) + { + fprintf(bcftools_stderr,"Wrong number of fields at %d-th sample ([%c][%c][%c]). ",i+1,ss[0],ss[1],ss[2]); + return -1; + } + + switch(ss[all*2+up]){ + case '0': + args->gts[2*i+all] = a0; + break; + case '1' : + args->gts[2*i+all] = a1; + break; + case '?' : + // there is no macro to express phased missing allele + args->gts[2*i+all] = bcf_gt_phased(-1); + break; + case '-' : + args->gts[2*i+all] = bcf_int32_vector_end; + break; + default : + fprintf(bcftools_stderr,"Could not parse: [%c][%s]\n", ss[all*2+up],tsv->ss); + return -1; + } + if( ss[all*2+up+1]=='*' ) up = up + 1; + } + + if(up && up != 2) + { + fprintf(bcftools_stderr,"Missing unphased marker '*': [%c][%s]", ss[2+up], tsv->ss); + return -1; + } + + // change alleles to unphased if the alleles are unphased + if ( up ) + { + args->gts[2*i] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i])); + args->gts[2*i+1] = bcf_gt_unphased(bcf_gt_allele(args->gts[2*i+1])); + } + nup = nup + up; + } + if ( tsv->ss[(nsamples-1)*4+3+nup] ) + { + fprintf(bcftools_stderr,"nup: %d", nup); + fprintf(bcftools_stderr,"Wrong number of fields (%d-th column = [%c]). ", nsamples*2,tsv->ss[(nsamples-1)*4+nup]); + return -1; + } + + if ( bcf_update_genotypes(args->header,rec,args->gts,nsamples*2) ) error("Could not update GT field\n"); + return 0; +} +static void gensample_to_vcf(args_t *args) +{ + /* + * Inpute: IMPUTE2 output (indentation changed here for clarity): + * + * 20:62116619_C_T 20:62116619 62116619 C T 0.969 0.031 0 ... + * --- 20:62116698_C_A 62116698 C A 1 0 0 ... + * + * Second column is expected in the form of CHROM:POS_REF_ALT. We use second + * column because the first can be empty ("--") when filling sites from reference + * panel. When the option --vcf-ids is given, the first column is used to set the + * VCF ID. + * + * Output: VCF with filled GT,GP + * + */ + kstring_t line = {0,0,0}; + + char *gen_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.gen.gz", args->infname); + gen_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + } + else + { + *sample_fname = 0; + gen_fname = strdup(args->infname); + sample_fname = strdup(sample_fname+1); + } + htsFile *gen_fh = hts_open(gen_fname, "r"); + if ( !gen_fh ) error("Could not read: %s\n", gen_fname); + if ( hts_getline(gen_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", gen_fname); + + // Find out the chromosome name, depending on the format variant (--3N6 or plain) and the ordering + // of the columns (CHROM:POS_REF_ALT comes first or second) + args->str.l = 0; + char *sb = line.s, *se = line.s; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + if ( args->gen_3N6 ) // first column, just CHROM + kputsn(sb, se-sb, &args->str); + else // first or second column, part of CHROM:POS_REF_ALT + { + char *sc = strchr(sb,':'); + if ( !sc || sc > se ) + { + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + sb = ++se; + sc = strchr(sb,':'); + if ( !sc ) error("Could not determine CHROM in %s: %s\n", gen_fname,line.s); + } + kputsn(sb, sc-sb, &args->str); + } + + // Initialize and print the VCF header, args->str.s contains the chr name + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + tsv_t *tsv; + if ( args->gen_3N6 ) + { + tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP"); + tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header); + } + else + tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,GT_GP"); + tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt_or_id, args); + tsv_register(tsv, "ID", tsv_setter_chrom_pos_ref_alt_id_or_die, args); + tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_register(tsv, "GT_GP", tsv_setter_gt_gp, args); + + // Find out sample names + int i, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nsamples); + if ( !samples ) error("Could not read %s\n", sample_fname); + for (i=2; iheader,samples[i]); + } + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + bcf1_t *rec = bcf_init(); + + nsamples -= 2; + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + args->flt = (float *) malloc(sizeof(float)*nsamples*3); + + do + { + bcf_clear(rec); + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + else + error("Error occurred while parsing: %s\n", line.s); + } + while ( hts_getline(gen_fh, KS_SEP_LINE, &line)>0 ); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(gen_fh) ) error("Close failed: %s\n", gen_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(gen_fname); + free(args->str.s); + free(line.s); + free(args->gts); + free(args->flt); + tsv_destroy(tsv); + + fprintf(bcftools_stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +static void haplegendsample_to_vcf(args_t *args) +{ + /* + * Convert from IMPUTE2 hap/legend/sample output files to VCF + * + * hap: + * 0 1 0 1 + * legend: + * id position a0 a1 + * 1:186946386_G_T 186946386 G T + * sample: + * sample population group sex + * sample1 sample1 sample1 2 + * sample2 sample2 sample2 2 + * + * Output: VCF with filled GT + */ + kstring_t line = {0,0,0}; + + if ( args->output_vcf_ids ) + error( + "The option --haplegendsample2vcf cannot be combined with --vcf-ids. This is because the\n" + "ID column must be formatted as \"CHROM:POS_REF_ALT\" to check sanity of the operation\n"); + + char *hap_fname = NULL, *leg_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.hap.gz", args->infname); + hap_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.legend.gz", args->infname); + leg_fname = strdup(args->str.s); + } + else + { + char *ss = sample_fname, *se = strchr(ss+1,','); + if ( !se ) error("Could not parse hap/legend/sample file names: %s\n", args->infname); + *ss = 0; + *se = 0; + hap_fname = strdup(args->infname); + leg_fname = strdup(ss+1); + sample_fname = strdup(se+1); + } + htsFile *hap_fh = hts_open(hap_fname, "r"); + if ( !hap_fh ) error("Could not read: %s\n", hap_fname); + + htsFile *leg_fh = hts_open(leg_fname,"r"); + if ( !leg_fh ) error("Could not read: %s\n", leg_fname); + + // Eat up first legend line, then determine chromosome name + if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname); + if ( hts_getline(leg_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", leg_fname); + + // Find out the chromosome name, sample names, init and print the VCF header + args->str.l = 0; + char *se = strchr(line.s,':'); + if ( !se ) error("Expected CHROM:POS_REF_ALT in first column of %s\n", leg_fname); + kputsn(line.s, se-line.s, &args->str); + + tsv_t *leg_tsv = tsv_init("CHROM_POS_REF_ALT,POS,REF_ALT"); + tsv_register(leg_tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args); + tsv_register(leg_tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(leg_tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_t *hap_tsv = tsv_init("HAPS"); + tsv_register(hap_tsv, "HAPS", tsv_setter_haps, args); + + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + int i, nrows, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nrows); + if ( !samples ) error("Could not read %s\n", sample_fname); + nsamples = nrows - 1; + + // sample_fname should contain a header line, so need to ignore first row + // returned from hts_readlist (i=1, and not i=0) + for (i=1; iheader,samples[i]); + } + bcf_hdr_add_sample(args->header,NULL); + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + bcf1_t *rec = bcf_init(); + + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + + while (1) + { + bcf_clear(rec); + args->n.total++; + if ( tsv_parse(leg_tsv, rec, line.s) ) + error("Error occurred while parsing %s: %s\n", leg_fname,line.s); + + if ( hts_getline(hap_fh, KS_SEP_LINE, &line)<=0 ) + error("Different number of records in %s and %s?\n", leg_fname,hap_fname); + + if ( tsv_parse(hap_tsv, rec, line.s) ) + error("Error occurred while parsing %s: %s\n", hap_fname,line.s); + + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + + if ( hts_getline(leg_fh, KS_SEP_LINE, &line)<=0 ) + { + if ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 ) + error("Different number of records in %s and %s?\n", leg_fname,hap_fname); + break; + } + } + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname); + if ( hts_close(leg_fh) ) error("Close failed: %s\n", leg_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(hap_fname); + free(leg_fname); + free(args->str.s); + free(line.s); + free(args->gts); + tsv_destroy(hap_tsv); + tsv_destroy(leg_tsv); + + fprintf(bcftools_stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +static void hapsample_to_vcf(args_t *args) +{ + /* + * Input: SHAPEIT output + * + * 20:19995888_A_G rsid1 19995888 A G 0 0 0 0 ... + * 20 20:19995888_A_G 19995888 A G 0 0 0 0 ... + * + * First column is expected in the form of CHROM:POS_REF_ALT + * + * Output: VCF with filled GT + * + */ + kstring_t line = {0,0,0}; + + char *hap_fname = NULL, *sample_fname = NULL; + sample_fname = strchr(args->infname,','); + if ( !sample_fname ) + { + args->str.l = 0; + ksprintf(&args->str,"%s.hap.gz", args->infname); + hap_fname = strdup(args->str.s); + args->str.l = 0; + ksprintf(&args->str,"%s.samples", args->infname); + sample_fname = strdup(args->str.s); + } + else + { + *sample_fname = 0; + hap_fname = strdup(args->infname); + sample_fname = strdup(sample_fname+1); + } + htsFile *hap_fh = hts_open(hap_fname, "r"); + if ( !hap_fh ) error("Could not read: %s\n", hap_fname); + if ( hts_getline(hap_fh, KS_SEP_LINE, &line) <= 0 ) error("Empty file: %s\n", hap_fname); + + // Find out the chromosome name, it can be either in the first or second column + args->str.l = 0; + char *sb = line.s, *se = line.s; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + if ( !args->output_vcf_ids ) + { + // first column should be just CHROM, but the second must be CHROM:POS_REF_ALT, use that + sb = ++se; + while ( *se && !isspace(*se) ) se++; + if ( !*se ) error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + if ( !strchr(sb,':') ) + error("Could not determine CHROM in the second column of %s: %s\n", hap_fname,line.s); + } + // Parse CHROM:POS_REF_ALT + char *sc = strchr(sb,':'); + if ( !sc || sc > se ) + error("Could not determine CHROM in %s: %s\n", hap_fname,line.s); + kputsn(sb, sc-sb, &args->str); + + // Initialize and print the VCF header, args->str.s contains the chr name + args->header = bcf_hdr_init("w"); + bcf_hdr_append(args->header, "##INFO="); + bcf_hdr_append(args->header, "##FORMAT="); + bcf_hdr_printf(args->header, "##contig=", args->str.s,0x7fffffff); // MAX_CSI_COOR + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + tsv_t *tsv; + if ( args->output_vcf_ids ) + { + tsv = tsv_init("CHROM_POS_REF_ALT,ID,POS,REF_ALT,HAPS"); + tsv_register(tsv, "ID", tsv_setter_id, args); + } + else + { + tsv = tsv_init("CHROM,CHROM_POS_REF_ALT,POS,REF_ALT,HAPS"); + tsv_register(tsv, "CHROM", tsv_setter_chrom_pos_ref_alt_or_chrom, args); + } + tsv_register(tsv, "CHROM_POS_REF_ALT", tsv_setter_chrom_pos_ref_alt, args); + tsv_register(tsv, "POS", tsv_setter_verify_pos, NULL); + tsv_register(tsv, "REF_ALT", tsv_setter_verify_ref_alt, args); + tsv_register(tsv, "HAPS", tsv_setter_haps, args); + + int i, nsamples; + char **samples = hts_readlist(sample_fname, 1, &nsamples); + if ( !samples ) error("Could not read %s\n", sample_fname); + for (i=2; iheader,samples[i]); + } + bcf_hdr_add_sample(args->header,NULL); + for (i=0; ioutput_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + bcf1_t *rec = bcf_init(); + + nsamples -= 2; + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsamples*2); + + do + { + bcf_clear(rec); + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + else + error("Error occurred while parsing: %s\n", line.s); + } + while ( hts_getline(hap_fh, KS_SEP_LINE, &line)>0 ); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + if ( hts_close(hap_fh) ) error("Close failed: %s\n", hap_fname); + bcf_hdr_destroy(args->header); + bcf_destroy(rec); + free(sample_fname); + free(hap_fname); + free(args->str.s); + free(line.s); + free(args->gts); + tsv_destroy(tsv); + + fprintf(bcftools_stderr,"Number of processed rows: \t%d\n", args->n.total); +} + +char *init_sample2sex(bcf_hdr_t *hdr, char *sex_fname) +{ + int i, nlines; + char *sample2sex = (char*) calloc(bcf_hdr_nsamples(hdr),1); + char **lines = hts_readlist(sex_fname, 1, &nlines); + if ( !lines ) error("Could not read %s\n", sex_fname); + for (i=0; igen_3N6 ) + kputs("%CHROM ", &str); + + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str); + + // insert rsid as second column if needed + if ( args->output_vcf_ids ) + kputs("%ID ", &str); + else + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT ", &str); + + kputs("%POS %REF %FIRST_ALT", &str); + if ( !args->tag || !strcmp(args->tag,"GT") ) kputs("%_GT_TO_PROB3",&str); + else if ( !strcmp(args->tag,"PL") ) kputs("%_PL_TO_PROB3",&str); + else if ( !strcmp(args->tag,"GP") ) kputs("%_GP_TO_PROB3",&str); + else error("todo: --tag %s\n", args->tag); + kputs("\n", &str); + open_vcf(args,str.s); + + int ret, gen_compressed = 1, sample_compressed = 0; + char *gen_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".gen.gz",&str); + gen_fname = strdup(str.s); + } + else if ( n_files==2 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) gen_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]); + } + else + { + error("Error parsing --gensample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (gen_fname) fprintf(bcftools_stderr, "Gen file: %s\n", gen_fname); + if (sample_fname) fprintf(bcftools_stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + if ( sample2sex ) + ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]); + else + ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!gen_fname) { + if ( str.m ) free(str.s); + return; + } + + int prev_rid = -1, prev_pos = -1; + int no_alt = 0, non_biallelic = 0, filtered = 0, ndup = 0, nok = 0; + BGZF *gout = bgzf_open(gen_fname, gen_compressed ? "wg" : "wu"); + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(bcftools_stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + // skip duplicate lines, or otherwise shapeit complains + if ( !args->keep_duplicates && prev_rid==line->rid && prev_pos==line->pos ) { ndup++; continue; } + prev_rid = line->rid; + prev_pos = line->pos; + + str.l = 0; + convert_line(args->convert, line, &str); + if ( str.l ) + { + int ret = bgzf_write(gout, str.s, str.l); + if ( ret!= str.l ) error("Error writing %s: %s\n", gen_fname,strerror(errno)); + nok++; + } + } + fprintf(bcftools_stderr, "%d records written, %d skipped: %d/%d/%d/%d no-ALT/non-biallelic/filtered/duplicated\n", + nok, no_alt+non_biallelic+filtered+ndup, no_alt, non_biallelic, filtered, ndup); + + if ( str.m ) free(str.s); + if ( bgzf_close(gout)!=0 ) error("Error closing %s: %s\n", gen_fname,strerror(errno)); + free(gen_fname); +} + +static void vcf_to_haplegendsample(args_t *args) +{ + kstring_t str = {0,0,0}; + if ( args->hap2dip ) + kputs("%_GT_TO_HAP2\n", &str); + else + kputs("%_GT_TO_HAP\n", &str); + open_vcf(args,str.s); + + int ret, hap_compressed = 1, legend_compressed = 1, sample_compressed = 0; + char *hap_fname = NULL, *legend_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".legend.gz",&str); + legend_fname = strdup(str.s); + str.l = l; + kputs(".hap.gz",&str); + hap_fname = strdup(str.s); + } + else if ( n_files==3 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) legend_fname = strdup(files[1]); + if (strlen(files[2]) && strcmp(files[2],".")!=0) sample_fname = strdup(files[2]); + } + else + { + error("Error parsing --hapslegendsample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (hap_fname) fprintf(bcftools_stderr, "Hap file: %s\n", hap_fname); + if (legend_fname) fprintf(bcftools_stderr, "Legend file: %s\n", legend_fname); + if (sample_fname) fprintf(bcftools_stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs("sample population group sex\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + ksprintf(&str, "%s %s %s %c\n", args->header->samples[i], args->header->samples[i], args->header->samples[i], sample2sex ? sample2sex[i] : '2'); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!hap_fname && !legend_fname) { + if ( str.m ) free(str.s); + return; + } + + // open haps and legend outputs + BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL; + if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize); + BGZF *lout = legend_fname ? bgzf_open(legend_fname, legend_compressed ? "wg" : "wu") : NULL; + if (legend_fname) { + str.l = 0; + kputs("id position a0 a1\n", &str); + ret = bgzf_write(lout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno)); + } + + int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0; + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(bcftools_stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + str.l = 0; + convert_line(args->convert, line, &str); + if ( !str.l ) continue; + + // write haps file + if (hap_fname) { + ret = bgzf_write(hout, str.s, str.l); // write hap file + if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno)); + } + if (legend_fname) { + str.l = 0; + if ( args->output_vcf_ids && (line->d.id[0]!='.' || line->d.id[1]!=0) ) + ksprintf(&str, "%s %"PRId64" %s %s\n", line->d.id, (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]); + else + ksprintf(&str, "%s:%"PRId64"_%s_%s %"PRId64" %s %s\n", bcf_seqname(args->header, line), (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1], (int64_t) line->pos+1, line->d.allele[0], line->d.allele[1]); + + // write legend file + ret = bgzf_write(lout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", legend_fname, strerror(errno)); + } + nok++; + } + fprintf(bcftools_stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok,no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered); + if ( str.m ) free(str.s); + if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno)); + if ( lout && bgzf_close(lout)!=0 ) error("Error closing %s: %s\n", legend_fname, strerror(errno)); + if (hap_fname) free(hap_fname); + if (legend_fname) free(legend_fname); +} + +static void vcf_to_hapsample(args_t *args) +{ + /* + * WTCCC style haplotypes file + * see https://mathgen.stats.ox.ac.uk/genetics_software/shapeit/shapeit.html#hapsample + * + * These are essentially the haplotypes from the impute2 format with some + * legend info tacked on to the first 5 columns + * + */ + kstring_t str = {0,0,0}; + + // print ID instead of CHROM:POS_REF_ALT1 + if ( args->output_vcf_ids ) + kputs("%CHROM:%POS\\_%REF\\_%FIRST_ALT %ID %POS %REF %FIRST_ALT ", &str); + else + kputs("%CHROM %CHROM:%POS\\_%REF\\_%FIRST_ALT %POS %REF %FIRST_ALT ", &str); + + if ( args->hap2dip ) + kputs("%_GT_TO_HAP2\n", &str); + else + kputs("%_GT_TO_HAP\n", &str); + open_vcf(args,str.s); + + int ret, hap_compressed = 1, sample_compressed = 0; + char *hap_fname = NULL, *sample_fname = NULL; + str.l = 0; + kputs(args->outfname,&str); + int n_files = 0, i; + char **files = hts_readlist(str.s, 0, &n_files); + if ( n_files==1 ) + { + int l = str.l; + kputs(".samples",&str); + sample_fname = strdup(str.s); + str.l = l; + kputs(".hap.gz",&str); + hap_fname = strdup(str.s); + } + else if ( n_files==2 ) + { + if (strlen(files[0]) && strcmp(files[0],".")!=0) hap_fname = strdup(files[0]); + if (strlen(files[1]) && strcmp(files[1],".")!=0) sample_fname = strdup(files[1]); + } + else + { + error("Error parsing --hapsample filenames: %s\n", args->outfname); + } + for (i=0; i3 && strcasecmp(".gz",sample_fname+strlen(sample_fname)-3)==0 ) sample_compressed = 0; + + if (hap_fname) fprintf(bcftools_stderr, "Hap file: %s\n", hap_fname); + if (sample_fname) fprintf(bcftools_stderr, "Sample file: %s\n", sample_fname); + + // write samples file + if (sample_fname) + { + char *sample2sex = NULL; + if ( args->sex_fname ) sample2sex = init_sample2sex(args->header,args->sex_fname); + + int i; + BGZF *sout = bgzf_open(sample_fname, sample_compressed ? "wg" : "wu"); + str.l = 0; + kputs(sample2sex ? "ID_1 ID_2 missing sex\n0 0 0 0\n" : "ID_1 ID_2 missing\n0 0 0\n", &str); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + for (i=0; iheader); i++) + { + str.l = 0; + if ( sample2sex ) + ksprintf(&str, "%s %s 0 %c\n", args->header->samples[i],args->header->samples[i],sample2sex[i]); + else + ksprintf(&str, "%s %s 0\n", args->header->samples[i],args->header->samples[i]); + ret = bgzf_write(sout, str.s, str.l); + if ( ret != str.l ) error("Error writing %s: %s\n", sample_fname, strerror(errno)); + } + if ( bgzf_close(sout)!=0 ) error("Error closing %s: %s\n", sample_fname, strerror(errno)); + free(sample_fname); + free(sample2sex); + } + if (!hap_fname) { + if ( str.m ) free(str.s); + return; + } + + // open haps output + BGZF *hout = hap_fname ? bgzf_open(hap_fname, hap_compressed ? "wg" : "wu") : NULL; + if ( hap_compressed && args->n_threads ) bgzf_thread_pool(hout, args->files->p->pool, args->files->p->qsize); + + int no_alt = 0, non_biallelic = 0, filtered = 0, nok = 0; + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) { filtered++; continue; } + } + + // ALT allele is required + if ( line->n_allele<2 ) { no_alt++; continue; } + // biallelic required + if ( line->n_allele>2 ) { + if (!non_biallelic) + fprintf(bcftools_stderr, "Warning: non-biallelic records are skipped. Consider splitting multi-allelic records into biallelic records using 'bcftools norm -m-'.\n"); + non_biallelic++; + continue; + } + + str.l = 0; + convert_line(args->convert, line, &str); + if ( !str.l ) continue; + + // write haps file + if (hap_fname) { + ret = bgzf_write(hout, str.s, str.l); // write hap file + if ( ret != str.l ) error("Error writing %s: %s\n", hap_fname, strerror(errno)); + } + nok++; + } + fprintf(bcftools_stderr, "%d records written, %d skipped: %d/%d/%d no-ALT/non-biallelic/filtered\n", nok, no_alt+non_biallelic+filtered, no_alt, non_biallelic, filtered); + if ( str.m ) free(str.s); + if ( hout && bgzf_close(hout)!=0 ) error("Error closing %s: %s\n", hap_fname, strerror(errno)); + if (hap_fname) free(hap_fname); +} + +static void bcf_hdr_set_chrs(bcf_hdr_t *hdr, faidx_t *fai) +{ + int i, n = faidx_nseq(fai); + for (i=0; i", seq,len); + } +} +static inline int acgt_to_5(char base) +{ + if ( base=='A' ) return 0; + if ( base=='C' ) return 1; + if ( base=='G' ) return 2; + if ( base=='T' ) return 3; + return 4; +} +static inline int tsv_setter_aa1(args_t *args, char *ss, char *se, int alleles[], int *nals, int ref, int32_t *gts) +{ + if ( se - ss > 2 ) return -1; // currently only SNPs + + if ( ss[0]=='-' || ss[0]=='.' ) + { + // missing GT + gts[0] = bcf_gt_missing; + gts[1] = bcf_gt_missing; + args->n.missing++; + return 0; + } + if ( ss[0]=='I' ) return -2; // skip insertions/deletions for now + if ( ss[0]=='D' ) return -2; + + int a0 = acgt_to_5(toupper(ss[0])); + int a1 = ss[1] ? acgt_to_5(toupper(ss[1])) : a0; + if ( alleles[a0]<0 ) alleles[a0] = (*nals)++; + if ( alleles[a1]<0 ) alleles[a1] = (*nals)++; + + gts[0] = bcf_gt_unphased(alleles[a0]); + gts[1] = ss[1] ? bcf_gt_unphased(alleles[a1]) : bcf_int32_vector_end; + + if ( ref==a0 && ref==a1 ) args->n.hom_rr++; // hom ref: RR + else if ( ref==a0 ) args->n.het_ra++; // het: RA + else if ( ref==a1 ) args->n.het_ra++; // het: AR + else if ( a0==a1 ) args->n.hom_aa++; // hom-alt: AA + else args->n.het_aa++; // non-ref het: AA + + return 0; +} +static int tsv_setter_aa(tsv_t *tsv, bcf1_t *rec, void *usr) +{ + args_t *args = (args_t*) usr; + + int len; + char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(args->header,rec->rid), rec->pos, rec->pos, &len); + if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1); + + int nals = 1, alleles[5] = { -1, -1, -1, -1, -1 }; // a,c,g,t,n + ref[0] = toupper(ref[0]); + int iref = acgt_to_5(ref[0]); + alleles[iref] = 0; + + rec->n_sample = bcf_hdr_nsamples(args->header); + + int i, ret; + for (i=0; in_sample; i++) + { + if ( i>0 ) + { + ret = tsv_next(tsv); + if ( ret==-1 ) error("Too few columns for %d samples at %s:%"PRId64"\n", rec->n_sample,bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1); + } + ret = tsv_setter_aa1(args, tsv->ss, tsv->se, alleles, &nals, iref, args->gts+i*2); + if ( ret==-1 ) error("Error parsing the site %s:%"PRId64", expected two characters\n", bcf_hdr_id2name(args->header,rec->rid),(int64_t) rec->pos+1); + if ( ret==-2 ) + { + // something else than a SNP + free(ref); + return -1; + } + } + + args->str.l = 0; + kputc(ref[0], &args->str); + for (i=0; i<5; i++) + { + if ( alleles[i]>0 ) + { + kputc(',', &args->str); + kputc("ACGTN"[i], &args->str); + } + } + bcf_update_alleles_str(args->header, rec, args->str.s); + if ( bcf_update_genotypes(args->header,rec,args->gts,rec->n_sample*2) ) error("Could not update the GT field\n"); + + free(ref); + return 0; +} + +static void tsv_to_vcf(args_t *args) +{ + if ( !args->ref_fname ) error("--tsv2vcf requires the --fasta-ref option\n"); + + args->ref = fai_load(args->ref_fname); + if ( !args->ref ) error("Could not load the reference %s\n", args->ref_fname); + + args->header = bcf_hdr_init("w"); + bcf_hdr_set_chrs(args->header, args->ref); + bcf_hdr_append(args->header, "##FORMAT="); + if (args->record_cmd_line) bcf_hdr_append_version(args->header, args->argc, args->argv, "bcftools_convert"); + + int i, nsmpl; + char **smpl; + if ( args->sample_list ) + { + smpl = hts_readlist(args->sample_list, args->sample_is_file, &nsmpl); + if ( !smpl ) error("Could not parse %s\n", args->sample_list); + for (i=0; iheader, smpl[i]); + free(smpl[i]); + } + free(smpl); + bcf_hdr_add_sample(args->header, NULL); + args->gts = (int32_t *) malloc(sizeof(int32_t)*nsmpl*2); + } + + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + if ( bcf_hdr_write(out_fh,args->header)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + + tsv_t *tsv = tsv_init(args->columns ? args->columns : "ID,CHROM,POS,AA"); + if ( tsv_register(tsv, "CHROM", tsv_setter_chrom, args->header) < 0 ) error("Expected CHROM column\n"); + if ( tsv_register(tsv, "POS", tsv_setter_pos, NULL) < 0 ) error("Expected POS column\n"); + if ( tsv_register(tsv, "ID", tsv_setter_id, args->header) < 0 && !args->columns ) error("Expected ID column\n"); + if ( tsv_register(tsv, "AA", tsv_setter_aa, args) < 0 ) + { + if ( args->sample_list ) error("Expected AA column with -s/-S\n"); + if ( tsv_register(tsv, "REF", tsv_setter_ref, args) < 0 || tsv_register(tsv, "ALT", tsv_setter_alt, args) < 0 ) + error("Expected REF and ALT columns when AA was not given\n"); + } + + bcf1_t *rec = bcf_init(); + bcf_float_set_missing(rec->qual); + + kstring_t line = {0,0,0}; + htsFile *in_fh = hts_open(args->infname, "r"); + if ( !in_fh ) error("Could not read: %s\n", args->infname); + while ( hts_getline(in_fh, KS_SEP_LINE, &line) > 0 ) + { + if ( line.s[0]=='#' ) continue; // skip comments + bcf_clear(rec); + + args->n.total++; + if ( !tsv_parse(tsv, rec, line.s) ) + { + if ( bcf_write(out_fh, args->header, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + args->n.written++; + } + else + args->n.skipped++; + } + if ( hts_close(in_fh) ) error("Close failed: %s\n", args->infname); + free(line.s); + + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + bcf_hdr_destroy(args->header); + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); + tsv_destroy(tsv); + bcf_destroy(rec); + free(args->str.s); + free(args->gts); + free(args->tsv.ref.s); + free(args->tsv.alt.s); + free(args->tsv.refalt.s); + + fprintf(bcftools_stderr,"Rows total: \t%d\n", args->n.total); + fprintf(bcftools_stderr,"Rows skipped: \t%d\n", args->n.skipped); + fprintf(bcftools_stderr,"Sites written: \t%d\n", args->n.written); + if ( args->sample_list ) + { + fprintf(bcftools_stderr,"Missing GTs: \t%d\n", args->n.missing); + fprintf(bcftools_stderr,"Hom RR: \t%d\n", args->n.hom_rr); + fprintf(bcftools_stderr,"Het RA: \t%d\n", args->n.het_ra); + fprintf(bcftools_stderr,"Hom AA: \t%d\n", args->n.hom_aa); + fprintf(bcftools_stderr,"Het AA: \t%d\n", args->n.het_aa); + } +} + +static void vcf_to_vcf(args_t *args) +{ + open_vcf(args,NULL); + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0); + if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,args->header,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) continue; + } + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + } + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); +} + +static void gvcf_to_vcf(args_t *args) +{ + if ( !args->ref_fname ) error("--gvcf2vcf requires the --fasta-ref option\n"); + + args->ref = fai_load(args->ref_fname); + if ( !args->ref ) error("Could not load the fai index for reference %s\n", args->ref_fname); + + open_vcf(args,NULL); + char wmode[8]; + set_wmode(wmode,args->output_type,args->outfname,args->clevel); + htsFile *out_fh = hts_open(args->outfname ? args->outfname : "-", wmode); + if ( out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->outfname, strerror(errno)); + if ( args->n_threads ) hts_set_threads(out_fh, args->n_threads); + + bcf_hdr_t *hdr = bcf_sr_get_header(args->files,0); + if (args->record_cmd_line) bcf_hdr_append_version(hdr, args->argc, args->argv, "bcftools_convert"); + if ( bcf_hdr_write(out_fh,hdr)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + if ( init_index2(out_fh,hdr,args->outfname,&args->index_fn, + args->write_index)<0 ) + error("Error: failed to initialise index for %s\n",args->outfname); + + int32_t *itmp = NULL, nitmp = 0; + + while ( bcf_sr_next_line(args->files) ) + { + bcf1_t *line = bcf_sr_get_line(args->files,0); + if ( args->filter ) + { + int pass = filter_test(args->filter, line, NULL); + if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1; + if ( !pass ) + { + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + } + + // check if alleles compatible with being a gVCF record + // ALT must be one of ., <*>, , + // check for INFO/END is below + int i, gallele = -1; + if (line->n_allele==1) + gallele = 0; // illumina/bcftools-call gvcf (if INFO/END present) + else if ( line->d.allele[1][0]=='<' ) + { + for (i=1; in_allele; i++) + { + if ( line->d.allele[i][1]=='*' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // mpileup/spec compliant gVCF + if ( line->d.allele[i][1]=='X' && line->d.allele[i][2]=='>' && line->d.allele[i][3]=='\0' ) { gallele = i; break; } // old mpileup gVCF + if ( strcmp(line->d.allele[i],"")==0 ) { gallele = i; break; } // GATK gVCF + } + } + + // no gVCF compatible alleles + if (gallele<0) + { + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + + int nend = bcf_get_info_int32(hdr,line,"END",&itmp,&nitmp); + if ( nend!=1 ) + { + // No INFO/END => not gVCF record + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + continue; + } + bcf_update_info_int32(hdr,line,"END",NULL,0); + int pos, len; + for (pos=line->pos; pospos = pos; + char *ref = faidx_fetch_seq(args->ref, (char*)bcf_hdr_id2name(hdr,line->rid), line->pos, line->pos, &len); + if ( !ref ) error("faidx_fetch_seq failed at %s:%"PRId64"\n", bcf_hdr_id2name(hdr,line->rid),(int64_t) line->pos+1); + strncpy(line->d.allele[0],ref,len); + if ( bcf_write(out_fh,hdr,line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->outfname); + free(ref); + } + } + free(itmp); + if ( args->write_index ) + { + if ( bcf_idx_save(out_fh)<0 ) + { + if ( hts_close(out_fh) ) error("Close failed: %s\n", args->outfname); + error("Error: cannot write to index %s\n", args->index_fn); + } + free(args->index_fn); + } + if ( hts_close(out_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->outfname); +} + +static void usage(void) +{ + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "About: Converts VCF/BCF to other formats and back. See man page for file\n"); + fprintf(bcftools_stderr, " formats details. When specifying output files explicitly instead\n"); + fprintf(bcftools_stderr, " of with PREFIX, one can use '-' for bcftools_stdout and '.' to suppress.\n"); + fprintf(bcftools_stderr, "Usage: bcftools convert [OPTIONS] INPUT_FILE\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "VCF input options:\n"); + fprintf(bcftools_stderr, " -e, --exclude EXPR Exclude sites for which the expression is true\n"); + fprintf(bcftools_stderr, " -i, --include EXPR Select sites for which the expression is true\n"); + fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n"); + fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n"); + fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"); + fprintf(bcftools_stderr, " -s, --samples LIST List of samples to include\n"); + fprintf(bcftools_stderr, " -S, --samples-file FILE File of samples to include\n"); + fprintf(bcftools_stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"); + fprintf(bcftools_stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "VCF output options:\n"); + fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n"); + fprintf(bcftools_stderr, " -o, --output FILE Output file name [bcftools_stdout]\n"); + fprintf(bcftools_stderr, " -O, --output-type u|b|v|z[0-9] u/b: un/compressed BCF, v/z: un/compressed VCF, 0-9: compression level [v]\n"); + fprintf(bcftools_stderr, " --threads INT Use multithreading with INT worker threads [0]\n"); + fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "GEN/SAMPLE conversion (input/output from IMPUTE2):\n"); + fprintf(bcftools_stderr, " -G, --gensample2vcf ... |,\n"); + fprintf(bcftools_stderr, " -g, --gensample ... |,\n"); + fprintf(bcftools_stderr, " --3N6 Use 3*N+6 column format instead of the old 3*N+5 column format\n"); + fprintf(bcftools_stderr, " --tag STRING Tag to take values for .gen file: GT,PL,GL,GP [GT]\n"); + fprintf(bcftools_stderr, " --chrom Output chromosome in first column instead of CHROM:POS_REF_ALT\n"); + fprintf(bcftools_stderr, " --keep-duplicates Keep duplicate positions\n"); + fprintf(bcftools_stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(bcftools_stderr, " --vcf-ids Output VCF IDs in second column instead of CHROM:POS_REF_ALT\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "gVCF conversion:\n"); + fprintf(bcftools_stderr, " --gvcf2vcf Expand gVCF reference blocks\n"); + fprintf(bcftools_stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "HAP/SAMPLE conversion (output from SHAPEIT):\n"); + fprintf(bcftools_stderr, " --hapsample2vcf ... |,\n"); + fprintf(bcftools_stderr, " --hapsample ... |,\n"); + fprintf(bcftools_stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n"); + fprintf(bcftools_stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(bcftools_stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "HAP/LEGEND/SAMPLE conversion:\n"); + fprintf(bcftools_stderr, " -H, --haplegendsample2vcf ... |,,\n"); + fprintf(bcftools_stderr, " -h, --haplegendsample ... |,,\n"); + fprintf(bcftools_stderr, " --haploid2diploid Convert haploid genotypes to diploid homozygotes\n"); + fprintf(bcftools_stderr, " --sex FILE Output sex column in the sample-file, input format is: Sample\\t[MF]\n"); + fprintf(bcftools_stderr, " --vcf-ids Output VCF IDs instead of CHROM:POS_REF_ALT\n"); + fprintf(bcftools_stderr, "\n"); + fprintf(bcftools_stderr, "TSV conversion:\n"); + fprintf(bcftools_stderr, " --tsv2vcf FILE\n"); + fprintf(bcftools_stderr, " -c, --columns STRING Columns of the input tsv file, see man page for details [ID,CHROM,POS,AA]\n"); + fprintf(bcftools_stderr, " -f, --fasta-ref FILE Reference sequence in fasta format\n"); + fprintf(bcftools_stderr, " -s, --samples LIST List of sample names\n"); + fprintf(bcftools_stderr, " -S, --samples-file FILE File of sample names\n"); + fprintf(bcftools_stderr, "\n"); + // fprintf(bcftools_stderr, "PLINK options:\n"); + // fprintf(bcftools_stderr, " -p, --plink |,,|,,|,\n"); + // fprintf(bcftools_stderr, " --tped make tped file instead\n"); + // fprintf(bcftools_stderr, " --bin make binary bed/fam/bim files\n"); + // fprintf(bcftools_stderr, "\n"); + // fprintf(bcftools_stderr, "PBWT options:\n"); + // fprintf(bcftools_stderr, " -b, --pbwt or ,,,\n"); + // fprintf(bcftools_stderr, "\n"); + bcftools_exit(1); +} + +int main_vcfconvert(int argc, char *argv[]) +{ + int c; + args_t *args = (args_t*) calloc(1,sizeof(args_t)); + args->argc = argc; args->argv = argv; + args->outfname = "-"; + args->output_type = FT_VCF; + args->n_threads = 0; + args->record_cmd_line = 1; + args->regions_overlap = 1; + args->targets_overlap = 0; + args->clevel = -1; + + static struct option loptions[] = + { + {"include",required_argument,NULL,'i'}, + {"exclude",required_argument,NULL,'e'}, + {"output",required_argument,NULL,'o'}, + {"output-type",required_argument,NULL,'O'}, + {"threads",required_argument,NULL,9}, + {"regions",required_argument,NULL,'r'}, + {"regions-file",required_argument,NULL,'R'}, + {"regions-overlap",required_argument,NULL,13}, + {"targets",required_argument,NULL,'t'}, + {"targets-file",required_argument,NULL,'T'}, + {"targets-overlap",required_argument,NULL,14}, + {"samples",required_argument,NULL,'s'}, + {"samples-file",required_argument,NULL,'S'}, + {"sex",required_argument,NULL,11}, + {"gensample",required_argument,NULL,'g'}, + {"gensample2vcf",required_argument,NULL,'G'}, + {"tag",required_argument,NULL,1}, + {"chrom",no_argument,NULL,8}, + {"3N6",no_argument,NULL,15}, + {"tsv2vcf",required_argument,NULL,2}, + {"hapsample",required_argument,NULL,7}, + {"hapsample2vcf",required_argument,NULL,3}, + {"vcf-ids",no_argument,NULL,4}, + {"haploid2diploid",no_argument,NULL,5}, + {"gvcf2vcf",no_argument,NULL,6}, + {"haplegendsample",required_argument,NULL,'h'}, + {"haplegendsample2vcf",required_argument,NULL,'H'}, + {"columns",required_argument,NULL,'c'}, + {"fasta-ref",required_argument,NULL,'f'}, + {"no-version",no_argument,NULL,10}, + {"keep-duplicates",no_argument,NULL,12}, + {"write-index",optional_argument,NULL,'W'}, + {NULL,0,NULL,0} + }; + char *tmp; + while ((c = getopt_long(argc, argv, "?h:r:R:s:S:t:T:i:e:g:G:o:O:c:f:H:W::",loptions,NULL)) >= 0) { + switch (c) { + case 'e': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break; + case 'i': + if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n"); + args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break; + case 'r': args->regions_list = optarg; break; + case 'R': args->regions_list = optarg; args->regions_is_file = 1; break; + case 't': args->targets_list = optarg; break; + case 'T': args->targets_list = optarg; args->targets_is_file = 1; break; + case 's': args->sample_list = optarg; break; + case 'S': args->sample_list = optarg; args->sample_is_file = 1; break; + case 'g': args->convert_func = vcf_to_gensample; args->outfname = optarg; break; + case 'G': args->convert_func = gensample_to_vcf; args->infname = optarg; break; + case 1 : args->tag = optarg; break; + case 2 : args->convert_func = tsv_to_vcf; args->infname = optarg; break; + case 3 : args->convert_func = hapsample_to_vcf; args->infname = optarg; break; + case 4 : args->output_vcf_ids = 1; break; + case 5 : args->hap2dip = 1; break; + case 6 : args->convert_func = gvcf_to_vcf; break; + case 7 : args->convert_func = vcf_to_hapsample; args->outfname = optarg; break; + case 8 : error("The --chrom option has been deprecated, please use --3N6 instead\n"); break; + case 15 : args->gen_3N6 = 1; break; + case 'W': + if (!(args->write_index = write_index_parse(optarg))) + error("Unsupported index format '%s'\n", optarg); + break; + case 'H': args->convert_func = haplegendsample_to_vcf; args->infname = optarg; break; + case 'f': args->ref_fname = optarg; break; + case 'c': args->columns = optarg; break; + case 'o': args->outfname = optarg; break; + case 'O': + switch (optarg[0]) { + case 'b': args->output_type = FT_BCF_GZ; break; + case 'u': args->output_type = FT_BCF; break; + case 'z': args->output_type = FT_VCF_GZ; break; + case 'v': args->output_type = FT_VCF; break; + default: + { + args->clevel = strtol(optarg,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg); + } + } + if ( optarg[1] ) + { + args->clevel = strtol(optarg+1,&tmp,10); + if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1); + } + break; + case 'h': args->convert_func = vcf_to_haplegendsample; args->outfname = optarg; break; + case 9 : args->n_threads = strtol(optarg, 0, 0); break; + case 10 : args->record_cmd_line = 0; break; + case 11 : args->sex_fname = optarg; break; + case 12 : args->keep_duplicates = 1; break; + case 13 : + args->regions_overlap = parse_overlap_option(optarg); + if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg); + break; + case 14 : + args->targets_overlap = parse_overlap_option(optarg); + if ( args->targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg); + break; + case '?': usage(); break; + default: error("Unknown argument: %s\n", optarg); + } + } + + if ( !args->infname ) + { + if ( optind>=argc ) + { + if ( !isatty(fileno((FILE *)stdin)) ) args->infname = "-"; + } + else args->infname = argv[optind]; + } + if ( !args->infname ) usage(); + + if ( args->convert_func ) args->convert_func(args); + else vcf_to_vcf(args); + + destroy_data(args); + free(args); + return 0; +} diff --git a/shared/package-files/cb/cba27ab9bb299be51ee2cd52f5b75467e80453a8ef910d08504c356b7b069a4c/tool.cpython-311.pyc b/shared/package-files/cb/cba27ab9bb299be51ee2cd52f5b75467e80453a8ef910d08504c356b7b069a4c/tool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da40077c927f0e02d4685e59326b4496ec31017a Binary files /dev/null and b/shared/package-files/cb/cba27ab9bb299be51ee2cd52f5b75467e80453a8ef910d08504c356b7b069a4c/tool.cpython-311.pyc differ diff --git a/shared/package-files/cb/cba88c3aa60fcea5f51cf1fb6b7c347ca366d87e4bf3f70c7998ecdd3e074eec/tools_common.cpython-311.pyc b/shared/package-files/cb/cba88c3aa60fcea5f51cf1fb6b7c347ca366d87e4bf3f70c7998ecdd3e074eec/tools_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5088ecd3404acd26823ea450008df88e4a31ff74 Binary files /dev/null and b/shared/package-files/cb/cba88c3aa60fcea5f51cf1fb6b7c347ca366d87e4bf3f70c7998ecdd3e074eec/tools_common.cpython-311.pyc differ diff --git a/shared/package-files/cb/cba957880d5f12731a5d5f378d3a1e20824a08b4ae506d530d209e265df51e6e/norm.h b/shared/package-files/cb/cba957880d5f12731a5d5f378d3a1e20824a08b4ae506d530d209e265df51e6e/norm.h new file mode 100644 index 0000000000000000000000000000000000000000..888e1d21deccf7c82904878f902aa32596841128 --- /dev/null +++ b/shared/package-files/cb/cba957880d5f12731a5d5f378d3a1e20824a08b4ae506d530d209e265df51e6e/norm.h @@ -0,0 +1,110 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype) { + return at::_ops::norm_ScalarOpt_dtype::call(self, p, dtype); +} + +// aten::norm.Scalar(Tensor self, Scalar p=2) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const at::Scalar & p=2) { + return at::_ops::norm_Scalar::call(self, p); +} + +// aten::norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim, at::ScalarType dtype) { + return at::_ops::norm_ScalarOpt_dim_dtype::call(self, p, dim, keepdim, dtype); +} + +// aten::norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim=false) { + return at::_ops::norm_ScalarOpt_dim::call(self, p, dim, keepdim); +} + +// aten::norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim, at::ScalarType dtype) { + return at::_ops::norm_dtype_out::call(self, p, dim, keepdim, dtype, out); +} +// aten::norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim, at::ScalarType dtype, at::Tensor & out) { + return at::_ops::norm_dtype_out::call(self, p, dim, keepdim, dtype, out); +} + +// aten::norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim=false) { + return at::_ops::norm_out::call(self, p, dim, keepdim, out); +} +// aten::norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::IntArrayRef dim, bool keepdim, at::Tensor & out) { + return at::_ops::norm_out::call(self, p, dim, keepdim, out); +} + +// aten::norm.names_ScalarOpt_dim_dtype(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim, at::ScalarType dtype) { + return at::_ops::norm_names_ScalarOpt_dim_dtype::call(self, p, dim, keepdim, dtype); +} + +// aten::norm.names_ScalarOpt_dim(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False) -> Tensor +inline at::Tensor norm(const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim=false) { + return at::_ops::norm_names_ScalarOpt_dim::call(self, p, dim, keepdim); +} + +// aten::norm.names_dtype_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim, at::ScalarType dtype) { + return at::_ops::norm_names_dtype_out::call(self, p, dim, keepdim, dtype, out); +} +// aten::norm.names_dtype_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim, at::ScalarType dtype, at::Tensor & out) { + return at::_ops::norm_names_dtype_out::call(self, p, dim, keepdim, dtype, out); +} + +// aten::norm.names_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim=false) { + return at::_ops::norm_names_out::call(self, p, dim, keepdim, out); +} +// aten::norm.names_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::DimnameList dim, bool keepdim, at::Tensor & out) { + return at::_ops::norm_names_out::call(self, p, dim, keepdim, out); +} + +// aten::norm.ScalarOpt_dtype_out(Tensor self, Scalar? p, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype) { + return at::_ops::norm_ScalarOpt_dtype_out::call(self, p, dtype, out); +} +// aten::norm.ScalarOpt_dtype_out(Tensor self, Scalar? p, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const ::std::optional & p, at::ScalarType dtype, at::Tensor & out) { + return at::_ops::norm_ScalarOpt_dtype_out::call(self, p, dtype, out); +} + +// aten::norm.Scalar_out(Tensor self, Scalar p=2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & p=2) { + return at::_ops::norm_Scalar_out::call(self, p, out); +} +// aten::norm.Scalar_out(Tensor self, Scalar p=2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & norm_outf(const at::Tensor & self, const at::Scalar & p, at::Tensor & out) { + return at::_ops::norm_Scalar_out::call(self, p, out); +} + +} diff --git a/shared/package-files/cb/cbabce7fc24a6609b2c83e6432ea762e1bfe889d270e13becd245a2b601ad9c1/pixel_shuffle_ops.h b/shared/package-files/cb/cbabce7fc24a6609b2c83e6432ea762e1bfe889d270e13becd245a2b601ad9c1/pixel_shuffle_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..659f68961f55cae3a51655b7d9643ee2584252c1 --- /dev/null +++ b/shared/package-files/cb/cbabce7fc24a6609b2c83e6432ea762e1bfe889d270e13becd245a2b601ad9c1/pixel_shuffle_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API pixel_shuffle { + using schema = at::Tensor (const at::Tensor &, int64_t); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::pixel_shuffle"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "pixel_shuffle(Tensor self, int upscale_factor) -> Tensor"; + static at::Tensor call(const at::Tensor & self, int64_t upscale_factor); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t upscale_factor); +}; + +struct TORCH_API pixel_shuffle_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::pixel_shuffle"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "pixel_shuffle.out(Tensor self, int upscale_factor, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, int64_t upscale_factor, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t upscale_factor, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cb/cbaddfe0e971255d5fff1d951a648e9121645ea88a4ca92c0e585d80ab56d648/test_evalf.cpython-311.pyc b/shared/package-files/cb/cbaddfe0e971255d5fff1d951a648e9121645ea88a4ca92c0e585d80ab56d648/test_evalf.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ddc6c49766b89136797f56210546cda07ceadd6 Binary files /dev/null and b/shared/package-files/cb/cbaddfe0e971255d5fff1d951a648e9121645ea88a4ca92c0e585d80ab56d648/test_evalf.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbbd33af1c2525a423b85a98142f4cc8cb23a6a14ec3a02cfe02151ab0e4f0c0/test_round_trip.cpython-311.pyc b/shared/package-files/cb/cbbd33af1c2525a423b85a98142f4cc8cb23a6a14ec3a02cfe02151ab0e4f0c0/test_round_trip.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1febf04ccb28e76383a3e4c11ab391c22b9c1843 Binary files /dev/null and b/shared/package-files/cb/cbbd33af1c2525a423b85a98142f4cc8cb23a6a14ec3a02cfe02151ab0e4f0c0/test_round_trip.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbbdeacb09503cc7fa90162382b063cb626c9f066ed91cf05b4b39c3587b50c0/test_string_array.cpython-311.pyc b/shared/package-files/cb/cbbdeacb09503cc7fa90162382b063cb626c9f066ed91cf05b4b39c3587b50c0/test_string_array.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b30da29f9486e124f78133c1e8b7fd0d9f2d011 Binary files /dev/null and b/shared/package-files/cb/cbbdeacb09503cc7fa90162382b063cb626c9f066ed91cf05b4b39c3587b50c0/test_string_array.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbc2169d54a4da987e65908f59db0010c93445dd88e6cf05ae19a633bb8f55a4/test_fillna.cpython-311.pyc b/shared/package-files/cb/cbc2169d54a4da987e65908f59db0010c93445dd88e6cf05ae19a633bb8f55a4/test_fillna.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fb457507beb27b0213cd5173fbc7bec8b75de44 Binary files /dev/null and b/shared/package-files/cb/cbc2169d54a4da987e65908f59db0010c93445dd88e6cf05ae19a633bb8f55a4/test_fillna.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbc2b4e6be903f0472da02912d530d1b9c460b2d8abe1a84a41bf84b6bcec57b/internal.py b/shared/package-files/cb/cbc2b4e6be903f0472da02912d530d1b9c460b2d8abe1a84a41bf84b6bcec57b/internal.py new file mode 100644 index 0000000000000000000000000000000000000000..5faf7d14d0da572a24a36085bdc334e468ab76a6 --- /dev/null +++ b/shared/package-files/cb/cbc2b4e6be903f0472da02912d530d1b9c460b2d8abe1a84a41bf84b6bcec57b/internal.py @@ -0,0 +1,285 @@ +# mypy: allow-untyped-defs +import collections +import copyreg +import io +import pickle +import sys +import threading +import traceback +from enum import Enum + +import torch +import torch.distributed as dist +from torch._C._distributed_rpc import _get_current_rpc_agent + + +__all__ = ["RPCExecMode", "serialize", "deserialize", "PythonUDF", "RemoteException"] + +# Thread local tensor tables to store tensors while pickling torch.Tensor +# objects +_thread_local_tensor_tables = threading.local() +_pickler = pickle.Pickler +_unpickler = pickle.Unpickler + + +class RPCExecMode(Enum): + SYNC = "sync" + ASYNC = "async" + ASYNC_JIT = "async_jit" + REMOTE = "remote" + + +class _InternalRPCPickler: + r""" + This class provides serialize() and deserialize() interfaces to serialize + data to be "binary string + tensor table" format + So for RPC python UDF function and args, non tensor data will be serialized + into regular binary string, tensor data will be put into thread local tensor + tables, this serialization format is consistent with builtin operator and args + using JIT pickler. This format will make tensor handling in C++ much easier, + e.g. attach tensor to distributed autograd graph in C++ + """ + + def __init__(self): + # Ignore type error because dispatch_table is defined in third-party package + self._dispatch_table = copyreg.dispatch_table.copy() # type: ignore[attr-defined] + self._dispatch_table[torch.Tensor] = self._tensor_reducer + # Used for registering customized picklers. + self._class_reducer_dict = {} + + def _register_reducer(self, obj_class, reducer): + # For the same class, only register the reducer once. + if obj_class not in self._class_reducer_dict: + self._class_reducer_dict[obj_class] = reducer + + @classmethod + def _tensor_receiver(cls, tensor_index): + global _thread_local_tensor_tables + return _thread_local_tensor_tables.recv_tables[tensor_index] + + def _tensor_reducer(self, tensor): + global _thread_local_tensor_tables + _thread_local_tensor_tables.send_tables.append(tensor) + tensor_index = len(_thread_local_tensor_tables.send_tables) - 1 + return (_InternalRPCPickler._tensor_receiver, (tensor_index,)) + + @classmethod + def _py_rref_receiver(cls, rref_fork_data): + return dist.rpc.PyRRef._deserialize(rref_fork_data) + + def _py_rref_reducer(self, py_rref): + rref_fork_data = py_rref._serialize() + return (_InternalRPCPickler._py_rref_receiver, (rref_fork_data,)) + + def _rref_reducer(self, rref): + return self._py_rref_reducer(rref) + + @classmethod + def _script_module_receiver(cls, script_module_serialized): + """ + Given a serialized representation of a ScriptModule created with torch.jit.save, + loads and returns the ScriptModule. + """ + f = io.BytesIO(script_module_serialized) + m = torch.jit.load(f) + return m + + def _script_module_reducer(self, script_module): + """ + Serializes a ScriptModule. + """ + f = io.BytesIO() + torch.jit.save(script_module, f) + return (_InternalRPCPickler._script_module_receiver, (f.getvalue(),)) + + def serialize(self, obj): + r""" + Serialize non tensor data into binary string, tensor data into + tensor table + """ + f = io.BytesIO() + p = _pickler(f) + p.dispatch_table = self._dispatch_table + + # rpc api could accept user picklers inheriting from _InternalRPCPickler to serialize rref, + # user picklers could have different initialization function from _InternalRPCPickler, + # but all the user picklers should call serialize() and use _rref_reducer to pickle rref + # in python. also, when _internal_rpc_pickler is imported to rpc/api.py, rpc.RRef is not + # compiled yet, it is not good place to access rpc.RRef inside _InternalRPCPickler constructor, + # so putting rref's dispatch table here + # + # The return value of a `rpc.remote(..)` call is type of `rpc.PyRRef`. + # The deserialized RRef object on an RPC receiver side is type of `rpc.PyRRef`. + # Ignore type error because dispatch_table is defined in third-party package + p.dispatch_table[dist.rpc.PyRRef] = self._py_rref_reducer # type: ignore[index] + # An RRef created locally by RRef Python constructor is type of `rpc.RRef`. + # Ignore type error because dispatch_table is defined in third-party package + p.dispatch_table[dist.rpc.RRef] = self._rref_reducer # type: ignore[index] + + # Add dispatch pickling for ScriptModule or its subclass. + if isinstance(obj, torch.jit.ScriptModule): + # Ignore type error because dispatch_table is defined in third-party package + p.dispatch_table[obj.__class__] = self._script_module_reducer # type: ignore[index] + + # Install customized picklers. + for class_name in self._class_reducer_dict.keys(): + p.dispatch_table[class_name] = self._class_reducer_dict[class_name] # type: ignore[index] + + # save _thread_local_tensor_tables.send_tables if it is in nested call + global _thread_local_tensor_tables + if hasattr(_thread_local_tensor_tables, "send_tables"): + old_send_tables = _thread_local_tensor_tables.send_tables + else: + old_send_tables = None + _thread_local_tensor_tables.send_tables = [] + + p.dump(obj) + + # restore _thread_local_tensor_tables.send_tables if return + # from nested call, otherwise clean up the table + tensors = _thread_local_tensor_tables.send_tables + if old_send_tables is not None: + _thread_local_tensor_tables.send_tables = old_send_tables + else: + del _thread_local_tensor_tables.send_tables + + return (f.getvalue(), tensors) + + def deserialize(self, binary_data, tensor_table): + r""" + Deserialize binary string + tensor table to original obj + """ + # save _thread_local_tensor_tables.recv_tables if it is in nested call + global _thread_local_tensor_tables + if hasattr(_thread_local_tensor_tables, "recv_tables"): + old_recv_tables = _thread_local_tensor_tables.recv_tables + else: + old_recv_tables = None + _thread_local_tensor_tables.recv_tables = tensor_table + + try: + unpickler = _unpickler(io.BytesIO(binary_data)) + ret = unpickler.load() + except AttributeError as e: + # Occurs when function is not found on module/class during + # unpickling. + except_str = ( + str(e) + + """ Default RPC pickler does not serialize + function code. Ensure that UDFs are defined on both caller and + callee modules.""" + ) + ret = AttributeError(except_str) + # Ensure the stack trace gets preserved + ret.__cause__ = e + + # restore _thread_local_tensor_tables.recv_tables if return + # from nested call, otherwise clean up the table + if old_recv_tables is not None: + _thread_local_tensor_tables.recv_tables = old_recv_tables + else: + del _thread_local_tensor_tables.recv_tables + + return ret + + +# Create _internal_rpc_pickler only once to initialize _dispatch_table only once +_internal_rpc_pickler = _InternalRPCPickler() + + +def serialize(obj): + return _internal_rpc_pickler.serialize(obj) + + +def deserialize(binary_data, tensor_table): + return _internal_rpc_pickler.deserialize(binary_data, tensor_table) + + +def _run_function(python_udf): + r""" + This function is exclusively called from C++. + See ``torch/csrc/distributed/rpc/python_rpc_handler.cpp``. + + Runs a Python UDF and returns its return value. + Wraps any exception in ``RemoteException`` if the function raises. + """ + try: + if isinstance(python_udf, AttributeError): + raise python_udf + result = python_udf.func(*python_udf.args, **python_udf.kwargs) + except Exception as e: + # except str = exception info + traceback string + except_str = ( + f"On {_get_current_rpc_agent().get_worker_info()}:\n" + f"{repr(e)}\n{traceback.format_exc()}" + ) + print(except_str, file=sys.stderr) + result = RemoteException(except_str, type(e)) + return result + + +def _handle_exception(result): + if isinstance(result, RemoteException): + exception_msg = result.msg.encode("utf-8").decode("unicode_escape") + # We wrap exception re-creation here in case some exception classes + # cannot be constructed directly from a string. + exc = None + try: + exc = result.exception_type(exception_msg) + except BaseException as e: + raise RuntimeError( # noqa: B904 + f"Failed to create original exception type. Error msg was {str(e)}" + f" Original exception on remote side was {exception_msg}" + ) from e + + if exc is not None: + raise exc + + +def _build_rpc_profiling_key( + exec_type, func_name, current_worker_name, dst_worker_name +): + """ + Builds the key that RPC calls are profiled with using the autograd profiler. + This will be the name of the corresponding Event recorded in the profiler. + + Args: + exec_type (RPCExecMode): Type of RPC/RRef call + func_name (str): Name of function being profiled. + current_worker_name (str): Name of current worker. + dst_worker_name (str): Name of the destination worker. + + Returns: + String representing profiling key + """ + profile_key = ( + f"rpc_{exec_type.value}#{func_name}({current_worker_name} -> {dst_worker_name})" + ) + return profile_key + + +def _start_record_function(exec_type, func_name, current_worker_name, dest_worker_name): + """ + This function should be called from RPC/RRef functions to create a + RecordFunction object for profiling. This function also runs the before + callbacks that start the profiling, though the user is responsible for + running the appropriate callbacks when the function to be profiled finishes. + + Args: + exec_type (RPCExecMode): Type of RPC/RRef call + func_name (str): Name of function being profiled. + current_worker_name (str): Name of current worker. + dest_worker_name (str): Name of the destination worker. + + Returns: + An instance of `torch.autograd._RecordFunction`. + """ + assert torch.autograd._profiler_enabled(), "Autograd profiler should be enabled." + profile_key = f"rpc_{exec_type.value}#{str(func_name)}({current_worker_name} -> {dest_worker_name})" + rf = torch.autograd._RecordFunction() # type: ignore[attr-defined] + torch.autograd._run_before_callbacks(rf, profile_key) # type: ignore[attr-defined] + return rf + + +PythonUDF = collections.namedtuple("PythonUDF", ["func", "args", "kwargs"]) +RemoteException = collections.namedtuple("RemoteException", ["msg", "exception_type"]) diff --git a/shared/package-files/cb/cbc493f9919185b1ab03f77ea0cdb16a904c6b486715c1202db2f1b7ca5c327e/_constants.py b/shared/package-files/cb/cbc493f9919185b1ab03f77ea0cdb16a904c6b486715c1202db2f1b7ca5c327e/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5206e6e0b7eaa80c4ac445ab9eb0616f598df1 --- /dev/null +++ b/shared/package-files/cb/cbc493f9919185b1ab03f77ea0cdb16a904c6b486715c1202db2f1b7ca5c327e/_constants.py @@ -0,0 +1,7 @@ +# ir_version used for the ONNX file. See https://github.com/onnx/onnx/blob/main/docs/IR.md#onnx-versioning +ONNX_IR_VERSION = 10 +# The opset version torchlib is implemented with. Update this number when updating torchlib +TORCHLIB_OPSET = 18 +TORCHLIB_DOMAIN = "pkg.torch.onnx" +# Domain used for functions translated from subgraphs +LOCAL_FUNCTION_DOMAIN = "pkg.torch.__subgraph__" diff --git a/shared/package-files/cb/cbcee2f4bccec1d6355caca654018da4de5b953f89345c36bd4acd0eba24273d/numpy.cpython-311.pyc b/shared/package-files/cb/cbcee2f4bccec1d6355caca654018da4de5b953f89345c36bd4acd0eba24273d/numpy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..506c0d364c76ab373b9123052e6b0186a1e0c6e5 Binary files /dev/null and b/shared/package-files/cb/cbcee2f4bccec1d6355caca654018da4de5b953f89345c36bd4acd0eba24273d/numpy.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbd5bc569da9ac6b4b92a92d0e2d7c292a749a1b5ae7976c183a03a661fda27a/onnx.h b/shared/package-files/cb/cbd5bc569da9ac6b4b92a92d0e2d7c292a749a1b5ae7976c183a03a661fda27a/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..e9886690406605a5d576b232a514204cb9f2fee4 --- /dev/null +++ b/shared/package-files/cb/cbd5bc569da9ac6b4b92a92d0e2d7c292a749a1b5ae7976c183a03a661fda27a/onnx.h @@ -0,0 +1,18 @@ +#pragma once + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Winconsistent-missing-destructor-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Wdeprecated-dynamic-exception-spec") +#include +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +#include + +namespace torch::jit { + +TORCH_API std::string prettyPrint(const ::ONNX_NAMESPACE::ModelProto& model); + +} // namespace torch::jit diff --git a/shared/package-files/cb/cbdb155328465f87096a0965b8cd45c2f055094a11eb0173a0cc92bf6130acf4/inverse_ops.h b/shared/package-files/cb/cbdb155328465f87096a0965b8cd45c2f055094a11eb0173a0cc92bf6130acf4/inverse_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7da8726ac113f6d2f7548a6456d3dd4ff32f8328 --- /dev/null +++ b/shared/package-files/cb/cbdb155328465f87096a0965b8cd45c2f055094a11eb0173a0cc92bf6130acf4/inverse_ops.h @@ -0,0 +1,40 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API inverse { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::inverse"; + static constexpr const char* overload_name = ""; + static constexpr const char* schema_str = "inverse(Tensor self) -> Tensor"; + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API inverse_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::inverse"; + static constexpr const char* overload_name = "out"; + static constexpr const char* schema_str = "inverse.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)"; + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/shared/package-files/cb/cbdeb99a810551c11f3543d093dc7f52587f4af252d13b6d4a9069e394ced8ec/latex_parser.cpython-311.pyc b/shared/package-files/cb/cbdeb99a810551c11f3543d093dc7f52587f4af252d13b6d4a9069e394ced8ec/latex_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..730e384b04d021be5882fa21724fc754c11cf440 Binary files /dev/null and b/shared/package-files/cb/cbdeb99a810551c11f3543d093dc7f52587f4af252d13b6d4a9069e394ced8ec/latex_parser.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbdfd5774519b8c9a6a5ba7cc3dc2bc0e3f0681413d2b950f86058405c288673/_linalg_solve_ex_native.h b/shared/package-files/cb/cbdfd5774519b8c9a6a5ba7cc3dc2bc0e3f0681413d2b950f86058405c288673/_linalg_solve_ex_native.h new file mode 100644 index 0000000000000000000000000000000000000000..b37b707251e12303f155e0b5debb0d4729d0e301 --- /dev/null +++ b/shared/package-files/cb/cbdfd5774519b8c9a6a5ba7cc3dc2bc0e3f0681413d2b950f86058405c288673/_linalg_solve_ex_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured__linalg_solve_ex_out : public at::meta::structured__linalg_solve_ex { +void impl(const at::Tensor & A, const at::Tensor & B, bool left, bool check_errors, const at::Tensor & result, const at::Tensor & LU, const at::Tensor & pivots, const at::Tensor & info); +}; +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cbe32474edf9e9db518e7b019547e6941314a3a381acf1469b9c8ee3e6037c4f/test_utilities.cpython-311.pyc b/shared/package-files/cb/cbe32474edf9e9db518e7b019547e6941314a3a381acf1469b9c8ee3e6037c4f/test_utilities.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f210b6842ee4af2e7b6e573ab8d10340904b2db Binary files /dev/null and b/shared/package-files/cb/cbe32474edf9e9db518e7b019547e6941314a3a381acf1469b9c8ee3e6037c4f/test_utilities.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbeee485a8c433ed1cc378900598f668335288bae002b2144cd4c73dca952b90/pass_base.cpython-311.pyc b/shared/package-files/cb/cbeee485a8c433ed1cc378900598f668335288bae002b2144cd4c73dca952b90/pass_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae84b382de2bfc8e500136d8358bc9a0aca7153 Binary files /dev/null and b/shared/package-files/cb/cbeee485a8c433ed1cc378900598f668335288bae002b2144cd4c73dca952b90/pass_base.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbf1f9726a1adc6cc6ce4f9414cc2818223b97d9e6e5b1021f56905a6bf9534c/numpy_nodes.cpython-311.pyc b/shared/package-files/cb/cbf1f9726a1adc6cc6ce4f9414cc2818223b97d9e6e5b1021f56905a6bf9534c/numpy_nodes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a2434abddef7587589d156f1de0af254565af70 Binary files /dev/null and b/shared/package-files/cb/cbf1f9726a1adc6cc6ce4f9414cc2818223b97d9e6e5b1021f56905a6bf9534c/numpy_nodes.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbf5c8fc0ac240ff8bd2c4e76a6977e22a5bb0840d3334320f3d07fca86194b3/sign_native.h b/shared/package-files/cb/cbf5c8fc0ac240ff8bd2c4e76a6977e22a5bb0840d3334320f3d07fca86194b3/sign_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4d8b12b345c0d387c7e69472eacab5d6cf12f981 --- /dev/null +++ b/shared/package-files/cb/cbf5c8fc0ac240ff8bd2c4e76a6977e22a5bb0840d3334320f3d07fca86194b3/sign_native.h @@ -0,0 +1,29 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_sign_out : public at::meta::structured_sign { +void impl(const at::Tensor & self, const at::Tensor & out); +}; +TORCH_API at::Tensor sign_sparse(const at::Tensor & self); +TORCH_API at::Tensor & sign_sparse_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sign_sparse_(at::Tensor & self); +TORCH_API at::Tensor sign_sparse_csr(const at::Tensor & self); +TORCH_API at::Tensor & sign_sparse_csr_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sign_sparse_csr_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/shared/package-files/cb/cbf69d44cbf2272863950b31b425066757d41fb65d7d42c04b04020b7d56e79e/scrolledlist.cpython-311.pyc b/shared/package-files/cb/cbf69d44cbf2272863950b31b425066757d41fb65d7d42c04b04020b7d56e79e/scrolledlist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53b6e114998cb4c786e0a6f26fe7edc464417e1a Binary files /dev/null and b/shared/package-files/cb/cbf69d44cbf2272863950b31b425066757d41fb65d7d42c04b04020b7d56e79e/scrolledlist.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbfa58bd8cb6e1f80cb22c1b238e1da2a8132f8ba11f0e5c1696073aee745fe4/mm_plus_mm.cpython-311.pyc b/shared/package-files/cb/cbfa58bd8cb6e1f80cb22c1b238e1da2a8132f8ba11f0e5c1696073aee745fe4/mm_plus_mm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fd6516f31388fe484ed866c96715f4463cc7b9d Binary files /dev/null and b/shared/package-files/cb/cbfa58bd8cb6e1f80cb22c1b238e1da2a8132f8ba11f0e5c1696073aee745fe4/mm_plus_mm.cpython-311.pyc differ diff --git a/shared/package-files/cb/cbfc5d79a023a4b0858734936f102f40945b73fab9c86e1827d4b54a535e0024/pgo.py b/shared/package-files/cb/cbfc5d79a023a4b0858734936f102f40945b73fab9c86e1827d4b54a535e0024/pgo.py new file mode 100644 index 0000000000000000000000000000000000000000..96ace1da75b4d5f08412eb009c3a1fdb0b9e3372 --- /dev/null +++ b/shared/package-files/cb/cbfc5d79a023a4b0858734936f102f40945b73fab9c86e1827d4b54a535e0024/pgo.py @@ -0,0 +1,750 @@ +""" +Profile Guided Optimization (PGO) implementation for Dynamo. + +This module provides functionality for caching and managing code state profiles +that guide optimization decisions in Dynamo. It implements both local and remote +caching mechanisms for storing profile information across runs, handles profile +merging across distributed ranks, and manages the lifecycle of profile data +during compilation. The profiles track dynamic vs static properties of tensors +and help Dynamo make better specialization decisions. +""" + +from __future__ import annotations + +import base64 +import copy +import dataclasses +import enum +import logging +import os +import pickle +import re +from collections import defaultdict +from typing import Optional, TYPE_CHECKING, TypeVar, Union +from typing_extensions import Self + +import torch._dynamo.config +import torch._utils_internal +import torch.compiler.config +import torch.distributed as dist +from torch._dynamo.utils import ( + CompileEventLogger, + dynamo_timed, + set_feature_use, + warn_once, +) +from torch._environment import is_fbcode +from torch._logging._internal import trace_structured_artifact +from torch.compiler._cache import CacheArtifactManager, CacheArtifactType + + +if TYPE_CHECKING: + import types + + from torch._dynamo.symbolic_convert import InstructionTranslator + from torch._inductor.remote_cache import JsonDataTy, RemoteCache + + +class ReservedWorkflowIdUserError(ValueError): + pass + + +log = logging.getLogger(__name__) + +LOCK_TIMEOUT = 10 + +# How does in memory representation work? Concretely, this module is +# responsible for holding GLOBAL state representing the state it holds, no +# other copies permitted. So we retire frame_state entirely and store it +# here. This should be reset when Dynamo is reset. We never GC information +# (similar to how the filesystem doesn't get cleaned up except by tmp +# cleaner), so the expectation is the information is relatively cheap and we +# don't mind leaking it. + + +# How exactly did we design the cache key? Here are some of the questions: +# +# - JOB_ID: Do we have a unique identifier for the "training run" (such that +# it stays the same if we're running the same code, and changes if we're +# running something different). +# +# - RANK: Are we sharing the cache across ranks, or does each rank get +# an individual cache? +# +# We choose to require job_id for PGO cache. This is to prevent +# situations where unrelated invocations of PyTorch unpredictably cause +# changes to each other's behavior. With a job_id, at least you know there +# is some "state" associated with it. (State dict might be another way to +# tell if a run is related or not.) You can opt-in to YOLO everything +# aliases everything by passing a shared job_id for all your invocations. +# +# We choose to NOT share PGO cache across ranks. With no RANK_SHARING, there +# is never contention between runs, so we can leisurely update a bundle with +# information we need. Because we are grouped by job_id, we can have a single +# consolidated bundle for everything (or not; maybe worry about O(n^2) IO if +# we updated every compile--let's just instrument this.) Can even take a +# filelock for extra safety (expect no contention); expect 50ns overhead from +# uncontended filelock. +# +# If we did share ranks, everyone is storming to modify the same cache files. +# We can do this by having folks atomic write to a CAS-store and then having +# readers do on-the-fly merging (this can be implemented in remote using +# prefix iteration). As an optional optimization, one rank can be elected to +# handling bundling post facto (ideally, this is done async, after quiescence, +# without compiler collective need to wait for everyone to finish writing +# their bits.) Not sure how you can avoid a listdir because if some rank shows +# up with some new entries we need to pull them in ASAP (unless you want to +# delay bundling). +# +# But compiler collectives fill a similar niche: compilers chat with each +# other so rank 0 has collected everything. So elect rank 0 only to write the +# bundle. Don't even need CAS-store atomic write; just one rank writing an +# updating bundles. The point is that use compiler collectives to share +# profiles across ranks, but use the PGO cache to persist profiles per rank +# across attempts. No need to have one mechanism to do everything. + + +@dataclasses.dataclass(frozen=True) +class CodeId: + filename: str + firstlineno: int + name: str + + @staticmethod + def make(code: types.CodeType) -> CodeId: + return CodeId(code.co_filename, code.co_firstlineno, code.co_name) + + +@dataclasses.dataclass +class CodeState: + automatic_dynamic: defaultdict[str, FrameStateSizeEntry] = dataclasses.field( + default_factory=lambda: defaultdict(FrameStateSizeEntry) + ) + + +_INIT_CODE_STATE: Optional[defaultdict[CodeId, CodeState]] = None +_CODE_STATE: Optional[defaultdict[CodeId, CodeState]] = None + + +@dataclasses.dataclass(frozen=True) +class InferStride: + """ + Denotes the quantity stride[dim] * size[dim], which is what the stride would + be for the next physical dimension that results in a contiguous layout. + + For example, given size = [2, 3], stride = [3, 1], we can replace this with + stride = [InferStride(1), 1], because InferStride(1) = stride[1] * size[1] = 1 * 3 = 3 + + Indirecting the representation in this way is important for the join operation + on strides as if we join [2, 3][3, 1] and [2, 4][4, 1], + we don't want [2, None][None, 1] which would get eventually symbolized into + [2, s0][s1, 1] (notice that the relationship between s0 and s1 is broken). + If we instead rewrite the expressions as InferStride so we have [2, 3][InferStride(1), 1] + and [2, 4][InferStride(1), 1] we now join to [2, None][InferStride(1), 1] will + result in [2, s0][s0, 1], as desired. + """ + + dim: int + + +_T = TypeVar("_T") + + +class AutoUnset(enum.Enum): + """ + The identity element of our semilattice, a generic "don't know" element that + is always subsumed when we get more information. + """ + + token = 0 + + +auto_unset = AutoUnset.token + + +class AutoDynamic(enum.Enum): + """ + The top element of our (bounded) semilattice, whenever you merge this with + any other element you always get it again + """ + + token = 0 + + +auto_dynamic = AutoDynamic.token + + +@dataclasses.dataclass +class FrameStateSizeEntry: + scalar: Union[int, AutoDynamic, AutoUnset] = dataclasses.field(default=auto_unset) + # NB: We don't have cases where we have a known dimensionality but + # we know NOTHING about the individual sizes + size: Union[AutoDynamic, AutoUnset, tuple[Union[int, AutoDynamic], ...]] = ( + dataclasses.field(default=auto_unset) + ) + stride: Union[ + AutoDynamic, AutoUnset, tuple[Union[int, AutoDynamic, InferStride], ...] + ] = dataclasses.field(default=auto_unset) + + def render(self) -> str: + # Special cases + def render_single(s: Union[int, AutoDynamic, AutoUnset, InferStride]) -> str: + if s is auto_dynamic: + return "?" + elif s is auto_unset: + # This basically shouldn't happen, this is for debugging + return "auto unset" + elif isinstance(s, InferStride): + return f"S({s.dim})" + else: + return str(s) + + def render_tuple(ss: tuple[Union[int, AutoDynamic, InferStride], ...]) -> str: + return "[" + ", ".join(render_single(s) for s in ss) + "]" + + # Common cases + if self.size is auto_dynamic and self.stride is auto_dynamic: + if self.scalar is auto_dynamic: + return "fully dynamic scalar or tensor" + else: + return f"scalar {self.scalar}" + elif self.scalar is auto_dynamic: + if isinstance(self.size, tuple) and isinstance(self.stride, tuple): + return f"tensor size={render_tuple(self.size)} stride={render_tuple(self.stride)}" + + # Fallback + return "unusual {repr(self)}" + + def __post_init__(self) -> None: + assert not isinstance(self.scalar, torch.SymInt), self.scalar + if isinstance(self.size, tuple): + for s in self.size: + assert not isinstance(s, torch.SymInt), s + if isinstance(self.stride, tuple): + for s1 in self.stride: + assert not isinstance(s1, torch.SymInt), s1 + + def is_size_dynamic(self, dim: int) -> bool: + if self.size is auto_dynamic: + return True + if self.size is auto_unset: + return False + return self.size[dim] is auto_dynamic + + def is_stride_dynamic(self, dim: int) -> bool: + # At the moment, dynamic strides is a bit buggy. Good test case + # here is `PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py + # TestAutograd.test_gradcheck_jacobian_mismatch` + # + # This if statement preserves historical behavior, which is that we + # ONLY make strides dynamic if the size is exactly static everywhere. + # We could potentially relax this but in general we should be very + # careful about when to infer dynamic strides. + # + # Actually, the existing algorithm is already somewhat problematic. + # Suppose a tensor that is sometimes: + # f32[2, 3, 5][15, 5, 1] and other times + # f32[2, 3, 5][5, 10, 1] (specifically, dim 0 and 1 are physically transposed). + # If we infer strides should be (DYNAMIC, DYNAMIC, 1). But this is + # silly: we really should have just guarded on dim order. + if not ( + isinstance(self.size, tuple) and all(type(s) is int for s in self.size) + ): + return False + if self.stride is auto_dynamic: + return True + if self.stride is auto_unset: + return False + return self.stride[dim] is auto_dynamic + + @staticmethod + def _munge_symint(xs: tuple[int, ...]) -> tuple[Union[AutoDynamic, int], ...]: + return tuple(auto_dynamic if isinstance(x, torch.SymInt) else x for x in xs) + + @classmethod + def make_scalar(cls, x: int) -> FrameStateSizeEntry: + return FrameStateSizeEntry(scalar=x, size=auto_dynamic, stride=auto_dynamic) + + @classmethod + def make_tensor( + cls, size: tuple[int, ...], stride: tuple[int, ...] + ) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_dynamic, + size=cls._munge_symint(size), + stride=cls._munge_symint(stride), + ) + + @classmethod + def make_size(cls, size: tuple[int, ...]) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_unset, + size=cls._munge_symint(size), + stride=auto_unset, + ) + + @staticmethod + def _merge_atom(x: _T, y: _T) -> Union[AutoDynamic, _T]: + if x is auto_unset: + return y + if y is auto_unset: + return x + if x is auto_dynamic or y is auto_dynamic or x != y: + return auto_dynamic + return x + + @classmethod + def _merge_atom_tup( + cls, + xs: Union[AutoDynamic, AutoUnset, tuple[_T, ...]], + ys: Union[AutoDynamic, AutoUnset, tuple[_T, ...]], + ) -> Union[AutoDynamic, AutoUnset, tuple[Union[AutoDynamic, _T], ...]]: + if xs is auto_unset: + return ys + if ys is auto_unset: + return xs + if xs is auto_dynamic or ys is auto_dynamic: + return auto_dynamic + if len(xs) != len(ys): + return auto_dynamic + return tuple(cls._merge_atom(x, y) for x, y in zip(xs, ys)) + + def __ior__(self, other: Self) -> Self: + self.scalar = self._merge_atom(self.scalar, other.scalar) + self.size = self._merge_atom_tup(self.size, other.size) + self.stride = self._merge_atom_tup(self.stride, other.stride) + return self + + +def update_automatic_dynamic( + tx: InstructionTranslator, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + code_id = CodeId.make(tx.f_code) + frame_state = get_code_state()[code_id] + is_update = name in frame_state.automatic_dynamic + mut_entry = frame_state.automatic_dynamic[name] + old_entry = copy.copy(mut_entry) + mut_entry |= entry + + # Do some logs (damn, I spend more code logging than I do actually doing + # the updates lol) + if is_update and old_entry.scalar != mut_entry.scalar: + log.debug( + "automatic dynamic int %s val %s != %s", + name, + entry.scalar, + old_entry.scalar, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "scalar", + "reason": "scalar change", + "cached": str(old_entry.scalar), + "new": str(entry.scalar), + }, + ) + if is_unspecialized_nn_module: + log.info( + "%s is converted to a symbolic integer. It is an attribute of a " + "user defined nn module class. If you wish to keep it static, you can " + "mark the nn module class as `torch._dynamo.mark_static`.", + name, + ) + + def log_tup( + tup_name: str, short_reason: str, long_reason: str, i: Optional[int] = None + ) -> None: + entry_tup = ( + getattr(entry, tup_name) if i is None else getattr(entry, tup_name)[i] + ) + old_entry_tup = ( + getattr(old_entry, tup_name) + if i is None + else getattr(old_entry, tup_name)[i] + ) + log.debug( + "automatic dynamic %s %s %s %s != %s", + tup_name, + name, + short_reason, + # NB: We used to only report len(...) here for dim mismatch + entry_tup, + old_entry_tup, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "all" if i is None else i, + "reason": long_reason, + "cached": str(old_entry_tup), + "new": str(entry_tup), + }, + ) + + if is_update and old_entry.size != mut_entry.size: + if isinstance(old_entry.size, tuple) and isinstance(entry.size, tuple): + if len(old_entry.size) != len(entry.size): + log_tup("size", "dim", "dimensionality change") + else: + for i in range(len(entry.size)): + if old_entry.size[i] != entry.size[i]: + log_tup("size", f"size({i})", "size change", i) + else: + log_tup("size", "other", "other") + + if is_update and old_entry.stride != mut_entry.stride: + if isinstance(old_entry.stride, tuple) and isinstance(entry.stride, tuple): + if len(old_entry.stride) != len(entry.stride): + log_tup("stride", "dim", "dimensionality change") + else: + for i in range(len(entry.stride)): + if old_entry.stride[i] != entry.stride[i]: + log_tup("stride", f"stride({i})", "stride change", i) + else: + log_tup("stride", "other", "other") + + return mut_entry + + +def process_automatic_dynamic( + tx: InstructionTranslator, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + if (st := tx.distributed_state) is None: + return update_automatic_dynamic( + tx, + name, + entry, + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + elif st.all_states is None: + # Preflight, always pretend as if it's static. The point here + # is we want to get through the preflight quickly, and static + # will run faster. The preexisting frame state will get + # applied anyway after we do compiler collectives. + # TODO: I'm not sure if we should just bong the entire pgo + # state here, it kind of depends if we're going to have other + # things that talk in compiler collective. Also, the PGO + # state, if we've already inferred something is automatic + # dynamic, will have lost the actual input sizes, which might + # be useful for debugging purposes (e.g., observing 0/1 + # specialization). Bonging the entire PGO state here would + # let us delete this logic here; the compiler collective + # would just directly update_automatic_dynamic + st.local_state.automatic_dynamic[name] = entry + return entry + else: + # Apply the updates. NB: all_states includes the local state + # too. + res = None + for sub_state in st.all_states: + if name in sub_state.automatic_dynamic: + res = update_automatic_dynamic( + tx, + name, + sub_state.automatic_dynamic[name], + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + assert res is not None + return res + + +def get_cache_key() -> Optional[str]: + # TODO: info versions of these logs that log only once + if torch._inductor.config.force_disable_caches: + warn_once( + "dynamo_pgo force disabled by torch._inductor.config.force_disable_caches" + ) + return None + + # NB: We always use global rank for keys, even though they are overkill + # for local only cache + rank = None + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + + tag = torch.compiler.config.cache_key_tag + + # NB: We namespace the cache keys so that only user-specified job id + # can alias with each other. + if (r := torch.compiler.config.job_id) is not None: + if r.startswith("mast:"): + raise ReservedWorkflowIdUserError( + "torch.compiler.config.job_id with prefix 'mast:' is reserved for " + "automatically generated job id associated with a specific MAST job " + "name and version." + ) + return f"{r}:{rank}:{tag}" + + if (name_version := torch._utils_internal.get_mast_job_name_version()) is not None: + mast_job_name, mast_job_version = name_version + return f"mast:{mast_job_name}:{mast_job_version}:{rank}:{tag}" + + return None + + +# This solely controls local PGO +def code_state_path(cache_key: str) -> Optional[str]: + if not torch._dynamo.config.automatic_dynamic_local_pgo: + log.debug("automatic_dynamic_local_pgo not enabled") + return None + + from torch._inductor.runtime.runtime_utils import cache_dir + + code_state_key = re.sub(r'[<>:"/\\|?*]', "_", f"code_state_{cache_key}.pkl") + return os.path.join(cache_dir(), "dynamo", code_state_key) + + +def should_use_remote_dynamo_pgo_cache() -> bool: + if torch._inductor.config.force_disable_caches: + return False + + if (r := torch._dynamo.config.automatic_dynamic_remote_pgo) is not None: + return r + + if not is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:dynamo_pgo_version" + ) + + +def get_remote_cache() -> Optional[RemoteCache[JsonDataTy]]: + from torch._inductor.remote_cache import create_cache + + if not should_use_remote_dynamo_pgo_cache(): + return None + + return create_cache( + "dynamo-pgo", + is_fbcode(), + "FbRemoteDynamoPGOCache", + "RemoteDynamoPGOCache", + ) + + +def render_code_state(cs: defaultdict[CodeId, CodeState]) -> str: + return "\n".join( + f"{k.filename}:{k.firstlineno}:{k.name}:\n" + + "\n".join( + f" {src}: {fs.render()}" for src, fs in v.automatic_dynamic.items() + ) + for k, v in cs.items() + ) + + +def get_code_state() -> defaultdict[CodeId, CodeState]: + global _CODE_STATE, _INIT_CODE_STATE + if _CODE_STATE is not None: + return _CODE_STATE + + # Initialize it (even if we don't look up profile) + _CODE_STATE = defaultdict(CodeState) + + cache_key = get_cache_key() + if cache_key is None: + return _CODE_STATE + + def hit(ty: str) -> defaultdict[CodeId, CodeState]: + global _INIT_CODE_STATE + assert isinstance(_CODE_STATE, defaultdict) + log.info("get_code_state %s hit %s, %d entries", path, ty, len(_CODE_STATE)) + trace_structured_artifact( + f"get_{ty}_code_state", + "string", + lambda: render_code_state(_CODE_STATE), + ) + set_feature_use("pgo", True) + _INIT_CODE_STATE = copy.deepcopy(_CODE_STATE) + return _CODE_STATE + + # Attempt local + path = code_state_path(cache_key) + if path is not None and os.path.exists(path): + with dynamo_timed( + name := "pgo.get_local_code_state", log_pt2_compile_event=True + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + # Read lock not necessary as we always write atomically write to + # the actual location + with open(path, "rb") as f: + try: + content = f.read() + _CODE_STATE = pickle.loads(content) + CompileEventLogger.pt2_compile(name, cache_size_bytes=f.tell()) + except Exception: + log.warning( + "get_code_state failed while reading %s", path, exc_info=True + ) + else: + CacheArtifactManager.record_artifact( + CacheArtifactType.PGO, cache_key, content + ) + return hit("local") + + # Attempt remote + remote_cache = get_remote_cache() + if remote_cache is not None: + with dynamo_timed( + name := "pgo.get_remote_code_state", log_pt2_compile_event=True + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + # TODO: I don't really understand why there's a JSON container format + try: + cache_data = remote_cache.get(cache_key) + except Exception: + log.warning( + "get_code_state failed remote read on %s", cache_key, exc_info=True + ) + else: + if cache_data is not None: + try: + assert isinstance(cache_data, dict) + data = cache_data["data"] + assert isinstance(data, str) + payload = base64.b64decode(data) + CompileEventLogger.pt2_compile( + name, cache_size_bytes=len(payload) + ) + _CODE_STATE = pickle.loads(payload) + except Exception: + log.warning( + "get_code_state failed parsing remote result on %s", + cache_key, + exc_info=True, + ) + else: + CacheArtifactManager.record_artifact( + CacheArtifactType.PGO, cache_key, payload + ) + return hit("remote") + else: + log.info("get_code_state remote miss on %s", cache_key) + + log.info("get_code_state using default") + + assert _CODE_STATE is not None + return _CODE_STATE + + +def put_code_state() -> None: + if _CODE_STATE is None: + log.info("put_code_state: never initialized, will not write") + return + + if _CODE_STATE == _INIT_CODE_STATE: + log.info("put_code_state: no change, skipping") + return + + cache_key = get_cache_key() + if cache_key is None: + log.info("put_code_state: no cache key, skipping") + return + + put_local_code_state(cache_key) + put_remote_code_state(cache_key) + + +def write_local_impl(cache_key: str, pickled_code: bytes) -> Optional[tuple[str, int]]: + path = code_state_path(cache_key) + + if path is None: + return None + + # If the user isn't misusing our API, we should have exclusive access to + # this directory. But it's not too hard + + tmp_path = path + ".tmp" + lock_path = path + ".lock" + # We /mostly/ don't need the lock but the tmp file could be clobbered + # TODO: use a safe tempfile create to eliminate lock + from torch.utils._filelock import FileLock + + os.makedirs(os.path.dirname(path), exist_ok=True) + + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + with open(tmp_path, "wb") as f: + f.write(pickled_code) + size = f.tell() + os.replace(tmp_path, path) + return path, size + + +def put_local_code_state(cache_key: str) -> None: + with dynamo_timed(name := "pgo.put_local_code_state", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + assert _CODE_STATE is not None + + pickled_code = pickle.dumps(_CODE_STATE) + + CacheArtifactManager.record_artifact( + CacheArtifactType.PGO, cache_key, pickled_code + ) + + meta = write_local_impl(cache_key, pickled_code) + if meta is None: + log.info("put_code_state: local cache disabled") + return + path, size = meta + + CompileEventLogger.pt2_compile(name, cache_size_bytes=size) + log.info("put_code_state: wrote local %s, %d entries", path, len(_CODE_STATE)) + trace_structured_artifact( + "put_local_code_state", + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +def put_remote_code_state(cache_key: str) -> None: + with dynamo_timed(name := "pgo.put_remote_code_state", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + assert _CODE_STATE is not None + + remote_cache = get_remote_cache() + + if remote_cache is None: + log.info("put_code_state: remote cache disabled") + return + + content = pickle.dumps(_CODE_STATE) + CompileEventLogger.pt2_compile(name, cache_size_bytes=len(content)) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + } + remote_cache.put(cache_key, cache_data) + log.info( + "put_code_state: wrote remote %s, %d entries", cache_key, len(_CODE_STATE) + ) + # TODO: don't log this multiple times + trace_structured_artifact( + "put_remote_code_state", + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +# NB: this does NOT reset the cached code state on disk +def reset_code_state() -> None: + global _CODE_STATE, _INIT_CODE_STATE + _CODE_STATE = None + _INIT_CODE_STATE = None diff --git a/shared/package-files/f8/f89b8aa1bb37bd5a59b014caa19c64162cb0bcbbfb34e018bbc1fcba922f8d2b/constraint_transformation.cpython-311.pyc b/shared/package-files/f8/f89b8aa1bb37bd5a59b014caa19c64162cb0bcbbfb34e018bbc1fcba922f8d2b/constraint_transformation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56294979c054d2c1c0472366c82edbdc69f6c70 Binary files /dev/null and b/shared/package-files/f8/f89b8aa1bb37bd5a59b014caa19c64162cb0bcbbfb34e018bbc1fcba922f8d2b/constraint_transformation.cpython-311.pyc differ diff --git a/shared/package-files/f8/f8fe49fb6502c33a434c4588e4f53f4535fe414d808ded3d8a8f7b22d1584c8d/test_missing.cpython-311.pyc b/shared/package-files/f8/f8fe49fb6502c33a434c4588e4f53f4535fe414d808ded3d8a8f7b22d1584c8d/test_missing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c98a9f01a307b61099be21eb4091bbce747e9a34 Binary files /dev/null and b/shared/package-files/f8/f8fe49fb6502c33a434c4588e4f53f4535fe414d808ded3d8a8f7b22d1584c8d/test_missing.cpython-311.pyc differ