Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- shared/package-files/18/1803d258c010f0c5dd395c23de2a2730bbc6f16fcdf45a2513a7129d4dfdb923/test_fillna.py +932 -0
- shared/package-files/18/180f0539d35295855bfb29426e4bc3975151a2d08857ed009d3dd2441c1de747/union_find.cpython-311.pyc +0 -0
- shared/package-files/18/181a71d8310cd917e57afd1c022a6fbf3651d6008e4bf6d637cbf34970f93912/take_along_dim_native.h +22 -0
- shared/package-files/18/1822d1c4023fdcfc260e63a5a36617872615921327c5a6341ec75a80535d459f/nll_loss_nd.h +48 -0
- shared/package-files/18/182d24026129d741f141943e1883646af15d3ba8fe6886b83accf6077c8afad6/conv.cpython-311.pyc +0 -0
- shared/package-files/18/1836c8c8830b13005f7e086e2d1f4ecef3818fc59a558065981bbaf221d27465/METADATA +35 -0
- shared/package-files/18/1841ca6850b8f13de8fbf4a61f8f3ae06bcacb1d4881b542e884883d5971edae/core.py +289 -0
- shared/package-files/18/184be769d39367769f56b6cde56139d8e8423fc83330823f00de281d0c6f129a/algorithms.py +180 -0
- shared/package-files/18/1855a71ae746e0bd92c9d8088768f15409d6c10fe017b666c406c5d90ca0473e/exceptions.cpython-311.pyc +0 -0
- shared/package-files/18/1858f22f67ad031bd5337abb36114419c5d2e60c8a8fc5736ea71b2b3a6a6ce9/test_dist.py +278 -0
- shared/package-files/18/18710c3cbccb74d874bc184bf77629cbfc5f77d6a35b873841c1a6f488cdf7cc/vcfconcat.c.pysam.c +1131 -0
- shared/package-files/18/1895dbf616c666a60e0d82ce37cac9f0d6dcb4f697d05db990675842610f3309/_python_dispatcher.py +182 -0
- shared/package-files/18/18997fb64e74e3ee39580491803bf92fd48372c763b6c651523246ba4672ab17/masked_select_native.h +24 -0
- shared/package-files/18/18a3580068ace53b220c9308bb42fa6c7dbf7083a9583be2470c427cf37d3eff/test_csv.py +2052 -0
- shared/package-files/18/18b3e34f27c92aa23f3d71876e7c0c31f0af84aee359a94da4d3a0dc4583463f/column_stack.h +40 -0
- shared/package-files/18/18b4a406131fbf52f475e9e6f0dca72a5995c70c6ededd43cb4c84e1555114d1/_embedding_bag_per_sample_weights_backward_native.h +23 -0
- shared/package-files/18/18b5dbc12be2b6c4209b1b4eb1b814b780d39144676f69345feefe48db035bd2/greedy_coloring.py +565 -0
- shared/package-files/18/18c8715d395075770237999a98fba25b0788af2a664cc8e1d5ea7c9076e55189/subclass_utils.cpython-311.pyc +0 -0
- shared/package-files/18/18c997e01eea439f7cf5fd8a0a2d40ab9081e5ce72777c412e45684da175b9b3/view_as_native.h +21 -0
- shared/package-files/18/18cba8485d6fa8a0ecfdedc927b63496916b9de5cc64b664fea202e5de90e545/dimensions.py +590 -0
- shared/package-files/18/18ce7de1e85300b021786ad70400ed8c62914d4886d3370b4a4cac7745d38d93/test_take.cpython-311.pyc +0 -0
- shared/package-files/18/18d9d81470e83b772439193c414f5e9ede0a99af0f3de750e8f642c9365dadf8/freezing_patterns.py +236 -0
- shared/package-files/18/18d9eacb499beb23cc6b7ce9184cf3da9eaec58ed5b686cfb705226a585f6044/testutil.py +357 -0
- shared/package-files/18/18fa735d24cc2205c4ac7ae5f696c3311396aa789cedfc5bd94046dcdc99e8c7/base.cpython-311.pyc +0 -0
- shared/package-files/1f/1f020c7c5914419cd809acc29f165377752a4226c2796c873cb925bd2b245651/sparse_mask_ops.h +40 -0
- shared/package-files/1f/1f09cbccf792216607230db0184b8b158c935cdabc76bd767749a0ed1a2f2017/topk_ops.h +40 -0
- shared/package-files/1f/1f0ea79d563a1c92738d97ec6d2864ef176324f73f9ebc151db2ecd3918c227e/common_op_utils.cpython-311.pyc +0 -0
- shared/package-files/1f/1f0ed3e5e6f1fcbfcda49fe73efd0fe8e0597846be9e19c52f47e1825d85fe9d/privateuse1_observer.h +46 -0
- shared/package-files/1f/1f127a18859cddbeae01958d878e6878f5e540b01d5fd2a6bb73c1c803af961e/__init__.py +44 -0
- shared/package-files/1f/1f135a9505b4371e447fe966c6d681fb6101e8ee951615f1319ede909c195728/digraph.cpython-311.pyc +0 -0
- shared/package-files/1f/1f141c8a5056c8578fd07d521b52006d28eed0e71aba4b4bdcdef6aedb5e11c3/graph_utils.h +23 -0
- shared/package-files/1f/1f150d886687fb5e2cf3f5d6c194e760a81f59b3bf615bc9f5c410b81e14339d/bilinear_compositeimplicitautograd_dispatch.h +23 -0
- shared/package-files/1f/1f167188f79a88bbf5d12ee265a5ab3ee2f0dbcb9cc2402f6ec107b9a1699fa1/max_pool3d_ops.h +29 -0
- shared/package-files/1f/1f18dce117e0cdaa54300973757689ec906060def79a91580c672507323ee435/_batch_norm_no_update_native.h +22 -0
- shared/package-files/1f/1f2c567ff74b7c1346c7b73e6210d45487fd3323c85bc4f34e34786a05e2adad/mish_ops.h +51 -0
- shared/package-files/1f/1f393973c495fa46e0e3bc0128b8b46077f582b0eec93a7a63ecd2e45109a527/random_matrix_models.cpython-311.pyc +0 -0
- shared/package-files/1f/1f40839461404ba18def05e0f92f5ae2653720a209bddd9942bcb1a56cc2e511/margin_ranking_loss_ops.h +29 -0
- shared/package-files/1f/1f40c65df3feb76ad084f1011fce46f4049bf92dcbff011e318bb0c466fbe346/rocm_kernel.cpython-311.pyc +0 -0
- shared/package-files/1f/1f44d7c30f0c69746d384a26a3e1e7e35123f7ac4aff623eb71c6a0ff0f49bbb/sym_size_native.h +21 -0
- shared/package-files/1f/1f4ccd493605c7b86f59ea081e80d2e3bdb4da7ec978c5c86d220be278cefb1c/utils.cpython-311.pyc +0 -0
- shared/package-files/1f/1f4e913f22201e2bfcbce280e625a9c162d16be13f68dd299b6e02d7ecd351d6/max_pool1d_ops.h +29 -0
- shared/package-files/1f/1f5065576692ea166941002500e21d1f951debccdac934079dd0c4d3e12890ff/_values_copy.h +40 -0
- shared/package-files/1f/1f5661ce49b51b7bf60235879541d756f2ccc241416a71e4a5a741ed042db8f3/decompose_mem_bound_mm.cpython-311.pyc +0 -0
- shared/package-files/1f/1f5a43dd31e0534906cd2383887121435b94aee8666217e980f77f23b92a85fe/uniform.h +40 -0
- shared/package-files/1f/1f5c7ca99426aa0460f84d3a03f7d4a049b843f5e9f1c56052c2078bb43fe6bb/_entry_points.cpython-311.pyc +0 -0
- shared/package-files/1f/1f5dcb75e3d3b2bede49e0aba78bf5dcbed3dd810ab1011c9d342fbc3f566d50/quasirandom.py +217 -0
- shared/package-files/1f/1f5ef44e371999fc2d2c3e17ee0ed00d82bda1594ea98c98e8f9e68cb8e3bdc3/test_codegen_julia.cpython-311.pyc +0 -0
- shared/package-files/1f/1f5fc20bebef01a4b6eb2b385ec4c590c813c544dc8808dd8ecc238b3922b2f4/device_launch_parameters.h +118 -0
- shared/package-files/1f/1f636095668cdc0d645d1b201b5ab162d54c4195d3253fd18853152e5f66c6f0/custom_ops.cpython-311.pyc +0 -0
- shared/package-files/1f/1f68d9683b0327f8bd1f64b05a9c2e15e97c06b67dc472aebe1f83400596f654/entry_points.txt +2 -0
shared/package-files/18/1803d258c010f0c5dd395c23de2a2730bbc6f16fcdf45a2513a7129d4dfdb923/test_fillna.py
ADDED
|
@@ -0,0 +1,932 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from pandas._config import using_pyarrow_string_dtype
|
| 5 |
+
|
| 6 |
+
import pandas.util._test_decorators as td
|
| 7 |
+
|
| 8 |
+
from pandas import (
|
| 9 |
+
Categorical,
|
| 10 |
+
DataFrame,
|
| 11 |
+
DatetimeIndex,
|
| 12 |
+
NaT,
|
| 13 |
+
PeriodIndex,
|
| 14 |
+
Series,
|
| 15 |
+
TimedeltaIndex,
|
| 16 |
+
Timestamp,
|
| 17 |
+
date_range,
|
| 18 |
+
to_datetime,
|
| 19 |
+
)
|
| 20 |
+
import pandas._testing as tm
|
| 21 |
+
from pandas.tests.frame.common import _check_mixed_float
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestFillNA:
|
| 25 |
+
def test_fillna_dict_inplace_nonunique_columns(
|
| 26 |
+
self, using_copy_on_write, warn_copy_on_write
|
| 27 |
+
):
|
| 28 |
+
df = DataFrame(
|
| 29 |
+
{"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]}
|
| 30 |
+
)
|
| 31 |
+
df.columns = ["A", "A", "A"]
|
| 32 |
+
orig = df[:]
|
| 33 |
+
|
| 34 |
+
# TODO(CoW-warn) better warning message
|
| 35 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 36 |
+
df.fillna({"A": 2}, inplace=True)
|
| 37 |
+
# The first and third columns can be set inplace, while the second cannot.
|
| 38 |
+
|
| 39 |
+
expected = DataFrame(
|
| 40 |
+
{"A": [2.0] * 3, "B": [2, Timestamp(1), 2], "C": [2, "foo", 2]}
|
| 41 |
+
)
|
| 42 |
+
expected.columns = ["A", "A", "A"]
|
| 43 |
+
tm.assert_frame_equal(df, expected)
|
| 44 |
+
|
| 45 |
+
# TODO: what's the expected/desired behavior with CoW?
|
| 46 |
+
if not using_copy_on_write:
|
| 47 |
+
assert tm.shares_memory(df.iloc[:, 0], orig.iloc[:, 0])
|
| 48 |
+
assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1])
|
| 49 |
+
if not using_copy_on_write:
|
| 50 |
+
assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2])
|
| 51 |
+
|
| 52 |
+
@td.skip_array_manager_not_yet_implemented
|
| 53 |
+
def test_fillna_on_column_view(self, using_copy_on_write):
|
| 54 |
+
# GH#46149 avoid unnecessary copies
|
| 55 |
+
arr = np.full((40, 50), np.nan)
|
| 56 |
+
df = DataFrame(arr, copy=False)
|
| 57 |
+
|
| 58 |
+
if using_copy_on_write:
|
| 59 |
+
with tm.raises_chained_assignment_error():
|
| 60 |
+
df[0].fillna(-1, inplace=True)
|
| 61 |
+
assert np.isnan(arr[:, 0]).all()
|
| 62 |
+
else:
|
| 63 |
+
with tm.assert_produces_warning(FutureWarning, match="inplace method"):
|
| 64 |
+
df[0].fillna(-1, inplace=True)
|
| 65 |
+
assert (arr[:, 0] == -1).all()
|
| 66 |
+
|
| 67 |
+
# i.e. we didn't create a new 49-column block
|
| 68 |
+
assert len(df._mgr.arrays) == 1
|
| 69 |
+
assert np.shares_memory(df.values, arr)
|
| 70 |
+
|
| 71 |
+
def test_fillna_datetime(self, datetime_frame):
|
| 72 |
+
tf = datetime_frame
|
| 73 |
+
tf.loc[tf.index[:5], "A"] = np.nan
|
| 74 |
+
tf.loc[tf.index[-5:], "A"] = np.nan
|
| 75 |
+
|
| 76 |
+
zero_filled = datetime_frame.fillna(0)
|
| 77 |
+
assert (zero_filled.loc[zero_filled.index[:5], "A"] == 0).all()
|
| 78 |
+
|
| 79 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 80 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 81 |
+
padded = datetime_frame.fillna(method="pad")
|
| 82 |
+
assert np.isnan(padded.loc[padded.index[:5], "A"]).all()
|
| 83 |
+
assert (
|
| 84 |
+
padded.loc[padded.index[-5:], "A"] == padded.loc[padded.index[-5], "A"]
|
| 85 |
+
).all()
|
| 86 |
+
|
| 87 |
+
msg = "Must specify a fill 'value' or 'method'"
|
| 88 |
+
with pytest.raises(ValueError, match=msg):
|
| 89 |
+
datetime_frame.fillna()
|
| 90 |
+
msg = "Cannot specify both 'value' and 'method'"
|
| 91 |
+
with pytest.raises(ValueError, match=msg):
|
| 92 |
+
datetime_frame.fillna(5, method="ffill")
|
| 93 |
+
|
| 94 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="can't fill 0 in string")
|
| 95 |
+
def test_fillna_mixed_type(self, float_string_frame):
|
| 96 |
+
mf = float_string_frame
|
| 97 |
+
mf.loc[mf.index[5:20], "foo"] = np.nan
|
| 98 |
+
mf.loc[mf.index[-10:], "A"] = np.nan
|
| 99 |
+
# TODO: make stronger assertion here, GH 25640
|
| 100 |
+
mf.fillna(value=0)
|
| 101 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 102 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 103 |
+
mf.fillna(method="pad")
|
| 104 |
+
|
| 105 |
+
def test_fillna_mixed_float(self, mixed_float_frame):
|
| 106 |
+
# mixed numeric (but no float16)
|
| 107 |
+
mf = mixed_float_frame.reindex(columns=["A", "B", "D"])
|
| 108 |
+
mf.loc[mf.index[-10:], "A"] = np.nan
|
| 109 |
+
result = mf.fillna(value=0)
|
| 110 |
+
_check_mixed_float(result, dtype={"C": None})
|
| 111 |
+
|
| 112 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 113 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 114 |
+
result = mf.fillna(method="pad")
|
| 115 |
+
_check_mixed_float(result, dtype={"C": None})
|
| 116 |
+
|
| 117 |
+
def test_fillna_empty(self, using_copy_on_write):
|
| 118 |
+
if using_copy_on_write:
|
| 119 |
+
pytest.skip("condition is unnecessary complex and is deprecated anyway")
|
| 120 |
+
# empty frame (GH#2778)
|
| 121 |
+
df = DataFrame(columns=["x"])
|
| 122 |
+
for m in ["pad", "backfill"]:
|
| 123 |
+
msg = "Series.fillna with 'method' is deprecated"
|
| 124 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 125 |
+
df.x.fillna(method=m, inplace=True)
|
| 126 |
+
df.x.fillna(method=m)
|
| 127 |
+
|
| 128 |
+
def test_fillna_different_dtype(self, using_infer_string):
|
| 129 |
+
# with different dtype (GH#3386)
|
| 130 |
+
df = DataFrame(
|
| 131 |
+
[["a", "a", np.nan, "a"], ["b", "b", np.nan, "b"], ["c", "c", np.nan, "c"]]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
if using_infer_string:
|
| 135 |
+
with tm.assert_produces_warning(FutureWarning, match="Downcasting"):
|
| 136 |
+
result = df.fillna({2: "foo"})
|
| 137 |
+
else:
|
| 138 |
+
result = df.fillna({2: "foo"})
|
| 139 |
+
expected = DataFrame(
|
| 140 |
+
[["a", "a", "foo", "a"], ["b", "b", "foo", "b"], ["c", "c", "foo", "c"]]
|
| 141 |
+
)
|
| 142 |
+
tm.assert_frame_equal(result, expected)
|
| 143 |
+
|
| 144 |
+
if using_infer_string:
|
| 145 |
+
with tm.assert_produces_warning(FutureWarning, match="Downcasting"):
|
| 146 |
+
return_value = df.fillna({2: "foo"}, inplace=True)
|
| 147 |
+
else:
|
| 148 |
+
return_value = df.fillna({2: "foo"}, inplace=True)
|
| 149 |
+
tm.assert_frame_equal(df, expected)
|
| 150 |
+
assert return_value is None
|
| 151 |
+
|
| 152 |
+
def test_fillna_limit_and_value(self):
|
| 153 |
+
# limit and value
|
| 154 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 3)))
|
| 155 |
+
df.iloc[2:7, 0] = np.nan
|
| 156 |
+
df.iloc[3:5, 2] = np.nan
|
| 157 |
+
|
| 158 |
+
expected = df.copy()
|
| 159 |
+
expected.iloc[2, 0] = 999
|
| 160 |
+
expected.iloc[3, 2] = 999
|
| 161 |
+
result = df.fillna(999, limit=1)
|
| 162 |
+
tm.assert_frame_equal(result, expected)
|
| 163 |
+
|
| 164 |
+
def test_fillna_datelike(self):
|
| 165 |
+
# with datelike
|
| 166 |
+
# GH#6344
|
| 167 |
+
df = DataFrame(
|
| 168 |
+
{
|
| 169 |
+
"Date": [NaT, Timestamp("2014-1-1")],
|
| 170 |
+
"Date2": [Timestamp("2013-1-1"), NaT],
|
| 171 |
+
}
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
expected = df.copy()
|
| 175 |
+
expected["Date"] = expected["Date"].fillna(df.loc[df.index[0], "Date2"])
|
| 176 |
+
result = df.fillna(value={"Date": df["Date2"]})
|
| 177 |
+
tm.assert_frame_equal(result, expected)
|
| 178 |
+
|
| 179 |
+
def test_fillna_tzaware(self):
|
| 180 |
+
# with timezone
|
| 181 |
+
# GH#15855
|
| 182 |
+
df = DataFrame({"A": [Timestamp("2012-11-11 00:00:00+01:00"), NaT]})
|
| 183 |
+
exp = DataFrame(
|
| 184 |
+
{
|
| 185 |
+
"A": [
|
| 186 |
+
Timestamp("2012-11-11 00:00:00+01:00"),
|
| 187 |
+
Timestamp("2012-11-11 00:00:00+01:00"),
|
| 188 |
+
]
|
| 189 |
+
}
|
| 190 |
+
)
|
| 191 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 192 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 193 |
+
res = df.fillna(method="pad")
|
| 194 |
+
tm.assert_frame_equal(res, exp)
|
| 195 |
+
|
| 196 |
+
df = DataFrame({"A": [NaT, Timestamp("2012-11-11 00:00:00+01:00")]})
|
| 197 |
+
exp = DataFrame(
|
| 198 |
+
{
|
| 199 |
+
"A": [
|
| 200 |
+
Timestamp("2012-11-11 00:00:00+01:00"),
|
| 201 |
+
Timestamp("2012-11-11 00:00:00+01:00"),
|
| 202 |
+
]
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 206 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 207 |
+
res = df.fillna(method="bfill")
|
| 208 |
+
tm.assert_frame_equal(res, exp)
|
| 209 |
+
|
| 210 |
+
def test_fillna_tzaware_different_column(self):
|
| 211 |
+
# with timezone in another column
|
| 212 |
+
# GH#15522
|
| 213 |
+
df = DataFrame(
|
| 214 |
+
{
|
| 215 |
+
"A": date_range("20130101", periods=4, tz="US/Eastern"),
|
| 216 |
+
"B": [1, 2, np.nan, np.nan],
|
| 217 |
+
}
|
| 218 |
+
)
|
| 219 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 220 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 221 |
+
result = df.fillna(method="pad")
|
| 222 |
+
expected = DataFrame(
|
| 223 |
+
{
|
| 224 |
+
"A": date_range("20130101", periods=4, tz="US/Eastern"),
|
| 225 |
+
"B": [1.0, 2.0, 2.0, 2.0],
|
| 226 |
+
}
|
| 227 |
+
)
|
| 228 |
+
tm.assert_frame_equal(result, expected)
|
| 229 |
+
|
| 230 |
+
def test_na_actions_categorical(self):
|
| 231 |
+
cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3])
|
| 232 |
+
vals = ["a", "b", np.nan, "d"]
|
| 233 |
+
df = DataFrame({"cats": cat, "vals": vals})
|
| 234 |
+
cat2 = Categorical([1, 2, 3, 3], categories=[1, 2, 3])
|
| 235 |
+
vals2 = ["a", "b", "b", "d"]
|
| 236 |
+
df_exp_fill = DataFrame({"cats": cat2, "vals": vals2})
|
| 237 |
+
cat3 = Categorical([1, 2, 3], categories=[1, 2, 3])
|
| 238 |
+
vals3 = ["a", "b", np.nan]
|
| 239 |
+
df_exp_drop_cats = DataFrame({"cats": cat3, "vals": vals3})
|
| 240 |
+
cat4 = Categorical([1, 2], categories=[1, 2, 3])
|
| 241 |
+
vals4 = ["a", "b"]
|
| 242 |
+
df_exp_drop_all = DataFrame({"cats": cat4, "vals": vals4})
|
| 243 |
+
|
| 244 |
+
# fillna
|
| 245 |
+
res = df.fillna(value={"cats": 3, "vals": "b"})
|
| 246 |
+
tm.assert_frame_equal(res, df_exp_fill)
|
| 247 |
+
|
| 248 |
+
msg = "Cannot setitem on a Categorical with a new category"
|
| 249 |
+
with pytest.raises(TypeError, match=msg):
|
| 250 |
+
df.fillna(value={"cats": 4, "vals": "c"})
|
| 251 |
+
|
| 252 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 253 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 254 |
+
res = df.fillna(method="pad")
|
| 255 |
+
tm.assert_frame_equal(res, df_exp_fill)
|
| 256 |
+
|
| 257 |
+
# dropna
|
| 258 |
+
res = df.dropna(subset=["cats"])
|
| 259 |
+
tm.assert_frame_equal(res, df_exp_drop_cats)
|
| 260 |
+
|
| 261 |
+
res = df.dropna()
|
| 262 |
+
tm.assert_frame_equal(res, df_exp_drop_all)
|
| 263 |
+
|
| 264 |
+
# make sure that fillna takes missing values into account
|
| 265 |
+
c = Categorical([np.nan, "b", np.nan], categories=["a", "b"])
|
| 266 |
+
df = DataFrame({"cats": c, "vals": [1, 2, 3]})
|
| 267 |
+
|
| 268 |
+
cat_exp = Categorical(["a", "b", "a"], categories=["a", "b"])
|
| 269 |
+
df_exp = DataFrame({"cats": cat_exp, "vals": [1, 2, 3]})
|
| 270 |
+
|
| 271 |
+
res = df.fillna("a")
|
| 272 |
+
tm.assert_frame_equal(res, df_exp)
|
| 273 |
+
|
| 274 |
+
def test_fillna_categorical_nan(self):
|
| 275 |
+
# GH#14021
|
| 276 |
+
# np.nan should always be a valid filler
|
| 277 |
+
cat = Categorical([np.nan, 2, np.nan])
|
| 278 |
+
val = Categorical([np.nan, np.nan, np.nan])
|
| 279 |
+
df = DataFrame({"cats": cat, "vals": val})
|
| 280 |
+
|
| 281 |
+
# GH#32950 df.median() is poorly behaved because there is no
|
| 282 |
+
# Categorical.median
|
| 283 |
+
median = Series({"cats": 2.0, "vals": np.nan})
|
| 284 |
+
|
| 285 |
+
res = df.fillna(median)
|
| 286 |
+
v_exp = [np.nan, np.nan, np.nan]
|
| 287 |
+
df_exp = DataFrame({"cats": [2, 2, 2], "vals": v_exp}, dtype="category")
|
| 288 |
+
tm.assert_frame_equal(res, df_exp)
|
| 289 |
+
|
| 290 |
+
result = df.cats.fillna(np.nan)
|
| 291 |
+
tm.assert_series_equal(result, df.cats)
|
| 292 |
+
|
| 293 |
+
result = df.vals.fillna(np.nan)
|
| 294 |
+
tm.assert_series_equal(result, df.vals)
|
| 295 |
+
|
| 296 |
+
idx = DatetimeIndex(
|
| 297 |
+
["2011-01-01 09:00", "2016-01-01 23:45", "2011-01-01 09:00", NaT, NaT]
|
| 298 |
+
)
|
| 299 |
+
df = DataFrame({"a": Categorical(idx)})
|
| 300 |
+
tm.assert_frame_equal(df.fillna(value=NaT), df)
|
| 301 |
+
|
| 302 |
+
idx = PeriodIndex(["2011-01", "2011-01", "2011-01", NaT, NaT], freq="M")
|
| 303 |
+
df = DataFrame({"a": Categorical(idx)})
|
| 304 |
+
tm.assert_frame_equal(df.fillna(value=NaT), df)
|
| 305 |
+
|
| 306 |
+
idx = TimedeltaIndex(["1 days", "2 days", "1 days", NaT, NaT])
|
| 307 |
+
df = DataFrame({"a": Categorical(idx)})
|
| 308 |
+
tm.assert_frame_equal(df.fillna(value=NaT), df)
|
| 309 |
+
|
| 310 |
+
def test_fillna_downcast(self):
|
| 311 |
+
# GH#15277
|
| 312 |
+
# infer int64 from float64
|
| 313 |
+
df = DataFrame({"a": [1.0, np.nan]})
|
| 314 |
+
msg = "The 'downcast' keyword in fillna is deprecated"
|
| 315 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 316 |
+
result = df.fillna(0, downcast="infer")
|
| 317 |
+
expected = DataFrame({"a": [1, 0]})
|
| 318 |
+
tm.assert_frame_equal(result, expected)
|
| 319 |
+
|
| 320 |
+
# infer int64 from float64 when fillna value is a dict
|
| 321 |
+
df = DataFrame({"a": [1.0, np.nan]})
|
| 322 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 323 |
+
result = df.fillna({"a": 0}, downcast="infer")
|
| 324 |
+
expected = DataFrame({"a": [1, 0]})
|
| 325 |
+
tm.assert_frame_equal(result, expected)
|
| 326 |
+
|
| 327 |
+
def test_fillna_downcast_false(self, frame_or_series):
|
| 328 |
+
# GH#45603 preserve object dtype with downcast=False
|
| 329 |
+
obj = frame_or_series([1, 2, 3], dtype="object")
|
| 330 |
+
msg = "The 'downcast' keyword in fillna"
|
| 331 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 332 |
+
result = obj.fillna("", downcast=False)
|
| 333 |
+
tm.assert_equal(result, obj)
|
| 334 |
+
|
| 335 |
+
def test_fillna_downcast_noop(self, frame_or_series):
|
| 336 |
+
# GH#45423
|
| 337 |
+
# Two relevant paths:
|
| 338 |
+
# 1) not _can_hold_na (e.g. integer)
|
| 339 |
+
# 2) _can_hold_na + noop + not can_hold_element
|
| 340 |
+
|
| 341 |
+
obj = frame_or_series([1, 2, 3], dtype=np.int64)
|
| 342 |
+
|
| 343 |
+
msg = "The 'downcast' keyword in fillna"
|
| 344 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 345 |
+
# GH#40988
|
| 346 |
+
res = obj.fillna("foo", downcast=np.dtype(np.int32))
|
| 347 |
+
expected = obj.astype(np.int32)
|
| 348 |
+
tm.assert_equal(res, expected)
|
| 349 |
+
|
| 350 |
+
obj2 = obj.astype(np.float64)
|
| 351 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 352 |
+
res2 = obj2.fillna("foo", downcast="infer")
|
| 353 |
+
expected2 = obj # get back int64
|
| 354 |
+
tm.assert_equal(res2, expected2)
|
| 355 |
+
|
| 356 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 357 |
+
# GH#40988
|
| 358 |
+
res3 = obj2.fillna("foo", downcast=np.dtype(np.int32))
|
| 359 |
+
tm.assert_equal(res3, expected)
|
| 360 |
+
|
| 361 |
+
@pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]])
|
| 362 |
+
def test_fillna_dictlike_value_duplicate_colnames(self, columns):
|
| 363 |
+
# GH#43476
|
| 364 |
+
df = DataFrame(np.nan, index=[0, 1], columns=columns)
|
| 365 |
+
with tm.assert_produces_warning(None):
|
| 366 |
+
result = df.fillna({"A": 0})
|
| 367 |
+
|
| 368 |
+
expected = df.copy()
|
| 369 |
+
expected["A"] = 0.0
|
| 370 |
+
tm.assert_frame_equal(result, expected)
|
| 371 |
+
|
| 372 |
+
def test_fillna_dtype_conversion(self, using_infer_string):
|
| 373 |
+
# make sure that fillna on an empty frame works
|
| 374 |
+
df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5])
|
| 375 |
+
result = df.dtypes
|
| 376 |
+
expected = Series([np.dtype("object")] * 5, index=[1, 2, 3, 4, 5])
|
| 377 |
+
tm.assert_series_equal(result, expected)
|
| 378 |
+
|
| 379 |
+
msg = "Downcasting object dtype arrays"
|
| 380 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 381 |
+
result = df.fillna(1)
|
| 382 |
+
expected = DataFrame(1, index=["A", "B", "C"], columns=[1, 2, 3, 4, 5])
|
| 383 |
+
tm.assert_frame_equal(result, expected)
|
| 384 |
+
|
| 385 |
+
# empty block
|
| 386 |
+
df = DataFrame(index=range(3), columns=["A", "B"], dtype="float64")
|
| 387 |
+
if using_infer_string:
|
| 388 |
+
with tm.assert_produces_warning(FutureWarning, match="Downcasting"):
|
| 389 |
+
result = df.fillna("nan")
|
| 390 |
+
else:
|
| 391 |
+
result = df.fillna("nan")
|
| 392 |
+
expected = DataFrame("nan", index=range(3), columns=["A", "B"])
|
| 393 |
+
tm.assert_frame_equal(result, expected)
|
| 394 |
+
|
| 395 |
+
@pytest.mark.parametrize("val", ["", 1, np.nan, 1.0])
|
| 396 |
+
def test_fillna_dtype_conversion_equiv_replace(self, val):
|
| 397 |
+
df = DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]})
|
| 398 |
+
expected = df.replace(np.nan, val)
|
| 399 |
+
result = df.fillna(val)
|
| 400 |
+
tm.assert_frame_equal(result, expected)
|
| 401 |
+
|
| 402 |
+
def test_fillna_datetime_columns(self):
|
| 403 |
+
# GH#7095
|
| 404 |
+
df = DataFrame(
|
| 405 |
+
{
|
| 406 |
+
"A": [-1, -2, np.nan],
|
| 407 |
+
"B": date_range("20130101", periods=3),
|
| 408 |
+
"C": ["foo", "bar", None],
|
| 409 |
+
"D": ["foo2", "bar2", None],
|
| 410 |
+
},
|
| 411 |
+
index=date_range("20130110", periods=3),
|
| 412 |
+
)
|
| 413 |
+
result = df.fillna("?")
|
| 414 |
+
expected = DataFrame(
|
| 415 |
+
{
|
| 416 |
+
"A": [-1, -2, "?"],
|
| 417 |
+
"B": date_range("20130101", periods=3),
|
| 418 |
+
"C": ["foo", "bar", "?"],
|
| 419 |
+
"D": ["foo2", "bar2", "?"],
|
| 420 |
+
},
|
| 421 |
+
index=date_range("20130110", periods=3),
|
| 422 |
+
)
|
| 423 |
+
tm.assert_frame_equal(result, expected)
|
| 424 |
+
|
| 425 |
+
df = DataFrame(
|
| 426 |
+
{
|
| 427 |
+
"A": [-1, -2, np.nan],
|
| 428 |
+
"B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), NaT],
|
| 429 |
+
"C": ["foo", "bar", None],
|
| 430 |
+
"D": ["foo2", "bar2", None],
|
| 431 |
+
},
|
| 432 |
+
index=date_range("20130110", periods=3),
|
| 433 |
+
)
|
| 434 |
+
result = df.fillna("?")
|
| 435 |
+
expected = DataFrame(
|
| 436 |
+
{
|
| 437 |
+
"A": [-1, -2, "?"],
|
| 438 |
+
"B": [Timestamp("2013-01-01"), Timestamp("2013-01-02"), "?"],
|
| 439 |
+
"C": ["foo", "bar", "?"],
|
| 440 |
+
"D": ["foo2", "bar2", "?"],
|
| 441 |
+
},
|
| 442 |
+
index=date_range("20130110", periods=3),
|
| 443 |
+
)
|
| 444 |
+
tm.assert_frame_equal(result, expected)
|
| 445 |
+
|
| 446 |
+
def test_ffill(self, datetime_frame):
|
| 447 |
+
datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan
|
| 448 |
+
datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan
|
| 449 |
+
|
| 450 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 451 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 452 |
+
alt = datetime_frame.fillna(method="ffill")
|
| 453 |
+
tm.assert_frame_equal(datetime_frame.ffill(), alt)
|
| 454 |
+
|
| 455 |
+
def test_bfill(self, datetime_frame):
|
| 456 |
+
datetime_frame.loc[datetime_frame.index[:5], "A"] = np.nan
|
| 457 |
+
datetime_frame.loc[datetime_frame.index[-5:], "A"] = np.nan
|
| 458 |
+
|
| 459 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 460 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 461 |
+
alt = datetime_frame.fillna(method="bfill")
|
| 462 |
+
|
| 463 |
+
tm.assert_frame_equal(datetime_frame.bfill(), alt)
|
| 464 |
+
|
| 465 |
+
def test_frame_pad_backfill_limit(self):
|
| 466 |
+
index = np.arange(10)
|
| 467 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index)
|
| 468 |
+
|
| 469 |
+
result = df[:2].reindex(index, method="pad", limit=5)
|
| 470 |
+
|
| 471 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 472 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 473 |
+
expected = df[:2].reindex(index).fillna(method="pad")
|
| 474 |
+
expected.iloc[-3:] = np.nan
|
| 475 |
+
tm.assert_frame_equal(result, expected)
|
| 476 |
+
|
| 477 |
+
result = df[-2:].reindex(index, method="backfill", limit=5)
|
| 478 |
+
|
| 479 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 480 |
+
expected = df[-2:].reindex(index).fillna(method="backfill")
|
| 481 |
+
expected.iloc[:3] = np.nan
|
| 482 |
+
tm.assert_frame_equal(result, expected)
|
| 483 |
+
|
| 484 |
+
def test_frame_fillna_limit(self):
|
| 485 |
+
index = np.arange(10)
|
| 486 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)), index=index)
|
| 487 |
+
|
| 488 |
+
result = df[:2].reindex(index)
|
| 489 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 490 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 491 |
+
result = result.fillna(method="pad", limit=5)
|
| 492 |
+
|
| 493 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 494 |
+
expected = df[:2].reindex(index).fillna(method="pad")
|
| 495 |
+
expected.iloc[-3:] = np.nan
|
| 496 |
+
tm.assert_frame_equal(result, expected)
|
| 497 |
+
|
| 498 |
+
result = df[-2:].reindex(index)
|
| 499 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 500 |
+
result = result.fillna(method="backfill", limit=5)
|
| 501 |
+
|
| 502 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 503 |
+
expected = df[-2:].reindex(index).fillna(method="backfill")
|
| 504 |
+
expected.iloc[:3] = np.nan
|
| 505 |
+
tm.assert_frame_equal(result, expected)
|
| 506 |
+
|
| 507 |
+
def test_fillna_skip_certain_blocks(self):
|
| 508 |
+
# don't try to fill boolean, int blocks
|
| 509 |
+
|
| 510 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)).astype(int))
|
| 511 |
+
|
| 512 |
+
# it works!
|
| 513 |
+
df.fillna(np.nan)
|
| 514 |
+
|
| 515 |
+
@pytest.mark.parametrize("type", [int, float])
|
| 516 |
+
def test_fillna_positive_limit(self, type):
|
| 517 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type)
|
| 518 |
+
|
| 519 |
+
msg = "Limit must be greater than 0"
|
| 520 |
+
with pytest.raises(ValueError, match=msg):
|
| 521 |
+
df.fillna(0, limit=-5)
|
| 522 |
+
|
| 523 |
+
@pytest.mark.parametrize("type", [int, float])
|
| 524 |
+
def test_fillna_integer_limit(self, type):
|
| 525 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))).astype(type)
|
| 526 |
+
|
| 527 |
+
msg = "Limit must be an integer"
|
| 528 |
+
with pytest.raises(ValueError, match=msg):
|
| 529 |
+
df.fillna(0, limit=0.5)
|
| 530 |
+
|
| 531 |
+
def test_fillna_inplace(self):
|
| 532 |
+
df = DataFrame(np.random.default_rng(2).standard_normal((10, 4)))
|
| 533 |
+
df.loc[:4, 1] = np.nan
|
| 534 |
+
df.loc[-4:, 3] = np.nan
|
| 535 |
+
|
| 536 |
+
expected = df.fillna(value=0)
|
| 537 |
+
assert expected is not df
|
| 538 |
+
|
| 539 |
+
df.fillna(value=0, inplace=True)
|
| 540 |
+
tm.assert_frame_equal(df, expected)
|
| 541 |
+
|
| 542 |
+
expected = df.fillna(value={0: 0}, inplace=True)
|
| 543 |
+
assert expected is None
|
| 544 |
+
|
| 545 |
+
df.loc[:4, 1] = np.nan
|
| 546 |
+
df.loc[-4:, 3] = np.nan
|
| 547 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 548 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 549 |
+
expected = df.fillna(method="ffill")
|
| 550 |
+
assert expected is not df
|
| 551 |
+
|
| 552 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 553 |
+
df.fillna(method="ffill", inplace=True)
|
| 554 |
+
tm.assert_frame_equal(df, expected)
|
| 555 |
+
|
| 556 |
+
def test_fillna_dict_series(self):
|
| 557 |
+
df = DataFrame(
|
| 558 |
+
{
|
| 559 |
+
"a": [np.nan, 1, 2, np.nan, np.nan],
|
| 560 |
+
"b": [1, 2, 3, np.nan, np.nan],
|
| 561 |
+
"c": [np.nan, 1, 2, 3, 4],
|
| 562 |
+
}
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
result = df.fillna({"a": 0, "b": 5})
|
| 566 |
+
|
| 567 |
+
expected = df.copy()
|
| 568 |
+
expected["a"] = expected["a"].fillna(0)
|
| 569 |
+
expected["b"] = expected["b"].fillna(5)
|
| 570 |
+
tm.assert_frame_equal(result, expected)
|
| 571 |
+
|
| 572 |
+
# it works
|
| 573 |
+
result = df.fillna({"a": 0, "b": 5, "d": 7})
|
| 574 |
+
|
| 575 |
+
# Series treated same as dict
|
| 576 |
+
result = df.fillna(df.max())
|
| 577 |
+
expected = df.fillna(df.max().to_dict())
|
| 578 |
+
tm.assert_frame_equal(result, expected)
|
| 579 |
+
|
| 580 |
+
# disable this for now
|
| 581 |
+
with pytest.raises(NotImplementedError, match="column by column"):
|
| 582 |
+
df.fillna(df.max(1), axis=1)
|
| 583 |
+
|
| 584 |
+
def test_fillna_dataframe(self):
|
| 585 |
+
# GH#8377
|
| 586 |
+
df = DataFrame(
|
| 587 |
+
{
|
| 588 |
+
"a": [np.nan, 1, 2, np.nan, np.nan],
|
| 589 |
+
"b": [1, 2, 3, np.nan, np.nan],
|
| 590 |
+
"c": [np.nan, 1, 2, 3, 4],
|
| 591 |
+
},
|
| 592 |
+
index=list("VWXYZ"),
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
# df2 may have different index and columns
|
| 596 |
+
df2 = DataFrame(
|
| 597 |
+
{
|
| 598 |
+
"a": [np.nan, 10, 20, 30, 40],
|
| 599 |
+
"b": [50, 60, 70, 80, 90],
|
| 600 |
+
"foo": ["bar"] * 5,
|
| 601 |
+
},
|
| 602 |
+
index=list("VWXuZ"),
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
result = df.fillna(df2)
|
| 606 |
+
|
| 607 |
+
# only those columns and indices which are shared get filled
|
| 608 |
+
expected = DataFrame(
|
| 609 |
+
{
|
| 610 |
+
"a": [np.nan, 1, 2, np.nan, 40],
|
| 611 |
+
"b": [1, 2, 3, np.nan, 90],
|
| 612 |
+
"c": [np.nan, 1, 2, 3, 4],
|
| 613 |
+
},
|
| 614 |
+
index=list("VWXYZ"),
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
tm.assert_frame_equal(result, expected)
|
| 618 |
+
|
| 619 |
+
def test_fillna_columns(self):
|
| 620 |
+
arr = np.random.default_rng(2).standard_normal((10, 10))
|
| 621 |
+
arr[:, ::2] = np.nan
|
| 622 |
+
df = DataFrame(arr)
|
| 623 |
+
|
| 624 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 625 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 626 |
+
result = df.fillna(method="ffill", axis=1)
|
| 627 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 628 |
+
expected = df.T.fillna(method="pad").T
|
| 629 |
+
tm.assert_frame_equal(result, expected)
|
| 630 |
+
|
| 631 |
+
df.insert(6, "foo", 5)
|
| 632 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 633 |
+
result = df.fillna(method="ffill", axis=1)
|
| 634 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 635 |
+
expected = df.astype(float).fillna(method="ffill", axis=1)
|
| 636 |
+
tm.assert_frame_equal(result, expected)
|
| 637 |
+
|
| 638 |
+
def test_fillna_invalid_method(self, float_frame):
|
| 639 |
+
with pytest.raises(ValueError, match="ffil"):
|
| 640 |
+
float_frame.fillna(method="ffil")
|
| 641 |
+
|
| 642 |
+
def test_fillna_invalid_value(self, float_frame):
|
| 643 |
+
# list
|
| 644 |
+
msg = '"value" parameter must be a scalar or dict, but you passed a "{}"'
|
| 645 |
+
with pytest.raises(TypeError, match=msg.format("list")):
|
| 646 |
+
float_frame.fillna([1, 2])
|
| 647 |
+
# tuple
|
| 648 |
+
with pytest.raises(TypeError, match=msg.format("tuple")):
|
| 649 |
+
float_frame.fillna((1, 2))
|
| 650 |
+
# frame with series
|
| 651 |
+
msg = (
|
| 652 |
+
'"value" parameter must be a scalar, dict or Series, but you '
|
| 653 |
+
'passed a "DataFrame"'
|
| 654 |
+
)
|
| 655 |
+
with pytest.raises(TypeError, match=msg):
|
| 656 |
+
float_frame.iloc[:, 0].fillna(float_frame)
|
| 657 |
+
|
| 658 |
+
def test_fillna_col_reordering(self):
|
| 659 |
+
cols = ["COL." + str(i) for i in range(5, 0, -1)]
|
| 660 |
+
data = np.random.default_rng(2).random((20, 5))
|
| 661 |
+
df = DataFrame(index=range(20), columns=cols, data=data)
|
| 662 |
+
msg = "DataFrame.fillna with 'method' is deprecated"
|
| 663 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 664 |
+
filled = df.fillna(method="ffill")
|
| 665 |
+
assert df.columns.tolist() == filled.columns.tolist()
|
| 666 |
+
|
| 667 |
+
@pytest.mark.xfail(using_pyarrow_string_dtype(), reason="can't fill 0 in string")
|
| 668 |
+
def test_fill_corner(self, float_frame, float_string_frame):
|
| 669 |
+
mf = float_string_frame
|
| 670 |
+
mf.loc[mf.index[5:20], "foo"] = np.nan
|
| 671 |
+
mf.loc[mf.index[-10:], "A"] = np.nan
|
| 672 |
+
|
| 673 |
+
filled = float_string_frame.fillna(value=0)
|
| 674 |
+
assert (filled.loc[filled.index[5:20], "foo"] == 0).all()
|
| 675 |
+
del float_string_frame["foo"]
|
| 676 |
+
|
| 677 |
+
float_frame.reindex(columns=[]).fillna(value=0)
|
| 678 |
+
|
| 679 |
+
def test_fillna_downcast_dict(self):
|
| 680 |
+
# GH#40809
|
| 681 |
+
df = DataFrame({"col1": [1, np.nan]})
|
| 682 |
+
|
| 683 |
+
msg = "The 'downcast' keyword in fillna"
|
| 684 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 685 |
+
result = df.fillna({"col1": 2}, downcast={"col1": "int64"})
|
| 686 |
+
expected = DataFrame({"col1": [1, 2]})
|
| 687 |
+
tm.assert_frame_equal(result, expected)
|
| 688 |
+
|
| 689 |
+
def test_fillna_with_columns_and_limit(self):
|
| 690 |
+
# GH40989
|
| 691 |
+
df = DataFrame(
|
| 692 |
+
[
|
| 693 |
+
[np.nan, 2, np.nan, 0],
|
| 694 |
+
[3, 4, np.nan, 1],
|
| 695 |
+
[np.nan, np.nan, np.nan, 5],
|
| 696 |
+
[np.nan, 3, np.nan, 4],
|
| 697 |
+
],
|
| 698 |
+
columns=list("ABCD"),
|
| 699 |
+
)
|
| 700 |
+
result = df.fillna(axis=1, value=100, limit=1)
|
| 701 |
+
result2 = df.fillna(axis=1, value=100, limit=2)
|
| 702 |
+
|
| 703 |
+
expected = DataFrame(
|
| 704 |
+
{
|
| 705 |
+
"A": Series([100, 3, 100, 100], dtype="float64"),
|
| 706 |
+
"B": [2, 4, np.nan, 3],
|
| 707 |
+
"C": [np.nan, 100, np.nan, np.nan],
|
| 708 |
+
"D": Series([0, 1, 5, 4], dtype="float64"),
|
| 709 |
+
},
|
| 710 |
+
index=[0, 1, 2, 3],
|
| 711 |
+
)
|
| 712 |
+
expected2 = DataFrame(
|
| 713 |
+
{
|
| 714 |
+
"A": Series([100, 3, 100, 100], dtype="float64"),
|
| 715 |
+
"B": Series([2, 4, 100, 3], dtype="float64"),
|
| 716 |
+
"C": [100, 100, np.nan, 100],
|
| 717 |
+
"D": Series([0, 1, 5, 4], dtype="float64"),
|
| 718 |
+
},
|
| 719 |
+
index=[0, 1, 2, 3],
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
tm.assert_frame_equal(result, expected)
|
| 723 |
+
tm.assert_frame_equal(result2, expected2)
|
| 724 |
+
|
| 725 |
+
def test_fillna_datetime_inplace(self):
|
| 726 |
+
# GH#48863
|
| 727 |
+
df = DataFrame(
|
| 728 |
+
{
|
| 729 |
+
"date1": to_datetime(["2018-05-30", None]),
|
| 730 |
+
"date2": to_datetime(["2018-09-30", None]),
|
| 731 |
+
}
|
| 732 |
+
)
|
| 733 |
+
expected = df.copy()
|
| 734 |
+
df.fillna(np.nan, inplace=True)
|
| 735 |
+
tm.assert_frame_equal(df, expected)
|
| 736 |
+
|
| 737 |
+
def test_fillna_inplace_with_columns_limit_and_value(self):
|
| 738 |
+
# GH40989
|
| 739 |
+
df = DataFrame(
|
| 740 |
+
[
|
| 741 |
+
[np.nan, 2, np.nan, 0],
|
| 742 |
+
[3, 4, np.nan, 1],
|
| 743 |
+
[np.nan, np.nan, np.nan, 5],
|
| 744 |
+
[np.nan, 3, np.nan, 4],
|
| 745 |
+
],
|
| 746 |
+
columns=list("ABCD"),
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
expected = df.fillna(axis=1, value=100, limit=1)
|
| 750 |
+
assert expected is not df
|
| 751 |
+
|
| 752 |
+
df.fillna(axis=1, value=100, limit=1, inplace=True)
|
| 753 |
+
tm.assert_frame_equal(df, expected)
|
| 754 |
+
|
| 755 |
+
@td.skip_array_manager_invalid_test
|
| 756 |
+
@pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}])
|
| 757 |
+
def test_inplace_dict_update_view(
|
| 758 |
+
self, val, using_copy_on_write, warn_copy_on_write
|
| 759 |
+
):
|
| 760 |
+
# GH#47188
|
| 761 |
+
df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]})
|
| 762 |
+
df_orig = df.copy()
|
| 763 |
+
result_view = df[:]
|
| 764 |
+
with tm.assert_cow_warning(warn_copy_on_write):
|
| 765 |
+
df.fillna(val, inplace=True)
|
| 766 |
+
expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]})
|
| 767 |
+
tm.assert_frame_equal(df, expected)
|
| 768 |
+
if using_copy_on_write:
|
| 769 |
+
tm.assert_frame_equal(result_view, df_orig)
|
| 770 |
+
else:
|
| 771 |
+
tm.assert_frame_equal(result_view, expected)
|
| 772 |
+
|
| 773 |
+
def test_single_block_df_with_horizontal_axis(self):
|
| 774 |
+
# GH 47713
|
| 775 |
+
df = DataFrame(
|
| 776 |
+
{
|
| 777 |
+
"col1": [5, 0, np.nan, 10, np.nan],
|
| 778 |
+
"col2": [7, np.nan, np.nan, 5, 3],
|
| 779 |
+
"col3": [12, np.nan, 1, 2, 0],
|
| 780 |
+
"col4": [np.nan, 1, 1, np.nan, 18],
|
| 781 |
+
}
|
| 782 |
+
)
|
| 783 |
+
result = df.fillna(50, limit=1, axis=1)
|
| 784 |
+
expected = DataFrame(
|
| 785 |
+
[
|
| 786 |
+
[5.0, 7.0, 12.0, 50.0],
|
| 787 |
+
[0.0, 50.0, np.nan, 1.0],
|
| 788 |
+
[50.0, np.nan, 1.0, 1.0],
|
| 789 |
+
[10.0, 5.0, 2.0, 50.0],
|
| 790 |
+
[50.0, 3.0, 0.0, 18.0],
|
| 791 |
+
],
|
| 792 |
+
columns=["col1", "col2", "col3", "col4"],
|
| 793 |
+
)
|
| 794 |
+
tm.assert_frame_equal(result, expected)
|
| 795 |
+
|
| 796 |
+
def test_fillna_with_multi_index_frame(self):
|
| 797 |
+
# GH 47649
|
| 798 |
+
pdf = DataFrame(
|
| 799 |
+
{
|
| 800 |
+
("x", "a"): [np.nan, 2.0, 3.0],
|
| 801 |
+
("x", "b"): [1.0, 2.0, np.nan],
|
| 802 |
+
("y", "c"): [1.0, 2.0, np.nan],
|
| 803 |
+
}
|
| 804 |
+
)
|
| 805 |
+
expected = DataFrame(
|
| 806 |
+
{
|
| 807 |
+
("x", "a"): [-1.0, 2.0, 3.0],
|
| 808 |
+
("x", "b"): [1.0, 2.0, -1.0],
|
| 809 |
+
("y", "c"): [1.0, 2.0, np.nan],
|
| 810 |
+
}
|
| 811 |
+
)
|
| 812 |
+
tm.assert_frame_equal(pdf.fillna({"x": -1}), expected)
|
| 813 |
+
tm.assert_frame_equal(pdf.fillna({"x": -1, ("x", "b"): -2}), expected)
|
| 814 |
+
|
| 815 |
+
expected = DataFrame(
|
| 816 |
+
{
|
| 817 |
+
("x", "a"): [-1.0, 2.0, 3.0],
|
| 818 |
+
("x", "b"): [1.0, 2.0, -2.0],
|
| 819 |
+
("y", "c"): [1.0, 2.0, np.nan],
|
| 820 |
+
}
|
| 821 |
+
)
|
| 822 |
+
tm.assert_frame_equal(pdf.fillna({("x", "b"): -2, "x": -1}), expected)
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def test_fillna_nonconsolidated_frame():
|
| 826 |
+
# https://github.com/pandas-dev/pandas/issues/36495
|
| 827 |
+
df = DataFrame(
|
| 828 |
+
[
|
| 829 |
+
[1, 1, 1, 1.0],
|
| 830 |
+
[2, 2, 2, 2.0],
|
| 831 |
+
[3, 3, 3, 3.0],
|
| 832 |
+
],
|
| 833 |
+
columns=["i1", "i2", "i3", "f1"],
|
| 834 |
+
)
|
| 835 |
+
df_nonconsol = df.pivot(index="i1", columns="i2")
|
| 836 |
+
result = df_nonconsol.fillna(0)
|
| 837 |
+
assert result.isna().sum().sum() == 0
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def test_fillna_nones_inplace():
|
| 841 |
+
# GH 48480
|
| 842 |
+
df = DataFrame(
|
| 843 |
+
[[None, None], [None, None]],
|
| 844 |
+
columns=["A", "B"],
|
| 845 |
+
)
|
| 846 |
+
msg = "Downcasting object dtype arrays"
|
| 847 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
| 848 |
+
df.fillna(value={"A": 1, "B": 2}, inplace=True)
|
| 849 |
+
|
| 850 |
+
expected = DataFrame([[1, 2], [1, 2]], columns=["A", "B"])
|
| 851 |
+
tm.assert_frame_equal(df, expected)
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@pytest.mark.parametrize("func", ["pad", "backfill"])
|
| 855 |
+
def test_pad_backfill_deprecated(func):
|
| 856 |
+
# GH#33396
|
| 857 |
+
df = DataFrame({"a": [1, 2, 3]})
|
| 858 |
+
with tm.assert_produces_warning(FutureWarning):
|
| 859 |
+
getattr(df, func)()
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
@pytest.mark.parametrize(
|
| 863 |
+
"data, expected_data, method, kwargs",
|
| 864 |
+
(
|
| 865 |
+
(
|
| 866 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 867 |
+
[np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan],
|
| 868 |
+
"ffill",
|
| 869 |
+
{"limit_area": "inside"},
|
| 870 |
+
),
|
| 871 |
+
(
|
| 872 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 873 |
+
[np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan],
|
| 874 |
+
"ffill",
|
| 875 |
+
{"limit_area": "inside", "limit": 1},
|
| 876 |
+
),
|
| 877 |
+
(
|
| 878 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 879 |
+
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0],
|
| 880 |
+
"ffill",
|
| 881 |
+
{"limit_area": "outside"},
|
| 882 |
+
),
|
| 883 |
+
(
|
| 884 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 885 |
+
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan],
|
| 886 |
+
"ffill",
|
| 887 |
+
{"limit_area": "outside", "limit": 1},
|
| 888 |
+
),
|
| 889 |
+
(
|
| 890 |
+
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
|
| 891 |
+
[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
|
| 892 |
+
"ffill",
|
| 893 |
+
{"limit_area": "outside", "limit": 1},
|
| 894 |
+
),
|
| 895 |
+
(
|
| 896 |
+
range(5),
|
| 897 |
+
range(5),
|
| 898 |
+
"ffill",
|
| 899 |
+
{"limit_area": "outside", "limit": 1},
|
| 900 |
+
),
|
| 901 |
+
(
|
| 902 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 903 |
+
[np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan],
|
| 904 |
+
"bfill",
|
| 905 |
+
{"limit_area": "inside"},
|
| 906 |
+
),
|
| 907 |
+
(
|
| 908 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 909 |
+
[np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan],
|
| 910 |
+
"bfill",
|
| 911 |
+
{"limit_area": "inside", "limit": 1},
|
| 912 |
+
),
|
| 913 |
+
(
|
| 914 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 915 |
+
[3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
|
| 916 |
+
"bfill",
|
| 917 |
+
{"limit_area": "outside"},
|
| 918 |
+
),
|
| 919 |
+
(
|
| 920 |
+
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan],
|
| 921 |
+
[np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan],
|
| 922 |
+
"bfill",
|
| 923 |
+
{"limit_area": "outside", "limit": 1},
|
| 924 |
+
),
|
| 925 |
+
),
|
| 926 |
+
)
|
| 927 |
+
def test_ffill_bfill_limit_area(data, expected_data, method, kwargs):
|
| 928 |
+
# GH#56492
|
| 929 |
+
df = DataFrame(data)
|
| 930 |
+
expected = DataFrame(expected_data)
|
| 931 |
+
result = getattr(df, method)(**kwargs)
|
| 932 |
+
tm.assert_frame_equal(result, expected)
|
shared/package-files/18/180f0539d35295855bfb29426e4bc3975151a2d08857ed009d3dd2441c1de747/union_find.cpython-311.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
shared/package-files/18/181a71d8310cd917e57afd1c022a6fbf3651d6008e4bf6d637cbf34970f93912/take_along_dim_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor take_along_dim(const at::Tensor & self, const at::Tensor & indices, ::std::optional<int64_t> dim=::std::nullopt);
|
| 20 |
+
TORCH_API at::Tensor & take_along_dim_out(const at::Tensor & self, const at::Tensor & indices, ::std::optional<int64_t> dim, at::Tensor & out);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/18/1822d1c4023fdcfc260e63a5a36617872615921327c5a6341ec75a80535d459f/nll_loss_nd.h
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/nll_loss_nd_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
|
| 27 |
+
inline at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) {
|
| 28 |
+
return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index);
|
| 29 |
+
}
|
| 30 |
+
namespace symint {
|
| 31 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, int64_t>>>
|
| 32 |
+
at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean, int64_t ignore_index=-100) {
|
| 33 |
+
return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index);
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// aten::nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
|
| 38 |
+
inline at::Tensor nll_loss_nd_symint(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) {
|
| 39 |
+
return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index);
|
| 40 |
+
}
|
| 41 |
+
namespace symint {
|
| 42 |
+
template <typename T, typename = std::enable_if_t<std::is_same_v<T, c10::SymInt>>>
|
| 43 |
+
at::Tensor nll_loss_nd(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean, c10::SymInt ignore_index=-100) {
|
| 44 |
+
return at::_ops::nll_loss_nd::call(self, target, weight, reduction, ignore_index);
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
}
|
shared/package-files/18/182d24026129d741f141943e1883646af15d3ba8fe6886b83accf6077c8afad6/conv.cpython-311.pyc
ADDED
|
Binary file (902 Bytes). View file
|
|
|
shared/package-files/18/1836c8c8830b13005f7e086e2d1f4ecef3818fc59a558065981bbaf221d27465/METADATA
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: nvidia-cublas-cu12
|
| 3 |
+
Version: 12.6.4.1
|
| 4 |
+
Summary: CUBLAS native runtime libraries
|
| 5 |
+
Home-page: https://developer.nvidia.com/cuda-zone
|
| 6 |
+
Author: Nvidia CUDA Installer Team
|
| 7 |
+
Author-email: compute_installer@nvidia.com
|
| 8 |
+
License: NVIDIA Proprietary Software
|
| 9 |
+
Keywords: cuda,nvidia,runtime,machine learning,deep learning
|
| 10 |
+
Classifier: Development Status :: 4 - Beta
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: Intended Audience :: Education
|
| 13 |
+
Classifier: Intended Audience :: Science/Research
|
| 14 |
+
Classifier: License :: Other/Proprietary License
|
| 15 |
+
Classifier: Natural Language :: English
|
| 16 |
+
Classifier: Programming Language :: Python :: 3
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.5
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 25 |
+
Classifier: Topic :: Scientific/Engineering
|
| 26 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 27 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 28 |
+
Classifier: Topic :: Software Development
|
| 29 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 30 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 31 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 32 |
+
Requires-Python: >=3
|
| 33 |
+
License-File: License.txt
|
| 34 |
+
|
| 35 |
+
CUBLAS native runtime libraries
|
shared/package-files/18/1841ca6850b8f13de8fbf4a61f8f3ae06bcacb1d4881b542e884883d5971edae/core.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""distutils.core
|
| 2 |
+
|
| 3 |
+
The only module that needs to be imported to use the Distutils; provides
|
| 4 |
+
the 'setup' function (which is to be called from the setup script). Also
|
| 5 |
+
indirectly provides the Distribution and Command classes, although they are
|
| 6 |
+
really defined in distutils.dist and distutils.cmd.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import tokenize
|
| 14 |
+
from collections.abc import Iterable
|
| 15 |
+
|
| 16 |
+
from .cmd import Command
|
| 17 |
+
from .debug import DEBUG
|
| 18 |
+
|
| 19 |
+
# Mainly import these so setup scripts can "from distutils.core import" them.
|
| 20 |
+
from .dist import Distribution
|
| 21 |
+
from .errors import (
|
| 22 |
+
CCompilerError,
|
| 23 |
+
DistutilsArgError,
|
| 24 |
+
DistutilsError,
|
| 25 |
+
DistutilsSetupError,
|
| 26 |
+
)
|
| 27 |
+
from .extension import Extension
|
| 28 |
+
|
| 29 |
+
__all__ = ['Distribution', 'Command', 'Extension', 'setup']
|
| 30 |
+
|
| 31 |
+
# This is a barebones help message generated displayed when the user
|
| 32 |
+
# runs the setup script with no arguments at all. More useful help
|
| 33 |
+
# is generated with various --help options: global help, list commands,
|
| 34 |
+
# and per-command help.
|
| 35 |
+
USAGE = """\
|
| 36 |
+
usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
|
| 37 |
+
or: %(script)s --help [cmd1 cmd2 ...]
|
| 38 |
+
or: %(script)s --help-commands
|
| 39 |
+
or: %(script)s cmd --help
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def gen_usage(script_name):
|
| 44 |
+
script = os.path.basename(script_name)
|
| 45 |
+
return USAGE % locals()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
|
| 49 |
+
_setup_stop_after = None
|
| 50 |
+
_setup_distribution = None
|
| 51 |
+
|
| 52 |
+
# Legal keyword arguments for the setup() function
|
| 53 |
+
setup_keywords = (
|
| 54 |
+
'distclass',
|
| 55 |
+
'script_name',
|
| 56 |
+
'script_args',
|
| 57 |
+
'options',
|
| 58 |
+
'name',
|
| 59 |
+
'version',
|
| 60 |
+
'author',
|
| 61 |
+
'author_email',
|
| 62 |
+
'maintainer',
|
| 63 |
+
'maintainer_email',
|
| 64 |
+
'url',
|
| 65 |
+
'license',
|
| 66 |
+
'description',
|
| 67 |
+
'long_description',
|
| 68 |
+
'keywords',
|
| 69 |
+
'platforms',
|
| 70 |
+
'classifiers',
|
| 71 |
+
'download_url',
|
| 72 |
+
'requires',
|
| 73 |
+
'provides',
|
| 74 |
+
'obsoletes',
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Legal keyword arguments for the Extension constructor
|
| 78 |
+
extension_keywords = (
|
| 79 |
+
'name',
|
| 80 |
+
'sources',
|
| 81 |
+
'include_dirs',
|
| 82 |
+
'define_macros',
|
| 83 |
+
'undef_macros',
|
| 84 |
+
'library_dirs',
|
| 85 |
+
'libraries',
|
| 86 |
+
'runtime_library_dirs',
|
| 87 |
+
'extra_objects',
|
| 88 |
+
'extra_compile_args',
|
| 89 |
+
'extra_link_args',
|
| 90 |
+
'swig_opts',
|
| 91 |
+
'export_symbols',
|
| 92 |
+
'depends',
|
| 93 |
+
'language',
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def setup(**attrs): # noqa: C901
|
| 98 |
+
"""The gateway to the Distutils: do everything your setup script needs
|
| 99 |
+
to do, in a highly flexible and user-driven way. Briefly: create a
|
| 100 |
+
Distribution instance; find and parse config files; parse the command
|
| 101 |
+
line; run each Distutils command found there, customized by the options
|
| 102 |
+
supplied to 'setup()' (as keyword arguments), in config files, and on
|
| 103 |
+
the command line.
|
| 104 |
+
|
| 105 |
+
The Distribution instance might be an instance of a class supplied via
|
| 106 |
+
the 'distclass' keyword argument to 'setup'; if no such class is
|
| 107 |
+
supplied, then the Distribution class (in dist.py) is instantiated.
|
| 108 |
+
All other arguments to 'setup' (except for 'cmdclass') are used to set
|
| 109 |
+
attributes of the Distribution instance.
|
| 110 |
+
|
| 111 |
+
The 'cmdclass' argument, if supplied, is a dictionary mapping command
|
| 112 |
+
names to command classes. Each command encountered on the command line
|
| 113 |
+
will be turned into a command class, which is in turn instantiated; any
|
| 114 |
+
class found in 'cmdclass' is used in place of the default, which is
|
| 115 |
+
(for command 'foo_bar') class 'foo_bar' in module
|
| 116 |
+
'distutils.command.foo_bar'. The command class must provide a
|
| 117 |
+
'user_options' attribute which is a list of option specifiers for
|
| 118 |
+
'distutils.fancy_getopt'. Any command-line options between the current
|
| 119 |
+
and the next command are used to set attributes of the current command
|
| 120 |
+
object.
|
| 121 |
+
|
| 122 |
+
When the entire command-line has been successfully parsed, calls the
|
| 123 |
+
'run()' method on each command object in turn. This method will be
|
| 124 |
+
driven entirely by the Distribution object (which each command object
|
| 125 |
+
has a reference to, thanks to its constructor), and the
|
| 126 |
+
command-specific options that became attributes of each command
|
| 127 |
+
object.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
global _setup_stop_after, _setup_distribution
|
| 131 |
+
|
| 132 |
+
# Determine the distribution class -- either caller-supplied or
|
| 133 |
+
# our Distribution (see below).
|
| 134 |
+
klass = attrs.get('distclass')
|
| 135 |
+
if klass:
|
| 136 |
+
attrs.pop('distclass')
|
| 137 |
+
else:
|
| 138 |
+
klass = Distribution
|
| 139 |
+
|
| 140 |
+
if 'script_name' not in attrs:
|
| 141 |
+
attrs['script_name'] = os.path.basename(sys.argv[0])
|
| 142 |
+
if 'script_args' not in attrs:
|
| 143 |
+
attrs['script_args'] = sys.argv[1:]
|
| 144 |
+
|
| 145 |
+
# Create the Distribution instance, using the remaining arguments
|
| 146 |
+
# (ie. everything except distclass) to initialize it
|
| 147 |
+
try:
|
| 148 |
+
_setup_distribution = dist = klass(attrs)
|
| 149 |
+
except DistutilsSetupError as msg:
|
| 150 |
+
if 'name' not in attrs:
|
| 151 |
+
raise SystemExit(f"error in setup command: {msg}")
|
| 152 |
+
else:
|
| 153 |
+
raise SystemExit("error in {} setup command: {}".format(attrs['name'], msg))
|
| 154 |
+
|
| 155 |
+
if _setup_stop_after == "init":
|
| 156 |
+
return dist
|
| 157 |
+
|
| 158 |
+
# Find and parse the config file(s): they will override options from
|
| 159 |
+
# the setup script, but be overridden by the command line.
|
| 160 |
+
dist.parse_config_files()
|
| 161 |
+
|
| 162 |
+
if DEBUG:
|
| 163 |
+
print("options (after parsing config files):")
|
| 164 |
+
dist.dump_option_dicts()
|
| 165 |
+
|
| 166 |
+
if _setup_stop_after == "config":
|
| 167 |
+
return dist
|
| 168 |
+
|
| 169 |
+
# Parse the command line and override config files; any
|
| 170 |
+
# command-line errors are the end user's fault, so turn them into
|
| 171 |
+
# SystemExit to suppress tracebacks.
|
| 172 |
+
try:
|
| 173 |
+
ok = dist.parse_command_line()
|
| 174 |
+
except DistutilsArgError as msg:
|
| 175 |
+
raise SystemExit(gen_usage(dist.script_name) + f"\nerror: {msg}")
|
| 176 |
+
|
| 177 |
+
if DEBUG:
|
| 178 |
+
print("options (after parsing command line):")
|
| 179 |
+
dist.dump_option_dicts()
|
| 180 |
+
|
| 181 |
+
if _setup_stop_after == "commandline":
|
| 182 |
+
return dist
|
| 183 |
+
|
| 184 |
+
# And finally, run all the commands found on the command line.
|
| 185 |
+
if ok:
|
| 186 |
+
return run_commands(dist)
|
| 187 |
+
|
| 188 |
+
return dist
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# setup ()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def run_commands(dist):
|
| 195 |
+
"""Given a Distribution object run all the commands,
|
| 196 |
+
raising ``SystemExit`` errors in the case of failure.
|
| 197 |
+
|
| 198 |
+
This function assumes that either ``sys.argv`` or ``dist.script_args``
|
| 199 |
+
is already set accordingly.
|
| 200 |
+
"""
|
| 201 |
+
try:
|
| 202 |
+
dist.run_commands()
|
| 203 |
+
except KeyboardInterrupt:
|
| 204 |
+
raise SystemExit("interrupted")
|
| 205 |
+
except OSError as exc:
|
| 206 |
+
if DEBUG:
|
| 207 |
+
sys.stderr.write(f"error: {exc}\n")
|
| 208 |
+
raise
|
| 209 |
+
else:
|
| 210 |
+
raise SystemExit(f"error: {exc}")
|
| 211 |
+
|
| 212 |
+
except (DistutilsError, CCompilerError) as msg:
|
| 213 |
+
if DEBUG:
|
| 214 |
+
raise
|
| 215 |
+
else:
|
| 216 |
+
raise SystemExit("error: " + str(msg))
|
| 217 |
+
|
| 218 |
+
return dist
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def run_setup(script_name, script_args: Iterable[str] | None = None, stop_after="run"):
|
| 222 |
+
"""Run a setup script in a somewhat controlled environment, and
|
| 223 |
+
return the Distribution instance that drives things. This is useful
|
| 224 |
+
if you need to find out the distribution meta-data (passed as
|
| 225 |
+
keyword args from 'script' to 'setup()', or the contents of the
|
| 226 |
+
config files or command-line.
|
| 227 |
+
|
| 228 |
+
'script_name' is a file that will be read and run with 'exec()';
|
| 229 |
+
'sys.argv[0]' will be replaced with 'script' for the duration of the
|
| 230 |
+
call. 'script_args' is a list of strings; if supplied,
|
| 231 |
+
'sys.argv[1:]' will be replaced by 'script_args' for the duration of
|
| 232 |
+
the call.
|
| 233 |
+
|
| 234 |
+
'stop_after' tells 'setup()' when to stop processing; possible
|
| 235 |
+
values:
|
| 236 |
+
init
|
| 237 |
+
stop after the Distribution instance has been created and
|
| 238 |
+
populated with the keyword arguments to 'setup()'
|
| 239 |
+
config
|
| 240 |
+
stop after config files have been parsed (and their data
|
| 241 |
+
stored in the Distribution instance)
|
| 242 |
+
commandline
|
| 243 |
+
stop after the command-line ('sys.argv[1:]' or 'script_args')
|
| 244 |
+
have been parsed (and the data stored in the Distribution)
|
| 245 |
+
run [default]
|
| 246 |
+
stop after all commands have been run (the same as if 'setup()'
|
| 247 |
+
had been called in the usual way
|
| 248 |
+
|
| 249 |
+
Returns the Distribution instance, which provides all information
|
| 250 |
+
used to drive the Distutils.
|
| 251 |
+
"""
|
| 252 |
+
if stop_after not in ('init', 'config', 'commandline', 'run'):
|
| 253 |
+
raise ValueError(f"invalid value for 'stop_after': {stop_after!r}")
|
| 254 |
+
|
| 255 |
+
global _setup_stop_after, _setup_distribution
|
| 256 |
+
_setup_stop_after = stop_after
|
| 257 |
+
|
| 258 |
+
save_argv = sys.argv.copy()
|
| 259 |
+
g = {'__file__': script_name, '__name__': '__main__'}
|
| 260 |
+
try:
|
| 261 |
+
try:
|
| 262 |
+
sys.argv[0] = script_name
|
| 263 |
+
if script_args is not None:
|
| 264 |
+
sys.argv[1:] = script_args
|
| 265 |
+
# tokenize.open supports automatic encoding detection
|
| 266 |
+
with tokenize.open(script_name) as f:
|
| 267 |
+
code = f.read().replace(r'\r\n', r'\n')
|
| 268 |
+
exec(code, g)
|
| 269 |
+
finally:
|
| 270 |
+
sys.argv = save_argv
|
| 271 |
+
_setup_stop_after = None
|
| 272 |
+
except SystemExit:
|
| 273 |
+
# Hmm, should we do something if exiting with a non-zero code
|
| 274 |
+
# (ie. error)?
|
| 275 |
+
pass
|
| 276 |
+
|
| 277 |
+
if _setup_distribution is None:
|
| 278 |
+
raise RuntimeError(
|
| 279 |
+
"'distutils.core.setup()' was never called -- "
|
| 280 |
+
f"perhaps '{script_name}' is not a Distutils setup script?"
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# I wonder if the setup script's namespace -- g and l -- would be of
|
| 284 |
+
# any interest to callers?
|
| 285 |
+
# print "_setup_distribution:", _setup_distribution
|
| 286 |
+
return _setup_distribution
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# run_setup ()
|
shared/package-files/18/184be769d39367769f56b6cde56139d8e8423fc83330823f00de281d0c6f129a/algorithms.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.numbers import oo
|
| 3 |
+
from sympy.core.relational import (Gt, Lt)
|
| 4 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 5 |
+
from sympy.functions.elementary.complexes import Abs
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 7 |
+
from sympy.logic.boolalg import And
|
| 8 |
+
from sympy.codegen.ast import (
|
| 9 |
+
Assignment, AddAugmentedAssignment, break_, CodeBlock, Declaration, FunctionDefinition,
|
| 10 |
+
Print, Return, Scope, While, Variable, Pointer, real
|
| 11 |
+
)
|
| 12 |
+
from sympy.codegen.cfunctions import isnan
|
| 13 |
+
|
| 14 |
+
""" This module collects functions for constructing ASTs representing algorithms. """
|
| 15 |
+
|
| 16 |
+
def newtons_method(expr, wrt, atol=1e-12, delta=None, *, rtol=4e-16, debug=False,
|
| 17 |
+
itermax=None, counter=None, delta_fn=lambda e, x: -e/e.diff(x),
|
| 18 |
+
cse=False, handle_nan=None,
|
| 19 |
+
bounds=None):
|
| 20 |
+
""" Generates an AST for Newton-Raphson method (a root-finding algorithm).
|
| 21 |
+
|
| 22 |
+
Explanation
|
| 23 |
+
===========
|
| 24 |
+
|
| 25 |
+
Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
|
| 26 |
+
method of root-finding.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
==========
|
| 30 |
+
|
| 31 |
+
expr : expression
|
| 32 |
+
wrt : Symbol
|
| 33 |
+
With respect to, i.e. what is the variable.
|
| 34 |
+
atol : number or expression
|
| 35 |
+
Absolute tolerance (stopping criterion)
|
| 36 |
+
rtol : number or expression
|
| 37 |
+
Relative tolerance (stopping criterion)
|
| 38 |
+
delta : Symbol
|
| 39 |
+
Will be a ``Dummy`` if ``None``.
|
| 40 |
+
debug : bool
|
| 41 |
+
Whether to print convergence information during iterations
|
| 42 |
+
itermax : number or expr
|
| 43 |
+
Maximum number of iterations.
|
| 44 |
+
counter : Symbol
|
| 45 |
+
Will be a ``Dummy`` if ``None``.
|
| 46 |
+
delta_fn: Callable[[Expr, Symbol], Expr]
|
| 47 |
+
computes the step, default is newtons method. For e.g. Halley's method
|
| 48 |
+
use delta_fn=lambda e, x: -2*e*e.diff(x)/(2*e.diff(x)**2 - e*e.diff(x, 2))
|
| 49 |
+
cse: bool
|
| 50 |
+
Perform common sub-expression elimination on delta expression
|
| 51 |
+
handle_nan: Token
|
| 52 |
+
How to handle occurrence of not-a-number (NaN).
|
| 53 |
+
bounds: Optional[tuple[Expr, Expr]]
|
| 54 |
+
Perform optimization within bounds
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
========
|
| 58 |
+
|
| 59 |
+
>>> from sympy import symbols, cos
|
| 60 |
+
>>> from sympy.codegen.ast import Assignment
|
| 61 |
+
>>> from sympy.codegen.algorithms import newtons_method
|
| 62 |
+
>>> x, dx, atol = symbols('x dx atol')
|
| 63 |
+
>>> expr = cos(x) - x**3
|
| 64 |
+
>>> algo = newtons_method(expr, x, atol=atol, delta=dx)
|
| 65 |
+
>>> algo.has(Assignment(dx, -expr/expr.diff(x)))
|
| 66 |
+
True
|
| 67 |
+
|
| 68 |
+
References
|
| 69 |
+
==========
|
| 70 |
+
|
| 71 |
+
.. [1] https://en.wikipedia.org/wiki/Newton%27s_method
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
if delta is None:
|
| 76 |
+
delta = Dummy()
|
| 77 |
+
Wrapper = Scope
|
| 78 |
+
name_d = 'delta'
|
| 79 |
+
else:
|
| 80 |
+
Wrapper = lambda x: x
|
| 81 |
+
name_d = delta.name
|
| 82 |
+
|
| 83 |
+
delta_expr = delta_fn(expr, wrt)
|
| 84 |
+
if cse:
|
| 85 |
+
from sympy.simplify.cse_main import cse
|
| 86 |
+
cses, (red,) = cse([delta_expr.factor()])
|
| 87 |
+
whl_bdy = [Assignment(dum, sub_e) for dum, sub_e in cses]
|
| 88 |
+
whl_bdy += [Assignment(delta, red)]
|
| 89 |
+
else:
|
| 90 |
+
whl_bdy = [Assignment(delta, delta_expr)]
|
| 91 |
+
if handle_nan is not None:
|
| 92 |
+
whl_bdy += [While(isnan(delta), CodeBlock(handle_nan, break_))]
|
| 93 |
+
whl_bdy += [AddAugmentedAssignment(wrt, delta)]
|
| 94 |
+
if bounds is not None:
|
| 95 |
+
whl_bdy += [Assignment(wrt, Min(Max(wrt, bounds[0]), bounds[1]))]
|
| 96 |
+
if debug:
|
| 97 |
+
prnt = Print([wrt, delta], r"{}=%12.5g {}=%12.5g\n".format(wrt.name, name_d))
|
| 98 |
+
whl_bdy += [prnt]
|
| 99 |
+
req = Gt(Abs(delta), atol + rtol*Abs(wrt))
|
| 100 |
+
declars = [Declaration(Variable(delta, type=real, value=oo))]
|
| 101 |
+
if itermax is not None:
|
| 102 |
+
counter = counter or Dummy(integer=True)
|
| 103 |
+
v_counter = Variable.deduced(counter, 0)
|
| 104 |
+
declars.append(Declaration(v_counter))
|
| 105 |
+
whl_bdy.append(AddAugmentedAssignment(counter, 1))
|
| 106 |
+
req = And(req, Lt(counter, itermax))
|
| 107 |
+
whl = While(req, CodeBlock(*whl_bdy))
|
| 108 |
+
blck = declars
|
| 109 |
+
if debug:
|
| 110 |
+
blck.append(Print([wrt], r"{}=%12.5g\n".format(wrt.name)))
|
| 111 |
+
blck += [whl]
|
| 112 |
+
return Wrapper(CodeBlock(*blck))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _symbol_of(arg):
|
| 116 |
+
if isinstance(arg, Declaration):
|
| 117 |
+
arg = arg.variable.symbol
|
| 118 |
+
elif isinstance(arg, Variable):
|
| 119 |
+
arg = arg.symbol
|
| 120 |
+
return arg
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def newtons_method_function(expr, wrt, params=None, func_name="newton", attrs=Tuple(), *, delta=None, **kwargs):
|
| 124 |
+
""" Generates an AST for a function implementing the Newton-Raphson method.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
==========
|
| 128 |
+
|
| 129 |
+
expr : expression
|
| 130 |
+
wrt : Symbol
|
| 131 |
+
With respect to, i.e. what is the variable
|
| 132 |
+
params : iterable of symbols
|
| 133 |
+
Symbols appearing in expr that are taken as constants during the iterations
|
| 134 |
+
(these will be accepted as parameters to the generated function).
|
| 135 |
+
func_name : str
|
| 136 |
+
Name of the generated function.
|
| 137 |
+
attrs : Tuple
|
| 138 |
+
Attribute instances passed as ``attrs`` to ``FunctionDefinition``.
|
| 139 |
+
\\*\\*kwargs :
|
| 140 |
+
Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`.
|
| 141 |
+
|
| 142 |
+
Examples
|
| 143 |
+
========
|
| 144 |
+
|
| 145 |
+
>>> from sympy import symbols, cos
|
| 146 |
+
>>> from sympy.codegen.algorithms import newtons_method_function
|
| 147 |
+
>>> from sympy.codegen.pyutils import render_as_module
|
| 148 |
+
>>> x = symbols('x')
|
| 149 |
+
>>> expr = cos(x) - x**3
|
| 150 |
+
>>> func = newtons_method_function(expr, x)
|
| 151 |
+
>>> py_mod = render_as_module(func) # source code as string
|
| 152 |
+
>>> namespace = {}
|
| 153 |
+
>>> exec(py_mod, namespace, namespace)
|
| 154 |
+
>>> res = eval('newton(0.5)', namespace)
|
| 155 |
+
>>> abs(res - 0.865474033102) < 1e-12
|
| 156 |
+
True
|
| 157 |
+
|
| 158 |
+
See Also
|
| 159 |
+
========
|
| 160 |
+
|
| 161 |
+
sympy.codegen.algorithms.newtons_method
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
if params is None:
|
| 165 |
+
params = (wrt,)
|
| 166 |
+
pointer_subs = {p.symbol: Symbol('(*%s)' % p.symbol.name)
|
| 167 |
+
for p in params if isinstance(p, Pointer)}
|
| 168 |
+
if delta is None:
|
| 169 |
+
delta = Symbol('d_' + wrt.name)
|
| 170 |
+
if expr.has(delta):
|
| 171 |
+
delta = None # will use Dummy
|
| 172 |
+
algo = newtons_method(expr, wrt, delta=delta, **kwargs).xreplace(pointer_subs)
|
| 173 |
+
if isinstance(algo, Scope):
|
| 174 |
+
algo = algo.body
|
| 175 |
+
not_in_params = expr.free_symbols.difference({_symbol_of(p) for p in params})
|
| 176 |
+
if not_in_params:
|
| 177 |
+
raise ValueError("Missing symbols in params: %s" % ', '.join(map(str, not_in_params)))
|
| 178 |
+
declars = tuple(Variable(p, real) for p in params)
|
| 179 |
+
body = CodeBlock(algo, Return(wrt))
|
| 180 |
+
return FunctionDefinition(real, func_name, declars, body, attrs=attrs)
|
shared/package-files/18/1855a71ae746e0bd92c9d8088768f15409d6c10fe017b666c406c5d90ca0473e/exceptions.cpython-311.pyc
ADDED
|
Binary file (943 Bytes). View file
|
|
|
shared/package-files/18/1858f22f67ad031bd5337abb36114419c5d2e60c8a8fc5736ea71b2b3a6a6ce9/test_dist.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import urllib.parse
|
| 4 |
+
import urllib.request
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
from setuptools import Distribution
|
| 9 |
+
from setuptools.dist import check_package_data, check_specifier
|
| 10 |
+
|
| 11 |
+
from .test_easy_install import make_trivial_sdist
|
| 12 |
+
from .test_find_packages import ensure_files
|
| 13 |
+
from .textwrap import DALS
|
| 14 |
+
|
| 15 |
+
from distutils.errors import DistutilsSetupError
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_dist_fetch_build_egg(tmpdir):
|
| 19 |
+
"""
|
| 20 |
+
Check multiple calls to `Distribution.fetch_build_egg` work as expected.
|
| 21 |
+
"""
|
| 22 |
+
index = tmpdir.mkdir('index')
|
| 23 |
+
index_url = urllib.parse.urljoin('file://', urllib.request.pathname2url(str(index)))
|
| 24 |
+
|
| 25 |
+
def sdist_with_index(distname, version):
|
| 26 |
+
dist_dir = index.mkdir(distname)
|
| 27 |
+
dist_sdist = f'{distname}-{version}.tar.gz'
|
| 28 |
+
make_trivial_sdist(str(dist_dir.join(dist_sdist)), distname, version)
|
| 29 |
+
with dist_dir.join('index.html').open('w') as fp:
|
| 30 |
+
fp.write(
|
| 31 |
+
DALS(
|
| 32 |
+
"""
|
| 33 |
+
<!DOCTYPE html><html><body>
|
| 34 |
+
<a href="{dist_sdist}" rel="internal">{dist_sdist}</a><br/>
|
| 35 |
+
</body></html>
|
| 36 |
+
"""
|
| 37 |
+
).format(dist_sdist=dist_sdist)
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
sdist_with_index('barbazquux', '3.2.0')
|
| 41 |
+
sdist_with_index('barbazquux-runner', '2.11.1')
|
| 42 |
+
with tmpdir.join('setup.cfg').open('w') as fp:
|
| 43 |
+
fp.write(
|
| 44 |
+
DALS(
|
| 45 |
+
"""
|
| 46 |
+
[easy_install]
|
| 47 |
+
index_url = {index_url}
|
| 48 |
+
"""
|
| 49 |
+
).format(index_url=index_url)
|
| 50 |
+
)
|
| 51 |
+
reqs = """
|
| 52 |
+
barbazquux-runner
|
| 53 |
+
barbazquux
|
| 54 |
+
""".split()
|
| 55 |
+
with tmpdir.as_cwd():
|
| 56 |
+
dist = Distribution()
|
| 57 |
+
dist.parse_config_files()
|
| 58 |
+
resolved_dists = [dist.fetch_build_egg(r) for r in reqs]
|
| 59 |
+
assert [dist.key for dist in resolved_dists if dist] == reqs
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EXAMPLE_BASE_INFO = dict(
|
| 63 |
+
name="package",
|
| 64 |
+
version="0.0.1",
|
| 65 |
+
author="Foo Bar",
|
| 66 |
+
author_email="foo@bar.net",
|
| 67 |
+
long_description="Long\ndescription",
|
| 68 |
+
description="Short description",
|
| 69 |
+
keywords=["one", "two"],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_provides_extras_deterministic_order():
|
| 74 |
+
attrs = dict(extras_require=dict(a=['foo'], b=['bar']))
|
| 75 |
+
dist = Distribution(attrs)
|
| 76 |
+
assert list(dist.metadata.provides_extras) == ['a', 'b']
|
| 77 |
+
attrs['extras_require'] = dict(reversed(attrs['extras_require'].items()))
|
| 78 |
+
dist = Distribution(attrs)
|
| 79 |
+
assert list(dist.metadata.provides_extras) == ['b', 'a']
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
CHECK_PACKAGE_DATA_TESTS = (
|
| 83 |
+
# Valid.
|
| 84 |
+
(
|
| 85 |
+
{
|
| 86 |
+
'': ['*.txt', '*.rst'],
|
| 87 |
+
'hello': ['*.msg'],
|
| 88 |
+
},
|
| 89 |
+
None,
|
| 90 |
+
),
|
| 91 |
+
# Not a dictionary.
|
| 92 |
+
(
|
| 93 |
+
(
|
| 94 |
+
('', ['*.txt', '*.rst']),
|
| 95 |
+
('hello', ['*.msg']),
|
| 96 |
+
),
|
| 97 |
+
(
|
| 98 |
+
"'package_data' must be a dictionary mapping package"
|
| 99 |
+
" names to lists of string wildcard patterns"
|
| 100 |
+
),
|
| 101 |
+
),
|
| 102 |
+
# Invalid key type.
|
| 103 |
+
(
|
| 104 |
+
{
|
| 105 |
+
400: ['*.txt', '*.rst'],
|
| 106 |
+
},
|
| 107 |
+
("keys of 'package_data' dict must be strings (got 400)"),
|
| 108 |
+
),
|
| 109 |
+
# Invalid value type.
|
| 110 |
+
(
|
| 111 |
+
{
|
| 112 |
+
'hello': '*.msg',
|
| 113 |
+
},
|
| 114 |
+
(
|
| 115 |
+
"\"values of 'package_data' dict\" must be of type <tuple[str, ...] | list[str]>"
|
| 116 |
+
" (got '*.msg')"
|
| 117 |
+
),
|
| 118 |
+
),
|
| 119 |
+
# Invalid value type (generators are single use)
|
| 120 |
+
(
|
| 121 |
+
{
|
| 122 |
+
'hello': (x for x in "generator"),
|
| 123 |
+
},
|
| 124 |
+
(
|
| 125 |
+
"\"values of 'package_data' dict\" must be of type <tuple[str, ...] | list[str]>"
|
| 126 |
+
" (got <generator object"
|
| 127 |
+
),
|
| 128 |
+
),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@pytest.mark.parametrize(('package_data', 'expected_message'), CHECK_PACKAGE_DATA_TESTS)
|
| 133 |
+
def test_check_package_data(package_data, expected_message):
|
| 134 |
+
if expected_message is None:
|
| 135 |
+
assert check_package_data(None, 'package_data', package_data) is None
|
| 136 |
+
else:
|
| 137 |
+
with pytest.raises(DistutilsSetupError, match=re.escape(expected_message)):
|
| 138 |
+
check_package_data(None, 'package_data', package_data)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_check_specifier():
|
| 142 |
+
# valid specifier value
|
| 143 |
+
attrs = {'name': 'foo', 'python_requires': '>=3.0, !=3.1'}
|
| 144 |
+
dist = Distribution(attrs)
|
| 145 |
+
check_specifier(dist, attrs, attrs['python_requires'])
|
| 146 |
+
|
| 147 |
+
attrs = {'name': 'foo', 'python_requires': ['>=3.0', '!=3.1']}
|
| 148 |
+
dist = Distribution(attrs)
|
| 149 |
+
check_specifier(dist, attrs, attrs['python_requires'])
|
| 150 |
+
|
| 151 |
+
# invalid specifier value
|
| 152 |
+
attrs = {'name': 'foo', 'python_requires': '>=invalid-version'}
|
| 153 |
+
with pytest.raises(DistutilsSetupError):
|
| 154 |
+
dist = Distribution(attrs)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_metadata_name():
|
| 158 |
+
with pytest.raises(DistutilsSetupError, match='missing.*name'):
|
| 159 |
+
Distribution()._validate_metadata()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@pytest.mark.parametrize(
|
| 163 |
+
('dist_name', 'py_module'),
|
| 164 |
+
[
|
| 165 |
+
("my.pkg", "my_pkg"),
|
| 166 |
+
("my-pkg", "my_pkg"),
|
| 167 |
+
("my_pkg", "my_pkg"),
|
| 168 |
+
("pkg", "pkg"),
|
| 169 |
+
],
|
| 170 |
+
)
|
| 171 |
+
def test_dist_default_py_modules(tmp_path, dist_name, py_module):
|
| 172 |
+
(tmp_path / f"{py_module}.py").touch()
|
| 173 |
+
|
| 174 |
+
(tmp_path / "setup.py").touch()
|
| 175 |
+
(tmp_path / "noxfile.py").touch()
|
| 176 |
+
# ^-- make sure common tool files are ignored
|
| 177 |
+
|
| 178 |
+
attrs = {**EXAMPLE_BASE_INFO, "name": dist_name, "src_root": str(tmp_path)}
|
| 179 |
+
# Find `py_modules` corresponding to dist_name if not given
|
| 180 |
+
dist = Distribution(attrs)
|
| 181 |
+
dist.set_defaults()
|
| 182 |
+
assert dist.py_modules == [py_module]
|
| 183 |
+
# When `py_modules` is given, don't do anything
|
| 184 |
+
dist = Distribution({**attrs, "py_modules": ["explicity_py_module"]})
|
| 185 |
+
dist.set_defaults()
|
| 186 |
+
assert dist.py_modules == ["explicity_py_module"]
|
| 187 |
+
# When `packages` is given, don't do anything
|
| 188 |
+
dist = Distribution({**attrs, "packages": ["explicity_package"]})
|
| 189 |
+
dist.set_defaults()
|
| 190 |
+
assert not dist.py_modules
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@pytest.mark.parametrize(
|
| 194 |
+
('dist_name', 'package_dir', 'package_files', 'packages'),
|
| 195 |
+
[
|
| 196 |
+
("my.pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]),
|
| 197 |
+
("my-pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]),
|
| 198 |
+
("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/mod.py"], ["my_pkg"]),
|
| 199 |
+
("my.pkg", None, ["my/pkg/__init__.py"], ["my", "my.pkg"]),
|
| 200 |
+
(
|
| 201 |
+
"my_pkg",
|
| 202 |
+
None,
|
| 203 |
+
["src/my_pkg/__init__.py", "src/my_pkg2/__init__.py"],
|
| 204 |
+
["my_pkg", "my_pkg2"],
|
| 205 |
+
),
|
| 206 |
+
(
|
| 207 |
+
"my_pkg",
|
| 208 |
+
{"pkg": "lib", "pkg2": "lib2"},
|
| 209 |
+
["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"],
|
| 210 |
+
["pkg", "pkg.nested", "pkg2"],
|
| 211 |
+
),
|
| 212 |
+
],
|
| 213 |
+
)
|
| 214 |
+
def test_dist_default_packages(
|
| 215 |
+
tmp_path, dist_name, package_dir, package_files, packages
|
| 216 |
+
):
|
| 217 |
+
ensure_files(tmp_path, package_files)
|
| 218 |
+
|
| 219 |
+
(tmp_path / "setup.py").touch()
|
| 220 |
+
(tmp_path / "noxfile.py").touch()
|
| 221 |
+
# ^-- should not be included by default
|
| 222 |
+
|
| 223 |
+
attrs = {
|
| 224 |
+
**EXAMPLE_BASE_INFO,
|
| 225 |
+
"name": dist_name,
|
| 226 |
+
"src_root": str(tmp_path),
|
| 227 |
+
"package_dir": package_dir,
|
| 228 |
+
}
|
| 229 |
+
# Find `packages` either corresponding to dist_name or inside src
|
| 230 |
+
dist = Distribution(attrs)
|
| 231 |
+
dist.set_defaults()
|
| 232 |
+
assert not dist.py_modules
|
| 233 |
+
assert not dist.py_modules
|
| 234 |
+
assert set(dist.packages) == set(packages)
|
| 235 |
+
# When `py_modules` is given, don't do anything
|
| 236 |
+
dist = Distribution({**attrs, "py_modules": ["explicit_py_module"]})
|
| 237 |
+
dist.set_defaults()
|
| 238 |
+
assert not dist.packages
|
| 239 |
+
assert set(dist.py_modules) == {"explicit_py_module"}
|
| 240 |
+
# When `packages` is given, don't do anything
|
| 241 |
+
dist = Distribution({**attrs, "packages": ["explicit_package"]})
|
| 242 |
+
dist.set_defaults()
|
| 243 |
+
assert not dist.py_modules
|
| 244 |
+
assert set(dist.packages) == {"explicit_package"}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@pytest.mark.parametrize(
|
| 248 |
+
('dist_name', 'package_dir', 'package_files'),
|
| 249 |
+
[
|
| 250 |
+
("my.pkg.nested", None, ["my/pkg/nested/__init__.py"]),
|
| 251 |
+
("my.pkg", None, ["my/pkg/__init__.py", "my/pkg/file.py"]),
|
| 252 |
+
("my_pkg", None, ["my_pkg.py"]),
|
| 253 |
+
("my_pkg", None, ["my_pkg/__init__.py", "my_pkg/nested/__init__.py"]),
|
| 254 |
+
("my_pkg", None, ["src/my_pkg/__init__.py", "src/my_pkg/nested/__init__.py"]),
|
| 255 |
+
(
|
| 256 |
+
"my_pkg",
|
| 257 |
+
{"my_pkg": "lib", "my_pkg.lib2": "lib2"},
|
| 258 |
+
["lib/__init__.py", "lib/nested/__init__.pyt", "lib2/__init__.py"],
|
| 259 |
+
),
|
| 260 |
+
# Should not try to guess a name from multiple py_modules/packages
|
| 261 |
+
("UNKNOWN", None, ["src/mod1.py", "src/mod2.py"]),
|
| 262 |
+
("UNKNOWN", None, ["src/pkg1/__ini__.py", "src/pkg2/__init__.py"]),
|
| 263 |
+
],
|
| 264 |
+
)
|
| 265 |
+
def test_dist_default_name(tmp_path, dist_name, package_dir, package_files):
|
| 266 |
+
"""Make sure dist.name is discovered from packages/py_modules"""
|
| 267 |
+
ensure_files(tmp_path, package_files)
|
| 268 |
+
attrs = {
|
| 269 |
+
**EXAMPLE_BASE_INFO,
|
| 270 |
+
"src_root": "/".join(os.path.split(tmp_path)), # POSIX-style
|
| 271 |
+
"package_dir": package_dir,
|
| 272 |
+
}
|
| 273 |
+
del attrs["name"]
|
| 274 |
+
|
| 275 |
+
dist = Distribution(attrs)
|
| 276 |
+
dist.set_defaults()
|
| 277 |
+
assert dist.py_modules or dist.packages
|
| 278 |
+
assert dist.get_name() == dist_name
|
shared/package-files/18/18710c3cbccb74d874bc184bf77629cbfc5f77d6a35b873841c1a6f488cdf7cc/vcfconcat.c.pysam.c
ADDED
|
@@ -0,0 +1,1131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "bcftools.pysam.h"
|
| 2 |
+
|
| 3 |
+
/* vcfconcat.c -- Concatenate or combine VCF/BCF files.
|
| 4 |
+
|
| 5 |
+
Copyright (C) 2013-2023 Genome Research Ltd.
|
| 6 |
+
|
| 7 |
+
Author: Petr Danecek <pd3@sanger.ac.uk>
|
| 8 |
+
|
| 9 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 10 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 11 |
+
in the Software without restriction, including without limitation the rights
|
| 12 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 13 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 14 |
+
furnished to do so, subject to the following conditions:
|
| 15 |
+
|
| 16 |
+
The above copyright notice and this permission notice shall be included in
|
| 17 |
+
all copies or substantial portions of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 20 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 21 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 22 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 23 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 24 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 25 |
+
THE SOFTWARE. */
|
| 26 |
+
|
| 27 |
+
#include <stdio.h>
|
| 28 |
+
#include <unistd.h>
|
| 29 |
+
#include <getopt.h>
|
| 30 |
+
#include <string.h>
|
| 31 |
+
#include <assert.h>
|
| 32 |
+
#include <errno.h>
|
| 33 |
+
#include <math.h>
|
| 34 |
+
#include <stdint.h>
|
| 35 |
+
#include <inttypes.h>
|
| 36 |
+
#include <htslib/vcf.h>
|
| 37 |
+
#include <htslib/synced_bcf_reader.h>
|
| 38 |
+
#include <htslib/kseq.h>
|
| 39 |
+
#include <htslib/bgzf.h>
|
| 40 |
+
#include <htslib/tbx.h> // for hts_get_bgzfp()
|
| 41 |
+
#include <htslib/thread_pool.h>
|
| 42 |
+
#include <htslib/hts_endian.h>
|
| 43 |
+
#include <sys/time.h>
|
| 44 |
+
#include "bcftools.h"
|
| 45 |
+
|
| 46 |
+
typedef struct _args_t
|
| 47 |
+
{
|
| 48 |
+
bcf_srs_t *files;
|
| 49 |
+
htsFile *out_fh;
|
| 50 |
+
int output_type, n_threads, record_cmd_line, clevel;
|
| 51 |
+
bcf_hdr_t *out_hdr;
|
| 52 |
+
int *seen_seq;
|
| 53 |
+
char *index_fn;
|
| 54 |
+
int write_index;
|
| 55 |
+
|
| 56 |
+
// phasing
|
| 57 |
+
int *start_pos, start_tid, ifname;
|
| 58 |
+
int *swap_phase, nswap, *nmatch, *nmism;
|
| 59 |
+
bcf1_t **buf;
|
| 60 |
+
uint8_t *buf_mask;
|
| 61 |
+
int nbuf, mbuf, prev_chr, min_PQ, prev_pos_check;
|
| 62 |
+
int32_t *GTa, *GTb, mGTa, mGTb, *phase_qual, *phase_set;
|
| 63 |
+
|
| 64 |
+
char **argv, *output_fname, *file_list, **fnames, *remove_dups, *regions_list;
|
| 65 |
+
int argc, nfnames, allow_overlaps, phased_concat, regions_is_file, regions_overlap;
|
| 66 |
+
int compact_PS, phase_set_changed, naive_concat, naive_concat_trust_headers;
|
| 67 |
+
int verbose, explicit_output_type, ligate_force, ligate_warn;
|
| 68 |
+
int sites_only;
|
| 69 |
+
htsThreadPool *tpool;
|
| 70 |
+
}
|
| 71 |
+
args_t;
|
| 72 |
+
|
| 73 |
+
static bcf_hdr_t *drop_hdr_genotypes(args_t *args, bcf_hdr_t *hdr)
|
| 74 |
+
{
|
| 75 |
+
if ( !args->sites_only ) return hdr;
|
| 76 |
+
bcf_hdr_t *rmme = hdr;
|
| 77 |
+
hdr = bcf_hdr_subset(rmme, 0, 0, 0);
|
| 78 |
+
bcf_hdr_remove(hdr, BCF_HL_FMT, NULL);
|
| 79 |
+
bcf_hdr_destroy(rmme);
|
| 80 |
+
return hdr;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
static void init_data(args_t *args)
|
| 84 |
+
{
|
| 85 |
+
bcf1_t *line = NULL;
|
| 86 |
+
|
| 87 |
+
// With phased concat, the chunks overlap and come in the right order. To
|
| 88 |
+
// avoid opening all files at once, store start positions to recognise need
|
| 89 |
+
// for the next one. This way we can keep only two open chunks at once.
|
| 90 |
+
if ( args->phased_concat )
|
| 91 |
+
{
|
| 92 |
+
args->start_pos = (int*) malloc(sizeof(int)*args->nfnames);
|
| 93 |
+
line = bcf_init();
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
if ( args->verbose ) fprintf(bcftools_stderr,"Checking the headers and starting positions of %d files\n", args->nfnames);
|
| 97 |
+
kstring_t str = {0,0,0};
|
| 98 |
+
int i, prev_chrid = -1;
|
| 99 |
+
for (i=0; i<args->nfnames; i++)
|
| 100 |
+
{
|
| 101 |
+
htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]);
|
| 102 |
+
bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]);
|
| 103 |
+
hdr = drop_hdr_genotypes(args, hdr);
|
| 104 |
+
|
| 105 |
+
args->out_hdr = bcf_hdr_merge(args->out_hdr,hdr);
|
| 106 |
+
if ( bcf_hdr_nsamples(hdr) != bcf_hdr_nsamples(args->out_hdr) )
|
| 107 |
+
error("Different number of samples in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]);
|
| 108 |
+
|
| 109 |
+
int j;
|
| 110 |
+
for (j=0; j<bcf_hdr_nsamples(hdr); j++)
|
| 111 |
+
if ( strcmp(args->out_hdr->samples[j],hdr->samples[j]) )
|
| 112 |
+
error("Different sample names in %s. Perhaps \"bcftools merge\" is what you are looking for?\n", args->fnames[i]);
|
| 113 |
+
|
| 114 |
+
if ( args->phased_concat )
|
| 115 |
+
{
|
| 116 |
+
int ret = bcf_read(fp, hdr, line);
|
| 117 |
+
if ( ret!=0 ) args->start_pos[i] = -2; // empty file
|
| 118 |
+
else
|
| 119 |
+
{
|
| 120 |
+
int chrid = bcf_hdr_id2int(args->out_hdr,BCF_DT_CTG,bcf_seqname(hdr,line));
|
| 121 |
+
args->start_pos[i] = chrid==prev_chrid ? line->pos : -1;
|
| 122 |
+
prev_chrid = chrid;
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
bcf_hdr_destroy(hdr);
|
| 126 |
+
if ( hts_close(fp)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,args->fnames[i]);
|
| 127 |
+
}
|
| 128 |
+
free(str.s);
|
| 129 |
+
if ( line ) bcf_destroy(line);
|
| 130 |
+
|
| 131 |
+
args->seen_seq = (int*) calloc(args->out_hdr->n[BCF_DT_CTG],sizeof(int));
|
| 132 |
+
|
| 133 |
+
if ( args->phased_concat )
|
| 134 |
+
{
|
| 135 |
+
bcf_hdr_append(args->out_hdr,"##FORMAT=<ID=PQ,Number=1,Type=Integer,Description=\"Phasing Quality (bigger is better)\">");
|
| 136 |
+
bcf_hdr_append(args->out_hdr,"##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase Set\">");
|
| 137 |
+
}
|
| 138 |
+
if (args->record_cmd_line) bcf_hdr_append_version(args->out_hdr, args->argc, args->argv, "bcftools_concat");
|
| 139 |
+
char wmode[8];
|
| 140 |
+
set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
|
| 141 |
+
args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
|
| 142 |
+
if ( args->out_fh == NULL ) error("Can't write to \"%s\": %s\n", args->output_fname, strerror(errno));
|
| 143 |
+
if ( args->allow_overlaps || args->phased_concat )
|
| 144 |
+
{
|
| 145 |
+
args->files = bcf_sr_init();
|
| 146 |
+
args->files->require_index = 1;
|
| 147 |
+
}
|
| 148 |
+
if ( args->n_threads )
|
| 149 |
+
{
|
| 150 |
+
if ( args->files )
|
| 151 |
+
{
|
| 152 |
+
if ( bcf_sr_set_threads(args->files, args->n_threads)<0 ) error("Failed to create threads\n");
|
| 153 |
+
args->tpool = args->files->p;
|
| 154 |
+
}
|
| 155 |
+
else
|
| 156 |
+
{
|
| 157 |
+
args->tpool = (htsThreadPool*) calloc(1, sizeof(htsThreadPool));
|
| 158 |
+
if ( !args->tpool ) error("Failed to allocate memory\n");
|
| 159 |
+
if ( !(args->tpool->pool = hts_tpool_init(args->n_threads)) ) error("Failed to initialize %d threads\n",args->n_threads);
|
| 160 |
+
}
|
| 161 |
+
hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->tpool);
|
| 162 |
+
}
|
| 163 |
+
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);
|
| 164 |
+
if ( init_index2(args->out_fh,args->out_hdr,args->output_fname,
|
| 165 |
+
&args->index_fn, args->write_index)<0 )
|
| 166 |
+
error("Error: failed to initialise index for %s\n",args->output_fname);
|
| 167 |
+
|
| 168 |
+
if ( args->allow_overlaps )
|
| 169 |
+
{
|
| 170 |
+
if ( args->regions_list )
|
| 171 |
+
{
|
| 172 |
+
bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,args->regions_overlap);
|
| 173 |
+
if ( bcf_sr_set_regions(args->files, args->regions_list, args->regions_is_file)<0 )
|
| 174 |
+
error("Failed to read the regions: %s\n", args->regions_list);
|
| 175 |
+
}
|
| 176 |
+
if ( args->remove_dups )
|
| 177 |
+
{
|
| 178 |
+
if ( !strcmp(args->remove_dups,"snps") ) args->files->collapse |= COLLAPSE_SNPS;
|
| 179 |
+
else if ( !strcmp(args->remove_dups,"indels") ) args->files->collapse |= COLLAPSE_INDELS;
|
| 180 |
+
else if ( !strcmp(args->remove_dups,"both") ) args->files->collapse |= COLLAPSE_SNPS | COLLAPSE_INDELS;
|
| 181 |
+
else if ( !strcmp(args->remove_dups,"any") ) args->files->collapse |= COLLAPSE_ANY;
|
| 182 |
+
else if ( !strcmp(args->remove_dups,"all") ) args->files->collapse |= COLLAPSE_ANY;
|
| 183 |
+
else if ( !strcmp(args->remove_dups,"none") ) args->files->collapse = COLLAPSE_NONE;
|
| 184 |
+
else if ( !strcmp(args->remove_dups,"exact") ) args->files->collapse = COLLAPSE_NONE;
|
| 185 |
+
else error("The -D string \"%s\" not recognised.\n", args->remove_dups);
|
| 186 |
+
}
|
| 187 |
+
for (i=0; i<args->nfnames; i++)
|
| 188 |
+
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));
|
| 189 |
+
}
|
| 190 |
+
else if ( args->phased_concat )
|
| 191 |
+
{
|
| 192 |
+
// Remove empty files from the list
|
| 193 |
+
int nok = 0;
|
| 194 |
+
while (1)
|
| 195 |
+
{
|
| 196 |
+
while ( nok<args->nfnames && args->start_pos[nok]!=-2 ) nok++;
|
| 197 |
+
if ( nok==args->nfnames ) break;
|
| 198 |
+
|
| 199 |
+
i = nok;
|
| 200 |
+
while ( i<args->nfnames && args->start_pos[i]==-2 ) i++;
|
| 201 |
+
if ( i==args->nfnames ) break;
|
| 202 |
+
|
| 203 |
+
int tmp = args->start_pos[nok]; args->start_pos[nok] = args->start_pos[i]; args->start_pos[i] = tmp;
|
| 204 |
+
char *str = args->fnames[nok]; args->fnames[nok] = args->fnames[i]; args->fnames[i] = str;
|
| 205 |
+
}
|
| 206 |
+
for (i=nok; i<args->nfnames; i++) free(args->fnames[i]);
|
| 207 |
+
args->nfnames = nok;
|
| 208 |
+
|
| 209 |
+
for (i=1; i<args->nfnames; i++)
|
| 210 |
+
if ( args->start_pos[i-1]!=-1 && args->start_pos[i]!=-1 && args->start_pos[i]<args->start_pos[i-1] )
|
| 211 |
+
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]);
|
| 212 |
+
|
| 213 |
+
args->prev_chr = -1;
|
| 214 |
+
args->swap_phase = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
|
| 215 |
+
args->nmatch = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
|
| 216 |
+
args->nmism = (int*) calloc(bcf_hdr_nsamples(args->out_hdr),sizeof(int));
|
| 217 |
+
args->phase_qual = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t));
|
| 218 |
+
args->phase_set = (int32_t*) malloc(bcf_hdr_nsamples(args->out_hdr)*sizeof(int32_t));
|
| 219 |
+
args->ifname = 0;
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
static void destroy_data(args_t *args)
|
| 224 |
+
{
|
| 225 |
+
int i;
|
| 226 |
+
if ( args->out_fh )
|
| 227 |
+
{
|
| 228 |
+
if ( args->write_index )
|
| 229 |
+
{
|
| 230 |
+
if ( bcf_idx_save(args->out_fh)<0 )
|
| 231 |
+
{
|
| 232 |
+
if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
|
| 233 |
+
error("Error: cannot write to index %s\n", args->index_fn);
|
| 234 |
+
}
|
| 235 |
+
free(args->index_fn);
|
| 236 |
+
}
|
| 237 |
+
if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n",args->output_fname?args->output_fname:"bcftools_stdout");
|
| 238 |
+
}
|
| 239 |
+
if ( args->tpool && !args->files )
|
| 240 |
+
{
|
| 241 |
+
hts_tpool_destroy(args->tpool->pool);
|
| 242 |
+
free(args->tpool);
|
| 243 |
+
}
|
| 244 |
+
if ( args->files ) bcf_sr_destroy(args->files);
|
| 245 |
+
if ( args->out_hdr ) bcf_hdr_destroy(args->out_hdr);
|
| 246 |
+
free(args->seen_seq);
|
| 247 |
+
free(args->start_pos);
|
| 248 |
+
free(args->swap_phase);
|
| 249 |
+
for (i=0; i<args->mbuf; i++) bcf_destroy(args->buf[i]);
|
| 250 |
+
free(args->buf);
|
| 251 |
+
free(args->buf_mask);
|
| 252 |
+
free(args->GTa);
|
| 253 |
+
free(args->GTb);
|
| 254 |
+
free(args->nmatch);
|
| 255 |
+
free(args->nmism);
|
| 256 |
+
free(args->phase_qual);
|
| 257 |
+
free(args->phase_set);
|
| 258 |
+
for (i=0; i<args->nfnames; i++) free(args->fnames[i]);
|
| 259 |
+
free(args->fnames);
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
int vcf_write_line(htsFile *fp, kstring_t *line);
|
| 263 |
+
|
| 264 |
+
#define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
|
| 265 |
+
static void phase_update(args_t *args, bcf_hdr_t *hdr, bcf1_t *rec)
|
| 266 |
+
{
|
| 267 |
+
int i, nGTs = bcf_get_genotypes(hdr, rec, &args->GTa, &args->mGTa);
|
| 268 |
+
if ( nGTs <= 0 ) return; // GT field is not present
|
| 269 |
+
for (i=0; i<bcf_hdr_nsamples(hdr); i++)
|
| 270 |
+
{
|
| 271 |
+
if ( !args->swap_phase[i] ) continue;
|
| 272 |
+
int *gt = &args->GTa[i*2];
|
| 273 |
+
if ( bcf_gt_is_missing(gt[0]) || gt[1]==bcf_int32_vector_end ) continue;
|
| 274 |
+
if ( !bcf_gt_is_phased(gt[1]) ) continue;
|
| 275 |
+
SWAP(int, gt[0], gt[1]);
|
| 276 |
+
gt[1] |= 1;
|
| 277 |
+
}
|
| 278 |
+
bcf_update_genotypes(hdr,rec,args->GTa,nGTs);
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
static void phased_flush(args_t *args)
|
| 282 |
+
{
|
| 283 |
+
if ( !args->nbuf ) return;
|
| 284 |
+
|
| 285 |
+
bcf_hdr_t *ahdr = args->files->readers[0].header;
|
| 286 |
+
bcf_hdr_t *bhdr = args->files->readers[1].header;
|
| 287 |
+
|
| 288 |
+
int i, j, nsmpl = bcf_hdr_nsamples(args->out_hdr);
|
| 289 |
+
static int gt_absent_warned = 0;
|
| 290 |
+
for (i=0; i<args->nbuf; i+=2)
|
| 291 |
+
{
|
| 292 |
+
if ( args->buf_mask[i/2]!=3 ) continue;
|
| 293 |
+
|
| 294 |
+
bcf1_t *arec = args->buf[i];
|
| 295 |
+
bcf1_t *brec = args->buf[i+1];
|
| 296 |
+
|
| 297 |
+
int nGTs = bcf_get_genotypes(ahdr, arec, &args->GTa, &args->mGTa);
|
| 298 |
+
if ( nGTs < 0 )
|
| 299 |
+
{
|
| 300 |
+
if ( !gt_absent_warned )
|
| 301 |
+
{
|
| 302 |
+
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);
|
| 303 |
+
gt_absent_warned = 1;
|
| 304 |
+
}
|
| 305 |
+
continue;
|
| 306 |
+
}
|
| 307 |
+
if ( nGTs != 2*nsmpl ) continue; // not diploid
|
| 308 |
+
nGTs = bcf_get_genotypes(bhdr, brec, &args->GTb, &args->mGTb);
|
| 309 |
+
if ( nGTs < 0 )
|
| 310 |
+
{
|
| 311 |
+
if ( !gt_absent_warned )
|
| 312 |
+
{
|
| 313 |
+
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);
|
| 314 |
+
gt_absent_warned = 1;
|
| 315 |
+
}
|
| 316 |
+
continue;
|
| 317 |
+
}
|
| 318 |
+
if ( nGTs != 2*nsmpl ) continue; // not diploid
|
| 319 |
+
|
| 320 |
+
for (j=0; j<nsmpl; j++)
|
| 321 |
+
{
|
| 322 |
+
int *gta = &args->GTa[j*2];
|
| 323 |
+
int *gtb = &args->GTb[j*2];
|
| 324 |
+
if ( gta[1]==bcf_int32_vector_end || gtb[1]==bcf_int32_vector_end ) continue;
|
| 325 |
+
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;
|
| 326 |
+
if ( !bcf_gt_is_phased(gta[1]) || !bcf_gt_is_phased(gtb[1]) ) continue;
|
| 327 |
+
if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gta[1]) || bcf_gt_allele(gtb[0])==bcf_gt_allele(gtb[1]) ) continue;
|
| 328 |
+
if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[0]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[1]) )
|
| 329 |
+
{
|
| 330 |
+
if ( args->swap_phase[j] ) args->nmism[j]++; else args->nmatch[j]++;
|
| 331 |
+
}
|
| 332 |
+
if ( bcf_gt_allele(gta[0])==bcf_gt_allele(gtb[1]) && bcf_gt_allele(gta[1])==bcf_gt_allele(gtb[0]) )
|
| 333 |
+
{
|
| 334 |
+
if ( args->swap_phase[j] ) args->nmatch[j]++; else args->nmism[j]++;
|
| 335 |
+
}
|
| 336 |
+
}
|
| 337 |
+
}
|
| 338 |
+
for (i=0; i<args->nbuf/2; i+=2)
|
| 339 |
+
{
|
| 340 |
+
bcf1_t *rec;
|
| 341 |
+
bcf_hdr_t *hdr;
|
| 342 |
+
int mask = args->buf_mask[i/2];
|
| 343 |
+
if ( mask & 1 ) { rec = args->buf[i]; hdr = args->files->readers[0].header; }
|
| 344 |
+
else { rec = args->buf[i+1]; hdr = args->files->readers[1].header; }
|
| 345 |
+
bcf_translate(args->out_hdr, hdr, rec);
|
| 346 |
+
if ( args->nswap && (mask&1) )
|
| 347 |
+
phase_update(args, args->out_hdr, rec);
|
| 348 |
+
if ( !args->compact_PS || args->phase_set_changed )
|
| 349 |
+
{
|
| 350 |
+
bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl);
|
| 351 |
+
args->phase_set_changed = 0;
|
| 352 |
+
}
|
| 353 |
+
if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
|
| 354 |
+
|
| 355 |
+
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);
|
| 356 |
+
args->prev_pos_check = rec->pos;
|
| 357 |
+
}
|
| 358 |
+
args->nswap = 0;
|
| 359 |
+
for (j=0; j<nsmpl; j++)
|
| 360 |
+
{
|
| 361 |
+
if ( args->nmatch[j] >= args->nmism[j] )
|
| 362 |
+
args->swap_phase[j] = 0;
|
| 363 |
+
else
|
| 364 |
+
{
|
| 365 |
+
args->swap_phase[j] = 1;
|
| 366 |
+
args->nswap++;
|
| 367 |
+
}
|
| 368 |
+
if ( args->nmatch[j] && args->nmism[j] )
|
| 369 |
+
{
|
| 370 |
+
// Entropy-inspired quality. The factor 0.7 shifts and scales to (0,1)
|
| 371 |
+
double f = (double)args->nmatch[j]/(args->nmatch[j]+args->nmism[j]);
|
| 372 |
+
args->phase_qual[j] = 99*(0.7 + f*log(f) + (1-f)*log(1-f))/0.7;
|
| 373 |
+
}
|
| 374 |
+
else
|
| 375 |
+
args->phase_qual[j] = 99;
|
| 376 |
+
args->nmatch[j] = 0;
|
| 377 |
+
args->nmism[j] = 0;
|
| 378 |
+
}
|
| 379 |
+
int PQ_printed = 0;
|
| 380 |
+
for (; i<args->nbuf; i+=2)
|
| 381 |
+
{
|
| 382 |
+
bcf1_t *rec;
|
| 383 |
+
bcf_hdr_t *hdr;
|
| 384 |
+
int mask = args->buf_mask[i/2];
|
| 385 |
+
if ( mask & 2 ) { rec = args->buf[i+1]; hdr = args->files->readers[1].header; }
|
| 386 |
+
else { rec = args->buf[i]; hdr = args->files->readers[0].header; }
|
| 387 |
+
bcf_translate(args->out_hdr, hdr, rec);
|
| 388 |
+
if ( !PQ_printed && mask==3 )
|
| 389 |
+
{
|
| 390 |
+
bcf_update_format_int32(args->out_hdr,rec,"PQ",args->phase_qual,nsmpl);
|
| 391 |
+
PQ_printed = 1;
|
| 392 |
+
for (j=0; j<nsmpl; j++)
|
| 393 |
+
if ( args->phase_qual[j] < args->min_PQ )
|
| 394 |
+
{
|
| 395 |
+
args->phase_set[j] = rec->pos+1;
|
| 396 |
+
args->phase_set_changed = 1;
|
| 397 |
+
}
|
| 398 |
+
else if ( args->compact_PS ) args->phase_set[j] = bcf_int32_missing;
|
| 399 |
+
}
|
| 400 |
+
if ( args->nswap )
|
| 401 |
+
phase_update(args, args->out_hdr, rec);
|
| 402 |
+
if ( !args->compact_PS || args->phase_set_changed )
|
| 403 |
+
{
|
| 404 |
+
bcf_update_format_int32(args->out_hdr,rec,"PS",args->phase_set,nsmpl);
|
| 405 |
+
args->phase_set_changed = 0;
|
| 406 |
+
}
|
| 407 |
+
if ( bcf_write(args->out_fh, args->out_hdr, rec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
|
| 408 |
+
|
| 409 |
+
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);
|
| 410 |
+
args->prev_pos_check = rec->pos;
|
| 411 |
+
}
|
| 412 |
+
args->nbuf = 0;
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
static void phased_push(args_t *args, bcf1_t *arec, bcf1_t *brec, int is_overlap)
|
| 416 |
+
{
|
| 417 |
+
bcf_hdr_t *ahdr = arec ? bcf_sr_get_header(args->files,0) : NULL;
|
| 418 |
+
bcf_hdr_t *bhdr = brec ? bcf_sr_get_header(args->files,1) : NULL;
|
| 419 |
+
|
| 420 |
+
if ( arec && arec->errcode )
|
| 421 |
+
error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(ahdr,arec),(int64_t) arec->pos+1, args->files->readers[0].fname);
|
| 422 |
+
if ( brec && brec->errcode )
|
| 423 |
+
error("Parse error at %s:%"PRId64", cannot proceed: %s\n", bcf_seqname(bhdr,brec),(int64_t) brec->pos+1, args->files->readers[1].fname);
|
| 424 |
+
|
| 425 |
+
int i, nsmpl = bcf_hdr_nsamples(args->out_hdr);
|
| 426 |
+
int chr_id = arec ? bcf_hdr_name2id(args->out_hdr,bcf_seqname(ahdr,arec)) : bcf_hdr_name2id(args->out_hdr,bcf_seqname(bhdr,brec));
|
| 427 |
+
if ( args->prev_chr<0 || args->prev_chr!=chr_id )
|
| 428 |
+
{
|
| 429 |
+
if ( args->prev_chr>=0 ) phased_flush(args);
|
| 430 |
+
|
| 431 |
+
for (i=0; i<nsmpl; i++)
|
| 432 |
+
args->phase_set[i] = arec ? arec->pos+1 : brec->pos+1;
|
| 433 |
+
args->phase_set_changed = 1;
|
| 434 |
+
|
| 435 |
+
if ( args->seen_seq[chr_id] ) error("The chromosome block %s is not contiguous\n", arec ? bcf_seqname(ahdr,arec) : bcf_seqname(bhdr,brec));
|
| 436 |
+
args->seen_seq[chr_id] = 1;
|
| 437 |
+
args->prev_chr = chr_id;
|
| 438 |
+
args->prev_pos_check = -1;
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
if ( !is_overlap )
|
| 442 |
+
{
|
| 443 |
+
assert(arec);
|
| 444 |
+
|
| 445 |
+
bcf_translate(args->out_hdr, ahdr, arec);
|
| 446 |
+
if ( args->nswap )
|
| 447 |
+
phase_update(args, args->out_hdr, arec);
|
| 448 |
+
if ( !args->compact_PS || args->phase_set_changed )
|
| 449 |
+
{
|
| 450 |
+
bcf_update_format_int32(args->out_hdr,arec,"PS",args->phase_set,nsmpl);
|
| 451 |
+
args->phase_set_changed = 0;
|
| 452 |
+
}
|
| 453 |
+
if ( bcf_write(args->out_fh, args->out_hdr, arec)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
|
| 454 |
+
|
| 455 |
+
if ( arec->pos < args->prev_pos_check )
|
| 456 |
+
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);
|
| 457 |
+
args->prev_pos_check = arec->pos;
|
| 458 |
+
return;
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
int m = args->mbuf;
|
| 462 |
+
args->nbuf += 2;
|
| 463 |
+
hts_expand(bcf1_t*,args->nbuf,args->mbuf,args->buf);
|
| 464 |
+
if ( m < args->mbuf ) args->buf_mask = (uint8_t*)realloc(args->buf_mask,sizeof(*args->buf_mask)*args->mbuf);
|
| 465 |
+
for (i=m; i<args->mbuf; i++)
|
| 466 |
+
args->buf[i] = bcf_init1();
|
| 467 |
+
|
| 468 |
+
if ( arec ) SWAP(bcf1_t*, args->files->readers[0].buffer[0], args->buf[args->nbuf-2]);
|
| 469 |
+
if ( brec ) SWAP(bcf1_t*, args->files->readers[1].buffer[0], args->buf[args->nbuf-1]);
|
| 470 |
+
args->buf_mask[args->nbuf/2-1] = (arec?1:0) | (brec?2:0);
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
static int _get_active_index(bcf_srs_t *sr)
|
| 474 |
+
{
|
| 475 |
+
int i;
|
| 476 |
+
for (i=0; i<sr->nreaders; i++)
|
| 477 |
+
if ( bcf_sr_has_line(sr,i) ) return i;
|
| 478 |
+
return -1;
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
static void concat(args_t *args)
|
| 482 |
+
{
|
| 483 |
+
static int site_drop_warned = 0;
|
| 484 |
+
int i;
|
| 485 |
+
if ( args->phased_concat ) // phased concat
|
| 486 |
+
{
|
| 487 |
+
// keep only two open files at a time
|
| 488 |
+
while ( args->ifname < args->nfnames )
|
| 489 |
+
{
|
| 490 |
+
int new_file = 0;
|
| 491 |
+
while ( args->files->nreaders < 2 && args->ifname < args->nfnames )
|
| 492 |
+
{
|
| 493 |
+
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));
|
| 494 |
+
new_file = 1;
|
| 495 |
+
|
| 496 |
+
args->ifname++;
|
| 497 |
+
if ( args->start_pos[args->ifname-1]==-1 ) break; // new chromosome, start with only one file open
|
| 498 |
+
if ( args->ifname < args->nfnames && args->start_pos[args->ifname]==-1 ) break; // next file starts on a different chromosome
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
// is there a line from the previous run? Seek the newly opened reader to that position
|
| 502 |
+
int seek_pos = -1;
|
| 503 |
+
int seek_chr = -1;
|
| 504 |
+
if ( bcf_sr_has_line(args->files,0) )
|
| 505 |
+
{
|
| 506 |
+
bcf1_t *line = bcf_sr_get_line(args->files,0);
|
| 507 |
+
bcf_sr_seek(args->files, bcf_seqname(args->files->readers[0].header,line), line->pos);
|
| 508 |
+
seek_pos = line->pos;
|
| 509 |
+
seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[0].header,line));
|
| 510 |
+
}
|
| 511 |
+
else if ( new_file )
|
| 512 |
+
bcf_sr_seek(args->files,NULL,0); // set to start
|
| 513 |
+
|
| 514 |
+
int nret, ir;
|
| 515 |
+
while ( (nret = bcf_sr_next_line(args->files)) )
|
| 516 |
+
{
|
| 517 |
+
int is_overlap = args->files->nreaders==1 ? 0 : 1;
|
| 518 |
+
if ( !bcf_sr_has_line(args->files,0) ) // no input from the first reader
|
| 519 |
+
{
|
| 520 |
+
// We are assuming that there is a perfect overlap, sites which are not present in both files are dropped
|
| 521 |
+
if ( bcf_sr_region_done(args->files,0) )
|
| 522 |
+
{
|
| 523 |
+
phased_flush(args);
|
| 524 |
+
bcf_sr_remove_reader(args->files, 0);
|
| 525 |
+
is_overlap = 0;
|
| 526 |
+
}
|
| 527 |
+
else if ( args->ligate_warn )
|
| 528 |
+
{
|
| 529 |
+
if ( !site_drop_warned )
|
| 530 |
+
{
|
| 531 |
+
ir = _get_active_index(args->files);
|
| 532 |
+
fprintf(bcftools_stderr,
|
| 533 |
+
"Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n"
|
| 534 |
+
" overlap, sites in overlapping regions present in one but missing in other are dropped.\n"
|
| 535 |
+
" This warning is printed only once.\n",
|
| 536 |
+
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);
|
| 537 |
+
site_drop_warned = 1;
|
| 538 |
+
}
|
| 539 |
+
continue;
|
| 540 |
+
}
|
| 541 |
+
else if ( !args->ligate_force )
|
| 542 |
+
{
|
| 543 |
+
ir = _get_active_index(args->files);
|
| 544 |
+
error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n",
|
| 545 |
+
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);
|
| 546 |
+
}
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
// Get a line to learn about current position
|
| 550 |
+
ir = _get_active_index(args->files);
|
| 551 |
+
bcf1_t *line = bcf_sr_get_line(args->files,ir);
|
| 552 |
+
|
| 553 |
+
// This can happen after bcf_sr_seek: indel may start before the coordinate which we seek to.
|
| 554 |
+
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;
|
| 555 |
+
seek_pos = seek_chr = -1;
|
| 556 |
+
|
| 557 |
+
// Check if the position overlaps with the next, yet unopened, reader
|
| 558 |
+
int must_seek = 0;
|
| 559 |
+
while ( args->ifname < args->nfnames && args->start_pos[args->ifname]!=-1 && line->pos >= args->start_pos[args->ifname] )
|
| 560 |
+
{
|
| 561 |
+
must_seek = 1;
|
| 562 |
+
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));
|
| 563 |
+
args->ifname++;
|
| 564 |
+
}
|
| 565 |
+
if ( must_seek )
|
| 566 |
+
{
|
| 567 |
+
bcf_sr_seek(args->files, bcf_seqname(args->files->readers[ir].header,line), line->pos);
|
| 568 |
+
seek_pos = line->pos;
|
| 569 |
+
seek_chr = bcf_hdr_name2id(args->out_hdr, bcf_seqname(args->files->readers[ir].header,line));
|
| 570 |
+
continue;
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
// We are assuming that there is a perfect overlap, sites which are not present in both files are dropped
|
| 574 |
+
if ( args->files->nreaders>1 && !bcf_sr_has_line(args->files,1) && !bcf_sr_region_done(args->files,1) && !args->ligate_force )
|
| 575 |
+
{
|
| 576 |
+
if ( args->ligate_warn && !site_drop_warned )
|
| 577 |
+
{
|
| 578 |
+
ir = _get_active_index(args->files);
|
| 579 |
+
fprintf(bcftools_stderr,
|
| 580 |
+
"Warning: Dropping the site %s:%"PRId64". The --ligate option is intended for VCFs with perfect\n"
|
| 581 |
+
" overlap, sites in overlapping regions present in one but missing in other are dropped.\n"
|
| 582 |
+
" This warning is printed only once.\n",
|
| 583 |
+
bcf_seqname(bcf_sr_get_header(args->files,ir),line), (int64_t) line->pos+1);
|
| 584 |
+
site_drop_warned = 1;
|
| 585 |
+
}
|
| 586 |
+
else if ( !args->ligate_warn )
|
| 587 |
+
{
|
| 588 |
+
ir = _get_active_index(args->files);
|
| 589 |
+
error("Error: The --ligate option is intended for VCFs with perfect overlap, the site %s:%"PRId64" breaks the assumption\n",
|
| 590 |
+
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);
|
| 591 |
+
}
|
| 592 |
+
continue;
|
| 593 |
+
}
|
| 594 |
+
|
| 595 |
+
bcf1_t *line0 = bcf_sr_get_line(args->files,0);
|
| 596 |
+
bcf1_t *line1 = args->files->nreaders > 1 ? bcf_sr_get_line(args->files,1) : NULL;
|
| 597 |
+
phased_push(args, line0, line1, is_overlap);
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
if ( args->files->nreaders )
|
| 601 |
+
{
|
| 602 |
+
phased_flush(args);
|
| 603 |
+
while ( args->files->nreaders )
|
| 604 |
+
bcf_sr_remove_reader(args->files, 0);
|
| 605 |
+
}
|
| 606 |
+
}
|
| 607 |
+
}
|
| 608 |
+
else if ( args->files ) // combining overlapping files, using synced reader
|
| 609 |
+
{
|
| 610 |
+
while ( bcf_sr_next_line(args->files) )
|
| 611 |
+
{
|
| 612 |
+
for (i=0; i<args->files->nreaders; i++)
|
| 613 |
+
{
|
| 614 |
+
bcf1_t *line = bcf_sr_get_line(args->files,i);
|
| 615 |
+
if ( !line ) continue;
|
| 616 |
+
if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0);
|
| 617 |
+
bcf_translate(args->out_hdr, args->files->readers[i].header, line);
|
| 618 |
+
if ( bcf_write1(args->out_fh, args->out_hdr, line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname);
|
| 619 |
+
if ( args->remove_dups ) break;
|
| 620 |
+
}
|
| 621 |
+
}
|
| 622 |
+
}
|
| 623 |
+
else // concatenate as is
|
| 624 |
+
{
|
| 625 |
+
struct timeval t0, t1;
|
| 626 |
+
kstring_t tmp = {0,0,0};
|
| 627 |
+
int prev_chr_id = -1, prev_pos;
|
| 628 |
+
bcf1_t *line = bcf_init();
|
| 629 |
+
for (i=0; i<args->nfnames; i++)
|
| 630 |
+
{
|
| 631 |
+
if ( args->verbose )
|
| 632 |
+
{
|
| 633 |
+
fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]);
|
| 634 |
+
gettimeofday(&t0, NULL);
|
| 635 |
+
}
|
| 636 |
+
htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("\nFailed to open: %s\n", args->fnames[i]);
|
| 637 |
+
if ( args->n_threads ) hts_set_opt(fp, HTS_OPT_THREAD_POOL, args->tpool);
|
| 638 |
+
bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("\nFailed to parse header: %s\n", args->fnames[i]);
|
| 639 |
+
if ( args->sites_only )
|
| 640 |
+
{
|
| 641 |
+
bcf_hdr_t *hdr_ori = hdr;
|
| 642 |
+
hdr = bcf_hdr_subset(hdr_ori, 0, 0, 0);
|
| 643 |
+
bcf_hdr_remove(hdr, BCF_HL_FMT, NULL);
|
| 644 |
+
bcf_hdr_destroy(hdr_ori);
|
| 645 |
+
}
|
| 646 |
+
if ( !fp->is_bin && args->output_type&FT_VCF )
|
| 647 |
+
{
|
| 648 |
+
line->max_unpack = BCF_UN_STR;
|
| 649 |
+
// if VCF is on both input and output, avoid VCF to BCF conversion
|
| 650 |
+
while ( hts_getline(fp, KS_SEP_LINE, &fp->line) >=0 )
|
| 651 |
+
{
|
| 652 |
+
char *str = fp->line.s;
|
| 653 |
+
|
| 654 |
+
// remove genotypes
|
| 655 |
+
if ( args->sites_only )
|
| 656 |
+
{
|
| 657 |
+
int ntab = 0;
|
| 658 |
+
while ( *str )
|
| 659 |
+
{
|
| 660 |
+
if ( *str == '\t' && ++ntab==8 )
|
| 661 |
+
{
|
| 662 |
+
*str = 0;
|
| 663 |
+
break;
|
| 664 |
+
}
|
| 665 |
+
str++;
|
| 666 |
+
}
|
| 667 |
+
str = fp->line.s;
|
| 668 |
+
}
|
| 669 |
+
while ( *str && *str!='\t' ) str++;
|
| 670 |
+
tmp.l = 0;
|
| 671 |
+
kputsn(fp->line.s,str-fp->line.s,&tmp);
|
| 672 |
+
int chr_id = bcf_hdr_name2id(args->out_hdr, tmp.s);
|
| 673 |
+
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]);
|
| 674 |
+
if ( prev_chr_id!=chr_id )
|
| 675 |
+
{
|
| 676 |
+
prev_pos = -1;
|
| 677 |
+
if ( args->seen_seq[chr_id] )
|
| 678 |
+
error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", tmp.s);
|
| 679 |
+
}
|
| 680 |
+
char *end;
|
| 681 |
+
int pos = strtol(str+1,&end,10) - 1;
|
| 682 |
+
if ( end==str+1 ) error("Could not parse line: %s\n", fp->line.s);
|
| 683 |
+
if ( prev_pos > pos )
|
| 684 |
+
error("\nThe chromosome block %s is not sorted, consider running with -a.\n", tmp.s);
|
| 685 |
+
args->seen_seq[chr_id] = 1;
|
| 686 |
+
prev_chr_id = chr_id;
|
| 687 |
+
|
| 688 |
+
if ( vcf_write_line(args->out_fh, &fp->line)!=0 ) error("\nFailed to write %"PRIu64" bytes\n", (uint64_t)fp->line.l);
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
else
|
| 692 |
+
{
|
| 693 |
+
// BCF conversion is required
|
| 694 |
+
line->max_unpack = 0;
|
| 695 |
+
while ( bcf_read(fp, hdr, line)==0 )
|
| 696 |
+
{
|
| 697 |
+
if ( args->sites_only ) bcf_subset(args->out_hdr, line, 0, 0);
|
| 698 |
+
bcf_translate(args->out_hdr, hdr, line);
|
| 699 |
+
|
| 700 |
+
if ( prev_chr_id!=line->rid )
|
| 701 |
+
{
|
| 702 |
+
prev_pos = -1;
|
| 703 |
+
if ( args->seen_seq[line->rid] )
|
| 704 |
+
error("\nThe chromosome block %s is not contiguous, consider running with -a.\n", bcf_seqname(args->out_hdr, line));
|
| 705 |
+
}
|
| 706 |
+
if ( prev_pos > line->pos )
|
| 707 |
+
error("\nThe chromosome block %s is not sorted, consider running with -a.\n", bcf_seqname(args->out_hdr, line));
|
| 708 |
+
args->seen_seq[line->rid] = 1;
|
| 709 |
+
prev_chr_id = line->rid;
|
| 710 |
+
|
| 711 |
+
if ( bcf_write(args->out_fh, args->out_hdr, line)!=0 ) error("\nFailed to write\n");
|
| 712 |
+
}
|
| 713 |
+
}
|
| 714 |
+
bcf_hdr_destroy(hdr);
|
| 715 |
+
hts_close(fp);
|
| 716 |
+
if ( args->verbose )
|
| 717 |
+
{
|
| 718 |
+
gettimeofday(&t1, NULL);
|
| 719 |
+
double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
|
| 720 |
+
fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6);
|
| 721 |
+
}
|
| 722 |
+
}
|
| 723 |
+
bcf_destroy(line);
|
| 724 |
+
free(tmp.s);
|
| 725 |
+
}
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
int print_vcf_gz_header(BGZF *fp, BGZF *bgzf_out, int print_header, kstring_t *tmp)
|
| 729 |
+
{
|
| 730 |
+
char *buffer = (char*) fp->uncompressed_block;
|
| 731 |
+
|
| 732 |
+
// Read the header and find the position of the data block
|
| 733 |
+
if ( buffer[0]!='#' ) error("Could not parse the header, expected '#', found '%c'\n", buffer[0]);
|
| 734 |
+
|
| 735 |
+
int nskip = 1; // end of the header in the current uncompressed block
|
| 736 |
+
while (1)
|
| 737 |
+
{
|
| 738 |
+
if ( buffer[nskip]=='\n' )
|
| 739 |
+
{
|
| 740 |
+
nskip++;
|
| 741 |
+
if ( nskip>=fp->block_length )
|
| 742 |
+
{
|
| 743 |
+
kputsn(buffer,nskip,tmp);
|
| 744 |
+
if ( bgzf_read_block(fp) != 0 ) return -1;
|
| 745 |
+
if ( !fp->block_length ) break;
|
| 746 |
+
nskip = 0;
|
| 747 |
+
}
|
| 748 |
+
// The header has finished
|
| 749 |
+
if ( buffer[nskip]!='#' )
|
| 750 |
+
{
|
| 751 |
+
kputsn(buffer,nskip,tmp);
|
| 752 |
+
break;
|
| 753 |
+
}
|
| 754 |
+
}
|
| 755 |
+
nskip++;
|
| 756 |
+
if ( nskip>=fp->block_length )
|
| 757 |
+
{
|
| 758 |
+
kputsn(buffer,fp->block_length,tmp);
|
| 759 |
+
if ( bgzf_read_block(fp) != 0 ) return -1;
|
| 760 |
+
if ( !fp->block_length ) break;
|
| 761 |
+
nskip = 0;
|
| 762 |
+
}
|
| 763 |
+
}
|
| 764 |
+
if ( print_header )
|
| 765 |
+
{
|
| 766 |
+
if ( bgzf_write(bgzf_out,tmp->s,tmp->l) != tmp->l ) error("Failed to write %"PRIu64" bytes\n", (uint64_t)tmp->l);
|
| 767 |
+
tmp->l = 0;
|
| 768 |
+
}
|
| 769 |
+
return nskip;
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
static inline int unpackInt16(const uint8_t *buffer)
|
| 773 |
+
{
|
| 774 |
+
return buffer[0] | buffer[1] << 8;
|
| 775 |
+
}
|
| 776 |
+
static int check_header(const uint8_t *header)
|
| 777 |
+
{
|
| 778 |
+
if ( header[0] != 31 || header[1] != 139 || header[2] != 8 ) return -2;
|
| 779 |
+
return ((header[3] & 4) != 0
|
| 780 |
+
&& unpackInt16((uint8_t*)&header[10]) == 6
|
| 781 |
+
&& header[12] == 'B' && header[13] == 'C'
|
| 782 |
+
&& unpackInt16((uint8_t*)&header[14]) == 2) ? 0 : -1;
|
| 783 |
+
}
|
| 784 |
+
static void _check_hrecs(const bcf_hdr_t *hdr0, const bcf_hdr_t *hdr, char *fname0, char *fname)
|
| 785 |
+
{
|
| 786 |
+
int j;
|
| 787 |
+
for (j=0; j<hdr0->nhrec; j++)
|
| 788 |
+
{
|
| 789 |
+
bcf_hrec_t *hrec0 = hdr0->hrec[j];
|
| 790 |
+
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
|
| 791 |
+
int itag = bcf_hrec_find_key(hrec0, "ID");
|
| 792 |
+
bcf_hrec_t *hrec = bcf_hdr_get_hrec(hdr, hrec0->type, "ID", hrec0->vals[itag], NULL);
|
| 793 |
+
|
| 794 |
+
char *type = NULL;
|
| 795 |
+
if ( hrec0->type==BCF_HL_FLT ) type = "FILTER";
|
| 796 |
+
if ( hrec0->type==BCF_HL_INFO ) type = "INFO";
|
| 797 |
+
if ( hrec0->type==BCF_HL_FMT ) type = "FORMAT";
|
| 798 |
+
if ( hrec0->type==BCF_HL_CTG ) type = "contig";
|
| 799 |
+
|
| 800 |
+
if ( !hrec )
|
| 801 |
+
error("Cannot use --naive, incompatible headers, the tag %s/%s not present in %s\n",type,hrec0->vals[itag],fname);
|
| 802 |
+
|
| 803 |
+
int idx0 = bcf_hrec_find_key(hrec0, "IDX");
|
| 804 |
+
int idx = bcf_hrec_find_key(hrec, "IDX");
|
| 805 |
+
if ( idx0<0 || idx<0 )
|
| 806 |
+
error("fixme: unexpected IDX<0 for %s/%s in %s or %s\n",type,hrec0->vals[itag],fname0,fname);
|
| 807 |
+
if ( strcmp(hrec0->vals[idx0],hrec->vals[idx]) )
|
| 808 |
+
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);
|
| 809 |
+
}
|
| 810 |
+
}
|
| 811 |
+
static void naive_concat_check_headers(args_t *args)
|
| 812 |
+
{
|
| 813 |
+
fprintf(bcftools_stderr,"Checking the headers of %d files.\n",args->nfnames);
|
| 814 |
+
bcf_hdr_t *hdr0 = NULL;
|
| 815 |
+
int i,j;
|
| 816 |
+
for (i=0; i<args->nfnames; i++)
|
| 817 |
+
{
|
| 818 |
+
htsFile *fp = hts_open(args->fnames[i], "r"); if ( !fp ) error("Failed to open: %s\n", args->fnames[i]);
|
| 819 |
+
bcf_hdr_t *hdr = bcf_hdr_read(fp); if ( !hdr ) error("Failed to parse header: %s\n", args->fnames[i]);
|
| 820 |
+
htsFormat type = *hts_get_format(fp);
|
| 821 |
+
hts_close(fp);
|
| 822 |
+
|
| 823 |
+
if ( i==0 )
|
| 824 |
+
{
|
| 825 |
+
hdr0 = hdr;
|
| 826 |
+
continue;
|
| 827 |
+
}
|
| 828 |
+
|
| 829 |
+
// check the samples
|
| 830 |
+
if ( bcf_hdr_nsamples(hdr0)!=bcf_hdr_nsamples(hdr) )
|
| 831 |
+
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]);
|
| 832 |
+
for (j=0; j<bcf_hdr_nsamples(hdr0); j++)
|
| 833 |
+
if ( strcmp(hdr0->samples[j],hdr->samples[j]) )
|
| 834 |
+
error("Cannot concatenate, different samples in %s vs %s\n",args->fnames[0],args->fnames[i]);
|
| 835 |
+
|
| 836 |
+
// if BCF, check if tag IDs are consistent in the dictionary of strings
|
| 837 |
+
if ( type.compression!=bgzf )
|
| 838 |
+
error("The --naive option works only for compressed BCFs or VCFs, sorry :-/\n");
|
| 839 |
+
|
| 840 |
+
_check_hrecs(hdr0,hdr,args->fnames[0],args->fnames[i]);
|
| 841 |
+
_check_hrecs(hdr,hdr0,args->fnames[i],args->fnames[0]);
|
| 842 |
+
|
| 843 |
+
bcf_hdr_destroy(hdr);
|
| 844 |
+
}
|
| 845 |
+
if ( hdr0 ) bcf_hdr_destroy(hdr0);
|
| 846 |
+
fprintf(bcftools_stderr,"Done, the headers are compatible.\n");
|
| 847 |
+
}
|
| 848 |
+
static void naive_concat(args_t *args)
|
| 849 |
+
{
|
| 850 |
+
if ( !args->naive_concat_trust_headers )
|
| 851 |
+
naive_concat_check_headers(args);
|
| 852 |
+
|
| 853 |
+
// only compressed BCF atm
|
| 854 |
+
BGZF *bgzf_out = bgzf_open(args->output_fname,"w");;
|
| 855 |
+
|
| 856 |
+
htsFormat output_type;
|
| 857 |
+
output_type.format = (args->output_type & FT_VCF) ? vcf : bcf;
|
| 858 |
+
output_type.compression = (args->output_type & FT_GZ) ? bgzf : no_compression;
|
| 859 |
+
|
| 860 |
+
struct timeval t0, t1;
|
| 861 |
+
const size_t page_size = BGZF_MAX_BLOCK_SIZE;
|
| 862 |
+
uint8_t *buf = (uint8_t*) malloc(page_size);
|
| 863 |
+
kstring_t tmp = {0,0,0};
|
| 864 |
+
int i, file_types = 0;
|
| 865 |
+
for (i=0; i<args->nfnames; i++)
|
| 866 |
+
{
|
| 867 |
+
if ( args->verbose )
|
| 868 |
+
{
|
| 869 |
+
fprintf(bcftools_stderr,"Concatenating %s", args->fnames[i]);
|
| 870 |
+
gettimeofday(&t0, NULL);
|
| 871 |
+
}
|
| 872 |
+
htsFile *hts_fp = hts_open(args->fnames[i],"r");
|
| 873 |
+
if ( !hts_fp ) error("\nFailed to open: %s\n", args->fnames[i]);
|
| 874 |
+
htsFormat type = *hts_get_format(hts_fp);
|
| 875 |
+
|
| 876 |
+
if ( type.compression!=bgzf )
|
| 877 |
+
error("\nThe --naive option works only for compressed BCFs or VCFs\n");
|
| 878 |
+
file_types |= type.format==vcf ? 1 : 2;
|
| 879 |
+
if ( file_types==3 )
|
| 880 |
+
error("\nThe --naive option works only for compressed files of the same type, all BCFs or all VCFs\n");
|
| 881 |
+
if ( args->explicit_output_type )
|
| 882 |
+
{
|
| 883 |
+
if ( output_type.format!=type.format )
|
| 884 |
+
error("\nThe --naive option works only for the output of the same type, all BCFs or all VCFs\n");
|
| 885 |
+
if ( output_type.compression!=type.compression )
|
| 886 |
+
error("\nThe --naive option works only for the output of the same compression type\n");
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
BGZF *fp = hts_get_bgzfp(hts_fp);
|
| 890 |
+
if ( !fp || bgzf_read_block(fp) != 0 || !fp->block_length )
|
| 891 |
+
error("\nFailed to read %s: %s\n", args->fnames[i], strerror(errno));
|
| 892 |
+
|
| 893 |
+
int nskip;
|
| 894 |
+
if ( type.format==bcf )
|
| 895 |
+
{
|
| 896 |
+
const size_t magic_len = 5 + 4; // "Magic" string + header length
|
| 897 |
+
uint8_t magic[magic_len];
|
| 898 |
+
if ( bgzf_read(fp, magic, magic_len) != magic_len ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]);
|
| 899 |
+
// First five bytes are the "Magic" string
|
| 900 |
+
if (strncmp((char*)magic, "BCF\2\2", 5) != 0) error("\nInvalid BCF magic string in %s\n", args->fnames[i]);
|
| 901 |
+
// Next four are the header length (little-endian)
|
| 902 |
+
tmp.l = le_to_u32(magic + 5);
|
| 903 |
+
hts_expand(char,tmp.l,tmp.m,tmp.s);
|
| 904 |
+
if ( bgzf_read(fp, tmp.s, tmp.l) != tmp.l ) error("\nFailed to read the BCF header in %s\n", args->fnames[i]);
|
| 905 |
+
|
| 906 |
+
// write only the first header
|
| 907 |
+
if ( i==0 )
|
| 908 |
+
{
|
| 909 |
+
if ( bgzf_write(bgzf_out, magic, magic_len) != magic_len ) error("\nFailed to write %zu bytes to %s\n", magic_len,args->output_fname);
|
| 910 |
+
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);
|
| 911 |
+
}
|
| 912 |
+
nskip = fp->block_offset;
|
| 913 |
+
}
|
| 914 |
+
else
|
| 915 |
+
{
|
| 916 |
+
nskip = print_vcf_gz_header(fp, bgzf_out, i==0?1:0, &tmp);
|
| 917 |
+
if ( nskip==-1 ) error("\nError reading %s\n", args->fnames[i]);
|
| 918 |
+
}
|
| 919 |
+
|
| 920 |
+
// Output all non-header data that were read together with the header block
|
| 921 |
+
if ( fp->block_length - nskip > 0 )
|
| 922 |
+
{
|
| 923 |
+
if ( bgzf_write(bgzf_out, (char *)fp->uncompressed_block+nskip, fp->block_length-nskip)<0 ) error("\nError: %d\n",fp->errcode);
|
| 924 |
+
}
|
| 925 |
+
if ( bgzf_flush(bgzf_out)<0 ) error("\nError: %d\n",bgzf_out->errcode);
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
// Stream the rest of the file as it is, without recompressing, but remove BGZF EOF blocks
|
| 929 |
+
// The final bgzf eof block will be added by bgzf_close.
|
| 930 |
+
ssize_t nread, nblock, nwr;
|
| 931 |
+
const int nheader = 18, neof = 28;
|
| 932 |
+
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";
|
| 933 |
+
while (1)
|
| 934 |
+
{
|
| 935 |
+
nread = bgzf_raw_read(fp, buf, nheader);
|
| 936 |
+
if ( !nread ) break;
|
| 937 |
+
if ( nread != nheader || check_header(buf)!=0 ) error("\nCould not parse the header of a bgzf block: %s\n",args->fnames[i]);
|
| 938 |
+
nblock = unpackInt16(buf+16) + 1;
|
| 939 |
+
assert( nblock <= page_size && nblock >= nheader );
|
| 940 |
+
nread += bgzf_raw_read(fp, buf+nheader, nblock - nheader);
|
| 941 |
+
if ( nread!=nblock ) error("\nCould not read %"PRId64" bytes: %s\n",(uint64_t)nblock,args->fnames[i]);
|
| 942 |
+
if ( nread==neof && !memcmp(buf,eof,neof) ) continue;
|
| 943 |
+
nwr = bgzf_raw_write(bgzf_out, buf, nread);
|
| 944 |
+
if ( nwr != nread ) error("\nWrite failed, wrote %"PRId64" instead of %d bytes.\n", (uint64_t)nwr,(int)nread);
|
| 945 |
+
}
|
| 946 |
+
if (hts_close(hts_fp)) error("\nClose failed: %s\n",args->fnames[i]);
|
| 947 |
+
if ( args->verbose )
|
| 948 |
+
{
|
| 949 |
+
gettimeofday(&t1, NULL);
|
| 950 |
+
double delta = (t1.tv_sec - t0.tv_sec) * 1e6 + (t1.tv_usec - t0.tv_usec);
|
| 951 |
+
fprintf(bcftools_stderr,"\t%f seconds\n",delta/1e6);
|
| 952 |
+
}
|
| 953 |
+
}
|
| 954 |
+
free(buf);
|
| 955 |
+
free(tmp.s);
|
| 956 |
+
if (bgzf_close(bgzf_out) < 0) error("Error: %d\n",bgzf_out->errcode);
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
static void usage(args_t *args)
|
| 960 |
+
{
|
| 961 |
+
fprintf(bcftools_stderr, "\n");
|
| 962 |
+
fprintf(bcftools_stderr, "About: Concatenate or combine VCF/BCF files. All source files must have the same sample\n");
|
| 963 |
+
fprintf(bcftools_stderr, " columns appearing in the same order. The program can be used, for example, to\n");
|
| 964 |
+
fprintf(bcftools_stderr, " concatenate chromosome VCFs into one VCF, or combine a SNP VCF and an indel\n");
|
| 965 |
+
fprintf(bcftools_stderr, " VCF into one. The input files must be sorted by chr and position. The files\n");
|
| 966 |
+
fprintf(bcftools_stderr, " must be given in the correct order to produce sorted VCF on output unless\n");
|
| 967 |
+
fprintf(bcftools_stderr, " the -a, --allow-overlaps option is specified. With the --naive option, the files\n");
|
| 968 |
+
fprintf(bcftools_stderr, " are concatenated without being recompressed, which is very fast.\n");
|
| 969 |
+
fprintf(bcftools_stderr, "Usage: bcftools concat [options] <A.vcf.gz> [<B.vcf.gz> [...]]\n");
|
| 970 |
+
fprintf(bcftools_stderr, "\n");
|
| 971 |
+
fprintf(bcftools_stderr, "Options:\n");
|
| 972 |
+
fprintf(bcftools_stderr, " -a, --allow-overlaps First coordinate of the next file can precede last record of the current file.\n");
|
| 973 |
+
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");
|
| 974 |
+
fprintf(bcftools_stderr, " -d, --rm-dups STRING Output duplicate records present in multiple files only once: <snps|indels|both|all|exact>\n");
|
| 975 |
+
fprintf(bcftools_stderr, " -D, --remove-duplicates Alias for -d exact\n");
|
| 976 |
+
fprintf(bcftools_stderr, " -f, --file-list FILE Read the list of files from a file.\n");
|
| 977 |
+
fprintf(bcftools_stderr, " -G, --drop-genotypes Drop individual genotype information.\n");
|
| 978 |
+
fprintf(bcftools_stderr, " -l, --ligate Ligate phased VCFs by matching phase at overlapping haplotypes\n");
|
| 979 |
+
fprintf(bcftools_stderr, " --ligate-force Ligate even non-overlapping chunks, keep all sites\n");
|
| 980 |
+
fprintf(bcftools_stderr, " --ligate-warn Drop sites in imperfect overlaps\n");
|
| 981 |
+
fprintf(bcftools_stderr, " --no-version Do not append version and command line to the header\n");
|
| 982 |
+
fprintf(bcftools_stderr, " -n, --naive Concatenate files without recompression, a header check compatibility is performed\n");
|
| 983 |
+
fprintf(bcftools_stderr, " --naive-force Same as --naive, but header compatibility is not checked. Dangerous, use with caution.\n");
|
| 984 |
+
fprintf(bcftools_stderr, " -o, --output FILE Write output to a file [standard output]\n");
|
| 985 |
+
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");
|
| 986 |
+
fprintf(bcftools_stderr, " -q, --min-PQ INT Break phase set if phasing quality is lower than <int> [30]\n");
|
| 987 |
+
fprintf(bcftools_stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
|
| 988 |
+
fprintf(bcftools_stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
|
| 989 |
+
fprintf(bcftools_stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
|
| 990 |
+
fprintf(bcftools_stderr, " --threads INT Use multithreading with <int> worker threads [0]\n");
|
| 991 |
+
fprintf(bcftools_stderr, " -v, --verbose 0|1 Set verbosity level [1]\n");
|
| 992 |
+
fprintf(bcftools_stderr, " -W, --write-index[=FMT] Automatically index the output files [off]\n");
|
| 993 |
+
fprintf(bcftools_stderr, "\n");
|
| 994 |
+
bcftools_exit(1);
|
| 995 |
+
}
|
| 996 |
+
|
| 997 |
+
int main_vcfconcat(int argc, char *argv[])
|
| 998 |
+
{
|
| 999 |
+
int c;
|
| 1000 |
+
args_t *args = (args_t*) calloc(1,sizeof(args_t));
|
| 1001 |
+
args->argc = argc; args->argv = argv;
|
| 1002 |
+
args->output_fname = "-";
|
| 1003 |
+
args->output_type = FT_VCF;
|
| 1004 |
+
args->n_threads = 0;
|
| 1005 |
+
args->record_cmd_line = 1;
|
| 1006 |
+
args->min_PQ = 30;
|
| 1007 |
+
args->verbose = 1;
|
| 1008 |
+
args->clevel = -1;
|
| 1009 |
+
|
| 1010 |
+
static struct option loptions[] =
|
| 1011 |
+
{
|
| 1012 |
+
{"verbose",required_argument,NULL,'v'},
|
| 1013 |
+
{"naive",no_argument,NULL,'n'},
|
| 1014 |
+
{"naive-force",no_argument,NULL,7},
|
| 1015 |
+
{"compact-PS",no_argument,NULL,'c'},
|
| 1016 |
+
{"regions",required_argument,NULL,'r'},
|
| 1017 |
+
{"regions-file",required_argument,NULL,'R'},
|
| 1018 |
+
{"regions-overlap",required_argument,NULL,12},
|
| 1019 |
+
{"remove-duplicates",no_argument,NULL,'D'},
|
| 1020 |
+
{"rm-dups",required_argument,NULL,'d'},
|
| 1021 |
+
{"allow-overlaps",no_argument,NULL,'a'},
|
| 1022 |
+
{"ligate",no_argument,NULL,'l'},
|
| 1023 |
+
{"ligate-force",no_argument,NULL,10},
|
| 1024 |
+
{"ligate-warn",no_argument,NULL,11},
|
| 1025 |
+
{"output",required_argument,NULL,'o'},
|
| 1026 |
+
{"output-type",required_argument,NULL,'O'},
|
| 1027 |
+
{"threads",required_argument,NULL,9},
|
| 1028 |
+
{"file-list",required_argument,NULL,'f'},
|
| 1029 |
+
{"min-PQ",required_argument,NULL,'q'},
|
| 1030 |
+
{"no-version",no_argument,NULL,8},
|
| 1031 |
+
{"write-index",optional_argument,NULL,'W'},
|
| 1032 |
+
{"drop-genotypes",no_argument,NULL,'G'},
|
| 1033 |
+
{NULL,0,NULL,0}
|
| 1034 |
+
};
|
| 1035 |
+
char *tmp;
|
| 1036 |
+
while ((c = getopt_long(argc, argv, "h:?o:O:f:alq:Dd:Gr:R:cnv:W::",loptions,NULL)) >= 0)
|
| 1037 |
+
{
|
| 1038 |
+
switch (c) {
|
| 1039 |
+
case 'c': args->compact_PS = 1; break;
|
| 1040 |
+
case 'r': args->regions_list = optarg; break;
|
| 1041 |
+
case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;
|
| 1042 |
+
case 'd': args->remove_dups = optarg; break;
|
| 1043 |
+
case 'D': args->remove_dups = "exact"; break;
|
| 1044 |
+
case 'q':
|
| 1045 |
+
args->min_PQ = strtol(optarg,&tmp,10);
|
| 1046 |
+
if ( *tmp ) error("Could not parse argument: --min-PQ %s\n", optarg);
|
| 1047 |
+
break;
|
| 1048 |
+
case 'n': args->naive_concat = 1; break;
|
| 1049 |
+
case 'a': args->allow_overlaps = 1; break;
|
| 1050 |
+
case 'l': args->phased_concat = 1; break;
|
| 1051 |
+
case 'f': args->file_list = optarg; break;
|
| 1052 |
+
case 'G': args->sites_only = 1; break;
|
| 1053 |
+
case 'o': args->output_fname = optarg; break;
|
| 1054 |
+
case 'O':
|
| 1055 |
+
args->explicit_output_type = 1;
|
| 1056 |
+
switch (optarg[0]) {
|
| 1057 |
+
case 'b': args->output_type = FT_BCF_GZ; break;
|
| 1058 |
+
case 'u': args->output_type = FT_BCF; break;
|
| 1059 |
+
case 'z': args->output_type = FT_VCF_GZ; break;
|
| 1060 |
+
case 'v': args->output_type = FT_VCF; break;
|
| 1061 |
+
default:
|
| 1062 |
+
{
|
| 1063 |
+
args->clevel = strtol(optarg,&tmp,10);
|
| 1064 |
+
if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
|
| 1065 |
+
}
|
| 1066 |
+
};
|
| 1067 |
+
if ( optarg[1] )
|
| 1068 |
+
{
|
| 1069 |
+
args->clevel = strtol(optarg+1,&tmp,10);
|
| 1070 |
+
if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --compression-level %s\n", optarg+1);
|
| 1071 |
+
}
|
| 1072 |
+
break;
|
| 1073 |
+
case 10 : args->ligate_force = 1; break;
|
| 1074 |
+
case 11 : args->ligate_warn = 1; break;
|
| 1075 |
+
case 9 : args->n_threads = strtol(optarg, 0, 0); break;
|
| 1076 |
+
case 8 : args->record_cmd_line = 0; break;
|
| 1077 |
+
case 7 : args->naive_concat = 1; args->naive_concat_trust_headers = 1; break;
|
| 1078 |
+
case 12 :
|
| 1079 |
+
args->regions_overlap = parse_overlap_option(optarg);
|
| 1080 |
+
if ( args->regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
|
| 1081 |
+
break;
|
| 1082 |
+
case 'v':
|
| 1083 |
+
args->verbose = strtol(optarg, &tmp, 0);
|
| 1084 |
+
if ( *tmp || args->verbose<0 || args->verbose>1 ) error("Error: currently only --verbose 0 or --verbose 1 is supported\n");
|
| 1085 |
+
break;
|
| 1086 |
+
case 'W':
|
| 1087 |
+
if (!(args->write_index = write_index_parse(optarg)))
|
| 1088 |
+
error("Unsupported index format '%s'\n", optarg);
|
| 1089 |
+
break;
|
| 1090 |
+
case 'h':
|
| 1091 |
+
case '?': usage(args); break;
|
| 1092 |
+
default: error("Unknown argument: %s\n", optarg);
|
| 1093 |
+
}
|
| 1094 |
+
}
|
| 1095 |
+
while ( optind<argc )
|
| 1096 |
+
{
|
| 1097 |
+
args->nfnames++;
|
| 1098 |
+
args->fnames = (char **)realloc(args->fnames,sizeof(char*)*args->nfnames);
|
| 1099 |
+
args->fnames[args->nfnames-1] = strdup(argv[optind]);
|
| 1100 |
+
optind++;
|
| 1101 |
+
}
|
| 1102 |
+
if ( args->ligate_force && args->ligate_warn ) error("The options cannot be combined: --ligate-force and --ligate-warn\n");
|
| 1103 |
+
if ( args->allow_overlaps && args->phased_concat ) error("The options -a and -l should not be combined. Please run with -l only.\n");
|
| 1104 |
+
if ( args->sites_only && args->phased_concat ) error("The options --drop-genotypes and --ligate cannot be combined\n");
|
| 1105 |
+
if ( args->compact_PS && !args->phased_concat ) error("The -c option is intended only with -l\n");
|
| 1106 |
+
if ( args->file_list )
|
| 1107 |
+
{
|
| 1108 |
+
if ( args->nfnames ) error("Cannot combine -l with file names on command line.\n");
|
| 1109 |
+
args->fnames = hts_readlines(args->file_list, &args->nfnames);
|
| 1110 |
+
if ( !args->fnames ) error("Could not read the file: %s\n", args->file_list);
|
| 1111 |
+
}
|
| 1112 |
+
if ( !args->nfnames ) usage(args);
|
| 1113 |
+
if ( args->remove_dups && !args->allow_overlaps ) error("The -D option is supported only with -a\n");
|
| 1114 |
+
if ( args->regions_list && !args->allow_overlaps ) error("The -r/-R option is supported only with -a\n");
|
| 1115 |
+
if ( args->naive_concat )
|
| 1116 |
+
{
|
| 1117 |
+
if ( args->write_index ) error("Error: cannot --write-index in the %s mode\n",args->naive_concat_trust_headers?"--naive-force":"--naive");
|
| 1118 |
+
if ( args->allow_overlaps ) error("The option --naive cannot be combined with --allow-overlaps\n");
|
| 1119 |
+
if ( args->phased_concat ) error("The option --naive cannot be combined with --ligate\n");
|
| 1120 |
+
if ( args->sites_only ) error("The option --naive cannot be combined with --drop-genotypes\n");
|
| 1121 |
+
naive_concat(args);
|
| 1122 |
+
destroy_data(args);
|
| 1123 |
+
free(args);
|
| 1124 |
+
return 0;
|
| 1125 |
+
}
|
| 1126 |
+
init_data(args);
|
| 1127 |
+
concat(args);
|
| 1128 |
+
destroy_data(args);
|
| 1129 |
+
free(args);
|
| 1130 |
+
return 0;
|
| 1131 |
+
}
|
shared/package-files/18/1895dbf616c666a60e0d82ce37cac9f0d6dcb4f697d05db990675842610f3309/_python_dispatcher.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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4 |
+
import torch._C as C
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
PythonDispatcher class is a thin python-binding to C++ dispatcher and it
|
| 9 |
+
is designed to show how dispatcher precompute works. In particular,
|
| 10 |
+
it shows for a certain op `foo`, what the computed dispatch table looks
|
| 11 |
+
like after user register their kernels to certains dispatch keys.
|
| 12 |
+
|
| 13 |
+
In the real C++ dispatcher we support many dispatch keys for different
|
| 14 |
+
functionalities. For simplicity PythonDispatcher only supports dispatch
|
| 15 |
+
keys for a single example of each use case. These use cases are listed below:
|
| 16 |
+
|
| 17 |
+
- CPU/AutogradCPU: represents in-tree backends which we usually have dedicated inference &
|
| 18 |
+
autograd kernel in pytorch core library.
|
| 19 |
+
E.g. CPU, CUDA
|
| 20 |
+
- FPGA/AutogradOther: represents in-tree backends which we usually have backend specific
|
| 21 |
+
inference kernels, but they share the same autograd kernel specified in AutogradOther.
|
| 22 |
+
E.g. FPGA, SparseCsrCPU
|
| 23 |
+
- XLA/AutogradXLA: represents out-of-tree backends which we don't have either inference or autograd
|
| 24 |
+
kernel defined in pytorch core library. Backend owner is responsible for registering both
|
| 25 |
+
inference & autograd kernels in their extensions(e.g. torch-xla) for the operators they support.
|
| 26 |
+
E.g. XLA, XPU, MPS
|
| 27 |
+
- CompositeExplicitAutograd: alias key mapped to inference kernels of all backends like CPU, CUDA, XLA etc.
|
| 28 |
+
Kernels registered to this key MUST work for inference for all backends.
|
| 29 |
+
- Autograd: alias key mapped to autograd of all backends like AutogradCPU, AutogradXLA, AutogradOther.
|
| 30 |
+
Kernels registered to this key MUST work for autograd for all backends.
|
| 31 |
+
- CompositeImplicitAutograd: alias key CompositeImplicitAutograd = CompositeExplicitAutograd + Autograd
|
| 32 |
+
Kernels registered to this key MUST work for both inference + autograd for all backends.
|
| 33 |
+
|
| 34 |
+
Note we only allow registrations to alias keys inside pytorch core library. E.g
|
| 35 |
+
you shouldn't register a CompositeImplicitAutograd or CompositeExplicitAutograd
|
| 36 |
+
kernel from torch-xla extension, instead you should upstream the kernel into
|
| 37 |
+
pytorch/pytorch repo so that it's available for all backends and continuously
|
| 38 |
+
tested even without the extension.
|
| 39 |
+
|
| 40 |
+
Usage:
|
| 41 |
+
dispatcher = PythonDispatcher()
|
| 42 |
+
dispatcher.register(["CPU", "XLA", "CompositeImplicitAutograd"])
|
| 43 |
+
print(dispatcher.dispatchTable()) # This tells you exactly which kernel is used for certain backend.
|
| 44 |
+
# For more debugging information
|
| 45 |
+
# print(dispatcher.keys())
|
| 46 |
+
# print(dispatcher.registrations())
|
| 47 |
+
# print(dispatcher.rawRegistrations())
|
| 48 |
+
# print(dispatcher.rawDispatchTable())
|
| 49 |
+
PythonDispatcher calls C++ dispatcher under the hood for to precompute dispatch table.
|
| 50 |
+
This file only provides the simplified API for developers, relevant test code is located in
|
| 51 |
+
test/test_dispatch.py
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class PythonDispatcher:
|
| 56 |
+
namespace = "__test__"
|
| 57 |
+
name = "foo"
|
| 58 |
+
# fmt: off
|
| 59 |
+
runtime_keys = [
|
| 60 |
+
"CPU", "AutogradCPU",
|
| 61 |
+
"FPGA", "AutogradOther",
|
| 62 |
+
"XLA", "AutogradXLA",
|
| 63 |
+
"Lazy", "AutogradLazy",
|
| 64 |
+
]
|
| 65 |
+
# fmt: on
|
| 66 |
+
alias_keys = [
|
| 67 |
+
"CompositeExplicitAutograd",
|
| 68 |
+
"Autograd",
|
| 69 |
+
"CompositeImplicitAutograd",
|
| 70 |
+
]
|
| 71 |
+
supported_keys = runtime_keys + alias_keys
|
| 72 |
+
|
| 73 |
+
def __init__(self) -> None:
|
| 74 |
+
C._dispatch_check_invariants(self.name) # type: ignore[attr-defined]
|
| 75 |
+
self.ref = C._dispatch_library("FRAGMENT", self.namespace, "")
|
| 76 |
+
self.ref.def_("foo(Tensor x) -> Tensor")
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
Returns a list of dispatch keys supported by PythonDispatcher.
|
| 80 |
+
You can register kernels to these keys.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def keys(self):
|
| 84 |
+
return self.supported_keys
|
| 85 |
+
|
| 86 |
+
"""
|
| 87 |
+
Register kernels to the target dispatchKeys.
|
| 88 |
+
dispatchKeys(list[str]): a list of dispatch keys that you want to register
|
| 89 |
+
your own kernel. Note that you don't need to write the kernel yourself in
|
| 90 |
+
this PythonDispatcher.E.g. for CPU key, a kernel(e.g fn_CPU for CPU) is
|
| 91 |
+
automatically generated and registered.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def register(self, dispatchKeys):
|
| 95 |
+
# Overriden is not supported and triggers a warning in C++ dispatcher.
|
| 96 |
+
if len(set(dispatchKeys)) != len(dispatchKeys):
|
| 97 |
+
raise RuntimeError(
|
| 98 |
+
f"Overriden is not allowed but found duplicates in {dispatchKeys}."
|
| 99 |
+
)
|
| 100 |
+
# We currently forbid this in codegen instead of C++ dispatcher.
|
| 101 |
+
if (
|
| 102 |
+
"CompositeImplicitAutograd" in dispatchKeys
|
| 103 |
+
and "CompositeExplicitAutograd" in dispatchKeys
|
| 104 |
+
):
|
| 105 |
+
raise RuntimeError(
|
| 106 |
+
"Registration to both CompositeImplicitAutograd and CompositeExplicitAutograd is not allowed."
|
| 107 |
+
)
|
| 108 |
+
for key in dispatchKeys:
|
| 109 |
+
if key not in self.supported_keys:
|
| 110 |
+
raise RuntimeError(
|
| 111 |
+
f"{key} is not supported, please select a dispatch key in {self.supported_keys}."
|
| 112 |
+
)
|
| 113 |
+
self.ref.impl_t_t("foo", dispatch=key, debug="fn_" + key)
|
| 114 |
+
|
| 115 |
+
"""
|
| 116 |
+
Helper function to format (key, kernel).
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def _format_line(self, key, kernel):
|
| 120 |
+
return f"{key:<15} {kernel}\n"
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
Helper function to print a table header.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def _format_header(self, header):
|
| 127 |
+
s = f"""
|
| 128 |
+
{header}
|
| 129 |
+
"""
|
| 130 |
+
s += self._format_line("key", "kernel")
|
| 131 |
+
s += "---------------------------\n"
|
| 132 |
+
return s
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
Returns raw output of all registration info for debugging only.
|
| 136 |
+
Use registrations() for a simplified version.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def rawRegistrations(self):
|
| 140 |
+
return C._dispatch_dump(f"{self.namespace}::{self.name}") # type: ignore[attr-defined]
|
| 141 |
+
|
| 142 |
+
"""
|
| 143 |
+
Returns raw output of computed dispatch table for debugging only.
|
| 144 |
+
Use dispatchTable() for a simplified version.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def rawDispatchTable(self):
|
| 148 |
+
return C._dispatch_dump_table(f"{self.namespace}::{self.name}") # type: ignore[attr-defined]
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
Returns a table(str) including all the registrations from users.
|
| 152 |
+
Note this includes registrations to both runtime keys and alias keys.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def registrations(self):
|
| 156 |
+
output = self._format_header("Registered Kernels")
|
| 157 |
+
state = self.rawRegistrations()
|
| 158 |
+
state_entries = state.split("\n")
|
| 159 |
+
for line in state_entries:
|
| 160 |
+
first = line.split(":")[0]
|
| 161 |
+
if any(first.startswith(k) for k in self.supported_keys):
|
| 162 |
+
kernel = line.split("::")[0].split(" ")[1]
|
| 163 |
+
output += self._format_line(first, kernel)
|
| 164 |
+
return output
|
| 165 |
+
|
| 166 |
+
"""
|
| 167 |
+
Returns the computed dispatch table(str). Note this only include
|
| 168 |
+
runtime keys, registrations to alias keys have been decoded to their
|
| 169 |
+
mapped runtime keys.
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def dispatchTable(self):
|
| 173 |
+
output = self._format_header("Computed Dispatch Table")
|
| 174 |
+
table = self.rawDispatchTable()
|
| 175 |
+
table_entries = table.split("\n")
|
| 176 |
+
regex = re.compile(r"registered at .*FallbackKernel\.cpp.*(\[)")
|
| 177 |
+
for line in table_entries:
|
| 178 |
+
k = line.split(":")[0]
|
| 179 |
+
if k in self.runtime_keys:
|
| 180 |
+
entry = regex.sub("[", line)
|
| 181 |
+
output += self._format_line(k, entry.split(": ")[1])
|
| 182 |
+
return output
|
shared/package-files/18/18997fb64e74e3ee39580491803bf92fd48372c763b6c651523246ba4672ab17/masked_select_native.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor masked_select_cpu(const at::Tensor & self, const at::Tensor & mask);
|
| 20 |
+
TORCH_API at::Tensor & masked_select_out_cpu(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out);
|
| 21 |
+
TORCH_API at::Tensor masked_select_cuda(const at::Tensor & self, const at::Tensor & mask);
|
| 22 |
+
TORCH_API at::Tensor & masked_select_out_cuda(const at::Tensor & self, const at::Tensor & mask, at::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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
import abc
|
| 19 |
+
import bz2
|
| 20 |
+
from datetime import date, datetime
|
| 21 |
+
from decimal import Decimal
|
| 22 |
+
import gc
|
| 23 |
+
import gzip
|
| 24 |
+
import io
|
| 25 |
+
import itertools
|
| 26 |
+
import os
|
| 27 |
+
import random
|
| 28 |
+
import select
|
| 29 |
+
import shutil
|
| 30 |
+
import signal
|
| 31 |
+
import string
|
| 32 |
+
import tempfile
|
| 33 |
+
import threading
|
| 34 |
+
import time
|
| 35 |
+
import unittest
|
| 36 |
+
import weakref
|
| 37 |
+
|
| 38 |
+
import pytest
|
| 39 |
+
|
| 40 |
+
import pyarrow as pa
|
| 41 |
+
from pyarrow.csv import (
|
| 42 |
+
open_csv, read_csv, ReadOptions, ParseOptions, ConvertOptions, ISO8601,
|
| 43 |
+
write_csv, WriteOptions, CSVWriter, InvalidRow)
|
| 44 |
+
from pyarrow.tests import util
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def generate_col_names():
|
| 48 |
+
# 'a', 'b'... 'z', then 'aa', 'ab'...
|
| 49 |
+
letters = string.ascii_lowercase
|
| 50 |
+
yield from letters
|
| 51 |
+
for first in letters:
|
| 52 |
+
for second in letters:
|
| 53 |
+
yield first + second
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def split_rows(arr, num_cols, num_rows):
|
| 57 |
+
# Split a num_cols x num_rows array into rows
|
| 58 |
+
for i in range(0, num_rows * num_cols, num_cols):
|
| 59 |
+
yield arr[i:i + num_cols]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def split_columns(arr, num_cols, num_rows):
|
| 63 |
+
# Split a num_cols x num_rows array into columns
|
| 64 |
+
for i in range(0, num_cols):
|
| 65 |
+
yield arr[i::num_cols]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def make_random_csv(num_cols=2, num_rows=10, linesep='\r\n', write_names=True):
|
| 69 |
+
rnd = random.Random(42)
|
| 70 |
+
arr = [rnd.randint(0, 1000) for _ in range(num_cols * num_rows)]
|
| 71 |
+
csv = io.StringIO()
|
| 72 |
+
col_names = list(itertools.islice(generate_col_names(), num_cols))
|
| 73 |
+
if write_names:
|
| 74 |
+
csv.write(",".join(col_names))
|
| 75 |
+
csv.write(linesep)
|
| 76 |
+
for row in split_rows(arr, num_cols, num_rows):
|
| 77 |
+
csv.write(",".join(map(str, row)))
|
| 78 |
+
csv.write(linesep)
|
| 79 |
+
csv = csv.getvalue().encode()
|
| 80 |
+
columns = [pa.array(row, type=pa.int64())
|
| 81 |
+
for row in split_columns(arr, num_cols, num_rows)]
|
| 82 |
+
expected = pa.Table.from_arrays(columns, col_names)
|
| 83 |
+
return csv, expected
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def make_empty_csv(column_names):
|
| 87 |
+
csv = io.StringIO()
|
| 88 |
+
csv.write(",".join(column_names))
|
| 89 |
+
csv.write("\n")
|
| 90 |
+
return csv.getvalue().encode()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def check_options_class(cls, **attr_values):
|
| 94 |
+
"""
|
| 95 |
+
Check setting and getting attributes of an *Options class.
|
| 96 |
+
"""
|
| 97 |
+
opts = cls()
|
| 98 |
+
|
| 99 |
+
for name, values in attr_values.items():
|
| 100 |
+
assert getattr(opts, name) == values[0], \
|
| 101 |
+
"incorrect default value for " + name
|
| 102 |
+
for v in values:
|
| 103 |
+
setattr(opts, name, v)
|
| 104 |
+
assert getattr(opts, name) == v, "failed setting value"
|
| 105 |
+
|
| 106 |
+
with pytest.raises(AttributeError):
|
| 107 |
+
opts.zzz_non_existent = True
|
| 108 |
+
|
| 109 |
+
# Check constructor named arguments
|
| 110 |
+
non_defaults = {name: values[1] for name, values in attr_values.items()}
|
| 111 |
+
opts = cls(**non_defaults)
|
| 112 |
+
for name, value in non_defaults.items():
|
| 113 |
+
assert getattr(opts, name) == value
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# The various options classes need to be picklable for dataset
|
| 117 |
+
def check_options_class_pickling(cls, pickler, **attr_values):
|
| 118 |
+
opts = cls(**attr_values)
|
| 119 |
+
new_opts = pickler.loads(pickler.dumps(opts,
|
| 120 |
+
protocol=pickler.HIGHEST_PROTOCOL))
|
| 121 |
+
for name, value in attr_values.items():
|
| 122 |
+
assert getattr(new_opts, name) == value
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class InvalidRowHandler:
|
| 126 |
+
def __init__(self, result):
|
| 127 |
+
self.result = result
|
| 128 |
+
self.rows = []
|
| 129 |
+
|
| 130 |
+
def __call__(self, row):
|
| 131 |
+
self.rows.append(row)
|
| 132 |
+
return self.result
|
| 133 |
+
|
| 134 |
+
def __eq__(self, other):
|
| 135 |
+
return (isinstance(other, InvalidRowHandler) and
|
| 136 |
+
other.result == self.result)
|
| 137 |
+
|
| 138 |
+
def __ne__(self, other):
|
| 139 |
+
return (not isinstance(other, InvalidRowHandler) or
|
| 140 |
+
other.result != self.result)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_split_rows_and_columns_utility():
|
| 144 |
+
num_cols = 5
|
| 145 |
+
num_rows = 2
|
| 146 |
+
arr = [x for x in range(1, 11)]
|
| 147 |
+
rows = list(split_rows(arr, num_cols, num_rows))
|
| 148 |
+
assert rows == [
|
| 149 |
+
[1, 2, 3, 4, 5],
|
| 150 |
+
[6, 7, 8, 9, 10]
|
| 151 |
+
]
|
| 152 |
+
columns = list(split_columns(arr, num_cols, num_rows))
|
| 153 |
+
assert columns == [
|
| 154 |
+
[1, 6],
|
| 155 |
+
[2, 7],
|
| 156 |
+
[3, 8],
|
| 157 |
+
[4, 9],
|
| 158 |
+
[5, 10]
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_read_options(pickle_module):
|
| 163 |
+
cls = ReadOptions
|
| 164 |
+
opts = cls()
|
| 165 |
+
|
| 166 |
+
check_options_class(cls, use_threads=[True, False],
|
| 167 |
+
skip_rows=[0, 3],
|
| 168 |
+
column_names=[[], ["ab", "cd"]],
|
| 169 |
+
autogenerate_column_names=[False, True],
|
| 170 |
+
encoding=['utf8', 'utf16'],
|
| 171 |
+
skip_rows_after_names=[0, 27])
|
| 172 |
+
|
| 173 |
+
check_options_class_pickling(cls, pickler=pickle_module,
|
| 174 |
+
use_threads=True,
|
| 175 |
+
skip_rows=3,
|
| 176 |
+
column_names=["ab", "cd"],
|
| 177 |
+
autogenerate_column_names=False,
|
| 178 |
+
encoding='utf16',
|
| 179 |
+
skip_rows_after_names=27)
|
| 180 |
+
|
| 181 |
+
assert opts.block_size > 0
|
| 182 |
+
opts.block_size = 12345
|
| 183 |
+
assert opts.block_size == 12345
|
| 184 |
+
|
| 185 |
+
opts = cls(block_size=1234)
|
| 186 |
+
assert opts.block_size == 1234
|
| 187 |
+
|
| 188 |
+
opts.validate()
|
| 189 |
+
|
| 190 |
+
match = "ReadOptions: block_size must be at least 1: 0"
|
| 191 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 192 |
+
opts = cls()
|
| 193 |
+
opts.block_size = 0
|
| 194 |
+
opts.validate()
|
| 195 |
+
|
| 196 |
+
match = "ReadOptions: skip_rows cannot be negative: -1"
|
| 197 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 198 |
+
opts = cls()
|
| 199 |
+
opts.skip_rows = -1
|
| 200 |
+
opts.validate()
|
| 201 |
+
|
| 202 |
+
match = "ReadOptions: skip_rows_after_names cannot be negative: -1"
|
| 203 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 204 |
+
opts = cls()
|
| 205 |
+
opts.skip_rows_after_names = -1
|
| 206 |
+
opts.validate()
|
| 207 |
+
|
| 208 |
+
match = "ReadOptions: autogenerate_column_names cannot be true when" \
|
| 209 |
+
" column_names are provided"
|
| 210 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 211 |
+
opts = cls()
|
| 212 |
+
opts.autogenerate_column_names = True
|
| 213 |
+
opts.column_names = ('a', 'b')
|
| 214 |
+
opts.validate()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_parse_options(pickle_module):
|
| 218 |
+
cls = ParseOptions
|
| 219 |
+
skip_handler = InvalidRowHandler('skip')
|
| 220 |
+
|
| 221 |
+
check_options_class(cls, delimiter=[',', 'x'],
|
| 222 |
+
escape_char=[False, 'y'],
|
| 223 |
+
quote_char=['"', 'z', False],
|
| 224 |
+
double_quote=[True, False],
|
| 225 |
+
newlines_in_values=[False, True],
|
| 226 |
+
ignore_empty_lines=[True, False],
|
| 227 |
+
invalid_row_handler=[None, skip_handler])
|
| 228 |
+
|
| 229 |
+
check_options_class_pickling(cls, pickler=pickle_module,
|
| 230 |
+
delimiter='x',
|
| 231 |
+
escape_char='y',
|
| 232 |
+
quote_char=False,
|
| 233 |
+
double_quote=False,
|
| 234 |
+
newlines_in_values=True,
|
| 235 |
+
ignore_empty_lines=False,
|
| 236 |
+
invalid_row_handler=skip_handler)
|
| 237 |
+
|
| 238 |
+
cls().validate()
|
| 239 |
+
opts = cls()
|
| 240 |
+
opts.delimiter = "\t"
|
| 241 |
+
opts.validate()
|
| 242 |
+
|
| 243 |
+
match = "ParseOptions: delimiter cannot be \\\\r or \\\\n"
|
| 244 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 245 |
+
opts = cls()
|
| 246 |
+
opts.delimiter = "\n"
|
| 247 |
+
opts.validate()
|
| 248 |
+
|
| 249 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 250 |
+
opts = cls()
|
| 251 |
+
opts.delimiter = "\r"
|
| 252 |
+
opts.validate()
|
| 253 |
+
|
| 254 |
+
match = "ParseOptions: quote_char cannot be \\\\r or \\\\n"
|
| 255 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 256 |
+
opts = cls()
|
| 257 |
+
opts.quote_char = "\n"
|
| 258 |
+
opts.validate()
|
| 259 |
+
|
| 260 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 261 |
+
opts = cls()
|
| 262 |
+
opts.quote_char = "\r"
|
| 263 |
+
opts.validate()
|
| 264 |
+
|
| 265 |
+
match = "ParseOptions: escape_char cannot be \\\\r or \\\\n"
|
| 266 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 267 |
+
opts = cls()
|
| 268 |
+
opts.escape_char = "\n"
|
| 269 |
+
opts.validate()
|
| 270 |
+
|
| 271 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 272 |
+
opts = cls()
|
| 273 |
+
opts.escape_char = "\r"
|
| 274 |
+
opts.validate()
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_convert_options(pickle_module):
|
| 278 |
+
cls = ConvertOptions
|
| 279 |
+
opts = cls()
|
| 280 |
+
|
| 281 |
+
check_options_class(
|
| 282 |
+
cls, check_utf8=[True, False],
|
| 283 |
+
strings_can_be_null=[False, True],
|
| 284 |
+
quoted_strings_can_be_null=[True, False],
|
| 285 |
+
decimal_point=['.', ','],
|
| 286 |
+
include_columns=[[], ['def', 'abc']],
|
| 287 |
+
include_missing_columns=[False, True],
|
| 288 |
+
auto_dict_encode=[False, True],
|
| 289 |
+
timestamp_parsers=[[], [ISO8601, '%y-%m']])
|
| 290 |
+
|
| 291 |
+
check_options_class_pickling(
|
| 292 |
+
cls, pickler=pickle_module,
|
| 293 |
+
check_utf8=False,
|
| 294 |
+
strings_can_be_null=True,
|
| 295 |
+
quoted_strings_can_be_null=False,
|
| 296 |
+
decimal_point=',',
|
| 297 |
+
include_columns=['def', 'abc'],
|
| 298 |
+
include_missing_columns=False,
|
| 299 |
+
auto_dict_encode=True,
|
| 300 |
+
timestamp_parsers=[ISO8601, '%y-%m'])
|
| 301 |
+
|
| 302 |
+
with pytest.raises(ValueError):
|
| 303 |
+
opts.decimal_point = '..'
|
| 304 |
+
|
| 305 |
+
assert opts.auto_dict_max_cardinality > 0
|
| 306 |
+
opts.auto_dict_max_cardinality = 99999
|
| 307 |
+
assert opts.auto_dict_max_cardinality == 99999
|
| 308 |
+
|
| 309 |
+
assert opts.column_types == {}
|
| 310 |
+
# Pass column_types as mapping
|
| 311 |
+
opts.column_types = {'b': pa.int16(), 'c': pa.float32()}
|
| 312 |
+
assert opts.column_types == {'b': pa.int16(), 'c': pa.float32()}
|
| 313 |
+
opts.column_types = {'v': 'int16', 'w': 'null'}
|
| 314 |
+
assert opts.column_types == {'v': pa.int16(), 'w': pa.null()}
|
| 315 |
+
# Pass column_types as schema
|
| 316 |
+
schema = pa.schema([('a', pa.int32()), ('b', pa.string())])
|
| 317 |
+
opts.column_types = schema
|
| 318 |
+
assert opts.column_types == {'a': pa.int32(), 'b': pa.string()}
|
| 319 |
+
# Pass column_types as sequence
|
| 320 |
+
opts.column_types = [('x', pa.binary())]
|
| 321 |
+
assert opts.column_types == {'x': pa.binary()}
|
| 322 |
+
|
| 323 |
+
with pytest.raises(TypeError, match='DataType expected'):
|
| 324 |
+
opts.column_types = {'a': None}
|
| 325 |
+
with pytest.raises(TypeError):
|
| 326 |
+
opts.column_types = 0
|
| 327 |
+
|
| 328 |
+
assert isinstance(opts.null_values, list)
|
| 329 |
+
assert '' in opts.null_values
|
| 330 |
+
assert 'N/A' in opts.null_values
|
| 331 |
+
opts.null_values = ['xxx', 'yyy']
|
| 332 |
+
assert opts.null_values == ['xxx', 'yyy']
|
| 333 |
+
|
| 334 |
+
assert isinstance(opts.true_values, list)
|
| 335 |
+
opts.true_values = ['xxx', 'yyy']
|
| 336 |
+
assert opts.true_values == ['xxx', 'yyy']
|
| 337 |
+
|
| 338 |
+
assert isinstance(opts.false_values, list)
|
| 339 |
+
opts.false_values = ['xxx', 'yyy']
|
| 340 |
+
assert opts.false_values == ['xxx', 'yyy']
|
| 341 |
+
|
| 342 |
+
assert opts.timestamp_parsers == []
|
| 343 |
+
opts.timestamp_parsers = [ISO8601]
|
| 344 |
+
assert opts.timestamp_parsers == [ISO8601]
|
| 345 |
+
|
| 346 |
+
opts = cls(column_types={'a': pa.null()},
|
| 347 |
+
null_values=['N', 'nn'], true_values=['T', 'tt'],
|
| 348 |
+
false_values=['F', 'ff'], auto_dict_max_cardinality=999,
|
| 349 |
+
timestamp_parsers=[ISO8601, '%Y-%m-%d'])
|
| 350 |
+
assert opts.column_types == {'a': pa.null()}
|
| 351 |
+
assert opts.null_values == ['N', 'nn']
|
| 352 |
+
assert opts.false_values == ['F', 'ff']
|
| 353 |
+
assert opts.true_values == ['T', 'tt']
|
| 354 |
+
assert opts.auto_dict_max_cardinality == 999
|
| 355 |
+
assert opts.timestamp_parsers == [ISO8601, '%Y-%m-%d']
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def test_write_options():
|
| 359 |
+
cls = WriteOptions
|
| 360 |
+
opts = cls()
|
| 361 |
+
|
| 362 |
+
check_options_class(
|
| 363 |
+
cls, include_header=[True, False], delimiter=[',', '\t', '|'],
|
| 364 |
+
quoting_style=['needed', 'none', 'all_valid'])
|
| 365 |
+
|
| 366 |
+
assert opts.batch_size > 0
|
| 367 |
+
opts.batch_size = 12345
|
| 368 |
+
assert opts.batch_size == 12345
|
| 369 |
+
|
| 370 |
+
opts = cls(batch_size=9876)
|
| 371 |
+
assert opts.batch_size == 9876
|
| 372 |
+
|
| 373 |
+
opts.validate()
|
| 374 |
+
|
| 375 |
+
match = "WriteOptions: batch_size must be at least 1: 0"
|
| 376 |
+
with pytest.raises(pa.ArrowInvalid, match=match):
|
| 377 |
+
opts = cls()
|
| 378 |
+
opts.batch_size = 0
|
| 379 |
+
opts.validate()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class BaseTestCSV(abc.ABC):
|
| 383 |
+
"""Common tests which are shared by streaming and non streaming readers"""
|
| 384 |
+
|
| 385 |
+
@abc.abstractmethod
|
| 386 |
+
def read_bytes(self, b, **kwargs):
|
| 387 |
+
"""
|
| 388 |
+
:param b: bytes to be parsed
|
| 389 |
+
:param kwargs: arguments passed on to open the csv file
|
| 390 |
+
:return: b parsed as a single RecordBatch
|
| 391 |
+
"""
|
| 392 |
+
raise NotImplementedError
|
| 393 |
+
|
| 394 |
+
@property
|
| 395 |
+
@abc.abstractmethod
|
| 396 |
+
def use_threads(self):
|
| 397 |
+
"""Whether this test is multi-threaded"""
|
| 398 |
+
raise NotImplementedError
|
| 399 |
+
|
| 400 |
+
@staticmethod
|
| 401 |
+
def check_names(table, names):
|
| 402 |
+
assert table.num_columns == len(names)
|
| 403 |
+
assert table.column_names == names
|
| 404 |
+
|
| 405 |
+
def test_header_skip_rows(self):
|
| 406 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 407 |
+
|
| 408 |
+
opts = ReadOptions()
|
| 409 |
+
opts.skip_rows = 1
|
| 410 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 411 |
+
self.check_names(table, ["ef", "gh"])
|
| 412 |
+
assert table.to_pydict() == {
|
| 413 |
+
"ef": ["ij", "mn"],
|
| 414 |
+
"gh": ["kl", "op"],
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
opts.skip_rows = 3
|
| 418 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 419 |
+
self.check_names(table, ["mn", "op"])
|
| 420 |
+
assert table.to_pydict() == {
|
| 421 |
+
"mn": [],
|
| 422 |
+
"op": [],
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
opts.skip_rows = 4
|
| 426 |
+
with pytest.raises(pa.ArrowInvalid):
|
| 427 |
+
# Not enough rows
|
| 428 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 429 |
+
|
| 430 |
+
# Can skip rows with a different number of columns
|
| 431 |
+
rows = b"abcd\n,,,,,\nij,kl\nmn,op\n"
|
| 432 |
+
opts.skip_rows = 2
|
| 433 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 434 |
+
self.check_names(table, ["ij", "kl"])
|
| 435 |
+
assert table.to_pydict() == {
|
| 436 |
+
"ij": ["mn"],
|
| 437 |
+
"kl": ["op"],
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
# Can skip all rows exactly when columns are given
|
| 441 |
+
opts.skip_rows = 4
|
| 442 |
+
opts.column_names = ['ij', 'kl']
|
| 443 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 444 |
+
self.check_names(table, ["ij", "kl"])
|
| 445 |
+
assert table.to_pydict() == {
|
| 446 |
+
"ij": [],
|
| 447 |
+
"kl": [],
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
def test_skip_rows_after_names(self):
|
| 451 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 452 |
+
|
| 453 |
+
opts = ReadOptions()
|
| 454 |
+
opts.skip_rows_after_names = 1
|
| 455 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 456 |
+
self.check_names(table, ["ab", "cd"])
|
| 457 |
+
assert table.to_pydict() == {
|
| 458 |
+
"ab": ["ij", "mn"],
|
| 459 |
+
"cd": ["kl", "op"],
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
# Can skip exact number of rows
|
| 463 |
+
opts.skip_rows_after_names = 3
|
| 464 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 465 |
+
self.check_names(table, ["ab", "cd"])
|
| 466 |
+
assert table.to_pydict() == {
|
| 467 |
+
"ab": [],
|
| 468 |
+
"cd": [],
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
# Can skip beyond all rows
|
| 472 |
+
opts.skip_rows_after_names = 4
|
| 473 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 474 |
+
self.check_names(table, ["ab", "cd"])
|
| 475 |
+
assert table.to_pydict() == {
|
| 476 |
+
"ab": [],
|
| 477 |
+
"cd": [],
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
# Can skip rows with a different number of columns
|
| 481 |
+
rows = b"abcd\n,,,,,\nij,kl\nmn,op\n"
|
| 482 |
+
opts.skip_rows_after_names = 2
|
| 483 |
+
opts.column_names = ["f0", "f1"]
|
| 484 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 485 |
+
self.check_names(table, ["f0", "f1"])
|
| 486 |
+
assert table.to_pydict() == {
|
| 487 |
+
"f0": ["ij", "mn"],
|
| 488 |
+
"f1": ["kl", "op"],
|
| 489 |
+
}
|
| 490 |
+
opts = ReadOptions()
|
| 491 |
+
|
| 492 |
+
# Can skip rows with new lines in the value
|
| 493 |
+
rows = b'ab,cd\n"e\nf","g\n\nh"\n"ij","k\nl"\nmn,op'
|
| 494 |
+
opts.skip_rows_after_names = 2
|
| 495 |
+
parse_opts = ParseOptions()
|
| 496 |
+
parse_opts.newlines_in_values = True
|
| 497 |
+
table = self.read_bytes(rows, read_options=opts,
|
| 498 |
+
parse_options=parse_opts)
|
| 499 |
+
self.check_names(table, ["ab", "cd"])
|
| 500 |
+
assert table.to_pydict() == {
|
| 501 |
+
"ab": ["mn"],
|
| 502 |
+
"cd": ["op"],
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
# Can skip rows when block ends in middle of quoted value
|
| 506 |
+
opts.skip_rows_after_names = 2
|
| 507 |
+
opts.block_size = 26
|
| 508 |
+
table = self.read_bytes(rows, read_options=opts,
|
| 509 |
+
parse_options=parse_opts)
|
| 510 |
+
self.check_names(table, ["ab", "cd"])
|
| 511 |
+
assert table.to_pydict() == {
|
| 512 |
+
"ab": ["mn"],
|
| 513 |
+
"cd": ["op"],
|
| 514 |
+
}
|
| 515 |
+
opts = ReadOptions()
|
| 516 |
+
|
| 517 |
+
# Can skip rows that are beyond the first block without lexer
|
| 518 |
+
rows, expected = make_random_csv(num_cols=5, num_rows=1000)
|
| 519 |
+
opts.skip_rows_after_names = 900
|
| 520 |
+
opts.block_size = len(rows) / 11
|
| 521 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 522 |
+
assert table.schema == expected.schema
|
| 523 |
+
assert table.num_rows == 100
|
| 524 |
+
table_dict = table.to_pydict()
|
| 525 |
+
for name, values in expected.to_pydict().items():
|
| 526 |
+
assert values[900:] == table_dict[name]
|
| 527 |
+
|
| 528 |
+
# Can skip rows that are beyond the first block with lexer
|
| 529 |
+
table = self.read_bytes(rows, read_options=opts,
|
| 530 |
+
parse_options=parse_opts)
|
| 531 |
+
assert table.schema == expected.schema
|
| 532 |
+
assert table.num_rows == 100
|
| 533 |
+
table_dict = table.to_pydict()
|
| 534 |
+
for name, values in expected.to_pydict().items():
|
| 535 |
+
assert values[900:] == table_dict[name]
|
| 536 |
+
|
| 537 |
+
# Skip rows and skip rows after names
|
| 538 |
+
rows, expected = make_random_csv(num_cols=5, num_rows=200,
|
| 539 |
+
write_names=False)
|
| 540 |
+
opts = ReadOptions()
|
| 541 |
+
opts.skip_rows = 37
|
| 542 |
+
opts.skip_rows_after_names = 41
|
| 543 |
+
opts.column_names = expected.schema.names
|
| 544 |
+
table = self.read_bytes(rows, read_options=opts,
|
| 545 |
+
parse_options=parse_opts)
|
| 546 |
+
assert table.schema == expected.schema
|
| 547 |
+
assert (table.num_rows ==
|
| 548 |
+
expected.num_rows - opts.skip_rows -
|
| 549 |
+
opts.skip_rows_after_names)
|
| 550 |
+
table_dict = table.to_pydict()
|
| 551 |
+
for name, values in expected.to_pydict().items():
|
| 552 |
+
assert (values[opts.skip_rows + opts.skip_rows_after_names:] ==
|
| 553 |
+
table_dict[name])
|
| 554 |
+
|
| 555 |
+
@pytest.mark.numpy
|
| 556 |
+
def test_row_number_offset_in_errors(self):
|
| 557 |
+
# Row numbers are only correctly counted in serial reads
|
| 558 |
+
def format_msg(msg_format, row, *args):
|
| 559 |
+
if self.use_threads:
|
| 560 |
+
row_info = ""
|
| 561 |
+
else:
|
| 562 |
+
row_info = "Row #{}: ".format(row)
|
| 563 |
+
return msg_format.format(row_info, *args)
|
| 564 |
+
|
| 565 |
+
csv, _ = make_random_csv(4, 100, write_names=True)
|
| 566 |
+
|
| 567 |
+
read_options = ReadOptions()
|
| 568 |
+
read_options.block_size = len(csv) / 3
|
| 569 |
+
convert_options = ConvertOptions()
|
| 570 |
+
convert_options.column_types = {"a": pa.int32()}
|
| 571 |
+
|
| 572 |
+
# Test without skip_rows and column names in the csv
|
| 573 |
+
csv_bad_columns = csv + b"1,2\r\n"
|
| 574 |
+
message_columns = format_msg("{}Expected 4 columns, got 2", 102)
|
| 575 |
+
with pytest.raises(pa.ArrowInvalid, match=message_columns):
|
| 576 |
+
self.read_bytes(csv_bad_columns,
|
| 577 |
+
read_options=read_options,
|
| 578 |
+
convert_options=convert_options)
|
| 579 |
+
|
| 580 |
+
csv_bad_type = csv + b"a,b,c,d\r\n"
|
| 581 |
+
message_value = format_msg(
|
| 582 |
+
"In CSV column #0: {}"
|
| 583 |
+
"CSV conversion error to int32: invalid value 'a'",
|
| 584 |
+
102, csv)
|
| 585 |
+
with pytest.raises(pa.ArrowInvalid, match=message_value):
|
| 586 |
+
self.read_bytes(csv_bad_type,
|
| 587 |
+
read_options=read_options,
|
| 588 |
+
convert_options=convert_options)
|
| 589 |
+
|
| 590 |
+
long_row = (b"this is a long row" * 15) + b",3\r\n"
|
| 591 |
+
csv_bad_columns_long = csv + long_row
|
| 592 |
+
message_long = format_msg("{}Expected 4 columns, got 2: {} ...", 102,
|
| 593 |
+
long_row[0:96].decode("utf-8"))
|
| 594 |
+
with pytest.raises(pa.ArrowInvalid, match=message_long):
|
| 595 |
+
self.read_bytes(csv_bad_columns_long,
|
| 596 |
+
read_options=read_options,
|
| 597 |
+
convert_options=convert_options)
|
| 598 |
+
|
| 599 |
+
# Test skipping rows after the names
|
| 600 |
+
read_options.skip_rows_after_names = 47
|
| 601 |
+
|
| 602 |
+
with pytest.raises(pa.ArrowInvalid, match=message_columns):
|
| 603 |
+
self.read_bytes(csv_bad_columns,
|
| 604 |
+
read_options=read_options,
|
| 605 |
+
convert_options=convert_options)
|
| 606 |
+
|
| 607 |
+
with pytest.raises(pa.ArrowInvalid, match=message_value):
|
| 608 |
+
self.read_bytes(csv_bad_type,
|
| 609 |
+
read_options=read_options,
|
| 610 |
+
convert_options=convert_options)
|
| 611 |
+
|
| 612 |
+
with pytest.raises(pa.ArrowInvalid, match=message_long):
|
| 613 |
+
self.read_bytes(csv_bad_columns_long,
|
| 614 |
+
read_options=read_options,
|
| 615 |
+
convert_options=convert_options)
|
| 616 |
+
|
| 617 |
+
read_options.skip_rows_after_names = 0
|
| 618 |
+
|
| 619 |
+
# Test without skip_rows and column names not in the csv
|
| 620 |
+
csv, _ = make_random_csv(4, 100, write_names=False)
|
| 621 |
+
read_options.column_names = ["a", "b", "c", "d"]
|
| 622 |
+
csv_bad_columns = csv + b"1,2\r\n"
|
| 623 |
+
message_columns = format_msg("{}Expected 4 columns, got 2", 101)
|
| 624 |
+
with pytest.raises(pa.ArrowInvalid, match=message_columns):
|
| 625 |
+
self.read_bytes(csv_bad_columns,
|
| 626 |
+
read_options=read_options,
|
| 627 |
+
convert_options=convert_options)
|
| 628 |
+
|
| 629 |
+
csv_bad_columns_long = csv + long_row
|
| 630 |
+
message_long = format_msg("{}Expected 4 columns, got 2: {} ...", 101,
|
| 631 |
+
long_row[0:96].decode("utf-8"))
|
| 632 |
+
with pytest.raises(pa.ArrowInvalid, match=message_long):
|
| 633 |
+
self.read_bytes(csv_bad_columns_long,
|
| 634 |
+
read_options=read_options,
|
| 635 |
+
convert_options=convert_options)
|
| 636 |
+
|
| 637 |
+
csv_bad_type = csv + b"a,b,c,d\r\n"
|
| 638 |
+
message_value = format_msg(
|
| 639 |
+
"In CSV column #0: {}"
|
| 640 |
+
"CSV conversion error to int32: invalid value 'a'",
|
| 641 |
+
101)
|
| 642 |
+
message_value = message_value.format(len(csv))
|
| 643 |
+
with pytest.raises(pa.ArrowInvalid, match=message_value):
|
| 644 |
+
self.read_bytes(csv_bad_type,
|
| 645 |
+
read_options=read_options,
|
| 646 |
+
convert_options=convert_options)
|
| 647 |
+
|
| 648 |
+
# Test with skip_rows and column names not in the csv
|
| 649 |
+
read_options.skip_rows = 23
|
| 650 |
+
with pytest.raises(pa.ArrowInvalid, match=message_columns):
|
| 651 |
+
self.read_bytes(csv_bad_columns,
|
| 652 |
+
read_options=read_options,
|
| 653 |
+
convert_options=convert_options)
|
| 654 |
+
|
| 655 |
+
with pytest.raises(pa.ArrowInvalid, match=message_value):
|
| 656 |
+
self.read_bytes(csv_bad_type,
|
| 657 |
+
read_options=read_options,
|
| 658 |
+
convert_options=convert_options)
|
| 659 |
+
|
| 660 |
+
def test_invalid_row_handler(self, pickle_module):
|
| 661 |
+
rows = b"a,b\nc\nd,e\nf,g,h\ni,j\n"
|
| 662 |
+
parse_opts = ParseOptions()
|
| 663 |
+
with pytest.raises(
|
| 664 |
+
ValueError,
|
| 665 |
+
match="Expected 2 columns, got 1: c"):
|
| 666 |
+
self.read_bytes(rows, parse_options=parse_opts)
|
| 667 |
+
|
| 668 |
+
# Skip requested
|
| 669 |
+
parse_opts.invalid_row_handler = InvalidRowHandler('skip')
|
| 670 |
+
table = self.read_bytes(rows, parse_options=parse_opts)
|
| 671 |
+
assert table.to_pydict() == {
|
| 672 |
+
'a': ["d", "i"],
|
| 673 |
+
'b': ["e", "j"],
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
def row_num(x):
|
| 677 |
+
return None if self.use_threads else x
|
| 678 |
+
expected_rows = [
|
| 679 |
+
InvalidRow(2, 1, row_num(2), "c"),
|
| 680 |
+
InvalidRow(2, 3, row_num(4), "f,g,h"),
|
| 681 |
+
]
|
| 682 |
+
assert parse_opts.invalid_row_handler.rows == expected_rows
|
| 683 |
+
|
| 684 |
+
# Error requested
|
| 685 |
+
parse_opts.invalid_row_handler = InvalidRowHandler('error')
|
| 686 |
+
with pytest.raises(
|
| 687 |
+
ValueError,
|
| 688 |
+
match="Expected 2 columns, got 1: c"):
|
| 689 |
+
self.read_bytes(rows, parse_options=parse_opts)
|
| 690 |
+
expected_rows = [InvalidRow(2, 1, row_num(2), "c")]
|
| 691 |
+
assert parse_opts.invalid_row_handler.rows == expected_rows
|
| 692 |
+
|
| 693 |
+
# Test ser/de
|
| 694 |
+
parse_opts.invalid_row_handler = InvalidRowHandler('skip')
|
| 695 |
+
parse_opts = pickle_module.loads(pickle_module.dumps(parse_opts))
|
| 696 |
+
|
| 697 |
+
table = self.read_bytes(rows, parse_options=parse_opts)
|
| 698 |
+
assert table.to_pydict() == {
|
| 699 |
+
'a': ["d", "i"],
|
| 700 |
+
'b': ["e", "j"],
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
def test_chunker_out_of_sync(self):
|
| 704 |
+
# GH-39892: if there are newlines in values, the parser may become
|
| 705 |
+
# out of sync with the chunker. In this case, we try to produce an
|
| 706 |
+
# informative error message.
|
| 707 |
+
rows = b"""a,b,c\nd,e,"f\n"\ng,h,i\n"""
|
| 708 |
+
expected = {
|
| 709 |
+
'a': ["d", "g"],
|
| 710 |
+
'b': ["e", "h"],
|
| 711 |
+
'c': ["f\n", "i"],
|
| 712 |
+
}
|
| 713 |
+
for block_size in range(8, 15):
|
| 714 |
+
# Sanity check: parsing works with newlines_in_values=True
|
| 715 |
+
d = self.read_bytes(
|
| 716 |
+
rows, parse_options=ParseOptions(newlines_in_values=True),
|
| 717 |
+
read_options=ReadOptions(block_size=block_size)).to_pydict()
|
| 718 |
+
assert d == expected
|
| 719 |
+
# With these block sizes, a block would end on the physical newline
|
| 720 |
+
# inside the quoted cell value, leading to a mismatch between
|
| 721 |
+
# CSV chunker and parser.
|
| 722 |
+
for block_size in range(8, 11):
|
| 723 |
+
with pytest.raises(ValueError,
|
| 724 |
+
match="cell values spanning multiple lines"):
|
| 725 |
+
self.read_bytes(
|
| 726 |
+
rows, read_options=ReadOptions(block_size=block_size))
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
class BaseCSVTableRead(BaseTestCSV):
|
| 730 |
+
|
| 731 |
+
def read_csv(self, csv, *args, validate_full=True, **kwargs):
|
| 732 |
+
"""
|
| 733 |
+
Reads the CSV file into memory using pyarrow's read_csv
|
| 734 |
+
csv The CSV bytes
|
| 735 |
+
args Positional arguments to be forwarded to pyarrow's read_csv
|
| 736 |
+
validate_full Whether or not to fully validate the resulting table
|
| 737 |
+
kwargs Keyword arguments to be forwarded to pyarrow's read_csv
|
| 738 |
+
"""
|
| 739 |
+
assert isinstance(self.use_threads, bool) # sanity check
|
| 740 |
+
read_options = kwargs.setdefault('read_options', ReadOptions())
|
| 741 |
+
read_options.use_threads = self.use_threads
|
| 742 |
+
table = read_csv(csv, *args, **kwargs)
|
| 743 |
+
table.validate(full=validate_full)
|
| 744 |
+
return table
|
| 745 |
+
|
| 746 |
+
def read_bytes(self, b, **kwargs):
|
| 747 |
+
return self.read_csv(pa.py_buffer(b), **kwargs)
|
| 748 |
+
|
| 749 |
+
def test_file_object(self):
|
| 750 |
+
data = b"a,b\n1,2\n"
|
| 751 |
+
expected_data = {'a': [1], 'b': [2]}
|
| 752 |
+
bio = io.BytesIO(data)
|
| 753 |
+
table = self.read_csv(bio)
|
| 754 |
+
assert table.to_pydict() == expected_data
|
| 755 |
+
# Text files not allowed
|
| 756 |
+
sio = io.StringIO(data.decode())
|
| 757 |
+
with pytest.raises(TypeError):
|
| 758 |
+
self.read_csv(sio)
|
| 759 |
+
|
| 760 |
+
def test_header(self):
|
| 761 |
+
rows = b"abc,def,gh\n"
|
| 762 |
+
table = self.read_bytes(rows)
|
| 763 |
+
assert isinstance(table, pa.Table)
|
| 764 |
+
self.check_names(table, ["abc", "def", "gh"])
|
| 765 |
+
assert table.num_rows == 0
|
| 766 |
+
|
| 767 |
+
def test_bom(self):
|
| 768 |
+
rows = b"\xef\xbb\xbfa,b\n1,2\n"
|
| 769 |
+
expected_data = {'a': [1], 'b': [2]}
|
| 770 |
+
table = self.read_bytes(rows)
|
| 771 |
+
assert table.to_pydict() == expected_data
|
| 772 |
+
|
| 773 |
+
def test_one_chunk(self):
|
| 774 |
+
# ARROW-7661: lack of newline at end of file should not produce
|
| 775 |
+
# an additional chunk.
|
| 776 |
+
rows = [b"a,b", b"1,2", b"3,4", b"56,78"]
|
| 777 |
+
for line_ending in [b'\n', b'\r', b'\r\n']:
|
| 778 |
+
for file_ending in [b'', line_ending]:
|
| 779 |
+
data = line_ending.join(rows) + file_ending
|
| 780 |
+
table = self.read_bytes(data)
|
| 781 |
+
assert len(table.to_batches()) == 1
|
| 782 |
+
assert table.to_pydict() == {
|
| 783 |
+
"a": [1, 3, 56],
|
| 784 |
+
"b": [2, 4, 78],
|
| 785 |
+
}
|
| 786 |
+
|
| 787 |
+
def test_header_column_names(self):
|
| 788 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 789 |
+
|
| 790 |
+
opts = ReadOptions()
|
| 791 |
+
opts.column_names = ["x", "y"]
|
| 792 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 793 |
+
self.check_names(table, ["x", "y"])
|
| 794 |
+
assert table.to_pydict() == {
|
| 795 |
+
"x": ["ab", "ef", "ij", "mn"],
|
| 796 |
+
"y": ["cd", "gh", "kl", "op"],
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
opts.skip_rows = 3
|
| 800 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 801 |
+
self.check_names(table, ["x", "y"])
|
| 802 |
+
assert table.to_pydict() == {
|
| 803 |
+
"x": ["mn"],
|
| 804 |
+
"y": ["op"],
|
| 805 |
+
}
|
| 806 |
+
|
| 807 |
+
opts.skip_rows = 4
|
| 808 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 809 |
+
self.check_names(table, ["x", "y"])
|
| 810 |
+
assert table.to_pydict() == {
|
| 811 |
+
"x": [],
|
| 812 |
+
"y": [],
|
| 813 |
+
}
|
| 814 |
+
|
| 815 |
+
opts.skip_rows = 5
|
| 816 |
+
with pytest.raises(pa.ArrowInvalid):
|
| 817 |
+
# Not enough rows
|
| 818 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 819 |
+
|
| 820 |
+
# Unexpected number of columns
|
| 821 |
+
opts.skip_rows = 0
|
| 822 |
+
opts.column_names = ["x", "y", "z"]
|
| 823 |
+
with pytest.raises(pa.ArrowInvalid,
|
| 824 |
+
match="Expected 3 columns, got 2"):
|
| 825 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 826 |
+
|
| 827 |
+
# Can skip rows with a different number of columns
|
| 828 |
+
rows = b"abcd\n,,,,,\nij,kl\nmn,op\n"
|
| 829 |
+
opts.skip_rows = 2
|
| 830 |
+
opts.column_names = ["x", "y"]
|
| 831 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 832 |
+
self.check_names(table, ["x", "y"])
|
| 833 |
+
assert table.to_pydict() == {
|
| 834 |
+
"x": ["ij", "mn"],
|
| 835 |
+
"y": ["kl", "op"],
|
| 836 |
+
}
|
| 837 |
+
|
| 838 |
+
def test_header_autogenerate_column_names(self):
|
| 839 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 840 |
+
|
| 841 |
+
opts = ReadOptions()
|
| 842 |
+
opts.autogenerate_column_names = True
|
| 843 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 844 |
+
self.check_names(table, ["f0", "f1"])
|
| 845 |
+
assert table.to_pydict() == {
|
| 846 |
+
"f0": ["ab", "ef", "ij", "mn"],
|
| 847 |
+
"f1": ["cd", "gh", "kl", "op"],
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
opts.skip_rows = 3
|
| 851 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 852 |
+
self.check_names(table, ["f0", "f1"])
|
| 853 |
+
assert table.to_pydict() == {
|
| 854 |
+
"f0": ["mn"],
|
| 855 |
+
"f1": ["op"],
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
# Not enough rows, impossible to infer number of columns
|
| 859 |
+
opts.skip_rows = 4
|
| 860 |
+
with pytest.raises(pa.ArrowInvalid):
|
| 861 |
+
table = self.read_bytes(rows, read_options=opts)
|
| 862 |
+
|
| 863 |
+
def test_include_columns(self):
|
| 864 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 865 |
+
|
| 866 |
+
convert_options = ConvertOptions()
|
| 867 |
+
convert_options.include_columns = ['ab']
|
| 868 |
+
table = self.read_bytes(rows, convert_options=convert_options)
|
| 869 |
+
self.check_names(table, ["ab"])
|
| 870 |
+
assert table.to_pydict() == {
|
| 871 |
+
"ab": ["ef", "ij", "mn"],
|
| 872 |
+
}
|
| 873 |
+
|
| 874 |
+
# Order of include_columns is respected, regardless of CSV order
|
| 875 |
+
convert_options.include_columns = ['cd', 'ab']
|
| 876 |
+
table = self.read_bytes(rows, convert_options=convert_options)
|
| 877 |
+
schema = pa.schema([('cd', pa.string()),
|
| 878 |
+
('ab', pa.string())])
|
| 879 |
+
assert table.schema == schema
|
| 880 |
+
assert table.to_pydict() == {
|
| 881 |
+
"cd": ["gh", "kl", "op"],
|
| 882 |
+
"ab": ["ef", "ij", "mn"],
|
| 883 |
+
}
|
| 884 |
+
|
| 885 |
+
# Include a column not in the CSV file => raises by default
|
| 886 |
+
convert_options.include_columns = ['xx', 'ab', 'yy']
|
| 887 |
+
with pytest.raises(KeyError,
|
| 888 |
+
match="Column 'xx' in include_columns "
|
| 889 |
+
"does not exist in CSV file"):
|
| 890 |
+
self.read_bytes(rows, convert_options=convert_options)
|
| 891 |
+
|
| 892 |
+
def test_include_missing_columns(self):
|
| 893 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 894 |
+
|
| 895 |
+
read_options = ReadOptions()
|
| 896 |
+
convert_options = ConvertOptions()
|
| 897 |
+
convert_options.include_columns = ['xx', 'ab', 'yy']
|
| 898 |
+
convert_options.include_missing_columns = True
|
| 899 |
+
table = self.read_bytes(rows, read_options=read_options,
|
| 900 |
+
convert_options=convert_options)
|
| 901 |
+
schema = pa.schema([('xx', pa.null()),
|
| 902 |
+
('ab', pa.string()),
|
| 903 |
+
('yy', pa.null())])
|
| 904 |
+
assert table.schema == schema
|
| 905 |
+
assert table.to_pydict() == {
|
| 906 |
+
"xx": [None, None, None],
|
| 907 |
+
"ab": ["ef", "ij", "mn"],
|
| 908 |
+
"yy": [None, None, None],
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
# Combining with `column_names`
|
| 912 |
+
read_options.column_names = ["xx", "yy"]
|
| 913 |
+
convert_options.include_columns = ["yy", "cd"]
|
| 914 |
+
table = self.read_bytes(rows, read_options=read_options,
|
| 915 |
+
convert_options=convert_options)
|
| 916 |
+
schema = pa.schema([('yy', pa.string()),
|
| 917 |
+
('cd', pa.null())])
|
| 918 |
+
assert table.schema == schema
|
| 919 |
+
assert table.to_pydict() == {
|
| 920 |
+
"yy": ["cd", "gh", "kl", "op"],
|
| 921 |
+
"cd": [None, None, None, None],
|
| 922 |
+
}
|
| 923 |
+
|
| 924 |
+
# And with `column_types` as well
|
| 925 |
+
convert_options.column_types = {"yy": pa.binary(),
|
| 926 |
+
"cd": pa.int32()}
|
| 927 |
+
table = self.read_bytes(rows, read_options=read_options,
|
| 928 |
+
convert_options=convert_options)
|
| 929 |
+
schema = pa.schema([('yy', pa.binary()),
|
| 930 |
+
('cd', pa.int32())])
|
| 931 |
+
assert table.schema == schema
|
| 932 |
+
assert table.to_pydict() == {
|
| 933 |
+
"yy": [b"cd", b"gh", b"kl", b"op"],
|
| 934 |
+
"cd": [None, None, None, None],
|
| 935 |
+
}
|
| 936 |
+
|
| 937 |
+
def test_simple_ints(self):
|
| 938 |
+
# Infer integer columns
|
| 939 |
+
rows = b"a,b,c\n1,2,3\n4,5,6\n"
|
| 940 |
+
table = self.read_bytes(rows)
|
| 941 |
+
schema = pa.schema([('a', pa.int64()),
|
| 942 |
+
('b', pa.int64()),
|
| 943 |
+
('c', pa.int64())])
|
| 944 |
+
assert table.schema == schema
|
| 945 |
+
assert table.to_pydict() == {
|
| 946 |
+
'a': [1, 4],
|
| 947 |
+
'b': [2, 5],
|
| 948 |
+
'c': [3, 6],
|
| 949 |
+
}
|
| 950 |
+
|
| 951 |
+
def test_simple_varied(self):
|
| 952 |
+
# Infer various kinds of data
|
| 953 |
+
rows = b"a,b,c,d\n1,2,3,0\n4.0,-5,foo,True\n"
|
| 954 |
+
table = self.read_bytes(rows)
|
| 955 |
+
schema = pa.schema([('a', pa.float64()),
|
| 956 |
+
('b', pa.int64()),
|
| 957 |
+
('c', pa.string()),
|
| 958 |
+
('d', pa.bool_())])
|
| 959 |
+
assert table.schema == schema
|
| 960 |
+
assert table.to_pydict() == {
|
| 961 |
+
'a': [1.0, 4.0],
|
| 962 |
+
'b': [2, -5],
|
| 963 |
+
'c': ["3", "foo"],
|
| 964 |
+
'd': [False, True],
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
def test_simple_nulls(self):
|
| 968 |
+
# Infer various kinds of data, with nulls
|
| 969 |
+
rows = (b"a,b,c,d,e,f\n"
|
| 970 |
+
b"1,2,,,3,N/A\n"
|
| 971 |
+
b"nan,-5,foo,,nan,TRUE\n"
|
| 972 |
+
b"4.5,#N/A,nan,,\xff,false\n")
|
| 973 |
+
table = self.read_bytes(rows)
|
| 974 |
+
schema = pa.schema([('a', pa.float64()),
|
| 975 |
+
('b', pa.int64()),
|
| 976 |
+
('c', pa.string()),
|
| 977 |
+
('d', pa.null()),
|
| 978 |
+
('e', pa.binary()),
|
| 979 |
+
('f', pa.bool_())])
|
| 980 |
+
assert table.schema == schema
|
| 981 |
+
assert table.to_pydict() == {
|
| 982 |
+
'a': [1.0, None, 4.5],
|
| 983 |
+
'b': [2, -5, None],
|
| 984 |
+
'c': ["", "foo", "nan"],
|
| 985 |
+
'd': [None, None, None],
|
| 986 |
+
'e': [b"3", b"nan", b"\xff"],
|
| 987 |
+
'f': [None, True, False],
|
| 988 |
+
}
|
| 989 |
+
|
| 990 |
+
def test_decimal_point(self):
|
| 991 |
+
# Infer floats with a custom decimal point
|
| 992 |
+
parse_options = ParseOptions(delimiter=';')
|
| 993 |
+
rows = b"a;b\n1.25;2,5\nNA;-3\n-4;NA"
|
| 994 |
+
|
| 995 |
+
table = self.read_bytes(rows, parse_options=parse_options)
|
| 996 |
+
schema = pa.schema([('a', pa.float64()),
|
| 997 |
+
('b', pa.string())])
|
| 998 |
+
assert table.schema == schema
|
| 999 |
+
assert table.to_pydict() == {
|
| 1000 |
+
'a': [1.25, None, -4.0],
|
| 1001 |
+
'b': ["2,5", "-3", "NA"],
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
convert_options = ConvertOptions(decimal_point=',')
|
| 1005 |
+
table = self.read_bytes(rows, parse_options=parse_options,
|
| 1006 |
+
convert_options=convert_options)
|
| 1007 |
+
schema = pa.schema([('a', pa.string()),
|
| 1008 |
+
('b', pa.float64())])
|
| 1009 |
+
assert table.schema == schema
|
| 1010 |
+
assert table.to_pydict() == {
|
| 1011 |
+
'a': ["1.25", "NA", "-4"],
|
| 1012 |
+
'b': [2.5, -3.0, None],
|
| 1013 |
+
}
|
| 1014 |
+
|
| 1015 |
+
def test_simple_timestamps(self):
|
| 1016 |
+
# Infer a timestamp column
|
| 1017 |
+
rows = (b"a,b,c\n"
|
| 1018 |
+
b"1970,1970-01-01 00:00:00,1970-01-01 00:00:00.123\n"
|
| 1019 |
+
b"1989,1989-07-14 01:00:00,1989-07-14 01:00:00.123456\n")
|
| 1020 |
+
table = self.read_bytes(rows)
|
| 1021 |
+
schema = pa.schema([('a', pa.int64()),
|
| 1022 |
+
('b', pa.timestamp('s')),
|
| 1023 |
+
('c', pa.timestamp('ns'))])
|
| 1024 |
+
assert table.schema == schema
|
| 1025 |
+
assert table.to_pydict() == {
|
| 1026 |
+
'a': [1970, 1989],
|
| 1027 |
+
'b': [datetime(1970, 1, 1), datetime(1989, 7, 14, 1)],
|
| 1028 |
+
'c': [datetime(1970, 1, 1, 0, 0, 0, 123000),
|
| 1029 |
+
datetime(1989, 7, 14, 1, 0, 0, 123456)],
|
| 1030 |
+
}
|
| 1031 |
+
|
| 1032 |
+
def test_timestamp_parsers(self):
|
| 1033 |
+
# Infer timestamps with custom parsers
|
| 1034 |
+
rows = b"a,b\n1970/01/01,1980-01-01 00\n1970/01/02,1980-01-02 00\n"
|
| 1035 |
+
opts = ConvertOptions()
|
| 1036 |
+
|
| 1037 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1038 |
+
schema = pa.schema([('a', pa.string()),
|
| 1039 |
+
('b', pa.timestamp('s'))])
|
| 1040 |
+
assert table.schema == schema
|
| 1041 |
+
assert table.to_pydict() == {
|
| 1042 |
+
'a': ['1970/01/01', '1970/01/02'],
|
| 1043 |
+
'b': [datetime(1980, 1, 1), datetime(1980, 1, 2)],
|
| 1044 |
+
}
|
| 1045 |
+
|
| 1046 |
+
opts.timestamp_parsers = ['%Y/%m/%d']
|
| 1047 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1048 |
+
schema = pa.schema([('a', pa.timestamp('s')),
|
| 1049 |
+
('b', pa.string())])
|
| 1050 |
+
assert table.schema == schema
|
| 1051 |
+
assert table.to_pydict() == {
|
| 1052 |
+
'a': [datetime(1970, 1, 1), datetime(1970, 1, 2)],
|
| 1053 |
+
'b': ['1980-01-01 00', '1980-01-02 00'],
|
| 1054 |
+
}
|
| 1055 |
+
|
| 1056 |
+
opts.timestamp_parsers = ['%Y/%m/%d', ISO8601]
|
| 1057 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1058 |
+
schema = pa.schema([('a', pa.timestamp('s')),
|
| 1059 |
+
('b', pa.timestamp('s'))])
|
| 1060 |
+
assert table.schema == schema
|
| 1061 |
+
assert table.to_pydict() == {
|
| 1062 |
+
'a': [datetime(1970, 1, 1), datetime(1970, 1, 2)],
|
| 1063 |
+
'b': [datetime(1980, 1, 1), datetime(1980, 1, 2)],
|
| 1064 |
+
}
|
| 1065 |
+
|
| 1066 |
+
def test_dates(self):
|
| 1067 |
+
# Dates are inferred as date32 by default
|
| 1068 |
+
rows = b"a,b\n1970-01-01,1970-01-02\n1971-01-01,1971-01-02\n"
|
| 1069 |
+
table = self.read_bytes(rows)
|
| 1070 |
+
schema = pa.schema([('a', pa.date32()),
|
| 1071 |
+
('b', pa.date32())])
|
| 1072 |
+
assert table.schema == schema
|
| 1073 |
+
assert table.to_pydict() == {
|
| 1074 |
+
'a': [date(1970, 1, 1), date(1971, 1, 1)],
|
| 1075 |
+
'b': [date(1970, 1, 2), date(1971, 1, 2)],
|
| 1076 |
+
}
|
| 1077 |
+
|
| 1078 |
+
# Can ask for date types explicitly
|
| 1079 |
+
opts = ConvertOptions()
|
| 1080 |
+
opts.column_types = {'a': pa.date32(), 'b': pa.date64()}
|
| 1081 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1082 |
+
schema = pa.schema([('a', pa.date32()),
|
| 1083 |
+
('b', pa.date64())])
|
| 1084 |
+
assert table.schema == schema
|
| 1085 |
+
assert table.to_pydict() == {
|
| 1086 |
+
'a': [date(1970, 1, 1), date(1971, 1, 1)],
|
| 1087 |
+
'b': [date(1970, 1, 2), date(1971, 1, 2)],
|
| 1088 |
+
}
|
| 1089 |
+
|
| 1090 |
+
# Can ask for timestamp types explicitly
|
| 1091 |
+
opts = ConvertOptions()
|
| 1092 |
+
opts.column_types = {'a': pa.timestamp('s'), 'b': pa.timestamp('ms')}
|
| 1093 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1094 |
+
schema = pa.schema([('a', pa.timestamp('s')),
|
| 1095 |
+
('b', pa.timestamp('ms'))])
|
| 1096 |
+
assert table.schema == schema
|
| 1097 |
+
assert table.to_pydict() == {
|
| 1098 |
+
'a': [datetime(1970, 1, 1), datetime(1971, 1, 1)],
|
| 1099 |
+
'b': [datetime(1970, 1, 2), datetime(1971, 1, 2)],
|
| 1100 |
+
}
|
| 1101 |
+
|
| 1102 |
+
def test_times(self):
|
| 1103 |
+
# Times are inferred as time32[s] by default
|
| 1104 |
+
from datetime import time
|
| 1105 |
+
|
| 1106 |
+
rows = b"a,b\n12:34:56,12:34:56.789\n23:59:59,23:59:59.999\n"
|
| 1107 |
+
table = self.read_bytes(rows)
|
| 1108 |
+
# Column 'b' has subseconds, so cannot be inferred as time32[s]
|
| 1109 |
+
schema = pa.schema([('a', pa.time32('s')),
|
| 1110 |
+
('b', pa.string())])
|
| 1111 |
+
assert table.schema == schema
|
| 1112 |
+
assert table.to_pydict() == {
|
| 1113 |
+
'a': [time(12, 34, 56), time(23, 59, 59)],
|
| 1114 |
+
'b': ["12:34:56.789", "23:59:59.999"],
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
# Can ask for time types explicitly
|
| 1118 |
+
opts = ConvertOptions()
|
| 1119 |
+
opts.column_types = {'a': pa.time64('us'), 'b': pa.time32('ms')}
|
| 1120 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1121 |
+
schema = pa.schema([('a', pa.time64('us')),
|
| 1122 |
+
('b', pa.time32('ms'))])
|
| 1123 |
+
assert table.schema == schema
|
| 1124 |
+
assert table.to_pydict() == {
|
| 1125 |
+
'a': [time(12, 34, 56), time(23, 59, 59)],
|
| 1126 |
+
'b': [time(12, 34, 56, 789000), time(23, 59, 59, 999000)],
|
| 1127 |
+
}
|
| 1128 |
+
|
| 1129 |
+
def test_auto_dict_encode(self):
|
| 1130 |
+
opts = ConvertOptions(auto_dict_encode=True)
|
| 1131 |
+
rows = "a,b\nab,1\ncdé,2\ncdé,3\nab,4".encode()
|
| 1132 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1133 |
+
schema = pa.schema([('a', pa.dictionary(pa.int32(), pa.string())),
|
| 1134 |
+
('b', pa.int64())])
|
| 1135 |
+
expected = {
|
| 1136 |
+
'a': ["ab", "cdé", "cdé", "ab"],
|
| 1137 |
+
'b': [1, 2, 3, 4],
|
| 1138 |
+
}
|
| 1139 |
+
assert table.schema == schema
|
| 1140 |
+
assert table.to_pydict() == expected
|
| 1141 |
+
|
| 1142 |
+
opts.auto_dict_max_cardinality = 2
|
| 1143 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1144 |
+
assert table.schema == schema
|
| 1145 |
+
assert table.to_pydict() == expected
|
| 1146 |
+
|
| 1147 |
+
# Cardinality above max => plain-encoded
|
| 1148 |
+
opts.auto_dict_max_cardinality = 1
|
| 1149 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1150 |
+
assert table.schema == pa.schema([('a', pa.string()),
|
| 1151 |
+
('b', pa.int64())])
|
| 1152 |
+
assert table.to_pydict() == expected
|
| 1153 |
+
|
| 1154 |
+
# With invalid UTF8, not checked
|
| 1155 |
+
opts.auto_dict_max_cardinality = 50
|
| 1156 |
+
opts.check_utf8 = False
|
| 1157 |
+
rows = b"a,b\nab,1\ncd\xff,2\nab,3"
|
| 1158 |
+
table = self.read_bytes(rows, convert_options=opts,
|
| 1159 |
+
validate_full=False)
|
| 1160 |
+
assert table.schema == schema
|
| 1161 |
+
dict_values = table['a'].chunk(0).dictionary
|
| 1162 |
+
assert len(dict_values) == 2
|
| 1163 |
+
assert dict_values[0].as_py() == "ab"
|
| 1164 |
+
assert dict_values[1].as_buffer() == b"cd\xff"
|
| 1165 |
+
|
| 1166 |
+
# With invalid UTF8, checked
|
| 1167 |
+
opts.check_utf8 = True
|
| 1168 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1169 |
+
schema = pa.schema([('a', pa.dictionary(pa.int32(), pa.binary())),
|
| 1170 |
+
('b', pa.int64())])
|
| 1171 |
+
expected = {
|
| 1172 |
+
'a': [b"ab", b"cd\xff", b"ab"],
|
| 1173 |
+
'b': [1, 2, 3],
|
| 1174 |
+
}
|
| 1175 |
+
assert table.schema == schema
|
| 1176 |
+
assert table.to_pydict() == expected
|
| 1177 |
+
|
| 1178 |
+
def test_custom_nulls(self):
|
| 1179 |
+
# Infer nulls with custom values
|
| 1180 |
+
opts = ConvertOptions(null_values=['Xxx', 'Zzz'])
|
| 1181 |
+
rows = b"""a,b,c,d\nZzz,"Xxx",1,2\nXxx,#N/A,,Zzz\n"""
|
| 1182 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1183 |
+
schema = pa.schema([('a', pa.null()),
|
| 1184 |
+
('b', pa.string()),
|
| 1185 |
+
('c', pa.string()),
|
| 1186 |
+
('d', pa.int64())])
|
| 1187 |
+
assert table.schema == schema
|
| 1188 |
+
assert table.to_pydict() == {
|
| 1189 |
+
'a': [None, None],
|
| 1190 |
+
'b': ["Xxx", "#N/A"],
|
| 1191 |
+
'c': ["1", ""],
|
| 1192 |
+
'd': [2, None],
|
| 1193 |
+
}
|
| 1194 |
+
|
| 1195 |
+
opts = ConvertOptions(null_values=['Xxx', 'Zzz'],
|
| 1196 |
+
strings_can_be_null=True)
|
| 1197 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1198 |
+
assert table.to_pydict() == {
|
| 1199 |
+
'a': [None, None],
|
| 1200 |
+
'b': [None, "#N/A"],
|
| 1201 |
+
'c': ["1", ""],
|
| 1202 |
+
'd': [2, None],
|
| 1203 |
+
}
|
| 1204 |
+
opts.quoted_strings_can_be_null = False
|
| 1205 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1206 |
+
assert table.to_pydict() == {
|
| 1207 |
+
'a': [None, None],
|
| 1208 |
+
'b': ["Xxx", "#N/A"],
|
| 1209 |
+
'c': ["1", ""],
|
| 1210 |
+
'd': [2, None],
|
| 1211 |
+
}
|
| 1212 |
+
|
| 1213 |
+
opts = ConvertOptions(null_values=[])
|
| 1214 |
+
rows = b"a,b\n#N/A,\n"
|
| 1215 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1216 |
+
schema = pa.schema([('a', pa.string()),
|
| 1217 |
+
('b', pa.string())])
|
| 1218 |
+
assert table.schema == schema
|
| 1219 |
+
assert table.to_pydict() == {
|
| 1220 |
+
'a': ["#N/A"],
|
| 1221 |
+
'b': [""],
|
| 1222 |
+
}
|
| 1223 |
+
|
| 1224 |
+
def test_custom_bools(self):
|
| 1225 |
+
# Infer booleans with custom values
|
| 1226 |
+
opts = ConvertOptions(true_values=['T', 'yes'],
|
| 1227 |
+
false_values=['F', 'no'])
|
| 1228 |
+
rows = (b"a,b,c\n"
|
| 1229 |
+
b"True,T,t\n"
|
| 1230 |
+
b"False,F,f\n"
|
| 1231 |
+
b"True,yes,yes\n"
|
| 1232 |
+
b"False,no,no\n"
|
| 1233 |
+
b"N/A,N/A,N/A\n")
|
| 1234 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1235 |
+
schema = pa.schema([('a', pa.string()),
|
| 1236 |
+
('b', pa.bool_()),
|
| 1237 |
+
('c', pa.string())])
|
| 1238 |
+
assert table.schema == schema
|
| 1239 |
+
assert table.to_pydict() == {
|
| 1240 |
+
'a': ["True", "False", "True", "False", "N/A"],
|
| 1241 |
+
'b': [True, False, True, False, None],
|
| 1242 |
+
'c': ["t", "f", "yes", "no", "N/A"],
|
| 1243 |
+
}
|
| 1244 |
+
|
| 1245 |
+
def test_column_types(self):
|
| 1246 |
+
# Ask for specific column types in ConvertOptions
|
| 1247 |
+
opts = ConvertOptions(column_types={'b': 'float32',
|
| 1248 |
+
'c': 'string',
|
| 1249 |
+
'd': 'boolean',
|
| 1250 |
+
'e': pa.decimal128(11, 2),
|
| 1251 |
+
'zz': 'null'})
|
| 1252 |
+
rows = b"a,b,c,d,e\n1,2,3,true,1.0\n4,-5,6,false,0\n"
|
| 1253 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1254 |
+
schema = pa.schema([('a', pa.int64()),
|
| 1255 |
+
('b', pa.float32()),
|
| 1256 |
+
('c', pa.string()),
|
| 1257 |
+
('d', pa.bool_()),
|
| 1258 |
+
('e', pa.decimal128(11, 2))])
|
| 1259 |
+
expected = {
|
| 1260 |
+
'a': [1, 4],
|
| 1261 |
+
'b': [2.0, -5.0],
|
| 1262 |
+
'c': ["3", "6"],
|
| 1263 |
+
'd': [True, False],
|
| 1264 |
+
'e': [Decimal("1.00"), Decimal("0.00")]
|
| 1265 |
+
}
|
| 1266 |
+
assert table.schema == schema
|
| 1267 |
+
assert table.to_pydict() == expected
|
| 1268 |
+
# Pass column_types as schema
|
| 1269 |
+
opts = ConvertOptions(
|
| 1270 |
+
column_types=pa.schema([('b', pa.float32()),
|
| 1271 |
+
('c', pa.string()),
|
| 1272 |
+
('d', pa.bool_()),
|
| 1273 |
+
('e', pa.decimal128(11, 2)),
|
| 1274 |
+
('zz', pa.bool_())]))
|
| 1275 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1276 |
+
assert table.schema == schema
|
| 1277 |
+
assert table.to_pydict() == expected
|
| 1278 |
+
# One of the columns in column_types fails converting
|
| 1279 |
+
rows = b"a,b,c,d,e\n1,XXX,3,true,5\n4,-5,6,false,7\n"
|
| 1280 |
+
with pytest.raises(pa.ArrowInvalid) as exc:
|
| 1281 |
+
self.read_bytes(rows, convert_options=opts)
|
| 1282 |
+
err = str(exc.value)
|
| 1283 |
+
assert "In CSV column #1: " in err
|
| 1284 |
+
assert "CSV conversion error to float: invalid value 'XXX'" in err
|
| 1285 |
+
|
| 1286 |
+
def test_column_types_dict(self):
|
| 1287 |
+
# Ask for dict-encoded column types in ConvertOptions
|
| 1288 |
+
column_types = [
|
| 1289 |
+
('a', pa.dictionary(pa.int32(), pa.utf8())),
|
| 1290 |
+
('b', pa.dictionary(pa.int32(), pa.int64())),
|
| 1291 |
+
('c', pa.dictionary(pa.int32(), pa.decimal128(11, 2))),
|
| 1292 |
+
('d', pa.dictionary(pa.int32(), pa.large_utf8()))]
|
| 1293 |
+
|
| 1294 |
+
opts = ConvertOptions(column_types=dict(column_types))
|
| 1295 |
+
rows = (b"a,b,c,d\n"
|
| 1296 |
+
b"abc,123456,1.0,zz\n"
|
| 1297 |
+
b"defg,123456,0.5,xx\n"
|
| 1298 |
+
b"abc,N/A,1.0,xx\n")
|
| 1299 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1300 |
+
|
| 1301 |
+
schema = pa.schema(column_types)
|
| 1302 |
+
expected = {
|
| 1303 |
+
'a': ["abc", "defg", "abc"],
|
| 1304 |
+
'b': [123456, 123456, None],
|
| 1305 |
+
'c': [Decimal("1.00"), Decimal("0.50"), Decimal("1.00")],
|
| 1306 |
+
'd': ["zz", "xx", "xx"],
|
| 1307 |
+
}
|
| 1308 |
+
assert table.schema == schema
|
| 1309 |
+
assert table.to_pydict() == expected
|
| 1310 |
+
|
| 1311 |
+
# Unsupported index type
|
| 1312 |
+
column_types[0] = ('a', pa.dictionary(pa.int8(), pa.utf8()))
|
| 1313 |
+
|
| 1314 |
+
opts = ConvertOptions(column_types=dict(column_types))
|
| 1315 |
+
with pytest.raises(NotImplementedError):
|
| 1316 |
+
table = self.read_bytes(rows, convert_options=opts)
|
| 1317 |
+
|
| 1318 |
+
def test_column_types_with_column_names(self):
|
| 1319 |
+
# When both `column_names` and `column_types` are given, names
|
| 1320 |
+
# in `column_types` should refer to names in `column_names`
|
| 1321 |
+
rows = b"a,b\nc,d\ne,f\n"
|
| 1322 |
+
read_options = ReadOptions(column_names=['x', 'y'])
|
| 1323 |
+
convert_options = ConvertOptions(column_types={'x': pa.binary()})
|
| 1324 |
+
table = self.read_bytes(rows, read_options=read_options,
|
| 1325 |
+
convert_options=convert_options)
|
| 1326 |
+
schema = pa.schema([('x', pa.binary()),
|
| 1327 |
+
('y', pa.string())])
|
| 1328 |
+
assert table.schema == schema
|
| 1329 |
+
assert table.to_pydict() == {
|
| 1330 |
+
'x': [b'a', b'c', b'e'],
|
| 1331 |
+
'y': ['b', 'd', 'f'],
|
| 1332 |
+
}
|
| 1333 |
+
|
| 1334 |
+
def test_no_ending_newline(self):
|
| 1335 |
+
# No \n after last line
|
| 1336 |
+
rows = b"a,b,c\n1,2,3\n4,5,6"
|
| 1337 |
+
table = self.read_bytes(rows)
|
| 1338 |
+
assert table.to_pydict() == {
|
| 1339 |
+
'a': [1, 4],
|
| 1340 |
+
'b': [2, 5],
|
| 1341 |
+
'c': [3, 6],
|
| 1342 |
+
}
|
| 1343 |
+
|
| 1344 |
+
def test_trivial(self):
|
| 1345 |
+
# A bit pointless, but at least it shouldn't crash
|
| 1346 |
+
rows = b",\n\n"
|
| 1347 |
+
table = self.read_bytes(rows)
|
| 1348 |
+
assert table.to_pydict() == {'': []}
|
| 1349 |
+
|
| 1350 |
+
def test_empty_lines(self):
|
| 1351 |
+
rows = b"a,b\n\r1,2\r\n\r\n3,4\r\n"
|
| 1352 |
+
table = self.read_bytes(rows)
|
| 1353 |
+
assert table.to_pydict() == {
|
| 1354 |
+
'a': [1, 3],
|
| 1355 |
+
'b': [2, 4],
|
| 1356 |
+
}
|
| 1357 |
+
parse_options = ParseOptions(ignore_empty_lines=False)
|
| 1358 |
+
table = self.read_bytes(rows, parse_options=parse_options)
|
| 1359 |
+
assert table.to_pydict() == {
|
| 1360 |
+
'a': [None, 1, None, 3],
|
| 1361 |
+
'b': [None, 2, None, 4],
|
| 1362 |
+
}
|
| 1363 |
+
read_options = ReadOptions(skip_rows=2)
|
| 1364 |
+
table = self.read_bytes(rows, parse_options=parse_options,
|
| 1365 |
+
read_options=read_options)
|
| 1366 |
+
assert table.to_pydict() == {
|
| 1367 |
+
'1': [None, 3],
|
| 1368 |
+
'2': [None, 4],
|
| 1369 |
+
}
|
| 1370 |
+
|
| 1371 |
+
def test_invalid_csv(self):
|
| 1372 |
+
# Various CSV errors
|
| 1373 |
+
rows = b"a,b,c\n1,2\n4,5,6\n"
|
| 1374 |
+
with pytest.raises(pa.ArrowInvalid, match="Expected 3 columns, got 2"):
|
| 1375 |
+
self.read_bytes(rows)
|
| 1376 |
+
rows = b"a,b,c\n1,2,3\n4"
|
| 1377 |
+
with pytest.raises(pa.ArrowInvalid, match="Expected 3 columns, got 1"):
|
| 1378 |
+
self.read_bytes(rows)
|
| 1379 |
+
for rows in [b"", b"\n", b"\r\n", b"\r", b"\n\n"]:
|
| 1380 |
+
with pytest.raises(pa.ArrowInvalid, match="Empty CSV file"):
|
| 1381 |
+
self.read_bytes(rows)
|
| 1382 |
+
|
| 1383 |
+
def test_options_delimiter(self):
|
| 1384 |
+
rows = b"a;b,c\nde,fg;eh\n"
|
| 1385 |
+
table = self.read_bytes(rows)
|
| 1386 |
+
assert table.to_pydict() == {
|
| 1387 |
+
'a;b': ['de'],
|
| 1388 |
+
'c': ['fg;eh'],
|
| 1389 |
+
}
|
| 1390 |
+
opts = ParseOptions(delimiter=';')
|
| 1391 |
+
table = self.read_bytes(rows, parse_options=opts)
|
| 1392 |
+
assert table.to_pydict() == {
|
| 1393 |
+
'a': ['de,fg'],
|
| 1394 |
+
'b,c': ['eh'],
|
| 1395 |
+
}
|
| 1396 |
+
|
| 1397 |
+
def test_small_random_csv(self):
|
| 1398 |
+
csv, expected = make_random_csv(num_cols=2, num_rows=10)
|
| 1399 |
+
table = self.read_bytes(csv)
|
| 1400 |
+
assert table.schema == expected.schema
|
| 1401 |
+
assert table.equals(expected)
|
| 1402 |
+
assert table.to_pydict() == expected.to_pydict()
|
| 1403 |
+
|
| 1404 |
+
def test_stress_block_sizes(self):
|
| 1405 |
+
# Test a number of small block sizes to stress block stitching
|
| 1406 |
+
csv_base, expected = make_random_csv(num_cols=2, num_rows=500)
|
| 1407 |
+
block_sizes = [11, 12, 13, 17, 37, 111]
|
| 1408 |
+
csvs = [csv_base, csv_base.rstrip(b'\r\n')]
|
| 1409 |
+
for csv in csvs:
|
| 1410 |
+
for block_size in block_sizes:
|
| 1411 |
+
read_options = ReadOptions(block_size=block_size)
|
| 1412 |
+
table = self.read_bytes(csv, read_options=read_options)
|
| 1413 |
+
assert table.schema == expected.schema
|
| 1414 |
+
if not table.equals(expected):
|
| 1415 |
+
# Better error output
|
| 1416 |
+
assert table.to_pydict() == expected.to_pydict()
|
| 1417 |
+
|
| 1418 |
+
def test_stress_convert_options_blowup(self):
|
| 1419 |
+
# ARROW-6481: A convert_options with a very large number of columns
|
| 1420 |
+
# should not blow memory and CPU time.
|
| 1421 |
+
try:
|
| 1422 |
+
clock = time.thread_time
|
| 1423 |
+
except AttributeError:
|
| 1424 |
+
clock = time.time
|
| 1425 |
+
num_columns = 10000
|
| 1426 |
+
col_names = ["K{}".format(i) for i in range(num_columns)]
|
| 1427 |
+
csv = make_empty_csv(col_names)
|
| 1428 |
+
t1 = clock()
|
| 1429 |
+
convert_options = ConvertOptions(
|
| 1430 |
+
column_types={k: pa.string() for k in col_names[::2]})
|
| 1431 |
+
table = self.read_bytes(csv, convert_options=convert_options)
|
| 1432 |
+
dt = clock() - t1
|
| 1433 |
+
# Check that processing time didn't blow up.
|
| 1434 |
+
# This is a conservative check (it takes less than 300 ms
|
| 1435 |
+
# in debug mode on my local machine).
|
| 1436 |
+
assert dt <= 10.0
|
| 1437 |
+
# Check result
|
| 1438 |
+
assert table.num_columns == num_columns
|
| 1439 |
+
assert table.num_rows == 0
|
| 1440 |
+
assert table.column_names == col_names
|
| 1441 |
+
|
| 1442 |
+
@pytest.mark.threading
|
| 1443 |
+
def test_cancellation(self):
|
| 1444 |
+
if (threading.current_thread().ident !=
|
| 1445 |
+
threading.main_thread().ident):
|
| 1446 |
+
pytest.skip("test only works from main Python thread")
|
| 1447 |
+
|
| 1448 |
+
def signal_from_thread():
|
| 1449 |
+
# Give our workload a chance to start up
|
| 1450 |
+
time.sleep(0.2)
|
| 1451 |
+
signal.raise_signal(signal.SIGINT)
|
| 1452 |
+
|
| 1453 |
+
# We start with a small CSV reading workload and increase its size
|
| 1454 |
+
# until it's large enough to get an interruption during it, even in
|
| 1455 |
+
# release mode on fast machines.
|
| 1456 |
+
last_duration = 0.0
|
| 1457 |
+
workload_size = 100_000
|
| 1458 |
+
attempts = 0
|
| 1459 |
+
|
| 1460 |
+
while last_duration < 5.0 and attempts < 10:
|
| 1461 |
+
print("workload size:", workload_size)
|
| 1462 |
+
large_csv = b"a,b,c\n" + b"1,2,3\n" * workload_size
|
| 1463 |
+
exc_info = None
|
| 1464 |
+
|
| 1465 |
+
try:
|
| 1466 |
+
# We use a signal fd to reliably ensure that the signal
|
| 1467 |
+
# has been delivered to Python, regardless of how exactly
|
| 1468 |
+
# it was caught.
|
| 1469 |
+
with util.signal_wakeup_fd() as sigfd:
|
| 1470 |
+
try:
|
| 1471 |
+
t = threading.Thread(target=signal_from_thread)
|
| 1472 |
+
t.start()
|
| 1473 |
+
t1 = time.time()
|
| 1474 |
+
try:
|
| 1475 |
+
self.read_bytes(large_csv)
|
| 1476 |
+
except KeyboardInterrupt as e:
|
| 1477 |
+
exc_info = e
|
| 1478 |
+
last_duration = time.time() - t1
|
| 1479 |
+
finally:
|
| 1480 |
+
# Wait for signal to arrive if it didn't already,
|
| 1481 |
+
# to avoid getting a KeyboardInterrupt after the
|
| 1482 |
+
# `except` block below.
|
| 1483 |
+
select.select([sigfd], [], [sigfd], 10.0)
|
| 1484 |
+
|
| 1485 |
+
except KeyboardInterrupt:
|
| 1486 |
+
# KeyboardInterrupt didn't interrupt `read_bytes` above.
|
| 1487 |
+
pass
|
| 1488 |
+
|
| 1489 |
+
if exc_info is not None:
|
| 1490 |
+
# We managed to get `self.read_bytes` interrupted, see if it
|
| 1491 |
+
# was actually interrupted inside Arrow C++ or in the Python
|
| 1492 |
+
# scaffolding.
|
| 1493 |
+
if exc_info.__context__ is not None:
|
| 1494 |
+
# Interrupted inside Arrow C++, we're satisfied now
|
| 1495 |
+
break
|
| 1496 |
+
|
| 1497 |
+
# Increase workload size to get a better chance
|
| 1498 |
+
workload_size = workload_size * 3
|
| 1499 |
+
|
| 1500 |
+
if exc_info is None:
|
| 1501 |
+
pytest.fail("Failed to get an interruption during CSV reading")
|
| 1502 |
+
|
| 1503 |
+
# Interruption should have arrived timely
|
| 1504 |
+
assert last_duration <= 2.0
|
| 1505 |
+
e = exc_info.__context__
|
| 1506 |
+
assert isinstance(e, pa.ArrowCancelled)
|
| 1507 |
+
assert e.signum == signal.SIGINT
|
| 1508 |
+
|
| 1509 |
+
@pytest.mark.threading
|
| 1510 |
+
def test_cancellation_disabled(self):
|
| 1511 |
+
# ARROW-12622: reader would segfault when the cancelling signal
|
| 1512 |
+
# handler was not enabled (e.g. if disabled, or if not on the
|
| 1513 |
+
# main thread)
|
| 1514 |
+
t = threading.Thread(
|
| 1515 |
+
target=lambda: self.read_bytes(b"f64\n0.1"))
|
| 1516 |
+
t.start()
|
| 1517 |
+
t.join()
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
class TestSerialCSVTableRead(BaseCSVTableRead):
|
| 1521 |
+
@property
|
| 1522 |
+
def use_threads(self):
|
| 1523 |
+
return False
|
| 1524 |
+
|
| 1525 |
+
|
| 1526 |
+
class TestThreadedCSVTableRead(BaseCSVTableRead):
|
| 1527 |
+
@property
|
| 1528 |
+
def use_threads(self):
|
| 1529 |
+
return True
|
| 1530 |
+
|
| 1531 |
+
|
| 1532 |
+
class BaseStreamingCSVRead(BaseTestCSV):
|
| 1533 |
+
|
| 1534 |
+
def open_csv(self, csv, *args, **kwargs):
|
| 1535 |
+
"""
|
| 1536 |
+
Reads the CSV file into memory using pyarrow's open_csv
|
| 1537 |
+
csv The CSV bytes
|
| 1538 |
+
args Positional arguments to be forwarded to pyarrow's open_csv
|
| 1539 |
+
kwargs Keyword arguments to be forwarded to pyarrow's open_csv
|
| 1540 |
+
"""
|
| 1541 |
+
read_options = kwargs.setdefault('read_options', ReadOptions())
|
| 1542 |
+
read_options.use_threads = self.use_threads
|
| 1543 |
+
return open_csv(csv, *args, **kwargs)
|
| 1544 |
+
|
| 1545 |
+
def open_bytes(self, b, **kwargs):
|
| 1546 |
+
return self.open_csv(pa.py_buffer(b), **kwargs)
|
| 1547 |
+
|
| 1548 |
+
def check_reader(self, reader, expected_schema, expected_data):
|
| 1549 |
+
assert reader.schema == expected_schema
|
| 1550 |
+
batches = list(reader)
|
| 1551 |
+
assert len(batches) == len(expected_data)
|
| 1552 |
+
for batch, expected_batch in zip(batches, expected_data):
|
| 1553 |
+
batch.validate(full=True)
|
| 1554 |
+
assert batch.schema == expected_schema
|
| 1555 |
+
assert batch.to_pydict() == expected_batch
|
| 1556 |
+
|
| 1557 |
+
def read_bytes(self, b, **kwargs):
|
| 1558 |
+
return self.open_bytes(b, **kwargs).read_all()
|
| 1559 |
+
|
| 1560 |
+
def test_file_object(self):
|
| 1561 |
+
data = b"a,b\n1,2\n3,4\n"
|
| 1562 |
+
expected_data = {'a': [1, 3], 'b': [2, 4]}
|
| 1563 |
+
bio = io.BytesIO(data)
|
| 1564 |
+
reader = self.open_csv(bio)
|
| 1565 |
+
expected_schema = pa.schema([('a', pa.int64()),
|
| 1566 |
+
('b', pa.int64())])
|
| 1567 |
+
self.check_reader(reader, expected_schema, [expected_data])
|
| 1568 |
+
|
| 1569 |
+
def test_header(self):
|
| 1570 |
+
rows = b"abc,def,gh\n"
|
| 1571 |
+
reader = self.open_bytes(rows)
|
| 1572 |
+
expected_schema = pa.schema([('abc', pa.null()),
|
| 1573 |
+
('def', pa.null()),
|
| 1574 |
+
('gh', pa.null())])
|
| 1575 |
+
self.check_reader(reader, expected_schema, [])
|
| 1576 |
+
|
| 1577 |
+
def test_inference(self):
|
| 1578 |
+
# Inference is done on first block
|
| 1579 |
+
rows = b"a,b\n123,456\nabc,de\xff\ngh,ij\n"
|
| 1580 |
+
expected_schema = pa.schema([('a', pa.string()),
|
| 1581 |
+
('b', pa.binary())])
|
| 1582 |
+
|
| 1583 |
+
read_options = ReadOptions()
|
| 1584 |
+
read_options.block_size = len(rows)
|
| 1585 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1586 |
+
self.check_reader(reader, expected_schema,
|
| 1587 |
+
[{'a': ['123', 'abc', 'gh'],
|
| 1588 |
+
'b': [b'456', b'de\xff', b'ij']}])
|
| 1589 |
+
|
| 1590 |
+
read_options.block_size = len(rows) - 1
|
| 1591 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1592 |
+
self.check_reader(reader, expected_schema,
|
| 1593 |
+
[{'a': ['123', 'abc'],
|
| 1594 |
+
'b': [b'456', b'de\xff']},
|
| 1595 |
+
{'a': ['gh'],
|
| 1596 |
+
'b': [b'ij']}])
|
| 1597 |
+
|
| 1598 |
+
def test_inference_failure(self):
|
| 1599 |
+
# Inference on first block, then conversion failure on second block
|
| 1600 |
+
rows = b"a,b\n123,456\nabc,de\xff\ngh,ij\n"
|
| 1601 |
+
read_options = ReadOptions()
|
| 1602 |
+
read_options.block_size = len(rows) - 7
|
| 1603 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1604 |
+
expected_schema = pa.schema([('a', pa.int64()),
|
| 1605 |
+
('b', pa.int64())])
|
| 1606 |
+
assert reader.schema == expected_schema
|
| 1607 |
+
assert reader.read_next_batch().to_pydict() == {
|
| 1608 |
+
'a': [123], 'b': [456]
|
| 1609 |
+
}
|
| 1610 |
+
# Second block
|
| 1611 |
+
with pytest.raises(ValueError,
|
| 1612 |
+
match="CSV conversion error to int64"):
|
| 1613 |
+
reader.read_next_batch()
|
| 1614 |
+
# EOF
|
| 1615 |
+
with pytest.raises(StopIteration):
|
| 1616 |
+
reader.read_next_batch()
|
| 1617 |
+
|
| 1618 |
+
def test_invalid_csv(self):
|
| 1619 |
+
# CSV errors on first block
|
| 1620 |
+
rows = b"a,b\n1,2,3\n4,5\n6,7\n"
|
| 1621 |
+
read_options = ReadOptions()
|
| 1622 |
+
read_options.block_size = 10
|
| 1623 |
+
with pytest.raises(pa.ArrowInvalid,
|
| 1624 |
+
match="Expected 2 columns, got 3"):
|
| 1625 |
+
reader = self.open_bytes(
|
| 1626 |
+
rows, read_options=read_options)
|
| 1627 |
+
|
| 1628 |
+
# CSV errors on second block
|
| 1629 |
+
rows = b"a,b\n1,2\n3,4,5\n6,7\n"
|
| 1630 |
+
read_options.block_size = 8
|
| 1631 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1632 |
+
assert reader.read_next_batch().to_pydict() == {'a': [1], 'b': [2]}
|
| 1633 |
+
with pytest.raises(pa.ArrowInvalid,
|
| 1634 |
+
match="Expected 2 columns, got 3"):
|
| 1635 |
+
reader.read_next_batch()
|
| 1636 |
+
# Cannot continue after a parse error
|
| 1637 |
+
with pytest.raises(StopIteration):
|
| 1638 |
+
reader.read_next_batch()
|
| 1639 |
+
|
| 1640 |
+
def test_options_delimiter(self):
|
| 1641 |
+
rows = b"a;b,c\nde,fg;eh\n"
|
| 1642 |
+
reader = self.open_bytes(rows)
|
| 1643 |
+
expected_schema = pa.schema([('a;b', pa.string()),
|
| 1644 |
+
('c', pa.string())])
|
| 1645 |
+
self.check_reader(reader, expected_schema,
|
| 1646 |
+
[{'a;b': ['de'],
|
| 1647 |
+
'c': ['fg;eh']}])
|
| 1648 |
+
|
| 1649 |
+
opts = ParseOptions(delimiter=';')
|
| 1650 |
+
reader = self.open_bytes(rows, parse_options=opts)
|
| 1651 |
+
expected_schema = pa.schema([('a', pa.string()),
|
| 1652 |
+
('b,c', pa.string())])
|
| 1653 |
+
self.check_reader(reader, expected_schema,
|
| 1654 |
+
[{'a': ['de,fg'],
|
| 1655 |
+
'b,c': ['eh']}])
|
| 1656 |
+
|
| 1657 |
+
def test_no_ending_newline(self):
|
| 1658 |
+
# No \n after last line
|
| 1659 |
+
rows = b"a,b,c\n1,2,3\n4,5,6"
|
| 1660 |
+
reader = self.open_bytes(rows)
|
| 1661 |
+
expected_schema = pa.schema([('a', pa.int64()),
|
| 1662 |
+
('b', pa.int64()),
|
| 1663 |
+
('c', pa.int64())])
|
| 1664 |
+
self.check_reader(reader, expected_schema,
|
| 1665 |
+
[{'a': [1, 4],
|
| 1666 |
+
'b': [2, 5],
|
| 1667 |
+
'c': [3, 6]}])
|
| 1668 |
+
|
| 1669 |
+
def test_empty_file(self):
|
| 1670 |
+
with pytest.raises(ValueError, match="Empty CSV file"):
|
| 1671 |
+
self.open_bytes(b"")
|
| 1672 |
+
|
| 1673 |
+
def test_column_options(self):
|
| 1674 |
+
# With column_names
|
| 1675 |
+
rows = b"1,2,3\n4,5,6"
|
| 1676 |
+
read_options = ReadOptions()
|
| 1677 |
+
read_options.column_names = ['d', 'e', 'f']
|
| 1678 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1679 |
+
expected_schema = pa.schema([('d', pa.int64()),
|
| 1680 |
+
('e', pa.int64()),
|
| 1681 |
+
('f', pa.int64())])
|
| 1682 |
+
self.check_reader(reader, expected_schema,
|
| 1683 |
+
[{'d': [1, 4],
|
| 1684 |
+
'e': [2, 5],
|
| 1685 |
+
'f': [3, 6]}])
|
| 1686 |
+
|
| 1687 |
+
# With include_columns
|
| 1688 |
+
convert_options = ConvertOptions()
|
| 1689 |
+
convert_options.include_columns = ['f', 'e']
|
| 1690 |
+
reader = self.open_bytes(rows, read_options=read_options,
|
| 1691 |
+
convert_options=convert_options)
|
| 1692 |
+
expected_schema = pa.schema([('f', pa.int64()),
|
| 1693 |
+
('e', pa.int64())])
|
| 1694 |
+
self.check_reader(reader, expected_schema,
|
| 1695 |
+
[{'e': [2, 5],
|
| 1696 |
+
'f': [3, 6]}])
|
| 1697 |
+
|
| 1698 |
+
# With column_types
|
| 1699 |
+
convert_options.column_types = {'e': pa.string()}
|
| 1700 |
+
reader = self.open_bytes(rows, read_options=read_options,
|
| 1701 |
+
convert_options=convert_options)
|
| 1702 |
+
expected_schema = pa.schema([('f', pa.int64()),
|
| 1703 |
+
('e', pa.string())])
|
| 1704 |
+
self.check_reader(reader, expected_schema,
|
| 1705 |
+
[{'e': ["2", "5"],
|
| 1706 |
+
'f': [3, 6]}])
|
| 1707 |
+
|
| 1708 |
+
# Missing columns in include_columns
|
| 1709 |
+
convert_options.include_columns = ['g', 'f', 'e']
|
| 1710 |
+
with pytest.raises(
|
| 1711 |
+
KeyError,
|
| 1712 |
+
match="Column 'g' in include_columns does not exist"):
|
| 1713 |
+
reader = self.open_bytes(rows, read_options=read_options,
|
| 1714 |
+
convert_options=convert_options)
|
| 1715 |
+
|
| 1716 |
+
convert_options.include_missing_columns = True
|
| 1717 |
+
reader = self.open_bytes(rows, read_options=read_options,
|
| 1718 |
+
convert_options=convert_options)
|
| 1719 |
+
expected_schema = pa.schema([('g', pa.null()),
|
| 1720 |
+
('f', pa.int64()),
|
| 1721 |
+
('e', pa.string())])
|
| 1722 |
+
self.check_reader(reader, expected_schema,
|
| 1723 |
+
[{'g': [None, None],
|
| 1724 |
+
'e': ["2", "5"],
|
| 1725 |
+
'f': [3, 6]}])
|
| 1726 |
+
|
| 1727 |
+
convert_options.column_types = {'e': pa.string(), 'g': pa.float64()}
|
| 1728 |
+
reader = self.open_bytes(rows, read_options=read_options,
|
| 1729 |
+
convert_options=convert_options)
|
| 1730 |
+
expected_schema = pa.schema([('g', pa.float64()),
|
| 1731 |
+
('f', pa.int64()),
|
| 1732 |
+
('e', pa.string())])
|
| 1733 |
+
self.check_reader(reader, expected_schema,
|
| 1734 |
+
[{'g': [None, None],
|
| 1735 |
+
'e': ["2", "5"],
|
| 1736 |
+
'f': [3, 6]}])
|
| 1737 |
+
|
| 1738 |
+
def test_encoding(self):
|
| 1739 |
+
# latin-1 (invalid utf-8)
|
| 1740 |
+
rows = b"a,b\nun,\xe9l\xe9phant"
|
| 1741 |
+
read_options = ReadOptions()
|
| 1742 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1743 |
+
expected_schema = pa.schema([('a', pa.string()),
|
| 1744 |
+
('b', pa.binary())])
|
| 1745 |
+
self.check_reader(reader, expected_schema,
|
| 1746 |
+
[{'a': ["un"],
|
| 1747 |
+
'b': [b"\xe9l\xe9phant"]}])
|
| 1748 |
+
|
| 1749 |
+
read_options.encoding = 'latin1'
|
| 1750 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1751 |
+
expected_schema = pa.schema([('a', pa.string()),
|
| 1752 |
+
('b', pa.string())])
|
| 1753 |
+
self.check_reader(reader, expected_schema,
|
| 1754 |
+
[{'a': ["un"],
|
| 1755 |
+
'b': ["éléphant"]}])
|
| 1756 |
+
|
| 1757 |
+
# utf-16
|
| 1758 |
+
rows = (b'\xff\xfea\x00,\x00b\x00\n\x00u\x00n\x00,'
|
| 1759 |
+
b'\x00\xe9\x00l\x00\xe9\x00p\x00h\x00a\x00n\x00t\x00')
|
| 1760 |
+
read_options.encoding = 'utf16'
|
| 1761 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1762 |
+
expected_schema = pa.schema([('a', pa.string()),
|
| 1763 |
+
('b', pa.string())])
|
| 1764 |
+
self.check_reader(reader, expected_schema,
|
| 1765 |
+
[{'a': ["un"],
|
| 1766 |
+
'b': ["éléphant"]}])
|
| 1767 |
+
|
| 1768 |
+
def test_small_random_csv(self):
|
| 1769 |
+
csv, expected = make_random_csv(num_cols=2, num_rows=10)
|
| 1770 |
+
reader = self.open_bytes(csv)
|
| 1771 |
+
table = reader.read_all()
|
| 1772 |
+
assert table.schema == expected.schema
|
| 1773 |
+
assert table.equals(expected)
|
| 1774 |
+
assert table.to_pydict() == expected.to_pydict()
|
| 1775 |
+
|
| 1776 |
+
def test_stress_block_sizes(self):
|
| 1777 |
+
# Test a number of small block sizes to stress block stitching
|
| 1778 |
+
csv_base, expected = make_random_csv(num_cols=2, num_rows=500)
|
| 1779 |
+
block_sizes = [19, 21, 23, 26, 37, 111]
|
| 1780 |
+
csvs = [csv_base, csv_base.rstrip(b'\r\n')]
|
| 1781 |
+
for csv in csvs:
|
| 1782 |
+
for block_size in block_sizes:
|
| 1783 |
+
# Need at least two lines for type inference
|
| 1784 |
+
assert csv[:block_size].count(b'\n') >= 2
|
| 1785 |
+
read_options = ReadOptions(block_size=block_size)
|
| 1786 |
+
reader = self.open_bytes(
|
| 1787 |
+
csv, read_options=read_options)
|
| 1788 |
+
table = reader.read_all()
|
| 1789 |
+
assert table.schema == expected.schema
|
| 1790 |
+
if not table.equals(expected):
|
| 1791 |
+
# Better error output
|
| 1792 |
+
assert table.to_pydict() == expected.to_pydict()
|
| 1793 |
+
|
| 1794 |
+
def test_batch_lifetime(self):
|
| 1795 |
+
gc.collect()
|
| 1796 |
+
old_allocated = pa.total_allocated_bytes()
|
| 1797 |
+
|
| 1798 |
+
# Memory occupation should not grow with CSV file size
|
| 1799 |
+
def check_one_batch(reader, expected):
|
| 1800 |
+
batch = reader.read_next_batch()
|
| 1801 |
+
assert batch.to_pydict() == expected
|
| 1802 |
+
|
| 1803 |
+
rows = b"10,11\n12,13\n14,15\n16,17\n"
|
| 1804 |
+
read_options = ReadOptions()
|
| 1805 |
+
read_options.column_names = ['a', 'b']
|
| 1806 |
+
read_options.block_size = 6
|
| 1807 |
+
reader = self.open_bytes(rows, read_options=read_options)
|
| 1808 |
+
check_one_batch(reader, {'a': [10], 'b': [11]})
|
| 1809 |
+
allocated_after_first_batch = pa.total_allocated_bytes()
|
| 1810 |
+
check_one_batch(reader, {'a': [12], 'b': [13]})
|
| 1811 |
+
assert pa.total_allocated_bytes() <= allocated_after_first_batch
|
| 1812 |
+
check_one_batch(reader, {'a': [14], 'b': [15]})
|
| 1813 |
+
assert pa.total_allocated_bytes() <= allocated_after_first_batch
|
| 1814 |
+
check_one_batch(reader, {'a': [16], 'b': [17]})
|
| 1815 |
+
assert pa.total_allocated_bytes() <= allocated_after_first_batch
|
| 1816 |
+
with pytest.raises(StopIteration):
|
| 1817 |
+
reader.read_next_batch()
|
| 1818 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 1819 |
+
reader = None
|
| 1820 |
+
assert pa.total_allocated_bytes() == old_allocated
|
| 1821 |
+
|
| 1822 |
+
def test_header_skip_rows(self):
|
| 1823 |
+
super().test_header_skip_rows()
|
| 1824 |
+
|
| 1825 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 1826 |
+
|
| 1827 |
+
# Skipping all rows immediately results in end of iteration
|
| 1828 |
+
opts = ReadOptions()
|
| 1829 |
+
opts.skip_rows = 4
|
| 1830 |
+
opts.column_names = ['ab', 'cd']
|
| 1831 |
+
reader = self.open_bytes(rows, read_options=opts)
|
| 1832 |
+
with pytest.raises(StopIteration):
|
| 1833 |
+
assert reader.read_next_batch()
|
| 1834 |
+
|
| 1835 |
+
@pytest.mark.numpy
|
| 1836 |
+
def test_skip_rows_after_names(self):
|
| 1837 |
+
super().test_skip_rows_after_names()
|
| 1838 |
+
|
| 1839 |
+
rows = b"ab,cd\nef,gh\nij,kl\nmn,op\n"
|
| 1840 |
+
|
| 1841 |
+
# Skipping all rows immediately results in end of iteration
|
| 1842 |
+
opts = ReadOptions()
|
| 1843 |
+
opts.skip_rows_after_names = 3
|
| 1844 |
+
reader = self.open_bytes(rows, read_options=opts)
|
| 1845 |
+
with pytest.raises(StopIteration):
|
| 1846 |
+
assert reader.read_next_batch()
|
| 1847 |
+
|
| 1848 |
+
# Skipping beyond all rows immediately results in end of iteration
|
| 1849 |
+
opts.skip_rows_after_names = 99999
|
| 1850 |
+
reader = self.open_bytes(rows, read_options=opts)
|
| 1851 |
+
with pytest.raises(StopIteration):
|
| 1852 |
+
assert reader.read_next_batch()
|
| 1853 |
+
|
| 1854 |
+
|
| 1855 |
+
class TestSerialStreamingCSVRead(BaseStreamingCSVRead):
|
| 1856 |
+
@property
|
| 1857 |
+
def use_threads(self):
|
| 1858 |
+
return False
|
| 1859 |
+
|
| 1860 |
+
|
| 1861 |
+
@pytest.mark.threading
|
| 1862 |
+
class TestThreadedStreamingCSVRead(BaseStreamingCSVRead):
|
| 1863 |
+
@property
|
| 1864 |
+
def use_threads(self):
|
| 1865 |
+
return True
|
| 1866 |
+
|
| 1867 |
+
|
| 1868 |
+
class BaseTestCompressedCSVRead:
|
| 1869 |
+
|
| 1870 |
+
def setUp(self):
|
| 1871 |
+
self.tmpdir = tempfile.mkdtemp(prefix='arrow-csv-test-')
|
| 1872 |
+
|
| 1873 |
+
def tearDown(self):
|
| 1874 |
+
shutil.rmtree(self.tmpdir)
|
| 1875 |
+
|
| 1876 |
+
def read_csv(self, csv_path):
|
| 1877 |
+
try:
|
| 1878 |
+
return read_csv(csv_path)
|
| 1879 |
+
except pa.ArrowNotImplementedError as e:
|
| 1880 |
+
pytest.skip(str(e))
|
| 1881 |
+
|
| 1882 |
+
def test_random_csv(self):
|
| 1883 |
+
csv, expected = make_random_csv(num_cols=2, num_rows=100)
|
| 1884 |
+
csv_path = os.path.join(self.tmpdir, self.csv_filename)
|
| 1885 |
+
self.write_file(csv_path, csv)
|
| 1886 |
+
table = self.read_csv(csv_path)
|
| 1887 |
+
table.validate(full=True)
|
| 1888 |
+
assert table.schema == expected.schema
|
| 1889 |
+
assert table.equals(expected)
|
| 1890 |
+
assert table.to_pydict() == expected.to_pydict()
|
| 1891 |
+
|
| 1892 |
+
|
| 1893 |
+
class TestGZipCSVRead(BaseTestCompressedCSVRead, unittest.TestCase):
|
| 1894 |
+
csv_filename = "compressed.csv.gz"
|
| 1895 |
+
|
| 1896 |
+
def write_file(self, path, contents):
|
| 1897 |
+
with gzip.open(path, 'wb', 3) as f:
|
| 1898 |
+
f.write(contents)
|
| 1899 |
+
|
| 1900 |
+
def test_concatenated(self):
|
| 1901 |
+
# ARROW-5974
|
| 1902 |
+
csv_path = os.path.join(self.tmpdir, self.csv_filename)
|
| 1903 |
+
with gzip.open(csv_path, 'wb', 3) as f:
|
| 1904 |
+
f.write(b"ab,cd\nef,gh\n")
|
| 1905 |
+
with gzip.open(csv_path, 'ab', 3) as f:
|
| 1906 |
+
f.write(b"ij,kl\nmn,op\n")
|
| 1907 |
+
table = self.read_csv(csv_path)
|
| 1908 |
+
assert table.to_pydict() == {
|
| 1909 |
+
'ab': ['ef', 'ij', 'mn'],
|
| 1910 |
+
'cd': ['gh', 'kl', 'op'],
|
| 1911 |
+
}
|
| 1912 |
+
|
| 1913 |
+
|
| 1914 |
+
class TestBZ2CSVRead(BaseTestCompressedCSVRead, unittest.TestCase):
|
| 1915 |
+
csv_filename = "compressed.csv.bz2"
|
| 1916 |
+
|
| 1917 |
+
def write_file(self, path, contents):
|
| 1918 |
+
with bz2.BZ2File(path, 'w') as f:
|
| 1919 |
+
f.write(contents)
|
| 1920 |
+
|
| 1921 |
+
|
| 1922 |
+
def test_read_csv_does_not_close_passed_file_handles():
|
| 1923 |
+
# ARROW-4823
|
| 1924 |
+
buf = io.BytesIO(b"a,b,c\n1,2,3\n4,5,6")
|
| 1925 |
+
read_csv(buf)
|
| 1926 |
+
assert not buf.closed
|
| 1927 |
+
|
| 1928 |
+
|
| 1929 |
+
def test_write_read_round_trip():
|
| 1930 |
+
t = pa.Table.from_arrays([[1, 2, 3], ["a", "b", "c"]], ["c1", "c2"])
|
| 1931 |
+
record_batch = t.to_batches(max_chunksize=4)[0]
|
| 1932 |
+
for data in [t, record_batch]:
|
| 1933 |
+
# Test with header
|
| 1934 |
+
buf = io.BytesIO()
|
| 1935 |
+
write_csv(data, buf, WriteOptions(include_header=True))
|
| 1936 |
+
buf.seek(0)
|
| 1937 |
+
assert t == read_csv(buf)
|
| 1938 |
+
|
| 1939 |
+
# Test without header
|
| 1940 |
+
buf = io.BytesIO()
|
| 1941 |
+
write_csv(data, buf, WriteOptions(include_header=False))
|
| 1942 |
+
buf.seek(0)
|
| 1943 |
+
|
| 1944 |
+
read_options = ReadOptions(column_names=t.column_names)
|
| 1945 |
+
assert t == read_csv(buf, read_options=read_options)
|
| 1946 |
+
|
| 1947 |
+
# Test with writer
|
| 1948 |
+
for read_options, parse_options, write_options in [
|
| 1949 |
+
(None, None, WriteOptions(include_header=True)),
|
| 1950 |
+
(ReadOptions(column_names=t.column_names), None,
|
| 1951 |
+
WriteOptions(include_header=False)),
|
| 1952 |
+
(None, ParseOptions(delimiter='|'),
|
| 1953 |
+
WriteOptions(include_header=True, delimiter='|')),
|
| 1954 |
+
(ReadOptions(column_names=t.column_names),
|
| 1955 |
+
ParseOptions(delimiter='\t'),
|
| 1956 |
+
WriteOptions(include_header=False, delimiter='\t')),
|
| 1957 |
+
]:
|
| 1958 |
+
buf = io.BytesIO()
|
| 1959 |
+
with CSVWriter(buf, t.schema, write_options=write_options) as writer:
|
| 1960 |
+
writer.write_table(t)
|
| 1961 |
+
buf.seek(0)
|
| 1962 |
+
assert t == read_csv(buf, read_options=read_options,
|
| 1963 |
+
parse_options=parse_options)
|
| 1964 |
+
buf = io.BytesIO()
|
| 1965 |
+
with CSVWriter(buf, t.schema, write_options=write_options) as writer:
|
| 1966 |
+
for batch in t.to_batches(max_chunksize=1):
|
| 1967 |
+
writer.write_batch(batch)
|
| 1968 |
+
buf.seek(0)
|
| 1969 |
+
assert t == read_csv(buf, read_options=read_options,
|
| 1970 |
+
parse_options=parse_options)
|
| 1971 |
+
|
| 1972 |
+
|
| 1973 |
+
def test_write_quoting_style():
|
| 1974 |
+
t = pa.Table.from_arrays([[1, 2, None], ["a", None, "c"]], ["c1", "c2"])
|
| 1975 |
+
buf = io.BytesIO()
|
| 1976 |
+
for write_options, res in [
|
| 1977 |
+
(WriteOptions(quoting_style='none'), b'"c1","c2"\n1,a\n2,\n,c\n'),
|
| 1978 |
+
(WriteOptions(), b'"c1","c2"\n1,"a"\n2,\n,"c"\n'),
|
| 1979 |
+
(WriteOptions(quoting_style='all_valid'),
|
| 1980 |
+
b'"c1","c2"\n"1","a"\n"2",\n,"c"\n'),
|
| 1981 |
+
]:
|
| 1982 |
+
with CSVWriter(buf, t.schema, write_options=write_options) as writer:
|
| 1983 |
+
writer.write_table(t)
|
| 1984 |
+
assert buf.getvalue() == res
|
| 1985 |
+
buf.seek(0)
|
| 1986 |
+
|
| 1987 |
+
# Test writing special characters with different quoting styles
|
| 1988 |
+
t = pa.Table.from_arrays([[",", "\""]], ["c1"])
|
| 1989 |
+
buf = io.BytesIO()
|
| 1990 |
+
for write_options, res in [
|
| 1991 |
+
(WriteOptions(quoting_style='needed'), b'"c1"\n","\n""""\n'),
|
| 1992 |
+
(WriteOptions(quoting_style='none'), pa.lib.ArrowInvalid),
|
| 1993 |
+
]:
|
| 1994 |
+
with CSVWriter(buf, t.schema, write_options=write_options) as writer:
|
| 1995 |
+
try:
|
| 1996 |
+
writer.write_table(t)
|
| 1997 |
+
except Exception as e:
|
| 1998 |
+
# This will trigger when we try to write a comma (,)
|
| 1999 |
+
# without quotes, which is invalid
|
| 2000 |
+
assert isinstance(e, res)
|
| 2001 |
+
break
|
| 2002 |
+
assert buf.getvalue() == res
|
| 2003 |
+
buf.seek(0)
|
| 2004 |
+
|
| 2005 |
+
|
| 2006 |
+
def test_read_csv_reference_cycle():
|
| 2007 |
+
# ARROW-13187
|
| 2008 |
+
def inner():
|
| 2009 |
+
buf = io.BytesIO(b"a,b,c\n1,2,3\n4,5,6")
|
| 2010 |
+
table = read_csv(buf)
|
| 2011 |
+
return weakref.ref(table)
|
| 2012 |
+
|
| 2013 |
+
with util.disabled_gc():
|
| 2014 |
+
wr = inner()
|
| 2015 |
+
assert wr() is None
|
| 2016 |
+
|
| 2017 |
+
|
| 2018 |
+
@pytest.mark.parametrize("type_factory", (
|
| 2019 |
+
lambda: pa.decimal128(20, 1),
|
| 2020 |
+
lambda: pa.decimal128(38, 15),
|
| 2021 |
+
lambda: pa.decimal256(20, 1),
|
| 2022 |
+
lambda: pa.decimal256(76, 10),
|
| 2023 |
+
))
|
| 2024 |
+
def test_write_csv_decimal(tmpdir, type_factory):
|
| 2025 |
+
type = type_factory()
|
| 2026 |
+
table = pa.table({"col": pa.array([1, 2]).cast(type)})
|
| 2027 |
+
|
| 2028 |
+
write_csv(table, tmpdir / "out.csv")
|
| 2029 |
+
out = read_csv(tmpdir / "out.csv")
|
| 2030 |
+
|
| 2031 |
+
assert out.column('col').cast(type) == table.column('col')
|
| 2032 |
+
|
| 2033 |
+
|
| 2034 |
+
def test_read_csv_gil_deadlock():
|
| 2035 |
+
# GH-38676
|
| 2036 |
+
# This test depends on several preconditions:
|
| 2037 |
+
# - the CSV input is a Python file object
|
| 2038 |
+
# - reading the CSV file produces an error
|
| 2039 |
+
data = b"a,b,c"
|
| 2040 |
+
|
| 2041 |
+
class MyBytesIO(io.BytesIO):
|
| 2042 |
+
def read(self, *args):
|
| 2043 |
+
time.sleep(0.001)
|
| 2044 |
+
return super().read(*args)
|
| 2045 |
+
|
| 2046 |
+
def readinto(self, *args):
|
| 2047 |
+
time.sleep(0.001)
|
| 2048 |
+
return super().readinto(*args)
|
| 2049 |
+
|
| 2050 |
+
for i in range(20):
|
| 2051 |
+
with pytest.raises(pa.ArrowInvalid):
|
| 2052 |
+
read_csv(MyBytesIO(data))
|
shared/package-files/18/18b3e34f27c92aa23f3d71876e7c0c31f0af84aee359a94da4d3a0dc4583463f/column_stack.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/column_stack_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::column_stack(Tensor[] tensors) -> Tensor
|
| 27 |
+
inline at::Tensor column_stack(at::TensorList tensors) {
|
| 28 |
+
return at::_ops::column_stack::call(tensors);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & column_stack_out(at::Tensor & out, at::TensorList tensors) {
|
| 33 |
+
return at::_ops::column_stack_out::call(tensors, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & column_stack_outf(at::TensorList tensors, at::Tensor & out) {
|
| 37 |
+
return at::_ops::column_stack_out::call(tensors, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/18/18b4a406131fbf52f475e9e6f0dca72a5995c70c6ededd43cb4c84e1555114d1/_embedding_bag_per_sample_weights_backward_native.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
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);
|
| 20 |
+
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);
|
| 21 |
+
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);
|
| 22 |
+
} // namespace native
|
| 23 |
+
} // namespace at
|
shared/package-files/18/18b5dbc12be2b6c4209b1b4eb1b814b780d39144676f69345feefe48db035bd2/greedy_coloring.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Greedy graph coloring using various strategies.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
from collections import defaultdict, deque
|
| 7 |
+
|
| 8 |
+
import networkx as nx
|
| 9 |
+
from networkx.utils import arbitrary_element, py_random_state
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"greedy_color",
|
| 13 |
+
"strategy_connected_sequential",
|
| 14 |
+
"strategy_connected_sequential_bfs",
|
| 15 |
+
"strategy_connected_sequential_dfs",
|
| 16 |
+
"strategy_independent_set",
|
| 17 |
+
"strategy_largest_first",
|
| 18 |
+
"strategy_random_sequential",
|
| 19 |
+
"strategy_saturation_largest_first",
|
| 20 |
+
"strategy_smallest_last",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def strategy_largest_first(G, colors):
|
| 25 |
+
"""Returns a list of the nodes of ``G`` in decreasing order by
|
| 26 |
+
degree.
|
| 27 |
+
|
| 28 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
return sorted(G, key=G.degree, reverse=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@py_random_state(2)
|
| 35 |
+
def strategy_random_sequential(G, colors, seed=None):
|
| 36 |
+
"""Returns a random permutation of the nodes of ``G`` as a list.
|
| 37 |
+
|
| 38 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 39 |
+
|
| 40 |
+
seed : integer, random_state, or None (default)
|
| 41 |
+
Indicator of random number generation state.
|
| 42 |
+
See :ref:`Randomness<randomness>`.
|
| 43 |
+
"""
|
| 44 |
+
nodes = list(G)
|
| 45 |
+
seed.shuffle(nodes)
|
| 46 |
+
return nodes
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def strategy_smallest_last(G, colors):
|
| 50 |
+
"""Returns a deque of the nodes of ``G``, "smallest" last.
|
| 51 |
+
|
| 52 |
+
Specifically, the degrees of each node are tracked in a bucket queue.
|
| 53 |
+
From this, the node of minimum degree is repeatedly popped from the
|
| 54 |
+
graph, updating its neighbors' degrees.
|
| 55 |
+
|
| 56 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 57 |
+
|
| 58 |
+
This implementation of the strategy runs in $O(n + m)$ time
|
| 59 |
+
(ignoring polylogarithmic factors), where $n$ is the number of nodes
|
| 60 |
+
and $m$ is the number of edges.
|
| 61 |
+
|
| 62 |
+
This strategy is related to :func:`strategy_independent_set`: if we
|
| 63 |
+
interpret each node removed as an independent set of size one, then
|
| 64 |
+
this strategy chooses an independent set of size one instead of a
|
| 65 |
+
maximal independent set.
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
H = G.copy()
|
| 69 |
+
result = deque()
|
| 70 |
+
|
| 71 |
+
# Build initial degree list (i.e. the bucket queue data structure)
|
| 72 |
+
degrees = defaultdict(set) # set(), for fast random-access removals
|
| 73 |
+
lbound = float("inf")
|
| 74 |
+
for node, d in H.degree():
|
| 75 |
+
degrees[d].add(node)
|
| 76 |
+
lbound = min(lbound, d) # Lower bound on min-degree.
|
| 77 |
+
|
| 78 |
+
def find_min_degree():
|
| 79 |
+
# Save time by starting the iterator at `lbound`, not 0.
|
| 80 |
+
# The value that we find will be our new `lbound`, which we set later.
|
| 81 |
+
return next(d for d in itertools.count(lbound) if d in degrees)
|
| 82 |
+
|
| 83 |
+
for _ in G:
|
| 84 |
+
# Pop a min-degree node and add it to the list.
|
| 85 |
+
min_degree = find_min_degree()
|
| 86 |
+
u = degrees[min_degree].pop()
|
| 87 |
+
if not degrees[min_degree]: # Clean up the degree list.
|
| 88 |
+
del degrees[min_degree]
|
| 89 |
+
result.appendleft(u)
|
| 90 |
+
|
| 91 |
+
# Update degrees of removed node's neighbors.
|
| 92 |
+
for v in H[u]:
|
| 93 |
+
degree = H.degree(v)
|
| 94 |
+
degrees[degree].remove(v)
|
| 95 |
+
if not degrees[degree]: # Clean up the degree list.
|
| 96 |
+
del degrees[degree]
|
| 97 |
+
degrees[degree - 1].add(v)
|
| 98 |
+
|
| 99 |
+
# Finally, remove the node.
|
| 100 |
+
H.remove_node(u)
|
| 101 |
+
lbound = min_degree - 1 # Subtract 1 in case of tied neighbors.
|
| 102 |
+
|
| 103 |
+
return result
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _maximal_independent_set(G):
|
| 107 |
+
"""Returns a maximal independent set of nodes in ``G`` by repeatedly
|
| 108 |
+
choosing an independent node of minimum degree (with respect to the
|
| 109 |
+
subgraph of unchosen nodes).
|
| 110 |
+
|
| 111 |
+
"""
|
| 112 |
+
result = set()
|
| 113 |
+
remaining = set(G)
|
| 114 |
+
while remaining:
|
| 115 |
+
G = G.subgraph(remaining)
|
| 116 |
+
v = min(remaining, key=G.degree)
|
| 117 |
+
result.add(v)
|
| 118 |
+
remaining -= set(G[v]) | {v}
|
| 119 |
+
return result
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def strategy_independent_set(G, colors):
|
| 123 |
+
"""Uses a greedy independent set removal strategy to determine the
|
| 124 |
+
colors.
|
| 125 |
+
|
| 126 |
+
This function updates ``colors`` **in-place** and return ``None``,
|
| 127 |
+
unlike the other strategy functions in this module.
|
| 128 |
+
|
| 129 |
+
This algorithm repeatedly finds and removes a maximal independent
|
| 130 |
+
set, assigning each node in the set an unused color.
|
| 131 |
+
|
| 132 |
+
``G`` is a NetworkX graph.
|
| 133 |
+
|
| 134 |
+
This strategy is related to :func:`strategy_smallest_last`: in that
|
| 135 |
+
strategy, an independent set of size one is chosen at each step
|
| 136 |
+
instead of a maximal independent set.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
remaining_nodes = set(G)
|
| 140 |
+
while len(remaining_nodes) > 0:
|
| 141 |
+
nodes = _maximal_independent_set(G.subgraph(remaining_nodes))
|
| 142 |
+
remaining_nodes -= nodes
|
| 143 |
+
yield from nodes
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def strategy_connected_sequential_bfs(G, colors):
|
| 147 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 148 |
+
breadth-first traversal.
|
| 149 |
+
|
| 150 |
+
The generated sequence has the property that for each node except
|
| 151 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 152 |
+
|
| 153 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 154 |
+
|
| 155 |
+
"""
|
| 156 |
+
return strategy_connected_sequential(G, colors, "bfs")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def strategy_connected_sequential_dfs(G, colors):
|
| 160 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 161 |
+
depth-first traversal.
|
| 162 |
+
|
| 163 |
+
The generated sequence has the property that for each node except
|
| 164 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 165 |
+
|
| 166 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 167 |
+
|
| 168 |
+
"""
|
| 169 |
+
return strategy_connected_sequential(G, colors, "dfs")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def strategy_connected_sequential(G, colors, traversal="bfs"):
|
| 173 |
+
"""Returns an iterable over nodes in ``G`` in the order given by a
|
| 174 |
+
breadth-first or depth-first traversal.
|
| 175 |
+
|
| 176 |
+
``traversal`` must be one of the strings ``'dfs'`` or ``'bfs'``,
|
| 177 |
+
representing depth-first traversal or breadth-first traversal,
|
| 178 |
+
respectively.
|
| 179 |
+
|
| 180 |
+
The generated sequence has the property that for each node except
|
| 181 |
+
the first, at least one neighbor appeared earlier in the sequence.
|
| 182 |
+
|
| 183 |
+
``G`` is a NetworkX graph. ``colors`` is ignored.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
if traversal == "bfs":
|
| 187 |
+
traverse = nx.bfs_edges
|
| 188 |
+
elif traversal == "dfs":
|
| 189 |
+
traverse = nx.dfs_edges
|
| 190 |
+
else:
|
| 191 |
+
raise nx.NetworkXError(
|
| 192 |
+
"Please specify one of the strings 'bfs' or"
|
| 193 |
+
" 'dfs' for connected sequential ordering"
|
| 194 |
+
)
|
| 195 |
+
for component in nx.connected_components(G):
|
| 196 |
+
source = arbitrary_element(component)
|
| 197 |
+
# Yield the source node, then all the nodes in the specified
|
| 198 |
+
# traversal order.
|
| 199 |
+
yield source
|
| 200 |
+
for _, end in traverse(G.subgraph(component), source):
|
| 201 |
+
yield end
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def strategy_saturation_largest_first(G, colors):
|
| 205 |
+
"""Iterates over all the nodes of ``G`` in "saturation order" (also
|
| 206 |
+
known as "DSATUR").
|
| 207 |
+
|
| 208 |
+
``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
|
| 209 |
+
``G`` to colors, for those nodes that have already been colored.
|
| 210 |
+
|
| 211 |
+
"""
|
| 212 |
+
distinct_colors = {v: set() for v in G}
|
| 213 |
+
|
| 214 |
+
# Add the node color assignments given in colors to the
|
| 215 |
+
# distinct colors set for each neighbor of that node
|
| 216 |
+
for node, color in colors.items():
|
| 217 |
+
for neighbor in G[node]:
|
| 218 |
+
distinct_colors[neighbor].add(color)
|
| 219 |
+
|
| 220 |
+
# Check that the color assignments in colors are valid
|
| 221 |
+
# i.e. no neighboring nodes have the same color
|
| 222 |
+
if len(colors) >= 2:
|
| 223 |
+
for node, color in colors.items():
|
| 224 |
+
if color in distinct_colors[node]:
|
| 225 |
+
raise nx.NetworkXError("Neighboring nodes must have different colors")
|
| 226 |
+
|
| 227 |
+
# If 0 nodes have been colored, simply choose the node of highest degree.
|
| 228 |
+
if not colors:
|
| 229 |
+
node = max(G, key=G.degree)
|
| 230 |
+
yield node
|
| 231 |
+
# Add the color 0 to the distinct colors set for each
|
| 232 |
+
# neighbor of that node.
|
| 233 |
+
for v in G[node]:
|
| 234 |
+
distinct_colors[v].add(0)
|
| 235 |
+
|
| 236 |
+
while len(G) != len(colors):
|
| 237 |
+
# Update the distinct color sets for the neighbors.
|
| 238 |
+
for node, color in colors.items():
|
| 239 |
+
for neighbor in G[node]:
|
| 240 |
+
distinct_colors[neighbor].add(color)
|
| 241 |
+
|
| 242 |
+
# Compute the maximum saturation and the set of nodes that
|
| 243 |
+
# achieve that saturation.
|
| 244 |
+
saturation = {v: len(c) for v, c in distinct_colors.items() if v not in colors}
|
| 245 |
+
# Yield the node with the highest saturation, and break ties by
|
| 246 |
+
# degree.
|
| 247 |
+
node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
|
| 248 |
+
yield node
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
#: Dictionary mapping name of a strategy as a string to the strategy function.
|
| 252 |
+
STRATEGIES = {
|
| 253 |
+
"largest_first": strategy_largest_first,
|
| 254 |
+
"random_sequential": strategy_random_sequential,
|
| 255 |
+
"smallest_last": strategy_smallest_last,
|
| 256 |
+
"independent_set": strategy_independent_set,
|
| 257 |
+
"connected_sequential_bfs": strategy_connected_sequential_bfs,
|
| 258 |
+
"connected_sequential_dfs": strategy_connected_sequential_dfs,
|
| 259 |
+
"connected_sequential": strategy_connected_sequential,
|
| 260 |
+
"saturation_largest_first": strategy_saturation_largest_first,
|
| 261 |
+
"DSATUR": strategy_saturation_largest_first,
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@nx._dispatchable
|
| 266 |
+
def greedy_color(G, strategy="largest_first", interchange=False):
|
| 267 |
+
"""Color a graph using various strategies of greedy graph coloring.
|
| 268 |
+
|
| 269 |
+
Attempts to color a graph using as few colors as possible, where no
|
| 270 |
+
neighbors of a node can have same color as the node itself. The
|
| 271 |
+
given strategy determines the order in which nodes are colored.
|
| 272 |
+
|
| 273 |
+
The strategies are described in [1]_, and smallest-last is based on
|
| 274 |
+
[2]_.
|
| 275 |
+
|
| 276 |
+
Parameters
|
| 277 |
+
----------
|
| 278 |
+
G : NetworkX graph
|
| 279 |
+
|
| 280 |
+
strategy : string or function(G, colors)
|
| 281 |
+
A function (or a string representing a function) that provides
|
| 282 |
+
the coloring strategy, by returning nodes in the ordering they
|
| 283 |
+
should be colored. ``G`` is the graph, and ``colors`` is a
|
| 284 |
+
dictionary of the currently assigned colors, keyed by nodes. The
|
| 285 |
+
function must return an iterable over all the nodes in ``G``.
|
| 286 |
+
|
| 287 |
+
If the strategy function is an iterator generator (that is, a
|
| 288 |
+
function with ``yield`` statements), keep in mind that the
|
| 289 |
+
``colors`` dictionary will be updated after each ``yield``, since
|
| 290 |
+
this function chooses colors greedily.
|
| 291 |
+
|
| 292 |
+
If ``strategy`` is a string, it must be one of the following,
|
| 293 |
+
each of which represents one of the built-in strategy functions.
|
| 294 |
+
|
| 295 |
+
* ``'largest_first'``
|
| 296 |
+
* ``'random_sequential'``
|
| 297 |
+
* ``'smallest_last'``
|
| 298 |
+
* ``'independent_set'``
|
| 299 |
+
* ``'connected_sequential_bfs'``
|
| 300 |
+
* ``'connected_sequential_dfs'``
|
| 301 |
+
* ``'connected_sequential'`` (alias for the previous strategy)
|
| 302 |
+
* ``'saturation_largest_first'``
|
| 303 |
+
* ``'DSATUR'`` (alias for the previous strategy)
|
| 304 |
+
|
| 305 |
+
interchange: bool
|
| 306 |
+
Will use the color interchange algorithm described by [3]_ if set
|
| 307 |
+
to ``True``.
|
| 308 |
+
|
| 309 |
+
Note that ``saturation_largest_first`` and ``independent_set``
|
| 310 |
+
do not work with interchange. Furthermore, if you use
|
| 311 |
+
interchange with your own strategy function, you cannot rely
|
| 312 |
+
on the values in the ``colors`` argument.
|
| 313 |
+
|
| 314 |
+
Returns
|
| 315 |
+
-------
|
| 316 |
+
A dictionary with keys representing nodes and values representing
|
| 317 |
+
corresponding coloring.
|
| 318 |
+
|
| 319 |
+
Examples
|
| 320 |
+
--------
|
| 321 |
+
>>> G = nx.cycle_graph(4)
|
| 322 |
+
>>> d = nx.coloring.greedy_color(G, strategy="largest_first")
|
| 323 |
+
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
|
| 324 |
+
True
|
| 325 |
+
|
| 326 |
+
Raises
|
| 327 |
+
------
|
| 328 |
+
NetworkXPointlessConcept
|
| 329 |
+
If ``strategy`` is ``saturation_largest_first`` or
|
| 330 |
+
``independent_set`` and ``interchange`` is ``True``.
|
| 331 |
+
|
| 332 |
+
References
|
| 333 |
+
----------
|
| 334 |
+
.. [1] Adrian Kosowski, and Krzysztof Manuszewski,
|
| 335 |
+
Classical Coloring of Graphs, Graph Colorings, 2-19, 2004.
|
| 336 |
+
ISBN 0-8218-3458-4.
|
| 337 |
+
.. [2] David W. Matula, and Leland L. Beck, "Smallest-last
|
| 338 |
+
ordering and clustering and graph coloring algorithms." *J. ACM* 30,
|
| 339 |
+
3 (July 1983), 417–427. <https://doi.org/10.1145/2402.322385>
|
| 340 |
+
.. [3] Maciej M. Sysło, Narsingh Deo, Janusz S. Kowalik,
|
| 341 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
| 342 |
+
ISBN 0-486-45353-7.
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
if len(G) == 0:
|
| 346 |
+
return {}
|
| 347 |
+
# Determine the strategy provided by the caller.
|
| 348 |
+
strategy = STRATEGIES.get(strategy, strategy)
|
| 349 |
+
if not callable(strategy):
|
| 350 |
+
raise nx.NetworkXError(
|
| 351 |
+
f"strategy must be callable or a valid string. {strategy} not valid."
|
| 352 |
+
)
|
| 353 |
+
# Perform some validation on the arguments before executing any
|
| 354 |
+
# strategy functions.
|
| 355 |
+
if interchange:
|
| 356 |
+
if strategy is strategy_independent_set:
|
| 357 |
+
msg = "interchange cannot be used with independent_set"
|
| 358 |
+
raise nx.NetworkXPointlessConcept(msg)
|
| 359 |
+
if strategy is strategy_saturation_largest_first:
|
| 360 |
+
msg = "interchange cannot be used with saturation_largest_first"
|
| 361 |
+
raise nx.NetworkXPointlessConcept(msg)
|
| 362 |
+
colors = {}
|
| 363 |
+
nodes = strategy(G, colors)
|
| 364 |
+
if interchange:
|
| 365 |
+
return _greedy_coloring_with_interchange(G, nodes)
|
| 366 |
+
for u in nodes:
|
| 367 |
+
# Set to keep track of colors of neighbors
|
| 368 |
+
nbr_colors = {colors[v] for v in G[u] if v in colors}
|
| 369 |
+
# Find the first unused color.
|
| 370 |
+
for color in itertools.count():
|
| 371 |
+
if color not in nbr_colors:
|
| 372 |
+
break
|
| 373 |
+
# Assign the new color to the current node.
|
| 374 |
+
colors[u] = color
|
| 375 |
+
return colors
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
# Tools for coloring with interchanges
|
| 379 |
+
class _Node:
|
| 380 |
+
__slots__ = ["node_id", "color", "adj_list", "adj_color"]
|
| 381 |
+
|
| 382 |
+
def __init__(self, node_id, n):
|
| 383 |
+
self.node_id = node_id
|
| 384 |
+
self.color = -1
|
| 385 |
+
self.adj_list = None
|
| 386 |
+
self.adj_color = [None for _ in range(n)]
|
| 387 |
+
|
| 388 |
+
def __repr__(self):
|
| 389 |
+
return (
|
| 390 |
+
f"Node_id: {self.node_id}, Color: {self.color}, "
|
| 391 |
+
f"Adj_list: ({self.adj_list}), adj_color: ({self.adj_color})"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
def assign_color(self, adj_entry, color):
|
| 395 |
+
adj_entry.col_prev = None
|
| 396 |
+
adj_entry.col_next = self.adj_color[color]
|
| 397 |
+
self.adj_color[color] = adj_entry
|
| 398 |
+
if adj_entry.col_next is not None:
|
| 399 |
+
adj_entry.col_next.col_prev = adj_entry
|
| 400 |
+
|
| 401 |
+
def clear_color(self, adj_entry, color):
|
| 402 |
+
if adj_entry.col_prev is None:
|
| 403 |
+
self.adj_color[color] = adj_entry.col_next
|
| 404 |
+
else:
|
| 405 |
+
adj_entry.col_prev.col_next = adj_entry.col_next
|
| 406 |
+
if adj_entry.col_next is not None:
|
| 407 |
+
adj_entry.col_next.col_prev = adj_entry.col_prev
|
| 408 |
+
|
| 409 |
+
def iter_neighbors(self):
|
| 410 |
+
adj_node = self.adj_list
|
| 411 |
+
while adj_node is not None:
|
| 412 |
+
yield adj_node
|
| 413 |
+
adj_node = adj_node.next
|
| 414 |
+
|
| 415 |
+
def iter_neighbors_color(self, color):
|
| 416 |
+
adj_color_node = self.adj_color[color]
|
| 417 |
+
while adj_color_node is not None:
|
| 418 |
+
yield adj_color_node.node_id
|
| 419 |
+
adj_color_node = adj_color_node.col_next
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class _AdjEntry:
|
| 423 |
+
__slots__ = ["node_id", "next", "mate", "col_next", "col_prev"]
|
| 424 |
+
|
| 425 |
+
def __init__(self, node_id):
|
| 426 |
+
self.node_id = node_id
|
| 427 |
+
self.next = None
|
| 428 |
+
self.mate = None
|
| 429 |
+
self.col_next = None
|
| 430 |
+
self.col_prev = None
|
| 431 |
+
|
| 432 |
+
def __repr__(self):
|
| 433 |
+
col_next = None if self.col_next is None else self.col_next.node_id
|
| 434 |
+
col_prev = None if self.col_prev is None else self.col_prev.node_id
|
| 435 |
+
return (
|
| 436 |
+
f"Node_id: {self.node_id}, Next: ({self.next}), "
|
| 437 |
+
f"Mate: ({self.mate.node_id}), "
|
| 438 |
+
f"col_next: ({col_next}), col_prev: ({col_prev})"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _greedy_coloring_with_interchange(G, nodes):
|
| 443 |
+
"""Return a coloring for `original_graph` using interchange approach
|
| 444 |
+
|
| 445 |
+
This procedure is an adaption of the algorithm described by [1]_,
|
| 446 |
+
and is an implementation of coloring with interchange. Please be
|
| 447 |
+
advised, that the datastructures used are rather complex because
|
| 448 |
+
they are optimized to minimize the time spent identifying
|
| 449 |
+
subcomponents of the graph, which are possible candidates for color
|
| 450 |
+
interchange.
|
| 451 |
+
|
| 452 |
+
Parameters
|
| 453 |
+
----------
|
| 454 |
+
G : NetworkX graph
|
| 455 |
+
The graph to be colored
|
| 456 |
+
|
| 457 |
+
nodes : list
|
| 458 |
+
nodes ordered using the strategy of choice
|
| 459 |
+
|
| 460 |
+
Returns
|
| 461 |
+
-------
|
| 462 |
+
dict :
|
| 463 |
+
A dictionary keyed by node to a color value
|
| 464 |
+
|
| 465 |
+
References
|
| 466 |
+
----------
|
| 467 |
+
.. [1] Maciej M. Syslo, Narsingh Deo, Janusz S. Kowalik,
|
| 468 |
+
Discrete Optimization Algorithms with Pascal Programs, 415-424, 1983.
|
| 469 |
+
ISBN 0-486-45353-7.
|
| 470 |
+
"""
|
| 471 |
+
n = len(G)
|
| 472 |
+
|
| 473 |
+
graph = {node: _Node(node, n) for node in G}
|
| 474 |
+
|
| 475 |
+
for node1, node2 in G.edges():
|
| 476 |
+
adj_entry1 = _AdjEntry(node2)
|
| 477 |
+
adj_entry2 = _AdjEntry(node1)
|
| 478 |
+
adj_entry1.mate = adj_entry2
|
| 479 |
+
adj_entry2.mate = adj_entry1
|
| 480 |
+
node1_head = graph[node1].adj_list
|
| 481 |
+
adj_entry1.next = node1_head
|
| 482 |
+
graph[node1].adj_list = adj_entry1
|
| 483 |
+
node2_head = graph[node2].adj_list
|
| 484 |
+
adj_entry2.next = node2_head
|
| 485 |
+
graph[node2].adj_list = adj_entry2
|
| 486 |
+
|
| 487 |
+
k = 0
|
| 488 |
+
for node in nodes:
|
| 489 |
+
# Find the smallest possible, unused color
|
| 490 |
+
neighbors = graph[node].iter_neighbors()
|
| 491 |
+
col_used = {graph[adj_node.node_id].color for adj_node in neighbors}
|
| 492 |
+
col_used.discard(-1)
|
| 493 |
+
k1 = next(itertools.dropwhile(lambda x: x in col_used, itertools.count()))
|
| 494 |
+
|
| 495 |
+
# k1 is now the lowest available color
|
| 496 |
+
if k1 > k:
|
| 497 |
+
connected = True
|
| 498 |
+
visited = set()
|
| 499 |
+
col1 = -1
|
| 500 |
+
col2 = -1
|
| 501 |
+
while connected and col1 < k:
|
| 502 |
+
col1 += 1
|
| 503 |
+
neighbor_cols = graph[node].iter_neighbors_color(col1)
|
| 504 |
+
col1_adj = list(neighbor_cols)
|
| 505 |
+
|
| 506 |
+
col2 = col1
|
| 507 |
+
while connected and col2 < k:
|
| 508 |
+
col2 += 1
|
| 509 |
+
visited = set(col1_adj)
|
| 510 |
+
frontier = list(col1_adj)
|
| 511 |
+
i = 0
|
| 512 |
+
while i < len(frontier):
|
| 513 |
+
search_node = frontier[i]
|
| 514 |
+
i += 1
|
| 515 |
+
col_opp = col2 if graph[search_node].color == col1 else col1
|
| 516 |
+
neighbor_cols = graph[search_node].iter_neighbors_color(col_opp)
|
| 517 |
+
|
| 518 |
+
for neighbor in neighbor_cols:
|
| 519 |
+
if neighbor not in visited:
|
| 520 |
+
visited.add(neighbor)
|
| 521 |
+
frontier.append(neighbor)
|
| 522 |
+
|
| 523 |
+
# Search if node is not adj to any col2 vertex
|
| 524 |
+
connected = (
|
| 525 |
+
len(
|
| 526 |
+
visited.intersection(graph[node].iter_neighbors_color(col2))
|
| 527 |
+
)
|
| 528 |
+
> 0
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# If connected is false then we can swap !!!
|
| 532 |
+
if not connected:
|
| 533 |
+
# Update all the nodes in the component
|
| 534 |
+
for search_node in visited:
|
| 535 |
+
graph[search_node].color = (
|
| 536 |
+
col2 if graph[search_node].color == col1 else col1
|
| 537 |
+
)
|
| 538 |
+
col2_adj = graph[search_node].adj_color[col2]
|
| 539 |
+
graph[search_node].adj_color[col2] = graph[search_node].adj_color[
|
| 540 |
+
col1
|
| 541 |
+
]
|
| 542 |
+
graph[search_node].adj_color[col1] = col2_adj
|
| 543 |
+
|
| 544 |
+
# Update all the neighboring nodes
|
| 545 |
+
for search_node in visited:
|
| 546 |
+
col = graph[search_node].color
|
| 547 |
+
col_opp = col1 if col == col2 else col2
|
| 548 |
+
for adj_node in graph[search_node].iter_neighbors():
|
| 549 |
+
if graph[adj_node.node_id].color != col_opp:
|
| 550 |
+
# Direct reference to entry
|
| 551 |
+
adj_mate = adj_node.mate
|
| 552 |
+
graph[adj_node.node_id].clear_color(adj_mate, col_opp)
|
| 553 |
+
graph[adj_node.node_id].assign_color(adj_mate, col)
|
| 554 |
+
k1 = col1
|
| 555 |
+
|
| 556 |
+
# We can color this node color k1
|
| 557 |
+
graph[node].color = k1
|
| 558 |
+
k = max(k1, k)
|
| 559 |
+
|
| 560 |
+
# Update the neighbors of this node
|
| 561 |
+
for adj_node in graph[node].iter_neighbors():
|
| 562 |
+
adj_mate = adj_node.mate
|
| 563 |
+
graph[adj_node.node_id].assign_color(adj_mate, k1)
|
| 564 |
+
|
| 565 |
+
return {node.node_id: node.color for node in graph.values()}
|
shared/package-files/18/18c8715d395075770237999a98fba25b0788af2a664cc8e1d5ea7c9076e55189/subclass_utils.cpython-311.pyc
ADDED
|
Binary file (19.9 kB). View file
|
|
|
shared/package-files/18/18c997e01eea439f7cf5fd8a0a2d40ab9081e5ce72777c412e45684da175b9b3/view_as_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor view_as(const at::Tensor & self, const at::Tensor & other);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/18/18cba8485d6fa8a0ecfdedc927b63496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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Definition of physical dimensions.
|
| 3 |
+
|
| 4 |
+
Unit systems will be constructed on top of these dimensions.
|
| 5 |
+
|
| 6 |
+
Most of the examples in the doc use MKS system and are presented from the
|
| 7 |
+
computer point of view: from a human point, adding length to time is not legal
|
| 8 |
+
in MKS but it is in natural system; for a computer in natural system there is
|
| 9 |
+
no time dimension (but a velocity dimension instead) - in the basis - so the
|
| 10 |
+
question of adding time to length has no meaning.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import collections
|
| 16 |
+
from functools import reduce
|
| 17 |
+
|
| 18 |
+
from sympy.core.basic import Basic
|
| 19 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 20 |
+
from sympy.core.singleton import S
|
| 21 |
+
from sympy.core.sorting import default_sort_key
|
| 22 |
+
from sympy.core.symbol import Symbol
|
| 23 |
+
from sympy.core.sympify import sympify
|
| 24 |
+
from sympy.matrices.dense import Matrix
|
| 25 |
+
from sympy.functions.elementary.trigonometric import TrigonometricFunction
|
| 26 |
+
from sympy.core.expr import Expr
|
| 27 |
+
from sympy.core.power import Pow
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class _QuantityMapper:
|
| 31 |
+
|
| 32 |
+
_quantity_scale_factors_global: dict[Expr, Expr] = {}
|
| 33 |
+
_quantity_dimensional_equivalence_map_global: dict[Expr, Expr] = {}
|
| 34 |
+
_quantity_dimension_global: dict[Expr, Expr] = {}
|
| 35 |
+
|
| 36 |
+
def __init__(self, *args, **kwargs):
|
| 37 |
+
self._quantity_dimension_map = {}
|
| 38 |
+
self._quantity_scale_factors = {}
|
| 39 |
+
|
| 40 |
+
def set_quantity_dimension(self, quantity, dimension):
|
| 41 |
+
"""
|
| 42 |
+
Set the dimension for the quantity in a unit system.
|
| 43 |
+
|
| 44 |
+
If this relation is valid in every unit system, use
|
| 45 |
+
``quantity.set_global_dimension(dimension)`` instead.
|
| 46 |
+
"""
|
| 47 |
+
from sympy.physics.units import Quantity
|
| 48 |
+
dimension = sympify(dimension)
|
| 49 |
+
if not isinstance(dimension, Dimension):
|
| 50 |
+
if dimension == 1:
|
| 51 |
+
dimension = Dimension(1)
|
| 52 |
+
else:
|
| 53 |
+
raise ValueError("expected dimension or 1")
|
| 54 |
+
elif isinstance(dimension, Quantity):
|
| 55 |
+
dimension = self.get_quantity_dimension(dimension)
|
| 56 |
+
self._quantity_dimension_map[quantity] = dimension
|
| 57 |
+
|
| 58 |
+
def set_quantity_scale_factor(self, quantity, scale_factor):
|
| 59 |
+
"""
|
| 60 |
+
Set the scale factor of a quantity relative to another quantity.
|
| 61 |
+
|
| 62 |
+
It should be used only once per quantity to just one other quantity,
|
| 63 |
+
the algorithm will then be able to compute the scale factors to all
|
| 64 |
+
other quantities.
|
| 65 |
+
|
| 66 |
+
In case the scale factor is valid in every unit system, please use
|
| 67 |
+
``quantity.set_global_relative_scale_factor(scale_factor)`` instead.
|
| 68 |
+
"""
|
| 69 |
+
from sympy.physics.units import Quantity
|
| 70 |
+
from sympy.physics.units.prefixes import Prefix
|
| 71 |
+
scale_factor = sympify(scale_factor)
|
| 72 |
+
# replace all prefixes by their ratio to canonical units:
|
| 73 |
+
scale_factor = scale_factor.replace(
|
| 74 |
+
lambda x: isinstance(x, Prefix),
|
| 75 |
+
lambda x: x.scale_factor
|
| 76 |
+
)
|
| 77 |
+
# replace all quantities by their ratio to canonical units:
|
| 78 |
+
scale_factor = scale_factor.replace(
|
| 79 |
+
lambda x: isinstance(x, Quantity),
|
| 80 |
+
lambda x: self.get_quantity_scale_factor(x)
|
| 81 |
+
)
|
| 82 |
+
self._quantity_scale_factors[quantity] = scale_factor
|
| 83 |
+
|
| 84 |
+
def get_quantity_dimension(self, unit):
|
| 85 |
+
from sympy.physics.units import Quantity
|
| 86 |
+
# First look-up the local dimension map, then the global one:
|
| 87 |
+
if unit in self._quantity_dimension_map:
|
| 88 |
+
return self._quantity_dimension_map[unit]
|
| 89 |
+
if unit in self._quantity_dimension_global:
|
| 90 |
+
return self._quantity_dimension_global[unit]
|
| 91 |
+
if unit in self._quantity_dimensional_equivalence_map_global:
|
| 92 |
+
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
|
| 93 |
+
if isinstance(dep_unit, Quantity):
|
| 94 |
+
return self.get_quantity_dimension(dep_unit)
|
| 95 |
+
else:
|
| 96 |
+
return Dimension(self.get_dimensional_expr(dep_unit))
|
| 97 |
+
if isinstance(unit, Quantity):
|
| 98 |
+
return Dimension(unit.name)
|
| 99 |
+
else:
|
| 100 |
+
return Dimension(1)
|
| 101 |
+
|
| 102 |
+
def get_quantity_scale_factor(self, unit):
|
| 103 |
+
if unit in self._quantity_scale_factors:
|
| 104 |
+
return self._quantity_scale_factors[unit]
|
| 105 |
+
if unit in self._quantity_scale_factors_global:
|
| 106 |
+
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
|
| 107 |
+
return mul_factor*self.get_quantity_scale_factor(other_unit)
|
| 108 |
+
return S.One
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class Dimension(Expr):
|
| 112 |
+
"""
|
| 113 |
+
This class represent the dimension of a physical quantities.
|
| 114 |
+
|
| 115 |
+
The ``Dimension`` constructor takes as parameters a name and an optional
|
| 116 |
+
symbol.
|
| 117 |
+
|
| 118 |
+
For example, in classical mechanics we know that time is different from
|
| 119 |
+
temperature and dimensions make this difference (but they do not provide
|
| 120 |
+
any measure of these quantities.
|
| 121 |
+
|
| 122 |
+
>>> from sympy.physics.units import Dimension
|
| 123 |
+
>>> length = Dimension('length')
|
| 124 |
+
>>> length
|
| 125 |
+
Dimension(length)
|
| 126 |
+
>>> time = Dimension('time')
|
| 127 |
+
>>> time
|
| 128 |
+
Dimension(time)
|
| 129 |
+
|
| 130 |
+
Dimensions can be composed using multiplication, division and
|
| 131 |
+
exponentiation (by a number) to give new dimensions. Addition and
|
| 132 |
+
subtraction is defined only when the two objects are the same dimension.
|
| 133 |
+
|
| 134 |
+
>>> velocity = length / time
|
| 135 |
+
>>> velocity
|
| 136 |
+
Dimension(length/time)
|
| 137 |
+
|
| 138 |
+
It is possible to use a dimension system object to get the dimensionsal
|
| 139 |
+
dependencies of a dimension, for example the dimension system used by the
|
| 140 |
+
SI units convention can be used:
|
| 141 |
+
|
| 142 |
+
>>> from sympy.physics.units.systems.si import dimsys_SI
|
| 143 |
+
>>> dimsys_SI.get_dimensional_dependencies(velocity)
|
| 144 |
+
{Dimension(length, L): 1, Dimension(time, T): -1}
|
| 145 |
+
>>> length + length
|
| 146 |
+
Dimension(length)
|
| 147 |
+
>>> l2 = length**2
|
| 148 |
+
>>> l2
|
| 149 |
+
Dimension(length**2)
|
| 150 |
+
>>> dimsys_SI.get_dimensional_dependencies(l2)
|
| 151 |
+
{Dimension(length, L): 2}
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
_op_priority = 13.0
|
| 156 |
+
|
| 157 |
+
# XXX: This doesn't seem to be used anywhere...
|
| 158 |
+
_dimensional_dependencies = {} # type: ignore
|
| 159 |
+
|
| 160 |
+
is_commutative = True
|
| 161 |
+
is_number = False
|
| 162 |
+
# make sqrt(M**2) --> M
|
| 163 |
+
is_positive = True
|
| 164 |
+
is_real = True
|
| 165 |
+
|
| 166 |
+
def __new__(cls, name, symbol=None):
|
| 167 |
+
|
| 168 |
+
if isinstance(name, str):
|
| 169 |
+
name = Symbol(name)
|
| 170 |
+
else:
|
| 171 |
+
name = sympify(name)
|
| 172 |
+
|
| 173 |
+
if not isinstance(name, Expr):
|
| 174 |
+
raise TypeError("Dimension name needs to be a valid math expression")
|
| 175 |
+
|
| 176 |
+
if isinstance(symbol, str):
|
| 177 |
+
symbol = Symbol(symbol)
|
| 178 |
+
elif symbol is not None:
|
| 179 |
+
assert isinstance(symbol, Symbol)
|
| 180 |
+
|
| 181 |
+
obj = Expr.__new__(cls, name)
|
| 182 |
+
|
| 183 |
+
obj._name = name
|
| 184 |
+
obj._symbol = symbol
|
| 185 |
+
return obj
|
| 186 |
+
|
| 187 |
+
@property
|
| 188 |
+
def name(self):
|
| 189 |
+
return self._name
|
| 190 |
+
|
| 191 |
+
@property
|
| 192 |
+
def symbol(self):
|
| 193 |
+
return self._symbol
|
| 194 |
+
|
| 195 |
+
def __str__(self):
|
| 196 |
+
"""
|
| 197 |
+
Display the string representation of the dimension.
|
| 198 |
+
"""
|
| 199 |
+
if self.symbol is None:
|
| 200 |
+
return "Dimension(%s)" % (self.name)
|
| 201 |
+
else:
|
| 202 |
+
return "Dimension(%s, %s)" % (self.name, self.symbol)
|
| 203 |
+
|
| 204 |
+
def __repr__(self):
|
| 205 |
+
return self.__str__()
|
| 206 |
+
|
| 207 |
+
def __neg__(self):
|
| 208 |
+
return self
|
| 209 |
+
|
| 210 |
+
def __add__(self, other):
|
| 211 |
+
from sympy.physics.units.quantities import Quantity
|
| 212 |
+
other = sympify(other)
|
| 213 |
+
if isinstance(other, Basic):
|
| 214 |
+
if other.has(Quantity):
|
| 215 |
+
raise TypeError("cannot sum dimension and quantity")
|
| 216 |
+
if isinstance(other, Dimension) and self == other:
|
| 217 |
+
return self
|
| 218 |
+
return super().__add__(other)
|
| 219 |
+
return self
|
| 220 |
+
|
| 221 |
+
def __radd__(self, other):
|
| 222 |
+
return self.__add__(other)
|
| 223 |
+
|
| 224 |
+
def __sub__(self, other):
|
| 225 |
+
# there is no notion of ordering (or magnitude) among dimension,
|
| 226 |
+
# subtraction is equivalent to addition when the operation is legal
|
| 227 |
+
return self + other
|
| 228 |
+
|
| 229 |
+
def __rsub__(self, other):
|
| 230 |
+
# there is no notion of ordering (or magnitude) among dimension,
|
| 231 |
+
# subtraction is equivalent to addition when the operation is legal
|
| 232 |
+
return self + other
|
| 233 |
+
|
| 234 |
+
def __pow__(self, other):
|
| 235 |
+
return self._eval_power(other)
|
| 236 |
+
|
| 237 |
+
def _eval_power(self, other):
|
| 238 |
+
other = sympify(other)
|
| 239 |
+
return Dimension(self.name**other)
|
| 240 |
+
|
| 241 |
+
def __mul__(self, other):
|
| 242 |
+
from sympy.physics.units.quantities import Quantity
|
| 243 |
+
if isinstance(other, Basic):
|
| 244 |
+
if other.has(Quantity):
|
| 245 |
+
raise TypeError("cannot sum dimension and quantity")
|
| 246 |
+
if isinstance(other, Dimension):
|
| 247 |
+
return Dimension(self.name*other.name)
|
| 248 |
+
if not other.free_symbols: # other.is_number cannot be used
|
| 249 |
+
return self
|
| 250 |
+
return super().__mul__(other)
|
| 251 |
+
return self
|
| 252 |
+
|
| 253 |
+
def __rmul__(self, other):
|
| 254 |
+
return self.__mul__(other)
|
| 255 |
+
|
| 256 |
+
def __truediv__(self, other):
|
| 257 |
+
return self*Pow(other, -1)
|
| 258 |
+
|
| 259 |
+
def __rtruediv__(self, other):
|
| 260 |
+
return other * pow(self, -1)
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
def _from_dimensional_dependencies(cls, dependencies):
|
| 264 |
+
return reduce(lambda x, y: x * y, (
|
| 265 |
+
d**e for d, e in dependencies.items()
|
| 266 |
+
), 1)
|
| 267 |
+
|
| 268 |
+
def has_integer_powers(self, dim_sys):
|
| 269 |
+
"""
|
| 270 |
+
Check if the dimension object has only integer powers.
|
| 271 |
+
|
| 272 |
+
All the dimension powers should be integers, but rational powers may
|
| 273 |
+
appear in intermediate steps. This method may be used to check that the
|
| 274 |
+
final result is well-defined.
|
| 275 |
+
"""
|
| 276 |
+
|
| 277 |
+
return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# Create dimensions according to the base units in MKSA.
|
| 281 |
+
# For other unit systems, they can be derived by transforming the base
|
| 282 |
+
# dimensional dependency dictionary.
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class DimensionSystem(Basic, _QuantityMapper):
|
| 286 |
+
r"""
|
| 287 |
+
DimensionSystem represents a coherent set of dimensions.
|
| 288 |
+
|
| 289 |
+
The constructor takes three parameters:
|
| 290 |
+
|
| 291 |
+
- base dimensions;
|
| 292 |
+
- derived dimensions: these are defined in terms of the base dimensions
|
| 293 |
+
(for example velocity is defined from the division of length by time);
|
| 294 |
+
- dependency of dimensions: how the derived dimensions depend
|
| 295 |
+
on the base dimensions.
|
| 296 |
+
|
| 297 |
+
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
|
| 298 |
+
may be omitted.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
|
| 302 |
+
dimensional_dependencies = dict(dimensional_dependencies)
|
| 303 |
+
|
| 304 |
+
def parse_dim(dim):
|
| 305 |
+
if isinstance(dim, str):
|
| 306 |
+
dim = Dimension(Symbol(dim))
|
| 307 |
+
elif isinstance(dim, Dimension):
|
| 308 |
+
pass
|
| 309 |
+
elif isinstance(dim, Symbol):
|
| 310 |
+
dim = Dimension(dim)
|
| 311 |
+
else:
|
| 312 |
+
raise TypeError("%s wrong type" % dim)
|
| 313 |
+
return dim
|
| 314 |
+
|
| 315 |
+
base_dims = [parse_dim(i) for i in base_dims]
|
| 316 |
+
derived_dims = [parse_dim(i) for i in derived_dims]
|
| 317 |
+
|
| 318 |
+
for dim in base_dims:
|
| 319 |
+
if (dim in dimensional_dependencies
|
| 320 |
+
and (len(dimensional_dependencies[dim]) != 1 or
|
| 321 |
+
dimensional_dependencies[dim].get(dim, None) != 1)):
|
| 322 |
+
raise IndexError("Repeated value in base dimensions")
|
| 323 |
+
dimensional_dependencies[dim] = Dict({dim: 1})
|
| 324 |
+
|
| 325 |
+
def parse_dim_name(dim):
|
| 326 |
+
if isinstance(dim, Dimension):
|
| 327 |
+
return dim
|
| 328 |
+
elif isinstance(dim, str):
|
| 329 |
+
return Dimension(Symbol(dim))
|
| 330 |
+
elif isinstance(dim, Symbol):
|
| 331 |
+
return Dimension(dim)
|
| 332 |
+
else:
|
| 333 |
+
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
|
| 334 |
+
|
| 335 |
+
for dim in dimensional_dependencies.keys():
|
| 336 |
+
dim = parse_dim(dim)
|
| 337 |
+
if (dim not in derived_dims) and (dim not in base_dims):
|
| 338 |
+
derived_dims.append(dim)
|
| 339 |
+
|
| 340 |
+
def parse_dict(d):
|
| 341 |
+
return Dict({parse_dim_name(i): j for i, j in d.items()})
|
| 342 |
+
|
| 343 |
+
# Make sure everything is a SymPy type:
|
| 344 |
+
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
|
| 345 |
+
dimensional_dependencies.items()}
|
| 346 |
+
|
| 347 |
+
for dim in derived_dims:
|
| 348 |
+
if dim in base_dims:
|
| 349 |
+
raise ValueError("Dimension %s both in base and derived" % dim)
|
| 350 |
+
if dim not in dimensional_dependencies:
|
| 351 |
+
# TODO: should this raise a warning?
|
| 352 |
+
dimensional_dependencies[dim] = Dict({dim: 1})
|
| 353 |
+
|
| 354 |
+
base_dims.sort(key=default_sort_key)
|
| 355 |
+
derived_dims.sort(key=default_sort_key)
|
| 356 |
+
|
| 357 |
+
base_dims = Tuple(*base_dims)
|
| 358 |
+
derived_dims = Tuple(*derived_dims)
|
| 359 |
+
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
|
| 360 |
+
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
|
| 361 |
+
return obj
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def base_dims(self):
|
| 365 |
+
return self.args[0]
|
| 366 |
+
|
| 367 |
+
@property
|
| 368 |
+
def derived_dims(self):
|
| 369 |
+
return self.args[1]
|
| 370 |
+
|
| 371 |
+
@property
|
| 372 |
+
def dimensional_dependencies(self):
|
| 373 |
+
return self.args[2]
|
| 374 |
+
|
| 375 |
+
def _get_dimensional_dependencies_for_name(self, dimension):
|
| 376 |
+
if isinstance(dimension, str):
|
| 377 |
+
dimension = Dimension(Symbol(dimension))
|
| 378 |
+
elif not isinstance(dimension, Dimension):
|
| 379 |
+
dimension = Dimension(dimension)
|
| 380 |
+
|
| 381 |
+
if dimension.name.is_Symbol:
|
| 382 |
+
# Dimensions not included in the dependencies are considered
|
| 383 |
+
# as base dimensions:
|
| 384 |
+
return dict(self.dimensional_dependencies.get(dimension, {dimension: 1}))
|
| 385 |
+
|
| 386 |
+
if dimension.name.is_number or dimension.name.is_NumberSymbol:
|
| 387 |
+
return {}
|
| 388 |
+
|
| 389 |
+
get_for_name = self._get_dimensional_dependencies_for_name
|
| 390 |
+
|
| 391 |
+
if dimension.name.is_Mul:
|
| 392 |
+
ret = collections.defaultdict(int)
|
| 393 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 394 |
+
for d in dicts:
|
| 395 |
+
for k, v in d.items():
|
| 396 |
+
ret[k] += v
|
| 397 |
+
return {k: v for (k, v) in ret.items() if v != 0}
|
| 398 |
+
|
| 399 |
+
if dimension.name.is_Add:
|
| 400 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 401 |
+
if all(d == dicts[0] for d in dicts[1:]):
|
| 402 |
+
return dicts[0]
|
| 403 |
+
raise TypeError("Only equivalent dimensions can be added or subtracted.")
|
| 404 |
+
|
| 405 |
+
if dimension.name.is_Pow:
|
| 406 |
+
dim_base = get_for_name(dimension.name.base)
|
| 407 |
+
dim_exp = get_for_name(dimension.name.exp)
|
| 408 |
+
if dim_exp == {} or dimension.name.exp.is_Symbol:
|
| 409 |
+
return {k: v * dimension.name.exp for (k, v) in dim_base.items()}
|
| 410 |
+
else:
|
| 411 |
+
raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
|
| 412 |
+
|
| 413 |
+
if dimension.name.is_Function:
|
| 414 |
+
args = (Dimension._from_dimensional_dependencies(
|
| 415 |
+
get_for_name(arg)) for arg in dimension.name.args)
|
| 416 |
+
result = dimension.name.func(*args)
|
| 417 |
+
|
| 418 |
+
dicts = [get_for_name(i) for i in dimension.name.args]
|
| 419 |
+
|
| 420 |
+
if isinstance(result, Dimension):
|
| 421 |
+
return self.get_dimensional_dependencies(result)
|
| 422 |
+
elif result.func == dimension.name.func:
|
| 423 |
+
if isinstance(dimension.name, TrigonometricFunction):
|
| 424 |
+
if dicts[0] in ({}, {Dimension('angle'): 1}):
|
| 425 |
+
return {}
|
| 426 |
+
else:
|
| 427 |
+
raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func))
|
| 428 |
+
else:
|
| 429 |
+
if all(item == {} for item in dicts):
|
| 430 |
+
return {}
|
| 431 |
+
else:
|
| 432 |
+
raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func))
|
| 433 |
+
else:
|
| 434 |
+
return get_for_name(result)
|
| 435 |
+
|
| 436 |
+
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name)))
|
| 437 |
+
|
| 438 |
+
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
|
| 439 |
+
dimdep = self._get_dimensional_dependencies_for_name(name)
|
| 440 |
+
if mark_dimensionless and dimdep == {}:
|
| 441 |
+
return {Dimension(1): 1}
|
| 442 |
+
return dict(dimdep.items())
|
| 443 |
+
|
| 444 |
+
def equivalent_dims(self, dim1, dim2):
|
| 445 |
+
deps1 = self.get_dimensional_dependencies(dim1)
|
| 446 |
+
deps2 = self.get_dimensional_dependencies(dim2)
|
| 447 |
+
return deps1 == deps2
|
| 448 |
+
|
| 449 |
+
def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
|
| 450 |
+
deps = dict(self.dimensional_dependencies)
|
| 451 |
+
if new_dim_deps:
|
| 452 |
+
deps.update(new_dim_deps)
|
| 453 |
+
|
| 454 |
+
new_dim_sys = DimensionSystem(
|
| 455 |
+
tuple(self.base_dims) + tuple(new_base_dims),
|
| 456 |
+
tuple(self.derived_dims) + tuple(new_derived_dims),
|
| 457 |
+
deps
|
| 458 |
+
)
|
| 459 |
+
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
|
| 460 |
+
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
|
| 461 |
+
return new_dim_sys
|
| 462 |
+
|
| 463 |
+
def is_dimensionless(self, dimension):
|
| 464 |
+
"""
|
| 465 |
+
Check if the dimension object really has a dimension.
|
| 466 |
+
|
| 467 |
+
A dimension should have at least one component with non-zero power.
|
| 468 |
+
"""
|
| 469 |
+
if dimension.name == 1:
|
| 470 |
+
return True
|
| 471 |
+
return self.get_dimensional_dependencies(dimension) == {}
|
| 472 |
+
|
| 473 |
+
@property
|
| 474 |
+
def list_can_dims(self):
|
| 475 |
+
"""
|
| 476 |
+
Useless method, kept for compatibility with previous versions.
|
| 477 |
+
|
| 478 |
+
DO NOT USE.
|
| 479 |
+
|
| 480 |
+
List all canonical dimension names.
|
| 481 |
+
"""
|
| 482 |
+
dimset = set()
|
| 483 |
+
for i in self.base_dims:
|
| 484 |
+
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
|
| 485 |
+
return tuple(sorted(dimset, key=str))
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def inv_can_transf_matrix(self):
|
| 489 |
+
"""
|
| 490 |
+
Useless method, kept for compatibility with previous versions.
|
| 491 |
+
|
| 492 |
+
DO NOT USE.
|
| 493 |
+
|
| 494 |
+
Compute the inverse transformation matrix from the base to the
|
| 495 |
+
canonical dimension basis.
|
| 496 |
+
|
| 497 |
+
It corresponds to the matrix where columns are the vector of base
|
| 498 |
+
dimensions in canonical basis.
|
| 499 |
+
|
| 500 |
+
This matrix will almost never be used because dimensions are always
|
| 501 |
+
defined with respect to the canonical basis, so no work has to be done
|
| 502 |
+
to get them in this basis. Nonetheless if this matrix is not square
|
| 503 |
+
(or not invertible) it means that we have chosen a bad basis.
|
| 504 |
+
"""
|
| 505 |
+
matrix = reduce(lambda x, y: x.row_join(y),
|
| 506 |
+
[self.dim_can_vector(d) for d in self.base_dims])
|
| 507 |
+
return matrix
|
| 508 |
+
|
| 509 |
+
@property
|
| 510 |
+
def can_transf_matrix(self):
|
| 511 |
+
"""
|
| 512 |
+
Useless method, kept for compatibility with previous versions.
|
| 513 |
+
|
| 514 |
+
DO NOT USE.
|
| 515 |
+
|
| 516 |
+
Return the canonical transformation matrix from the canonical to the
|
| 517 |
+
base dimension basis.
|
| 518 |
+
|
| 519 |
+
It is the inverse of the matrix computed with inv_can_transf_matrix().
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
#TODO: the inversion will fail if the system is inconsistent, for
|
| 523 |
+
# example if the matrix is not a square
|
| 524 |
+
return reduce(lambda x, y: x.row_join(y),
|
| 525 |
+
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
|
| 526 |
+
).inv()
|
| 527 |
+
|
| 528 |
+
def dim_can_vector(self, dim):
|
| 529 |
+
"""
|
| 530 |
+
Useless method, kept for compatibility with previous versions.
|
| 531 |
+
|
| 532 |
+
DO NOT USE.
|
| 533 |
+
|
| 534 |
+
Dimensional representation in terms of the canonical base dimensions.
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
vec = []
|
| 538 |
+
for d in self.list_can_dims:
|
| 539 |
+
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
|
| 540 |
+
return Matrix(vec)
|
| 541 |
+
|
| 542 |
+
def dim_vector(self, dim):
|
| 543 |
+
"""
|
| 544 |
+
Useless method, kept for compatibility with previous versions.
|
| 545 |
+
|
| 546 |
+
DO NOT USE.
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
Vector representation in terms of the base dimensions.
|
| 550 |
+
"""
|
| 551 |
+
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
|
| 552 |
+
|
| 553 |
+
def print_dim_base(self, dim):
|
| 554 |
+
"""
|
| 555 |
+
Give the string expression of a dimension in term of the basis symbols.
|
| 556 |
+
"""
|
| 557 |
+
dims = self.dim_vector(dim)
|
| 558 |
+
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
|
| 559 |
+
res = S.One
|
| 560 |
+
for (s, p) in zip(symbols, dims):
|
| 561 |
+
res *= s**p
|
| 562 |
+
return res
|
| 563 |
+
|
| 564 |
+
@property
|
| 565 |
+
def dim(self):
|
| 566 |
+
"""
|
| 567 |
+
Useless method, kept for compatibility with previous versions.
|
| 568 |
+
|
| 569 |
+
DO NOT USE.
|
| 570 |
+
|
| 571 |
+
Give the dimension of the system.
|
| 572 |
+
|
| 573 |
+
That is return the number of dimensions forming the basis.
|
| 574 |
+
"""
|
| 575 |
+
return len(self.base_dims)
|
| 576 |
+
|
| 577 |
+
@property
|
| 578 |
+
def is_consistent(self):
|
| 579 |
+
"""
|
| 580 |
+
Useless method, kept for compatibility with previous versions.
|
| 581 |
+
|
| 582 |
+
DO NOT USE.
|
| 583 |
+
|
| 584 |
+
Check if the system is well defined.
|
| 585 |
+
"""
|
| 586 |
+
|
| 587 |
+
# not enough or too many base dimensions compared to independent
|
| 588 |
+
# dimensions
|
| 589 |
+
# in vector language: the set of vectors do not form a basis
|
| 590 |
+
return self.inv_can_transf_matrix.is_square
|
shared/package-files/18/18ce7de1e85300b021786ad70400ed8c62914d4886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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._inductor.compile_fx import fake_tensor_prop
|
| 6 |
+
from torch._inductor.utils import GPU_TYPES
|
| 7 |
+
|
| 8 |
+
from ..._dynamo.utils import counters
|
| 9 |
+
from .. import config
|
| 10 |
+
from ..pattern_matcher import (
|
| 11 |
+
_return_true,
|
| 12 |
+
CallFunction,
|
| 13 |
+
fwd_only,
|
| 14 |
+
Ignored,
|
| 15 |
+
init_once_fakemode,
|
| 16 |
+
KeywordArg,
|
| 17 |
+
Match,
|
| 18 |
+
PatternMatcherPass,
|
| 19 |
+
register_graph_pattern,
|
| 20 |
+
register_replacement,
|
| 21 |
+
stable_topological_sort,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
aten = torch.ops.aten
|
| 26 |
+
|
| 27 |
+
# First pass_patterns[0] are applied, then [1], then [2]
|
| 28 |
+
pass_patterns = [
|
| 29 |
+
PatternMatcherPass(),
|
| 30 |
+
PatternMatcherPass(),
|
| 31 |
+
PatternMatcherPass(),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
binary_folding_pass = PatternMatcherPass()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def freezing_passes(gm: torch.fx.GraphModule, aot_example_inputs):
|
| 38 |
+
"""
|
| 39 |
+
Passes that are applied to the graph to freeze pass.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from ..freezing import constant_fold
|
| 43 |
+
|
| 44 |
+
lazy_init()
|
| 45 |
+
# We need a few rounds of binary folding to get rid of all the
|
| 46 |
+
# unnecessary nodes, but may need a good method to chose the rounds number.
|
| 47 |
+
# works like: conv+binary+binary.
|
| 48 |
+
binary_folding = counters["inductor"]["binary_folding"]
|
| 49 |
+
fake_tensor_prop(gm, aot_example_inputs, True)
|
| 50 |
+
|
| 51 |
+
torch._inductor.fx_passes.binary_folding.mark_mixed_dtype_allowed_computation_ops(
|
| 52 |
+
gm
|
| 53 |
+
)
|
| 54 |
+
for _ in range(4):
|
| 55 |
+
constant_fold(gm)
|
| 56 |
+
# Make sure meta['val'] is properly set for all nodes
|
| 57 |
+
fake_tensor_prop(gm, aot_example_inputs, True)
|
| 58 |
+
binary_folding_pass.apply(gm.graph) # type: ignore[arg-type]
|
| 59 |
+
# If we don't have binary folding, we don't need to run the pass again.
|
| 60 |
+
# TODO: remove the need to run fake_tensor_prop on the whole model.
|
| 61 |
+
if counters["inductor"]["binary_folding"] == binary_folding:
|
| 62 |
+
break
|
| 63 |
+
binary_folding = counters["inductor"]["binary_folding"]
|
| 64 |
+
|
| 65 |
+
torch._inductor.fx_passes.binary_folding.recover_original_precision_folded_computation_ops(
|
| 66 |
+
gm
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
constant_fold(gm)
|
| 70 |
+
fake_tensor_prop(gm, aot_example_inputs, True)
|
| 71 |
+
|
| 72 |
+
for pattern in pass_patterns:
|
| 73 |
+
pattern.apply(gm.graph) # type: ignore[arg-type]
|
| 74 |
+
|
| 75 |
+
# The CPU weight packing always assume the conv's weight is channels last,
|
| 76 |
+
# So make sure the layout_optimization is on when doing it.
|
| 77 |
+
if (
|
| 78 |
+
torch._C._has_mkldnn
|
| 79 |
+
and config.cpp.weight_prepack
|
| 80 |
+
and config.layout_optimization
|
| 81 |
+
):
|
| 82 |
+
from .mkldnn_fusion import _eliminate_duplicate_packed_nodes
|
| 83 |
+
|
| 84 |
+
_eliminate_duplicate_packed_nodes(gm)
|
| 85 |
+
|
| 86 |
+
stable_topological_sort(gm.graph)
|
| 87 |
+
gm.recompile()
|
| 88 |
+
gm.graph.lint()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@init_once_fakemode
|
| 92 |
+
def lazy_init():
|
| 93 |
+
if torch._C._has_mkldnn and config.cpp.weight_prepack:
|
| 94 |
+
from .mkldnn_fusion import _mkldnn_weight_pack_init
|
| 95 |
+
|
| 96 |
+
_mkldnn_weight_pack_init()
|
| 97 |
+
|
| 98 |
+
from .binary_folding import binary_folding_init
|
| 99 |
+
|
| 100 |
+
addmm_patterns_init()
|
| 101 |
+
binary_folding_init()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def register_freezing_graph_pattern(pattern, extra_check=_return_true, pass_number=0):
|
| 105 |
+
while pass_number > len(pass_patterns) - 1:
|
| 106 |
+
pass_patterns.append(PatternMatcherPass())
|
| 107 |
+
return register_graph_pattern(
|
| 108 |
+
pattern,
|
| 109 |
+
extra_check=extra_check,
|
| 110 |
+
pass_dict=pass_patterns[pass_number],
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def register_binary_folding_pattern(pattern, extra_check=_return_true):
|
| 115 |
+
return register_graph_pattern(
|
| 116 |
+
pattern,
|
| 117 |
+
extra_check=extra_check,
|
| 118 |
+
pass_dict=binary_folding_pass,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@functools.lru_cache(None)
|
| 123 |
+
def addmm_patterns_init():
|
| 124 |
+
device = next(
|
| 125 |
+
(gpu for gpu in GPU_TYPES if getattr(torch, gpu).is_available()), "cpu"
|
| 126 |
+
)
|
| 127 |
+
val = functools.partial(torch.empty, (10, 10), device=device, requires_grad=False)
|
| 128 |
+
|
| 129 |
+
def check_concat_weights(match):
|
| 130 |
+
is_cpu = match.kwargs["inp"].meta["val"].is_cpu
|
| 131 |
+
if is_cpu and not config.cpp.enable_concat_linear:
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
weight_inputs = ["w1", "w2"]
|
| 135 |
+
if "w3" in match.kwargs:
|
| 136 |
+
weight_inputs.append("w3")
|
| 137 |
+
|
| 138 |
+
equal_shape_inputs = [weight_inputs]
|
| 139 |
+
|
| 140 |
+
if "b1" in match.kwargs:
|
| 141 |
+
bias_inputs = ["b1", "b2"]
|
| 142 |
+
if "b3" in match.kwargs:
|
| 143 |
+
bias_inputs.append("b3")
|
| 144 |
+
|
| 145 |
+
equal_shape_inputs.append(bias_inputs)
|
| 146 |
+
|
| 147 |
+
for equal_shape_group in equal_shape_inputs:
|
| 148 |
+
inps = [match.kwargs[name] for name in equal_shape_group]
|
| 149 |
+
|
| 150 |
+
if not all(
|
| 151 |
+
inp.op == "get_attr"
|
| 152 |
+
and inp.meta["val"].shape == inps[0].meta["val"].shape
|
| 153 |
+
for inp in inps
|
| 154 |
+
):
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def matmul_fuse_pattern(inp, w1, w2, w3):
|
| 160 |
+
return (inp @ w1, inp @ w2, inp @ w3)
|
| 161 |
+
|
| 162 |
+
def matmul_replacement(inp, w1, w2, w3):
|
| 163 |
+
cat_t = torch.cat((w1, w2, w3), dim=1)
|
| 164 |
+
mm = inp @ cat_t
|
| 165 |
+
return mm.chunk(3, dim=1)
|
| 166 |
+
|
| 167 |
+
register_replacement(
|
| 168 |
+
matmul_fuse_pattern,
|
| 169 |
+
matmul_replacement,
|
| 170 |
+
[val(), val(), val(), val()],
|
| 171 |
+
fwd_only,
|
| 172 |
+
pass_patterns[0],
|
| 173 |
+
extra_check=check_concat_weights,
|
| 174 |
+
exclusive_arg_names=("w1", "w2", "w3"),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def matmul_fuse_pattern_two(inp, w1, w2):
|
| 178 |
+
return (inp @ w1, inp @ w2)
|
| 179 |
+
|
| 180 |
+
def matmul_replacement_two(inp, w1, w2):
|
| 181 |
+
cat_t = torch.cat((w1, w2), dim=1)
|
| 182 |
+
mm = inp @ cat_t
|
| 183 |
+
return mm.chunk(2, dim=1)
|
| 184 |
+
|
| 185 |
+
register_replacement(
|
| 186 |
+
matmul_fuse_pattern_two,
|
| 187 |
+
matmul_replacement_two,
|
| 188 |
+
[val(), val(), val()],
|
| 189 |
+
fwd_only,
|
| 190 |
+
pass_patterns[0],
|
| 191 |
+
extra_check=check_concat_weights,
|
| 192 |
+
exclusive_arg_names=("w1", "w2"),
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
def addmm_fuse_pattern_second(inp, w1, w2, w3, b1, b2, b3):
|
| 196 |
+
return (
|
| 197 |
+
aten.addmm(b1, inp, w1),
|
| 198 |
+
aten.addmm(b2, inp, w2),
|
| 199 |
+
aten.addmm(b3, inp, w3),
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
def addmm_fuse_replacement_second(inp, w1, w2, w3, b1, b2, b3):
|
| 203 |
+
cat_w = torch.cat((w1, w2, w3), dim=1)
|
| 204 |
+
cat_b = torch.cat((b1, b2, b3))
|
| 205 |
+
return aten.addmm(cat_b, inp, cat_w).chunk(3, dim=1)
|
| 206 |
+
|
| 207 |
+
register_replacement(
|
| 208 |
+
addmm_fuse_pattern_second,
|
| 209 |
+
addmm_fuse_replacement_second,
|
| 210 |
+
[val() for _ in range(7)],
|
| 211 |
+
fwd_only,
|
| 212 |
+
pass_patterns[0],
|
| 213 |
+
extra_check=check_concat_weights,
|
| 214 |
+
exclusive_arg_names=("w1", "w2", "w3", "b1", "b2", "b3"),
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def same_dtype(match):
|
| 219 |
+
return match.output_node().args[0].meta["val"].dtype == match.kwargs["dtype"]
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@register_graph_pattern(
|
| 223 |
+
CallFunction(
|
| 224 |
+
torch.ops.prims.convert_element_type.default,
|
| 225 |
+
Ignored(),
|
| 226 |
+
KeywordArg("dtype"),
|
| 227 |
+
),
|
| 228 |
+
pass_dict=pass_patterns[0],
|
| 229 |
+
extra_check=same_dtype,
|
| 230 |
+
)
|
| 231 |
+
def unnecessary_dtype_convert(match: Match, **kwargs):
|
| 232 |
+
"""Remove unnecessary dtype conversion op, probably left as a result of Conv-Bn folding"""
|
| 233 |
+
graph = match.graph
|
| 234 |
+
node = match.output_node()
|
| 235 |
+
node.replace_all_uses_with(node.args[0]) # type: ignore[arg-type]
|
| 236 |
+
graph.erase_node(node)
|
shared/package-files/18/18d9eacb499beb23cc6b7ce9184cf3da9eaec58ed5b686cfb705226a585f6044/testutil.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.combinatorics import Permutation
|
| 2 |
+
from sympy.combinatorics.util import _distribute_gens_by_base
|
| 3 |
+
|
| 4 |
+
rmul = Permutation.rmul
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _cmp_perm_lists(first, second):
|
| 8 |
+
"""
|
| 9 |
+
Compare two lists of permutations as sets.
|
| 10 |
+
|
| 11 |
+
Explanation
|
| 12 |
+
===========
|
| 13 |
+
|
| 14 |
+
This is used for testing purposes. Since the array form of a
|
| 15 |
+
permutation is currently a list, Permutation is not hashable
|
| 16 |
+
and cannot be put into a set.
|
| 17 |
+
|
| 18 |
+
Examples
|
| 19 |
+
========
|
| 20 |
+
|
| 21 |
+
>>> from sympy.combinatorics.permutations import Permutation
|
| 22 |
+
>>> from sympy.combinatorics.testutil import _cmp_perm_lists
|
| 23 |
+
>>> a = Permutation([0, 2, 3, 4, 1])
|
| 24 |
+
>>> b = Permutation([1, 2, 0, 4, 3])
|
| 25 |
+
>>> c = Permutation([3, 4, 0, 1, 2])
|
| 26 |
+
>>> ls1 = [a, b, c]
|
| 27 |
+
>>> ls2 = [b, c, a]
|
| 28 |
+
>>> _cmp_perm_lists(ls1, ls2)
|
| 29 |
+
True
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
return {tuple(a) for a in first} == \
|
| 33 |
+
{tuple(a) for a in second}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _naive_list_centralizer(self, other, af=False):
|
| 37 |
+
from sympy.combinatorics.perm_groups import PermutationGroup
|
| 38 |
+
"""
|
| 39 |
+
Return a list of elements for the centralizer of a subgroup/set/element.
|
| 40 |
+
|
| 41 |
+
Explanation
|
| 42 |
+
===========
|
| 43 |
+
|
| 44 |
+
This is a brute force implementation that goes over all elements of the
|
| 45 |
+
group and checks for membership in the centralizer. It is used to
|
| 46 |
+
test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``.
|
| 47 |
+
|
| 48 |
+
Examples
|
| 49 |
+
========
|
| 50 |
+
|
| 51 |
+
>>> from sympy.combinatorics.testutil import _naive_list_centralizer
|
| 52 |
+
>>> from sympy.combinatorics.named_groups import DihedralGroup
|
| 53 |
+
>>> D = DihedralGroup(4)
|
| 54 |
+
>>> _naive_list_centralizer(D, D)
|
| 55 |
+
[Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])]
|
| 56 |
+
|
| 57 |
+
See Also
|
| 58 |
+
========
|
| 59 |
+
|
| 60 |
+
sympy.combinatorics.perm_groups.centralizer
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
from sympy.combinatorics.permutations import _af_commutes_with
|
| 64 |
+
if hasattr(other, 'generators'):
|
| 65 |
+
elements = list(self.generate_dimino(af=True))
|
| 66 |
+
gens = [x._array_form for x in other.generators]
|
| 67 |
+
commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens)
|
| 68 |
+
centralizer_list = []
|
| 69 |
+
if not af:
|
| 70 |
+
for element in elements:
|
| 71 |
+
if commutes_with_gens(element):
|
| 72 |
+
centralizer_list.append(Permutation._af_new(element))
|
| 73 |
+
else:
|
| 74 |
+
for element in elements:
|
| 75 |
+
if commutes_with_gens(element):
|
| 76 |
+
centralizer_list.append(element)
|
| 77 |
+
return centralizer_list
|
| 78 |
+
elif hasattr(other, 'getitem'):
|
| 79 |
+
return _naive_list_centralizer(self, PermutationGroup(other), af)
|
| 80 |
+
elif hasattr(other, 'array_form'):
|
| 81 |
+
return _naive_list_centralizer(self, PermutationGroup([other]), af)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _verify_bsgs(group, base, gens):
|
| 85 |
+
"""
|
| 86 |
+
Verify the correctness of a base and strong generating set.
|
| 87 |
+
|
| 88 |
+
Explanation
|
| 89 |
+
===========
|
| 90 |
+
|
| 91 |
+
This is a naive implementation using the definition of a base and a strong
|
| 92 |
+
generating set relative to it. There are other procedures for
|
| 93 |
+
verifying a base and strong generating set, but this one will
|
| 94 |
+
serve for more robust testing.
|
| 95 |
+
|
| 96 |
+
Examples
|
| 97 |
+
========
|
| 98 |
+
|
| 99 |
+
>>> from sympy.combinatorics.named_groups import AlternatingGroup
|
| 100 |
+
>>> from sympy.combinatorics.testutil import _verify_bsgs
|
| 101 |
+
>>> A = AlternatingGroup(4)
|
| 102 |
+
>>> A.schreier_sims()
|
| 103 |
+
>>> _verify_bsgs(A, A.base, A.strong_gens)
|
| 104 |
+
True
|
| 105 |
+
|
| 106 |
+
See Also
|
| 107 |
+
========
|
| 108 |
+
|
| 109 |
+
sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims
|
| 110 |
+
|
| 111 |
+
"""
|
| 112 |
+
from sympy.combinatorics.perm_groups import PermutationGroup
|
| 113 |
+
strong_gens_distr = _distribute_gens_by_base(base, gens)
|
| 114 |
+
current_stabilizer = group
|
| 115 |
+
for i in range(len(base)):
|
| 116 |
+
candidate = PermutationGroup(strong_gens_distr[i])
|
| 117 |
+
if current_stabilizer.order() != candidate.order():
|
| 118 |
+
return False
|
| 119 |
+
current_stabilizer = current_stabilizer.stabilizer(base[i])
|
| 120 |
+
if current_stabilizer.order() != 1:
|
| 121 |
+
return False
|
| 122 |
+
return True
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _verify_centralizer(group, arg, centr=None):
|
| 126 |
+
"""
|
| 127 |
+
Verify the centralizer of a group/set/element inside another group.
|
| 128 |
+
|
| 129 |
+
This is used for testing ``.centralizer()`` from
|
| 130 |
+
``sympy.combinatorics.perm_groups``
|
| 131 |
+
|
| 132 |
+
Examples
|
| 133 |
+
========
|
| 134 |
+
|
| 135 |
+
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
|
| 136 |
+
... AlternatingGroup)
|
| 137 |
+
>>> from sympy.combinatorics.perm_groups import PermutationGroup
|
| 138 |
+
>>> from sympy.combinatorics.permutations import Permutation
|
| 139 |
+
>>> from sympy.combinatorics.testutil import _verify_centralizer
|
| 140 |
+
>>> S = SymmetricGroup(5)
|
| 141 |
+
>>> A = AlternatingGroup(5)
|
| 142 |
+
>>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])])
|
| 143 |
+
>>> _verify_centralizer(S, A, centr)
|
| 144 |
+
True
|
| 145 |
+
|
| 146 |
+
See Also
|
| 147 |
+
========
|
| 148 |
+
|
| 149 |
+
_naive_list_centralizer,
|
| 150 |
+
sympy.combinatorics.perm_groups.PermutationGroup.centralizer,
|
| 151 |
+
_cmp_perm_lists
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
if centr is None:
|
| 155 |
+
centr = group.centralizer(arg)
|
| 156 |
+
centr_list = list(centr.generate_dimino(af=True))
|
| 157 |
+
centr_list_naive = _naive_list_centralizer(group, arg, af=True)
|
| 158 |
+
return _cmp_perm_lists(centr_list, centr_list_naive)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _verify_normal_closure(group, arg, closure=None):
|
| 162 |
+
from sympy.combinatorics.perm_groups import PermutationGroup
|
| 163 |
+
"""
|
| 164 |
+
Verify the normal closure of a subgroup/subset/element in a group.
|
| 165 |
+
|
| 166 |
+
This is used to test
|
| 167 |
+
sympy.combinatorics.perm_groups.PermutationGroup.normal_closure
|
| 168 |
+
|
| 169 |
+
Examples
|
| 170 |
+
========
|
| 171 |
+
|
| 172 |
+
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
|
| 173 |
+
... AlternatingGroup)
|
| 174 |
+
>>> from sympy.combinatorics.testutil import _verify_normal_closure
|
| 175 |
+
>>> S = SymmetricGroup(3)
|
| 176 |
+
>>> A = AlternatingGroup(3)
|
| 177 |
+
>>> _verify_normal_closure(S, A, closure=A)
|
| 178 |
+
True
|
| 179 |
+
|
| 180 |
+
See Also
|
| 181 |
+
========
|
| 182 |
+
|
| 183 |
+
sympy.combinatorics.perm_groups.PermutationGroup.normal_closure
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
if closure is None:
|
| 187 |
+
closure = group.normal_closure(arg)
|
| 188 |
+
conjugates = set()
|
| 189 |
+
if hasattr(arg, 'generators'):
|
| 190 |
+
subgr_gens = arg.generators
|
| 191 |
+
elif hasattr(arg, '__getitem__'):
|
| 192 |
+
subgr_gens = arg
|
| 193 |
+
elif hasattr(arg, 'array_form'):
|
| 194 |
+
subgr_gens = [arg]
|
| 195 |
+
for el in group.generate_dimino():
|
| 196 |
+
conjugates.update(gen ^ el for gen in subgr_gens)
|
| 197 |
+
naive_closure = PermutationGroup(list(conjugates))
|
| 198 |
+
return closure.is_subgroup(naive_closure)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def canonicalize_naive(g, dummies, sym, *v):
|
| 202 |
+
"""
|
| 203 |
+
Canonicalize tensor formed by tensors of the different types.
|
| 204 |
+
|
| 205 |
+
Explanation
|
| 206 |
+
===========
|
| 207 |
+
|
| 208 |
+
sym_i symmetry under exchange of two component tensors of type `i`
|
| 209 |
+
None no symmetry
|
| 210 |
+
0 commuting
|
| 211 |
+
1 anticommuting
|
| 212 |
+
|
| 213 |
+
Parameters
|
| 214 |
+
==========
|
| 215 |
+
|
| 216 |
+
g : Permutation representing the tensor.
|
| 217 |
+
dummies : List of dummy indices.
|
| 218 |
+
msym : Symmetry of the metric.
|
| 219 |
+
v : A list of (base_i, gens_i, n_i, sym_i) for tensors of type `i`.
|
| 220 |
+
base_i, gens_i BSGS for tensors of this type
|
| 221 |
+
n_i number of tensors of type `i`
|
| 222 |
+
|
| 223 |
+
Returns
|
| 224 |
+
=======
|
| 225 |
+
|
| 226 |
+
Returns 0 if the tensor is zero, else returns the array form of
|
| 227 |
+
the permutation representing the canonical form of the tensor.
|
| 228 |
+
|
| 229 |
+
Examples
|
| 230 |
+
========
|
| 231 |
+
|
| 232 |
+
>>> from sympy.combinatorics.testutil import canonicalize_naive
|
| 233 |
+
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs
|
| 234 |
+
>>> from sympy.combinatorics import Permutation
|
| 235 |
+
>>> g = Permutation([1, 3, 2, 0, 4, 5])
|
| 236 |
+
>>> base2, gens2 = get_symmetric_group_sgs(2)
|
| 237 |
+
>>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0))
|
| 238 |
+
[0, 2, 1, 3, 4, 5]
|
| 239 |
+
"""
|
| 240 |
+
from sympy.combinatorics.perm_groups import PermutationGroup
|
| 241 |
+
from sympy.combinatorics.tensor_can import gens_products, dummy_sgs
|
| 242 |
+
from sympy.combinatorics.permutations import _af_rmul
|
| 243 |
+
v1 = []
|
| 244 |
+
for i in range(len(v)):
|
| 245 |
+
base_i, gens_i, n_i, sym_i = v[i]
|
| 246 |
+
v1.append((base_i, gens_i, [[]]*n_i, sym_i))
|
| 247 |
+
size, sbase, sgens = gens_products(*v1)
|
| 248 |
+
dgens = dummy_sgs(dummies, sym, size-2)
|
| 249 |
+
if isinstance(sym, int):
|
| 250 |
+
num_types = 1
|
| 251 |
+
dummies = [dummies]
|
| 252 |
+
sym = [sym]
|
| 253 |
+
else:
|
| 254 |
+
num_types = len(sym)
|
| 255 |
+
dgens = []
|
| 256 |
+
for i in range(num_types):
|
| 257 |
+
dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2))
|
| 258 |
+
S = PermutationGroup(sgens)
|
| 259 |
+
D = PermutationGroup([Permutation(x) for x in dgens])
|
| 260 |
+
dlist = list(D.generate(af=True))
|
| 261 |
+
g = g.array_form
|
| 262 |
+
st = set()
|
| 263 |
+
for s in S.generate(af=True):
|
| 264 |
+
h = _af_rmul(g, s)
|
| 265 |
+
for d in dlist:
|
| 266 |
+
q = tuple(_af_rmul(d, h))
|
| 267 |
+
st.add(q)
|
| 268 |
+
a = list(st)
|
| 269 |
+
a.sort()
|
| 270 |
+
prev = (0,)*size
|
| 271 |
+
for h in a:
|
| 272 |
+
if h[:-2] == prev[:-2]:
|
| 273 |
+
if h[-1] != prev[-1]:
|
| 274 |
+
return 0
|
| 275 |
+
prev = h
|
| 276 |
+
return list(a[0])
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def graph_certificate(gr):
|
| 280 |
+
"""
|
| 281 |
+
Return a certificate for the graph
|
| 282 |
+
|
| 283 |
+
Parameters
|
| 284 |
+
==========
|
| 285 |
+
|
| 286 |
+
gr : adjacency list
|
| 287 |
+
|
| 288 |
+
Explanation
|
| 289 |
+
===========
|
| 290 |
+
|
| 291 |
+
The graph is assumed to be unoriented and without
|
| 292 |
+
external lines.
|
| 293 |
+
|
| 294 |
+
Associate to each vertex of the graph a symmetric tensor with
|
| 295 |
+
number of indices equal to the degree of the vertex; indices
|
| 296 |
+
are contracted when they correspond to the same line of the graph.
|
| 297 |
+
The canonical form of the tensor gives a certificate for the graph.
|
| 298 |
+
|
| 299 |
+
This is not an efficient algorithm to get the certificate of a graph.
|
| 300 |
+
|
| 301 |
+
Examples
|
| 302 |
+
========
|
| 303 |
+
|
| 304 |
+
>>> from sympy.combinatorics.testutil import graph_certificate
|
| 305 |
+
>>> 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]}
|
| 306 |
+
>>> 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]}
|
| 307 |
+
>>> c1 = graph_certificate(gr1)
|
| 308 |
+
>>> c2 = graph_certificate(gr2)
|
| 309 |
+
>>> c1
|
| 310 |
+
[0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21]
|
| 311 |
+
>>> c1 == c2
|
| 312 |
+
True
|
| 313 |
+
"""
|
| 314 |
+
from sympy.combinatorics.permutations import _af_invert
|
| 315 |
+
from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize
|
| 316 |
+
items = list(gr.items())
|
| 317 |
+
items.sort(key=lambda x: len(x[1]), reverse=True)
|
| 318 |
+
pvert = [x[0] for x in items]
|
| 319 |
+
pvert = _af_invert(pvert)
|
| 320 |
+
|
| 321 |
+
# the indices of the tensor are twice the number of lines of the graph
|
| 322 |
+
num_indices = 0
|
| 323 |
+
for v, neigh in items:
|
| 324 |
+
num_indices += len(neigh)
|
| 325 |
+
# associate to each vertex its indices; for each line
|
| 326 |
+
# between two vertices assign the
|
| 327 |
+
# even index to the vertex which comes first in items,
|
| 328 |
+
# the odd index to the other vertex
|
| 329 |
+
vertices = [[] for i in items]
|
| 330 |
+
i = 0
|
| 331 |
+
for v, neigh in items:
|
| 332 |
+
for v2 in neigh:
|
| 333 |
+
if pvert[v] < pvert[v2]:
|
| 334 |
+
vertices[pvert[v]].append(i)
|
| 335 |
+
vertices[pvert[v2]].append(i+1)
|
| 336 |
+
i += 2
|
| 337 |
+
g = []
|
| 338 |
+
for v in vertices:
|
| 339 |
+
g.extend(v)
|
| 340 |
+
assert len(g) == num_indices
|
| 341 |
+
g += [num_indices, num_indices + 1]
|
| 342 |
+
size = num_indices + 2
|
| 343 |
+
assert sorted(g) == list(range(size))
|
| 344 |
+
g = Permutation(g)
|
| 345 |
+
vlen = [0]*(len(vertices[0])+1)
|
| 346 |
+
for neigh in vertices:
|
| 347 |
+
vlen[len(neigh)] += 1
|
| 348 |
+
v = []
|
| 349 |
+
for i in range(len(vlen)):
|
| 350 |
+
n = vlen[i]
|
| 351 |
+
if n:
|
| 352 |
+
base, gens = get_symmetric_group_sgs(i)
|
| 353 |
+
v.append((base, gens, n, 0))
|
| 354 |
+
v.reverse()
|
| 355 |
+
dummies = list(range(num_indices))
|
| 356 |
+
can = canonicalize(g, dummies, 0, *v)
|
| 357 |
+
return can
|
shared/package-files/18/18fa735d24cc2205c4ac7ae5f696c3311396aa789cedfc5bd94046dcdc99e8c7/base.cpython-311.pyc
ADDED
|
Binary file (23.1 kB). View file
|
|
|
shared/package-files/1f/1f020c7c5914419cd809acc29f165377752a4226c2796c873cb925bd2b245651/sparse_mask_ops.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API sparse_mask {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::sparse_mask";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "sparse_mask(Tensor self, Tensor mask) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self, const at::Tensor & mask);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API sparse_mask_out {
|
| 30 |
+
using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::sparse_mask";
|
| 34 |
+
static constexpr const char* overload_name = "out";
|
| 35 |
+
static constexpr const char* schema_str = "sparse_mask.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!)";
|
| 36 |
+
static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out);
|
| 37 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, at::Tensor & out);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f09cbccf792216607230db0184b8b158c935cdabc76bd767749a0ed1a2f2017/topk_ops.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API topk_values {
|
| 19 |
+
using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, c10::SymInt, int64_t, bool, bool, at::Tensor &, at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::topk";
|
| 23 |
+
static constexpr const char* overload_name = "values";
|
| 24 |
+
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)";
|
| 25 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices);
|
| 26 |
+
static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted, at::Tensor & values, at::Tensor & indices);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API topk {
|
| 30 |
+
using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, c10::SymInt, int64_t, bool, bool);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::topk";
|
| 34 |
+
static constexpr const char* overload_name = "";
|
| 35 |
+
static constexpr const char* schema_str = "topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)";
|
| 36 |
+
static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted);
|
| 37 |
+
static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymInt k, int64_t dim, bool largest, bool sorted);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f0ea79d563a1c92738d97ec6d2864ef176324f73f9ebc151db2ecd3918c227e/common_op_utils.cpython-311.pyc
ADDED
|
Binary file (3.41 kB). View file
|
|
|
shared/package-files/1f/1f0ed3e5e6f1fcbfcda49fe73efd0fe8e0597846be9e19c52f47e1825d85fe9d/privateuse1_observer.h
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <torch/csrc/profiler/api.h>
|
| 3 |
+
|
| 4 |
+
namespace torch::profiler::impl {
|
| 5 |
+
|
| 6 |
+
using CallBackFnPtr = void (*)(
|
| 7 |
+
const ProfilerConfig& config,
|
| 8 |
+
const std::unordered_set<at::RecordScope>& scopes);
|
| 9 |
+
|
| 10 |
+
struct PushPRIVATEUSE1CallbacksStub {
|
| 11 |
+
PushPRIVATEUSE1CallbacksStub() = default;
|
| 12 |
+
PushPRIVATEUSE1CallbacksStub(const PushPRIVATEUSE1CallbacksStub&) = delete;
|
| 13 |
+
PushPRIVATEUSE1CallbacksStub& operator=(const PushPRIVATEUSE1CallbacksStub&) =
|
| 14 |
+
delete;
|
| 15 |
+
PushPRIVATEUSE1CallbacksStub(PushPRIVATEUSE1CallbacksStub&&) = default;
|
| 16 |
+
PushPRIVATEUSE1CallbacksStub& operator=(PushPRIVATEUSE1CallbacksStub&&) =
|
| 17 |
+
default;
|
| 18 |
+
~PushPRIVATEUSE1CallbacksStub() = default;
|
| 19 |
+
|
| 20 |
+
template <typename... ArgTypes>
|
| 21 |
+
void operator()(ArgTypes&&... args) {
|
| 22 |
+
return (*push_privateuse1_callbacks_fn)(std::forward<ArgTypes>(args)...);
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
void set_privateuse1_dispatch_ptr(CallBackFnPtr fn_ptr) {
|
| 26 |
+
push_privateuse1_callbacks_fn = fn_ptr;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
private:
|
| 30 |
+
CallBackFnPtr push_privateuse1_callbacks_fn = nullptr;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
extern TORCH_API struct PushPRIVATEUSE1CallbacksStub
|
| 34 |
+
pushPRIVATEUSE1CallbacksStub;
|
| 35 |
+
|
| 36 |
+
struct RegisterPRIVATEUSE1Observer {
|
| 37 |
+
RegisterPRIVATEUSE1Observer(
|
| 38 |
+
PushPRIVATEUSE1CallbacksStub& stub,
|
| 39 |
+
CallBackFnPtr value) {
|
| 40 |
+
stub.set_privateuse1_dispatch_ptr(value);
|
| 41 |
+
}
|
| 42 |
+
};
|
| 43 |
+
|
| 44 |
+
#define REGISTER_PRIVATEUSE1_OBSERVER(name, fn) \
|
| 45 |
+
static RegisterPRIVATEUSE1Observer name##__register(name, fn);
|
| 46 |
+
} // namespace torch::profiler::impl
|
shared/package-files/1f/1f127a18859cddbeae01958d878e6878f5e540b01d5fd2a6bb73c1c803af961e/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
:mod:`torch.distributed.optim` exposes DistributedOptimizer, which takes a list
|
| 3 |
+
of remote parameters (:class:`~torch.distributed.rpc.RRef`) and runs the
|
| 4 |
+
optimizer locally on the workers where the parameters live. The distributed
|
| 5 |
+
optimizer can use any of the local optimizer :ref:`optimizer-algorithms` to
|
| 6 |
+
apply the gradients on each worker.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import optim
|
| 13 |
+
|
| 14 |
+
from .apply_optimizer_in_backward import (
|
| 15 |
+
_apply_optimizer_in_backward,
|
| 16 |
+
_get_in_backward_optimizers,
|
| 17 |
+
)
|
| 18 |
+
from .functional_adadelta import _FunctionalAdadelta
|
| 19 |
+
from .functional_adagrad import _FunctionalAdagrad
|
| 20 |
+
from .functional_adam import _FunctionalAdam
|
| 21 |
+
from .functional_adamax import _FunctionalAdamax
|
| 22 |
+
from .functional_adamw import _FunctionalAdamW
|
| 23 |
+
from .functional_rmsprop import _FunctionalRMSprop
|
| 24 |
+
from .functional_rprop import _FunctionalRprop
|
| 25 |
+
from .functional_sgd import _FunctionalSGD
|
| 26 |
+
from .named_optimizer import _NamedOptimizer
|
| 27 |
+
from .utils import as_functional_optim
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# DistributedOptimizer imports torch.distributed.rpc names, so gate availability
|
| 31 |
+
# based on RPC being available.
|
| 32 |
+
if hasattr(torch._C, "_rpc_init"):
|
| 33 |
+
from .optimizer import DistributedOptimizer
|
| 34 |
+
|
| 35 |
+
from .post_localSGD_optimizer import PostLocalSGDOptimizer
|
| 36 |
+
from .zero_redundancy_optimizer import ZeroRedundancyOptimizer
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
__all__ = [
|
| 40 |
+
"as_functional_optim",
|
| 41 |
+
"DistributedOptimizer",
|
| 42 |
+
"PostLocalSGDOptimizer",
|
| 43 |
+
"ZeroRedundancyOptimizer",
|
| 44 |
+
]
|
shared/package-files/1f/1f135a9505b4371e447fe966c6d681fb6101e8ee951615f1319ede909c195728/digraph.cpython-311.pyc
ADDED
|
Binary file (55.4 kB). View file
|
|
|
shared/package-files/1f/1f141c8a5056c8578fd07d521b52006d28eed0e71aba4b4bdcdef6aedb5e11c3/graph_utils.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/jit/ir/ir.h>
|
| 4 |
+
|
| 5 |
+
#include <vector>
|
| 6 |
+
|
| 7 |
+
namespace torch::jit {
|
| 8 |
+
|
| 9 |
+
TORCH_API TypePtr getTensorType(const at::Tensor& t, bool complete);
|
| 10 |
+
|
| 11 |
+
TORCH_API TypePtr inferShapeAndTypeForInput(
|
| 12 |
+
TypePtr input_type,
|
| 13 |
+
Stack::const_iterator& s_iter,
|
| 14 |
+
const Stack::const_iterator& s_iter_end,
|
| 15 |
+
bool complete);
|
| 16 |
+
|
| 17 |
+
TORCH_API void setInputTensorTypes(
|
| 18 |
+
Graph& g,
|
| 19 |
+
const Stack& stack,
|
| 20 |
+
bool complete,
|
| 21 |
+
const std::vector<int>& param_count_list = {});
|
| 22 |
+
|
| 23 |
+
} // namespace torch::jit
|
shared/package-files/1f/1f150d886687fb5e2cf3f5d6c194e760a81f59b3bf615bc9f5c410b81e14339d/bilinear_compositeimplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor bilinear(const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={});
|
| 21 |
+
|
| 22 |
+
} // namespace compositeimplicitautograd
|
| 23 |
+
} // namespace at
|
shared/package-files/1f/1f167188f79a88bbf5d12ee265a5ab3ee2f0dbcb9cc2402f6ec107b9a1699fa1/max_pool3d_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API max_pool3d {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::max_pool3d";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
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";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode);
|
| 26 |
+
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);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f18dce117e0cdaa54300973757689ec906060def79a91580c672507323ee435/_batch_norm_no_update_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _batch_norm_no_update(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum, double eps);
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _batch_norm_no_update_out(const at::Tensor & input, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & bias, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
shared/package-files/1f/1f2c567ff74b7c1346c7b73e6210d45487fd3323c85bc4f34e34786a05e2adad/mish_ops.h
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API mish {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::mish";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "mish(Tensor self) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
struct TORCH_API mish_ {
|
| 30 |
+
using schema = at::Tensor & (at::Tensor &);
|
| 31 |
+
using ptr_schema = schema*;
|
| 32 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 33 |
+
static constexpr const char* name = "aten::mish_";
|
| 34 |
+
static constexpr const char* overload_name = "";
|
| 35 |
+
static constexpr const char* schema_str = "mish_(Tensor(a!) self) -> Tensor(a!)";
|
| 36 |
+
static at::Tensor & call(at::Tensor & self);
|
| 37 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self);
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
struct TORCH_API mish_out {
|
| 41 |
+
using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
|
| 42 |
+
using ptr_schema = schema*;
|
| 43 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 44 |
+
static constexpr const char* name = "aten::mish";
|
| 45 |
+
static constexpr const char* overload_name = "out";
|
| 46 |
+
static constexpr const char* schema_str = "mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)";
|
| 47 |
+
static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
|
| 48 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f393973c495fa46e0e3bc0128b8b46077f582b0eec93a7a63ecd2e45109a527/random_matrix_models.cpython-311.pyc
ADDED
|
Binary file (25.7 kB). View file
|
|
|
shared/package-files/1f/1f40839461404ba18def05e0f92f5ae2653720a209bddd9942bcb1a56cc2e511/margin_ranking_loss_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API margin_ranking_loss {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, double, int64_t);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::margin_ranking_loss";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
static constexpr const char* schema_str = "margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor";
|
| 25 |
+
static at::Tensor call(const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & target, double margin, int64_t reduction);
|
| 26 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input1, const at::Tensor & input2, const at::Tensor & target, double margin, int64_t reduction);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f40c65df3feb76ad084f1011fce46f4049bf92dcbff011e318bb0c466fbe346/rocm_kernel.cpython-311.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
shared/package-files/1f/1f44d7c30f0c69746d384a26a3e1e7e35123f7ac4aff623eb71c6a0ff0f49bbb/sym_size_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <optional>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API c10::SymInt sym_size(const at::Tensor & self, int64_t dim);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/1f/1f4ccd493605c7b86f59ea081e80d2e3bdb4da7ec978c5c86d220be278cefb1c/utils.cpython-311.pyc
ADDED
|
Binary file (2.67 kB). View file
|
|
|
shared/package-files/1f/1f4e913f22201e2bfcbce280e625a9c162d16be13f68dd299b6e02d7ecd351d6/max_pool1d_ops.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <string_view>
|
| 6 |
+
#include <tuple>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 10 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 11 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 12 |
+
#include <ATen/core/ATen_fwd.h>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
namespace _ops {
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
struct TORCH_API max_pool1d {
|
| 19 |
+
using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool);
|
| 20 |
+
using ptr_schema = schema*;
|
| 21 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 22 |
+
static constexpr const char* name = "aten::max_pool1d";
|
| 23 |
+
static constexpr const char* overload_name = "";
|
| 24 |
+
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";
|
| 25 |
+
static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode);
|
| 26 |
+
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);
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
}} // namespace at::_ops
|
shared/package-files/1f/1f5065576692ea166941002500e21d1f951debccdac934079dd0c4d3e12890ff/_values_copy.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/_values_copy_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::_values_copy(Tensor self) -> Tensor
|
| 27 |
+
inline at::Tensor _values_copy(const at::Tensor & self) {
|
| 28 |
+
return at::_ops::_values_copy::call(self);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// aten::_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 32 |
+
inline at::Tensor & _values_copy_out(at::Tensor & out, const at::Tensor & self) {
|
| 33 |
+
return at::_ops::_values_copy_out::call(self, out);
|
| 34 |
+
}
|
| 35 |
+
// aten::_values_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
|
| 36 |
+
inline at::Tensor & _values_copy_outf(const at::Tensor & self, at::Tensor & out) {
|
| 37 |
+
return at::_ops::_values_copy_out::call(self, out);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/1f/1f5661ce49b51b7bf60235879541d756f2ccc241416a71e4a5a741ed042db8f3/decompose_mem_bound_mm.cpython-311.pyc
ADDED
|
Binary file (8.86 kB). View file
|
|
|
shared/package-files/1f/1f5a43dd31e0534906cd2383887121435b94aee8666217e980f77f23b92a85fe/uniform.h
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <optional>
|
| 17 |
+
#include <string_view>
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#include <ATen/ops/uniform_ops.h>
|
| 22 |
+
|
| 23 |
+
namespace at {
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
// aten::uniform.out(Tensor self, float from=0, float to=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
|
| 27 |
+
inline at::Tensor & uniform_out(at::Tensor & out, const at::Tensor & self, double from=0, double to=1, ::std::optional<at::Generator> generator=::std::nullopt) {
|
| 28 |
+
return at::_ops::uniform_out::call(self, from, to, generator, out);
|
| 29 |
+
}
|
| 30 |
+
// aten::uniform.out(Tensor self, float from=0, float to=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
|
| 31 |
+
inline at::Tensor & uniform_outf(const at::Tensor & self, double from, double to, ::std::optional<at::Generator> generator, at::Tensor & out) {
|
| 32 |
+
return at::_ops::uniform_out::call(self, from, to, generator, out);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::uniform(Tensor self, float from=0, float to=1, *, Generator? generator=None) -> Tensor
|
| 36 |
+
inline at::Tensor uniform(const at::Tensor & self, double from=0, double to=1, ::std::optional<at::Generator> generator=::std::nullopt) {
|
| 37 |
+
return at::_ops::uniform::call(self, from, to, generator);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
}
|
shared/package-files/1f/1f5c7ca99426aa0460f84d3a03f7d4a049b843f5e9f1c56052c2078bb43fe6bb/_entry_points.cpython-311.pyc
ADDED
|
Binary file (5.13 kB). View file
|
|
|
shared/package-files/1f/1f5dcb75e3d3b2bede49e0aba78bf5dcbed3dd810ab1011c9d342fbc3f566d50/quasirandom.py
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SobolEngine:
|
| 8 |
+
r"""
|
| 9 |
+
The :class:`torch.quasirandom.SobolEngine` is an engine for generating
|
| 10 |
+
(scrambled) Sobol sequences. Sobol sequences are an example of low
|
| 11 |
+
discrepancy quasi-random sequences.
|
| 12 |
+
|
| 13 |
+
This implementation of an engine for Sobol sequences is capable of
|
| 14 |
+
sampling sequences up to a maximum dimension of 21201. It uses direction
|
| 15 |
+
numbers from https://web.maths.unsw.edu.au/~fkuo/sobol/ obtained using the
|
| 16 |
+
search criterion D(6) up to the dimension 21201. This is the recommended
|
| 17 |
+
choice by the authors.
|
| 18 |
+
|
| 19 |
+
References:
|
| 20 |
+
- Art B. Owen. Scrambling Sobol and Niederreiter-Xing points.
|
| 21 |
+
Journal of Complexity, 14(4):466-489, December 1998.
|
| 22 |
+
|
| 23 |
+
- I. M. Sobol. The distribution of points in a cube and the accurate
|
| 24 |
+
evaluation of integrals.
|
| 25 |
+
Zh. Vychisl. Mat. i Mat. Phys., 7:784-802, 1967.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
dimension (Int): The dimensionality of the sequence to be drawn
|
| 29 |
+
scramble (bool, optional): Setting this to ``True`` will produce
|
| 30 |
+
scrambled Sobol sequences. Scrambling is
|
| 31 |
+
capable of producing better Sobol
|
| 32 |
+
sequences. Default: ``False``.
|
| 33 |
+
seed (Int, optional): This is the seed for the scrambling. The seed
|
| 34 |
+
of the random number generator is set to this,
|
| 35 |
+
if specified. Otherwise, it uses a random seed.
|
| 36 |
+
Default: ``None``
|
| 37 |
+
|
| 38 |
+
Examples::
|
| 39 |
+
|
| 40 |
+
>>> # xdoctest: +SKIP("unseeded random state")
|
| 41 |
+
>>> soboleng = torch.quasirandom.SobolEngine(dimension=5)
|
| 42 |
+
>>> soboleng.draw(3)
|
| 43 |
+
tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 44 |
+
[0.5000, 0.5000, 0.5000, 0.5000, 0.5000],
|
| 45 |
+
[0.7500, 0.2500, 0.2500, 0.2500, 0.7500]])
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
MAXBIT = 30
|
| 49 |
+
MAXDIM = 21201
|
| 50 |
+
|
| 51 |
+
def __init__(self, dimension, scramble=False, seed=None):
|
| 52 |
+
if dimension > self.MAXDIM or dimension < 1:
|
| 53 |
+
raise ValueError(
|
| 54 |
+
"Supported range of dimensionality "
|
| 55 |
+
f"for SobolEngine is [1, {self.MAXDIM}]"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
self.seed = seed
|
| 59 |
+
self.scramble = scramble
|
| 60 |
+
self.dimension = dimension
|
| 61 |
+
|
| 62 |
+
cpu = torch.device("cpu")
|
| 63 |
+
|
| 64 |
+
self.sobolstate = torch.zeros(
|
| 65 |
+
dimension, self.MAXBIT, device=cpu, dtype=torch.long
|
| 66 |
+
)
|
| 67 |
+
torch._sobol_engine_initialize_state_(self.sobolstate, self.dimension)
|
| 68 |
+
|
| 69 |
+
if not self.scramble:
|
| 70 |
+
self.shift = torch.zeros(self.dimension, device=cpu, dtype=torch.long)
|
| 71 |
+
else:
|
| 72 |
+
self._scramble()
|
| 73 |
+
|
| 74 |
+
self.quasi = self.shift.clone(memory_format=torch.contiguous_format)
|
| 75 |
+
self._first_point = (self.quasi / 2**self.MAXBIT).reshape(1, -1)
|
| 76 |
+
self.num_generated = 0
|
| 77 |
+
|
| 78 |
+
def draw(
|
| 79 |
+
self,
|
| 80 |
+
n: int = 1,
|
| 81 |
+
out: Optional[torch.Tensor] = None,
|
| 82 |
+
dtype: Optional[torch.dtype] = None,
|
| 83 |
+
) -> torch.Tensor:
|
| 84 |
+
r"""
|
| 85 |
+
Function to draw a sequence of :attr:`n` points from a Sobol sequence.
|
| 86 |
+
Note that the samples are dependent on the previous samples. The size
|
| 87 |
+
of the result is :math:`(n, dimension)`.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
n (Int, optional): The length of sequence of points to draw.
|
| 91 |
+
Default: 1
|
| 92 |
+
out (Tensor, optional): The output tensor
|
| 93 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of the
|
| 94 |
+
returned tensor.
|
| 95 |
+
Default: ``None``
|
| 96 |
+
"""
|
| 97 |
+
if dtype is None:
|
| 98 |
+
dtype = torch.get_default_dtype()
|
| 99 |
+
|
| 100 |
+
if self.num_generated == 0:
|
| 101 |
+
if n == 1:
|
| 102 |
+
result = self._first_point.to(dtype)
|
| 103 |
+
else:
|
| 104 |
+
result, self.quasi = torch._sobol_engine_draw(
|
| 105 |
+
self.quasi,
|
| 106 |
+
n - 1,
|
| 107 |
+
self.sobolstate,
|
| 108 |
+
self.dimension,
|
| 109 |
+
self.num_generated,
|
| 110 |
+
dtype=dtype,
|
| 111 |
+
)
|
| 112 |
+
result = torch.cat((self._first_point.to(dtype), result), dim=-2)
|
| 113 |
+
else:
|
| 114 |
+
result, self.quasi = torch._sobol_engine_draw(
|
| 115 |
+
self.quasi,
|
| 116 |
+
n,
|
| 117 |
+
self.sobolstate,
|
| 118 |
+
self.dimension,
|
| 119 |
+
self.num_generated - 1,
|
| 120 |
+
dtype=dtype,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
self.num_generated += n
|
| 124 |
+
|
| 125 |
+
if out is not None:
|
| 126 |
+
out.resize_as_(result).copy_(result)
|
| 127 |
+
return out
|
| 128 |
+
|
| 129 |
+
return result
|
| 130 |
+
|
| 131 |
+
def draw_base2(
|
| 132 |
+
self,
|
| 133 |
+
m: int,
|
| 134 |
+
out: Optional[torch.Tensor] = None,
|
| 135 |
+
dtype: Optional[torch.dtype] = None,
|
| 136 |
+
) -> torch.Tensor:
|
| 137 |
+
r"""
|
| 138 |
+
Function to draw a sequence of :attr:`2**m` points from a Sobol sequence.
|
| 139 |
+
Note that the samples are dependent on the previous samples. The size
|
| 140 |
+
of the result is :math:`(2**m, dimension)`.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
m (Int): The (base2) exponent of the number of points to draw.
|
| 144 |
+
out (Tensor, optional): The output tensor
|
| 145 |
+
dtype (:class:`torch.dtype`, optional): the desired data type of the
|
| 146 |
+
returned tensor.
|
| 147 |
+
Default: ``None``
|
| 148 |
+
"""
|
| 149 |
+
n = 2**m
|
| 150 |
+
total_n = self.num_generated + n
|
| 151 |
+
if not (total_n & (total_n - 1) == 0):
|
| 152 |
+
raise ValueError(
|
| 153 |
+
"The balance properties of Sobol' points require "
|
| 154 |
+
f"n to be a power of 2. {self.num_generated} points have been "
|
| 155 |
+
f"previously generated, then: n={self.num_generated}+2**{m}={total_n}. "
|
| 156 |
+
"If you still want to do this, please use "
|
| 157 |
+
"'SobolEngine.draw()' instead."
|
| 158 |
+
)
|
| 159 |
+
return self.draw(n=n, out=out, dtype=dtype)
|
| 160 |
+
|
| 161 |
+
def reset(self):
|
| 162 |
+
r"""
|
| 163 |
+
Function to reset the ``SobolEngine`` to base state.
|
| 164 |
+
"""
|
| 165 |
+
self.quasi.copy_(self.shift)
|
| 166 |
+
self.num_generated = 0
|
| 167 |
+
return self
|
| 168 |
+
|
| 169 |
+
def fast_forward(self, n):
|
| 170 |
+
r"""
|
| 171 |
+
Function to fast-forward the state of the ``SobolEngine`` by
|
| 172 |
+
:attr:`n` steps. This is equivalent to drawing :attr:`n` samples
|
| 173 |
+
without using the samples.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
n (Int): The number of steps to fast-forward by.
|
| 177 |
+
"""
|
| 178 |
+
if self.num_generated == 0:
|
| 179 |
+
torch._sobol_engine_ff_(
|
| 180 |
+
self.quasi, n - 1, self.sobolstate, self.dimension, self.num_generated
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
torch._sobol_engine_ff_(
|
| 184 |
+
self.quasi, n, self.sobolstate, self.dimension, self.num_generated - 1
|
| 185 |
+
)
|
| 186 |
+
self.num_generated += n
|
| 187 |
+
return self
|
| 188 |
+
|
| 189 |
+
def _scramble(self):
|
| 190 |
+
g: Optional[torch.Generator] = None
|
| 191 |
+
if self.seed is not None:
|
| 192 |
+
g = torch.Generator()
|
| 193 |
+
g.manual_seed(self.seed)
|
| 194 |
+
|
| 195 |
+
cpu = torch.device("cpu")
|
| 196 |
+
|
| 197 |
+
# Generate shift vector
|
| 198 |
+
shift_ints = torch.randint(
|
| 199 |
+
2, (self.dimension, self.MAXBIT), device=cpu, generator=g
|
| 200 |
+
)
|
| 201 |
+
self.shift = torch.mv(
|
| 202 |
+
shift_ints, torch.pow(2, torch.arange(0, self.MAXBIT, device=cpu))
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Generate lower triangular matrices (stacked across dimensions)
|
| 206 |
+
ltm_dims = (self.dimension, self.MAXBIT, self.MAXBIT)
|
| 207 |
+
ltm = torch.randint(2, ltm_dims, device=cpu, generator=g).tril()
|
| 208 |
+
|
| 209 |
+
torch._sobol_engine_scramble_(self.sobolstate, ltm, self.dimension)
|
| 210 |
+
|
| 211 |
+
def __repr__(self):
|
| 212 |
+
fmt_string = [f"dimension={self.dimension}"]
|
| 213 |
+
if self.scramble:
|
| 214 |
+
fmt_string += ["scramble=True"]
|
| 215 |
+
if self.seed is not None:
|
| 216 |
+
fmt_string += [f"seed={self.seed}"]
|
| 217 |
+
return self.__class__.__name__ + "(" + ", ".join(fmt_string) + ")"
|
shared/package-files/1f/1f5ef44e371999fc2d2c3e17ee0ed00d82bda1594ea98c98e8f9e68cb8e3bdc3/test_codegen_julia.cpython-311.pyc
ADDED
|
Binary file (25.7 kB). View file
|
|
|
shared/package-files/1f/1f5fc20bebef01a4b6eb2b385ec4c590c813c544dc8808dd8ecc238b3922b2f4/device_launch_parameters.h
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* Copyright 1993-2012 NVIDIA Corporation. All rights reserved.
|
| 3 |
+
*
|
| 4 |
+
* NOTICE TO LICENSEE:
|
| 5 |
+
*
|
| 6 |
+
* This source code and/or documentation ("Licensed Deliverables") are
|
| 7 |
+
* subject to NVIDIA intellectual property rights under U.S. and
|
| 8 |
+
* international Copyright laws.
|
| 9 |
+
*
|
| 10 |
+
* These Licensed Deliverables contained herein is PROPRIETARY and
|
| 11 |
+
* CONFIDENTIAL to NVIDIA and is being provided under the terms and
|
| 12 |
+
* conditions of a form of NVIDIA software license agreement by and
|
| 13 |
+
* between NVIDIA and Licensee ("License Agreement") or electronically
|
| 14 |
+
* accepted by Licensee. Notwithstanding any terms or conditions to
|
| 15 |
+
* the contrary in the License Agreement, reproduction or disclosure
|
| 16 |
+
* of the Licensed Deliverables to any third party without the express
|
| 17 |
+
* written consent of NVIDIA is prohibited.
|
| 18 |
+
*
|
| 19 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 20 |
+
* LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
|
| 21 |
+
* SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS
|
| 22 |
+
* PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
|
| 23 |
+
* NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
|
| 24 |
+
* DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
|
| 25 |
+
* NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
|
| 26 |
+
* NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
|
| 27 |
+
* LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
|
| 28 |
+
* SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
|
| 29 |
+
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 30 |
+
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 31 |
+
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 32 |
+
* OF THESE LICENSED DELIVERABLES.
|
| 33 |
+
*
|
| 34 |
+
* U.S. Government End Users. These Licensed Deliverables are a
|
| 35 |
+
* "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
|
| 36 |
+
* 1995), consisting of "commercial computer software" and "commercial
|
| 37 |
+
* computer software documentation" as such terms are used in 48
|
| 38 |
+
* C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
|
| 39 |
+
* only as a commercial end item. Consistent with 48 C.F.R.12.212 and
|
| 40 |
+
* 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
|
| 41 |
+
* U.S. Government End Users acquire the Licensed Deliverables with
|
| 42 |
+
* only those rights set forth herein.
|
| 43 |
+
*
|
| 44 |
+
* Any use of the Licensed Deliverables in individual and commercial
|
| 45 |
+
* software must include, in the user documentation and internal
|
| 46 |
+
* comments to the code, the above Disclaimer and U.S. Government End
|
| 47 |
+
* Users Notice.
|
| 48 |
+
*/
|
| 49 |
+
|
| 50 |
+
#if !defined(__DEVICE_LAUNCH_PARAMETERS_H__)
|
| 51 |
+
#define __DEVICE_LAUNCH_PARAMETERS_H__
|
| 52 |
+
|
| 53 |
+
#include "vector_types.h"
|
| 54 |
+
|
| 55 |
+
#if !defined(__STORAGE__)
|
| 56 |
+
|
| 57 |
+
#if defined(__CUDACC_RTC__)
|
| 58 |
+
#define __STORAGE__ \
|
| 59 |
+
extern const __device__
|
| 60 |
+
#else /* !__CUDACC_RTC__ */
|
| 61 |
+
#define __STORAGE__ \
|
| 62 |
+
extern const
|
| 63 |
+
#endif /* __CUDACC_RTC__ */
|
| 64 |
+
|
| 65 |
+
#endif /* __STORAGE__ */
|
| 66 |
+
|
| 67 |
+
#if defined(__cplusplus)
|
| 68 |
+
extern "C" {
|
| 69 |
+
#endif /* __cplusplus */
|
| 70 |
+
|
| 71 |
+
uint3 __device_builtin__ __STORAGE__ threadIdx;
|
| 72 |
+
uint3 __device_builtin__ __STORAGE__ blockIdx;
|
| 73 |
+
dim3 __device_builtin__ __STORAGE__ blockDim;
|
| 74 |
+
dim3 __device_builtin__ __STORAGE__ gridDim;
|
| 75 |
+
int __device_builtin__ __STORAGE__ warpSize;
|
| 76 |
+
|
| 77 |
+
#undef __STORAGE__
|
| 78 |
+
|
| 79 |
+
#if defined(__cplusplus)
|
| 80 |
+
}
|
| 81 |
+
#endif /* __cplusplus */
|
| 82 |
+
|
| 83 |
+
#if !defined(__cudaGet_threadIdx)
|
| 84 |
+
|
| 85 |
+
#define __cudaGet_threadIdx() \
|
| 86 |
+
threadIdx
|
| 87 |
+
|
| 88 |
+
#endif /* __cudaGet_threadIdx */
|
| 89 |
+
|
| 90 |
+
#if !defined(__cudaGet_blockIdx)
|
| 91 |
+
|
| 92 |
+
#define __cudaGet_blockIdx() \
|
| 93 |
+
blockIdx
|
| 94 |
+
|
| 95 |
+
#endif /* __cudaGet_blockIdx */
|
| 96 |
+
|
| 97 |
+
#if !defined(__cudaGet_blockDim)
|
| 98 |
+
|
| 99 |
+
#define __cudaGet_blockDim() \
|
| 100 |
+
blockDim
|
| 101 |
+
|
| 102 |
+
#endif /* __cudaGet_blockDim */
|
| 103 |
+
|
| 104 |
+
#if !defined(__cudaGet_gridDim)
|
| 105 |
+
|
| 106 |
+
#define __cudaGet_gridDim() \
|
| 107 |
+
gridDim
|
| 108 |
+
|
| 109 |
+
#endif /* __cudaGet_gridDim */
|
| 110 |
+
|
| 111 |
+
#if !defined(__cudaGet_warpSize)
|
| 112 |
+
|
| 113 |
+
#define __cudaGet_warpSize() \
|
| 114 |
+
warpSize
|
| 115 |
+
|
| 116 |
+
#endif /* __cudaGet_warpSize */
|
| 117 |
+
|
| 118 |
+
#endif /* !__DEVICE_LAUNCH_PARAMETERS_H__ */
|
shared/package-files/1f/1f636095668cdc0d645d1b201b5ab162d54c4195d3253fd18853152e5f66c6f0/custom_ops.cpython-311.pyc
ADDED
|
Binary file (7.52 kB). View file
|
|
|
shared/package-files/1f/1f68d9683b0327f8bd1f64b05a9c2e15e97c06b67dc472aebe1f83400596f654/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[networkx.backends]
|
| 2 |
+
nx_loopback = networkx.classes.tests.dispatch_interface:backend_interface
|