diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index 6ceca297be3d..a2050013f9e3 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -434,7 +434,8 @@ set(ARROW_SRCS type_traits.cc visitor.cc c/bridge.cc - c/dlpack.cc) + c/dlpack.cc + testing/random.cc) arrow_add_object_library(ARROW_ARRAY array/array_base.cc @@ -737,7 +738,6 @@ set(ARROW_TESTING_SRCS testing/gtest_util.cc testing/math.cc testing/process.cc - testing/random.cc testing/util.cc) # diff --git a/cpp/src/arrow/meson.build b/cpp/src/arrow/meson.build index ae77a3d99e21..57edffd17395 100644 --- a/cpp/src/arrow/meson.build +++ b/cpp/src/arrow/meson.build @@ -159,6 +159,7 @@ arrow_components = { 'visitor.cc', 'c/bridge.cc', 'c/dlpack.cc', + 'testing/random.cc', ], }, } @@ -311,7 +312,6 @@ arrow_testing_srcs = [ 'testing/gtest_util.cc', 'testing/math.cc', 'testing/process.cc', - 'testing/random.cc', 'testing/util.cc', ] diff --git a/cpp/src/arrow/testing/random.cc b/cpp/src/arrow/testing/random.cc index db7a60e4400f..85b1fcb223ce 100644 --- a/cpp/src/arrow/testing/random.cc +++ b/cpp/src/arrow/testing/random.cc @@ -17,8 +17,6 @@ #include "arrow/testing/random.h" -#include - #include #include #include @@ -35,7 +33,6 @@ #include "arrow/buffer.h" #include "arrow/extension_type.h" #include "arrow/record_batch.h" -#include "arrow/testing/gtest_util.h" #include "arrow/type.h" #include "arrow/type_fwd.h" #include "arrow/type_traits.h" @@ -364,7 +361,7 @@ struct DecimalGenerator { // Second compute decimal values from the individual components, // building up a decimal array. DecimalBuilderType builder(type_, memory_pool, alignment); - ABORT_NOT_OK(builder.Reserve(size)); + ARROW_CHECK_OK(builder.Reserve(size)); const DecimalValue kDigitsMultiplier = DecimalValue::GetScaleMultiplier(kMaxDigitsInInteger); @@ -386,7 +383,7 @@ struct DecimalGenerator { } } std::shared_ptr array; - ABORT_NOT_OK(builder.Finish(&array)); + ARROW_CHECK_OK(builder.Finish(&array)); return array; } }; @@ -473,7 +470,7 @@ static std::shared_ptr GenerateBinaryArray( using OffsetArrayType = typename TypeTraits::ArrayType; if (null_probability < 0 || null_probability > 1) { - ABORT_NOT_OK(Status::Invalid("null_probability must be between 0 and 1")); + ARROW_CHECK_OK(Status::Invalid("null_probability must be between 0 and 1")); } auto lengths = std::dynamic_pointer_cast(gen->Numeric( @@ -495,14 +492,14 @@ static std::shared_ptr GenerateBinaryArray( for (int64_t i = 0; i < size; ++i) { if (lengths->IsValid(i)) { options.GenerateData(str_buffer.data(), lengths->Value(i)); - ABORT_NOT_OK(builder.Append(str_buffer.data(), lengths->Value(i))); + ARROW_CHECK_OK(builder.Append(str_buffer.data(), lengths->Value(i))); } else { - ABORT_NOT_OK(builder.AppendNull()); + ARROW_CHECK_OK(builder.AppendNull()); } } std::shared_ptr result; - ABORT_NOT_OK(builder.Finish(&result)); + ARROW_CHECK_OK(builder.Finish(&result)); return result; } @@ -562,14 +559,14 @@ std::shared_ptr RandomArrayGenerator::StringWithRepeats( if (indices->IsValid(i)) { const auto index = indices->Value(i); const auto value = dictionary->GetView(index); - ABORT_NOT_OK(builder.Append(value)); + ARROW_CHECK_OK(builder.Append(value)); } else { - ABORT_NOT_OK(builder.AppendNull()); + ARROW_CHECK_OK(builder.AppendNull()); } } std::shared_ptr result; - ABORT_NOT_OK(builder.Finish(&result)); + ARROW_CHECK_OK(builder.Finish(&result)); return result; } @@ -577,7 +574,7 @@ std::shared_ptr RandomArrayGenerator::FixedSizeBinary( int64_t size, int32_t byte_width, double null_probability, uint8_t min_byte, uint8_t max_byte, int64_t alignment, MemoryPool* memory_pool) { if (null_probability < 0 || null_probability > 1) { - ABORT_NOT_OK(Status::Invalid("null_probability must be between 0 and 1")); + ARROW_CHECK_OK(Status::Invalid("null_probability must be between 0 and 1")); } // Visual Studio does not implement uniform_int_distribution for char types. @@ -719,8 +716,8 @@ enable_if_parameter_free GetMetadata(const KeyValueMetadata* metad const auto& value = metadata->value(index); T output{}; if (!internal::ParseValue(value.data(), value.length(), &output)) { - ABORT_NOT_OK(Status::Invalid("Could not parse ", key, " = ", value, " as ", - ArrowType::type_name())); + ARROW_CHECK_OK(Status::Invalid("Could not parse ", key, " = ", value, " as ", + ArrowType::type_name())); } return output; } @@ -1034,14 +1031,14 @@ std::shared_ptr RandomArrayGenerator::DenseUnion(const ArrayVector& field // Generate array of offsets const auto& concrete_ids = checked_cast(*type_ids); Int32Builder offsets_builder(memory_pool, alignment); - ABORT_NOT_OK(offsets_builder.Reserve(size)); + ARROW_CHECK_OK(offsets_builder.Reserve(size)); std::vector last_offsets(fields.size(), 0); for (int64_t i = 0; i < size; ++i) { const auto field_id = concrete_ids.Value(i); offsets_builder.UnsafeAppend(last_offsets[field_id]++); } std::shared_ptr offsets; - ABORT_NOT_OK(offsets_builder.Finish(&offsets)); + ARROW_CHECK_OK(offsets_builder.Finish(&offsets)); return *DenseUnionArray::Make(*type_ids, *offsets, fields, type_codes); } @@ -1059,15 +1056,15 @@ std::shared_ptr RandomArrayGenerator::ArrayOf(std::shared_ptr t std::shared_ptr RandomArrayGenerator::ArrayOf(const Field& field, int64_t length, int64_t alignment, MemoryPool* memory_pool) { -#define VALIDATE_RANGE(PARAM, MIN, MAX) \ - if (PARAM < MIN || PARAM > MAX) { \ - ABORT_NOT_OK(Status::Invalid(field.ToString(), ": ", ARROW_STRINGIFY(PARAM), \ - " must be in [", MIN, ", ", MAX, " ] but got ", \ - PARAM)); \ +#define VALIDATE_RANGE(PARAM, MIN, MAX) \ + if (PARAM < MIN || PARAM > MAX) { \ + ARROW_CHECK_OK(Status::Invalid(field.ToString(), ": ", ARROW_STRINGIFY(PARAM), \ + " must be in [", MIN, ", ", MAX, " ] but got ", \ + PARAM)); \ } #define VALIDATE_MIN_MAX(MIN, MAX) \ if (MIN > MAX) { \ - ABORT_NOT_OK( \ + ARROW_CHECK_OK( \ Status::Invalid(field.ToString(), ": min ", MIN, " must be <= max ", MAX)); \ } #define GENERATE_INTEGRAL_CASE_VIEW(BASE_TYPE, VIEW_TYPE) \ @@ -1343,9 +1340,9 @@ std::shared_ptr RandomArrayGenerator::ArrayOf(const Field& field, int64_t values_length, alignment, memory_pool); auto merged = field.metadata() ? field.metadata() : key_value_metadata({}, {}); if (merged->Contains("min")) - ABORT_NOT_OK(Status::Invalid(field.ToString(), ": cannot specify min")); + ARROW_CHECK_OK(Status::Invalid(field.ToString(), ": cannot specify min")); if (merged->Contains("max")) - ABORT_NOT_OK(Status::Invalid(field.ToString(), ": cannot specify max")); + ARROW_CHECK_OK(Status::Invalid(field.ToString(), ": cannot specify max")); merged = merged->Merge( *key_value_metadata({{"min", "0"}, {"max", ToChars(values_length - 1)}})); auto indices = ArrayOf( @@ -1401,7 +1398,7 @@ std::shared_ptr RandomArrayGenerator::ArrayOf(const Field& field, int64_t const auto unique_values = GetMetadata(field.metadata().get(), "unique", -1); if (unique_values > 0) { - ABORT_NOT_OK( + ARROW_CHECK_OK( Status::NotImplemented("Generating random array with repeated values for " "large string/large binary types")); } @@ -1424,7 +1421,7 @@ std::shared_ptr RandomArrayGenerator::ArrayOf(const Field& field, int64_t #undef VALIDATE_RANGE #undef VALIDATE_MIN_MAX - ABORT_NOT_OK( + ARROW_CHECK_OK( Status::NotImplemented("Generating random array for field ", field.ToString())); return nullptr; } diff --git a/cpp/src/arrow/testing/random.h b/cpp/src/arrow/testing/random.h index a953547c3ca8..d3200c678e24 100644 --- a/cpp/src/arrow/testing/random.h +++ b/cpp/src/arrow/testing/random.h @@ -26,9 +26,9 @@ #include #include "arrow/testing/uniform_real.h" -#include "arrow/testing/visibility.h" #include "arrow/type.h" #include "arrow/util/float16.h" +#include "arrow/util/visibility.h" namespace arrow { @@ -39,7 +39,7 @@ namespace random { using SeedType = int32_t; constexpr SeedType kSeedMax = std::numeric_limits::max(); -class ARROW_TESTING_EXPORT RandomArrayGenerator { +class ARROW_EXPORT RandomArrayGenerator { public: explicit RandomArrayGenerator(SeedType seed) : seed_distribution_(static_cast(1), kSeedMax), seed_rng_(seed) {} @@ -696,14 +696,14 @@ class ARROW_TESTING_EXPORT RandomArrayGenerator { }; /// Generate a batch with random data. See RandomArrayGenerator::BatchOf. -ARROW_TESTING_EXPORT +ARROW_EXPORT std::shared_ptr GenerateBatch( const FieldVector& fields, int64_t size, SeedType seed, int64_t alignment = kDefaultBufferAlignment, MemoryPool* memory_pool = default_memory_pool()); /// Generate an array with random data. See RandomArrayGenerator::BatchOf. -ARROW_TESTING_EXPORT +ARROW_EXPORT std::shared_ptr GenerateArray( const Field& field, int64_t size, SeedType seed, int64_t alignment = kDefaultBufferAlignment, @@ -715,9 +715,9 @@ std::shared_ptr GenerateArray( // Assorted functions // -ARROW_TESTING_EXPORT +ARROW_EXPORT void rand_day_millis(int64_t N, std::vector* out); -ARROW_TESTING_EXPORT +ARROW_EXPORT void rand_month_day_nanos(int64_t N, std::vector* out); @@ -733,7 +733,7 @@ void rand_month_day_nanos(int64_t N, /// \param[in] seed Random seed for reproducibility /// \param[in] num_chars Number of Unicode code points to generate /// \return a generated UTF-8 encoded string -ARROW_TESTING_EXPORT +ARROW_EXPORT std::string RandomUtf8String(random::SeedType seed, int num_chars); template diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index 750f0f06f576..8f117c677461 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -720,7 +720,8 @@ set(CYTHON_EXTENSIONS _feather _fs _json - _pyarrow_cpp_tests) + _pyarrow_cpp_tests + _testing) set_source_files_properties(pyarrow/lib.pyx PROPERTIES CYTHON_API TRUE) set(LINK_LIBS arrow_python) diff --git a/python/pyarrow/_testing.pyx b/python/pyarrow/_testing.pyx new file mode 100644 index 000000000000..5f7de1913f88 --- /dev/null +++ b/python/pyarrow/_testing.pyx @@ -0,0 +1,187 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# cython: language_level = 3 +# distutils: language = c++ + +from cython.operator cimport dereference as deref + +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow cimport CArray, CDataType, CField, CMemoryPool, CRecordBatch +from pyarrow.includes.libarrow_testing cimport ( + CRandomArrayGenerator, CSeedType, kDefaultBufferAlignment +) +from pyarrow.lib cimport ( + _Weakrefable, Field, MemoryPool, Schema, Table, + ensure_type, maybe_unbox_memory_pool, + pyarrow_unwrap_data_type, pyarrow_unwrap_field, + pyarrow_wrap_array, pyarrow_wrap_batch +) + + +cdef CSeedType _validate_seed(object seed) except ? 0: + if isinstance(seed, bool) or not isinstance(seed, int): + raise TypeError(f"seed must be an int, got {type(seed).__name__}") + if seed < -2**31 or seed > 2**31 - 1: + raise OverflowError( + f"seed must be in [-2147483648, 2147483647], got {seed}") + return seed + + +cdef class RandomArrayGenerator(_Weakrefable): + """ + Generator for random Arrow arrays, record batches, and tables. + + Parameters + ---------- + seed : int, default 0 + Random seed used to initialize the generator (32-bit signed integer). + """ + cdef: + unique_ptr[CRandomArrayGenerator] generator + + def __cinit__(self, seed=0): + cdef CSeedType c_seed = _validate_seed(seed) + self.generator.reset(new CRandomArrayGenerator(c_seed)) + + def array_of(self, type_or_field, int64_t size, *, + null_probability=None, MemoryPool memory_pool=None): + """ + Generate a random Array of the specified DataType or Field. + + Parameters + ---------- + type_or_field : DataType or Field + The Arrow type or field describing the array to generate. + When a Field is passed, generation options can be configured via + field metadata (e.g., ``min``, ``max``, ``null_probability``, + ``nan_probability``, ``true_probability``, ``min_length``, + ``max_length``, ``unique``). + size : int + The number of elements in the generated array. + null_probability : float, optional + Probability of a slot being null when ``type_or_field`` is a + DataType. Cannot be specified when passing a Field. + memory_pool : MemoryPool, optional + Memory pool to allocate buffers from. + + Returns + ------- + Array + A randomly generated Arrow array. + """ + cdef: + CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool) + shared_ptr[CField] c_field + shared_ptr[CDataType] c_type + double c_null_prob + shared_ptr[CArray] c_arr + + if size < 0: + raise ValueError(f"size must be non-negative, got {size}") + + if isinstance(type_or_field, Field): + if null_probability is not None: + raise ValueError( + "null_probability cannot be passed when type_or_field " + "is a Field; set 'null_probability' in field metadata " + "instead") + c_field = pyarrow_unwrap_field(type_or_field) + with nogil: + c_arr = self.generator.get().ArrayOf( + deref(c_field), size, kDefaultBufferAlignment, pool) + return pyarrow_wrap_array(c_arr) + + c_type = pyarrow_unwrap_data_type( + ensure_type(type_or_field, allow_none=False)) + if null_probability is None: + c_null_prob = 0.0 + elif isinstance(null_probability, bool): + raise TypeError( + f"null_probability must be a float, got {type(null_probability).__name__}") + else: + c_null_prob = float(null_probability) + if not (0.0 <= c_null_prob <= 1.0): + raise ValueError( + f"null_probability must be in [0, 1], got {null_probability}") + with nogil: + c_arr = self.generator.get().ArrayOf( + c_type, size, c_null_prob, kDefaultBufferAlignment, pool) + return pyarrow_wrap_array(c_arr) + + def batch_of(self, schema_or_fields, int64_t size, *, + MemoryPool memory_pool=None): + """ + Generate a random RecordBatch of the specified Schema or fields. + + Parameters + ---------- + schema_or_fields : Schema or iterable of Field + Schema or fields describing the columns to generate. + size : int + The number of rows in the generated RecordBatch. + memory_pool : MemoryPool, optional + Memory pool to allocate buffers from. + + Returns + ------- + RecordBatch + A randomly generated Arrow record batch. + """ + cdef: + CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool) + vector[shared_ptr[CField]] c_fields + shared_ptr[CRecordBatch] c_batch + + if size < 0: + raise ValueError(f"size must be non-negative, got {size}") + + for item in schema_or_fields: + if not isinstance(item, Field): + raise TypeError( + f"Expected Field instances, got {type(item).__name__}") + c_fields.push_back(pyarrow_unwrap_field(item)) + + with nogil: + c_batch = self.generator.get().BatchOf( + c_fields, size, kDefaultBufferAlignment, pool) + batch = pyarrow_wrap_batch(c_batch) + if isinstance(schema_or_fields, Schema) and schema_or_fields.metadata: + batch = batch.replace_schema_metadata(schema_or_fields.metadata) + return batch + + def table_of(self, schema_or_fields, int64_t size, *, + MemoryPool memory_pool=None): + """ + Generate a random Table of the specified Schema or fields. + + Parameters + ---------- + schema_or_fields : Schema or iterable of Field + Schema or fields describing the columns to generate. + size : int + The number of rows in the generated Table. + memory_pool : MemoryPool, optional + Memory pool to allocate buffers from. + + Returns + ------- + Table + A randomly generated Arrow table. + """ + batch = self.batch_of(schema_or_fields, size, memory_pool=memory_pool) + return Table.from_batches([batch], schema=batch.schema) diff --git a/python/pyarrow/includes/libarrow_testing.pxd b/python/pyarrow/includes/libarrow_testing.pxd new file mode 100644 index 000000000000..62156b19cb70 --- /dev/null +++ b/python/pyarrow/includes/libarrow_testing.pxd @@ -0,0 +1,44 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# distutils: language = c++ + +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow cimport ( + CArray, CDataType, CField, CMemoryPool, CRecordBatch +) + + +cdef extern from "arrow/type_fwd.h" namespace "arrow" nogil: + const int64_t kDefaultBufferAlignment + + +cdef extern from "arrow/testing/random.h" namespace "arrow::random" nogil: + ctypedef int32_t CSeedType "arrow::random::SeedType" + + cdef cppclass CRandomArrayGenerator "arrow::random::RandomArrayGenerator": + CRandomArrayGenerator(CSeedType seed) + shared_ptr[CArray] ArrayOf( + shared_ptr[CDataType] type, int64_t size, + double null_probability, int64_t alignment, + CMemoryPool* memory_pool) + shared_ptr[CArray] ArrayOf( + const CField& field, int64_t size, int64_t alignment, + CMemoryPool* memory_pool) + shared_ptr[CRecordBatch] BatchOf( + const vector[shared_ptr[CField]]& fields, int64_t size, + int64_t alignment, CMemoryPool* memory_pool) diff --git a/python/pyarrow/testing.py b/python/pyarrow/testing.py new file mode 100644 index 000000000000..55e0c14f515f --- /dev/null +++ b/python/pyarrow/testing.py @@ -0,0 +1,28 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Testing utilities for generating random Arrow data. + +This module is experimental and intended for testing. Exact generated +distributions and APIs may change across releases. +""" + +from pyarrow._testing import RandomArrayGenerator + +__all__ = [ + "RandomArrayGenerator", +] diff --git a/python/pyarrow/tests/parquet/common.py b/python/pyarrow/tests/parquet/common.py index 5390a24b90d2..32ef6e3a36df 100644 --- a/python/pyarrow/tests/parquet/common.py +++ b/python/pyarrow/tests/parquet/common.py @@ -23,7 +23,7 @@ np = None import pyarrow as pa -from pyarrow.tests import util +import pyarrow.testing as pat def _write_table(table, path, **kwargs): @@ -82,51 +82,50 @@ def _roundtrip_pandas_dataframe(df, write_kwargs): return result.to_pandas() -def _random_integers(size, dtype): - # We do not generate integers outside the int64 range - platform_int_info = np.iinfo('int_') - iinfo = np.iinfo(dtype) - return np.random.randint(max(iinfo.min, platform_int_info.min), - min(iinfo.max, platform_int_info.max), - size=size, dtype=dtype) - - def _range_integers(size, dtype): return pa.array(np.arange(size, dtype=dtype)) -def _test_dict(size=10000, seed=0): - np.random.seed(seed) - return { - 'uint8': _random_integers(size, np.uint8), - 'uint16': _random_integers(size, np.uint16), - 'uint32': _random_integers(size, np.uint32), - 'uint64': _random_integers(size, np.uint64), - 'int8': _random_integers(size, np.int8), - 'int16': _random_integers(size, np.int16), - 'int32': _random_integers(size, np.int32), - 'int64': _random_integers(size, np.int64), - 'float32': np.random.randn(size).astype(np.float32), - 'float64': np.arange(size, dtype=np.float64), - 'bool': np.random.randn(size) > 0, - 'strings': [util.rands(10) for i in range(size)], - 'all_none': [None] * size, - 'all_none_category': [None] * size - } - - def _test_dataframe(size=10000, seed=0): - import pandas as pd - - df = pd.DataFrame(_test_dict(size, seed)) - - # TODO(PARQUET-1015) - # df['all_none_category'] = df['all_none_category'].astype('category') - return df + return _test_table(size, seed).to_pandas() def _test_table(size=10000, seed=0): - return pa.Table.from_pydict(_test_dict(size, seed)) + fields = [ + pa.field('uint8', pa.uint8(), nullable=False), + pa.field('uint16', pa.uint16(), nullable=False), + pa.field('uint32', pa.uint32(), nullable=False), + pa.field( + 'uint64', + pa.uint64(), + nullable=False, + metadata={'max': str(2**63 - 1)}, + ), + pa.field('int8', pa.int8(), nullable=False), + pa.field('int16', pa.int16(), nullable=False), + pa.field('int32', pa.int32(), nullable=False), + pa.field('int64', pa.int64(), nullable=False), + pa.field( + 'float32', + pa.float32(), + nullable=False, + metadata={'min': '-1000.0', 'max': '1000.0'}, + ), + pa.field('bool', pa.bool_(), nullable=False, + metadata={'true_probability': '0.5'}), + pa.field( + 'strings', + pa.utf8(), + nullable=False, + metadata={'min_length': '10', 'max_length': '10'}, + ), + pa.field('all_none', pa.null()), + pa.field('all_none_category', pa.null()), + ] + table = pat.RandomArrayGenerator(seed).table_of(fields, size) + float64_col = pa.arange(0, size).cast(pa.float64()) + table = table.add_column(9, 'float64', float64_col) + return pa.Table.from_arrays(table.columns, names=table.column_names) def make_sample_file(table_or_df): diff --git a/python/pyarrow/tests/parquet/test_basic.py b/python/pyarrow/tests/parquet/test_basic.py index ba88118b82b8..2a3854556b49 100644 --- a/python/pyarrow/tests/parquet/test_basic.py +++ b/python/pyarrow/tests/parquet/test_basic.py @@ -78,7 +78,6 @@ def test_set_data_page_size(): _check_roundtrip(t, data_page_size=target_page_size) -@pytest.mark.numpy def test_set_write_batch_size(): table = _test_table(100) @@ -87,7 +86,6 @@ def test_set_write_batch_size(): ) -@pytest.mark.numpy def test_set_dictionary_pagesize_limit(): table = _test_table(100) diff --git a/python/pyarrow/tests/parquet/test_data_types.py b/python/pyarrow/tests/parquet/test_data_types.py index a585871ebe5d..cd79c58912e0 100644 --- a/python/pyarrow/tests/parquet/test_data_types.py +++ b/python/pyarrow/tests/parquet/test_data_types.py @@ -177,7 +177,6 @@ def test_direct_read_dictionary_subfield(): assert result[0].num_chunks == 1 -@pytest.mark.numpy def test_dictionary_array_automatically_read(): # ARROW-3246 @@ -190,10 +189,10 @@ def test_dictionary_array_automatically_read(): chunk_size = 100 chunks = [] for i in range(num_chunks): - indices = np.random.randint(0, dict_length, - size=chunk_size).astype(np.int32) - chunks.append(pa.DictionaryArray.from_arrays(pa.array(indices), - dict_values)) + indices = util.random_array( + pa.int32(), chunk_size, seed=i, min=0, max=dict_length - 1 + ) + chunks.append(pa.DictionaryArray.from_arrays(indices, dict_values)) table = pa.table([pa.chunked_array(chunks)], names=['f0']) result = _simple_table_write_read(table) diff --git a/python/pyarrow/tests/parquet/test_dataset.py b/python/pyarrow/tests/parquet/test_dataset.py index 28b636637965..5d587fbb50fe 100644 --- a/python/pyarrow/tests/parquet/test_dataset.py +++ b/python/pyarrow/tests/parquet/test_dataset.py @@ -742,7 +742,6 @@ def test_dataset_read_pandas(tempdir): tm.assert_frame_equal(result.reindex(columns=expected.columns), expected) -@pytest.mark.numpy def test_dataset_memory_map(tempdir): # ARROW-2627: Check that we can use ParquetDataset with memory-mapping dirpath = tempdir / guid() @@ -757,7 +756,6 @@ def test_dataset_memory_map(tempdir): assert dataset.read().equals(table) -@pytest.mark.numpy def test_dataset_enable_buffered_stream(tempdir): dirpath = tempdir / guid() dirpath.mkdir() @@ -776,7 +774,6 @@ def test_dataset_enable_buffered_stream(tempdir): assert dataset.read().equals(table) -@pytest.mark.numpy def test_dataset_enable_pre_buffer(tempdir): dirpath = tempdir / guid() dirpath.mkdir() @@ -810,7 +807,6 @@ def _assert_dataset_paths(dataset, paths): assert set(paths) == set(dataset.files) -@pytest.mark.numpy @pytest.mark.parametrize('dir_prefix', ['_', '.']) def test_ignore_private_directories(tempdir, dir_prefix): dirpath = tempdir / guid() @@ -827,7 +823,6 @@ def test_ignore_private_directories(tempdir, dir_prefix): _assert_dataset_paths(dataset, paths) -@pytest.mark.numpy def test_ignore_hidden_files_dot(tempdir): dirpath = tempdir / guid() dirpath.mkdir() @@ -846,7 +841,6 @@ def test_ignore_hidden_files_dot(tempdir): _assert_dataset_paths(dataset, paths) -@pytest.mark.numpy def test_ignore_hidden_files_underscore(tempdir): dirpath = tempdir / guid() dirpath.mkdir() @@ -865,7 +859,6 @@ def test_ignore_hidden_files_underscore(tempdir): _assert_dataset_paths(dataset, paths) -@pytest.mark.numpy @pytest.mark.parametrize('dir_prefix', ['_', '.']) def test_ignore_no_private_directories_in_base_path(tempdir, dir_prefix): # ARROW-8427 - don't ignore explicitly listed files if parent directory diff --git a/python/pyarrow/tests/parquet/test_parquet_writer.py b/python/pyarrow/tests/parquet/test_parquet_writer.py index 264392bae109..3f30f0f47ede 100644 --- a/python/pyarrow/tests/parquet/test_parquet_writer.py +++ b/python/pyarrow/tests/parquet/test_parquet_writer.py @@ -409,7 +409,6 @@ def test_parquet_writer_filesystem_s3fs(s3_example_s3fs): tm.assert_frame_equal(result, df) -@pytest.mark.numpy def test_parquet_writer_filesystem_buffer_raises(): table = _test_table(100) filesystem = fs.LocalFileSystem() diff --git a/python/pyarrow/tests/test_feather.py b/python/pyarrow/tests/test_feather.py index d9cee7a31dc6..357295cf6134 100644 --- a/python/pyarrow/tests/test_feather.py +++ b/python/pyarrow/tests/test_feather.py @@ -30,6 +30,7 @@ np = None import pyarrow as pa +from pyarrow.tests import util import pyarrow.tests.strategies as past from pyarrow.feather import (read_feather, write_feather, read_table, FeatherDataset) @@ -145,13 +146,14 @@ def f(): pytest.raises(exc, f) -@pytest.mark.numpy def test_dataset(version): num_values = (100, 100) num_files = 5 paths = [random_path() for i in range(num_files)] data = { - "col_" + str(i): np.random.randn(num_values[0]) + f"col_{i}": util.random_array( + pa.float64(), num_values[0], seed=i, min=-10.0, max=10.0 + ) for i in range(num_values[1]) } table = pa.table(data) @@ -556,15 +558,12 @@ def test_read_columns(version): columns=['boo', 'woo']) -@pytest.mark.numpy def test_overwritten_file(version): path = random_path() TEST_FILES.append(path) num_values = 100 - np.random.seed(0) - - values = np.random.randint(0, 10, size=num_values) + values = util.random_array(pa.int64(), num_values, min=0, max=9) table = pa.table({'ints': values}) write_feather(table, path) diff --git a/python/pyarrow/tests/test_io.py b/python/pyarrow/tests/test_io.py index 1cfebb4936a1..474bd8072d1a 100644 --- a/python/pyarrow/tests/test_io.py +++ b/python/pyarrow/tests/test_io.py @@ -39,6 +39,7 @@ from pyarrow.util import guid from pyarrow import Codec import pyarrow as pa +from pyarrow.tests import util def check_large_seeks(file_factory, expected_error=None): @@ -810,7 +811,6 @@ def test_cache_options_pickling(pickle_module): assert pickle_module.loads(pickle_module.dumps(option)) == option -@pytest.mark.numpy @pytest.mark.parametrize("compression", [ pytest.param( "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) @@ -826,9 +826,9 @@ def test_compress_decompress(compression): pytest.skip(f"{compression} support is not built") INPUT_SIZE = 10000 - test_data = (np.random.randint(0, 255, size=INPUT_SIZE) - .astype(np.uint8) - .tobytes()) + test_data = util.random_array( + pa.uint8(), INPUT_SIZE, min=0, max=254 + ).buffers()[1].to_pybytes() test_buf = pa.py_buffer(test_data) compressed_buf = pa.compress(test_buf, codec=compression) @@ -851,7 +851,6 @@ def test_compress_decompress(compression): pa.decompress(compressed_bytes, codec=compression) -@pytest.mark.numpy @pytest.mark.parametrize("compression", [ pytest.param( "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) @@ -887,9 +886,9 @@ def test_compression_level(compression): return INPUT_SIZE = 10000 - test_data = (np.random.randint(0, 255, size=INPUT_SIZE) - .astype(np.uint8) - .tobytes()) + test_data = util.random_array( + pa.uint8(), INPUT_SIZE, min=0, max=254 + ).buffers()[1].to_pybytes() test_buf = pa.py_buffer(test_data) min_level = Codec.minimum_compression_level(compression) @@ -923,9 +922,7 @@ def test_compression_level(compression): # The goal of this part is to ensure the compression_level is being # passed down to the C++ layer, not to verify the compression algs # themselves - rng = np.random.default_rng(seed=42) - values = rng.integers(0, 100, 1000) - arr = pa.array(values) + arr = util.random_array(pa.int64(), 1000, seed=42, min=0, max=99) hard_to_compress_buffer = arr.buffers()[1] weak_codec = Codec(compression, min_level) diff --git a/python/pyarrow/tests/test_json.py b/python/pyarrow/tests/test_json.py index 3dc54d53fba9..199d524dbb55 100644 --- a/python/pyarrow/tests/test_json.py +++ b/python/pyarrow/tests/test_json.py @@ -21,6 +21,7 @@ import io import itertools import json +import random import string import sys import unittest @@ -32,6 +33,7 @@ import pytest import pyarrow as pa +from pyarrow.tests import util from pyarrow.json import read_json, open_json, ReadOptions, ParseOptions @@ -46,21 +48,24 @@ def generate_col_names(): def make_random_json(num_cols=2, num_rows=10, linesep='\r\n', *, extra_whitespace=False): - rnd = np.random.RandomState(42) - arr = rnd.randint(0, 1000, size=(num_cols, num_rows)) col_names = list(itertools.islice(generate_col_names(), num_cols)) + columns = [ + util.random_array(pa.int64(), num_rows, seed=42 + i, min=0, max=999) + for i in range(num_cols) + ] + expected = pa.Table.from_arrays(columns, col_names) + rnd = random.Random(42) + cols = [col.to_pylist() for col in columns] lines = [] max_line_len = 0 - for row in arr.T: - json_obj = OrderedDict([(k, int(v)) for (k, v) in zip(col_names, row)]) + for row in zip(*cols): + json_obj = OrderedDict(zip(col_names, row)) line = json.dumps(json_obj) if extra_whitespace: - line += ' ' * rnd.randint(0, 5) + line += ' ' * rnd.randint(0, 4) lines.append(line) max_line_len = max(max_line_len, len(line)) data = linesep.join(lines).encode() - columns = [pa.array(col, type=pa.int64()) for col in arr] - expected = pa.Table.from_arrays(columns, col_names) return data, max_line_len, expected @@ -300,7 +305,6 @@ def test_explicit_schema_with_unexpected_behaviour(self): match="JSON parse error: unexpected field"): self.read_bytes(rows, parse_options=opts) - @pytest.mark.numpy def test_small_random_json(self): for extra_whitespace in (False, True): data, _, expected = make_random_json(num_cols=2, num_rows=10, @@ -310,7 +314,6 @@ def test_small_random_json(self): assert table.equals(expected) assert table.to_pydict() == expected.to_pydict() - @pytest.mark.numpy def test_load_large_json(self): for extra_whitespace in (False, True): data, _, expected = make_random_json(num_cols=2, num_rows=100100, @@ -321,7 +324,6 @@ def test_load_large_json(self): assert table.num_rows == 100100 assert expected.num_rows == 100100 - @pytest.mark.numpy def test_stress_block_sizes(self): # Test a number of small block sizes to stress block stitching for extra_whitespace in (False, True): diff --git a/python/pyarrow/tests/test_testing.py b/python/pyarrow/tests/test_testing.py new file mode 100644 index 000000000000..6ab00ad5b80c --- /dev/null +++ b/python/pyarrow/tests/test_testing.py @@ -0,0 +1,238 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import math + +import pytest + +import pyarrow as pa +import pyarrow.testing as pat + + +@pytest.mark.parametrize("dtype", [ + pa.null(), + pa.bool_(), + pa.int8(), + pa.int16(), + pa.int32(), + pa.int64(), + pa.uint8(), + pa.uint16(), + pa.uint32(), + pa.uint64(), + pa.float16(), + pa.float32(), + pa.float64(), + pa.decimal32(5, 2), + pa.decimal64(10, 2), + pa.decimal128(19, 4), + pa.decimal256(38, 4), + pa.string(), + pa.binary(), + pa.large_string(), + pa.large_binary(), + pa.string_view(), + pa.binary_view(), + pa.binary(8), + pa.date32(), + pa.date64(), + pa.time32("s"), + pa.time32("ms"), + pa.time64("us"), + pa.time64("ns"), + pa.timestamp("us"), + pa.duration("ms"), + pa.month_day_nano_interval(), + pa.list_(pa.int32()), + pa.large_list(pa.utf8()), + pa.list_view(pa.int32()), + pa.large_list_view(pa.utf8()), + pa.list_(pa.int16(), 3), + pa.struct([pa.field("a", pa.int32()), pa.field("b", pa.utf8())]), + pa.map_(pa.utf8(), pa.int64()), + pa.dictionary(pa.int16(), pa.utf8()), + pa.union([pa.field("a", pa.int32()), pa.field("b", pa.utf8())], mode="sparse"), + pa.union([pa.field("a", pa.int32()), pa.field("b", pa.utf8())], mode="dense"), + pa.run_end_encoded(pa.int32(), pa.int16()), +]) +def test_generate_array_types(dtype): + arr = pat.RandomArrayGenerator(seed=42).array_of( + dtype, 25, null_probability=0.2) + arr.validate(full=True) + assert arr.type == dtype + assert len(arr) == 25 + + empty = pat.RandomArrayGenerator(seed=42).array_of(dtype, 0) + empty.validate(full=True) + assert empty.type == dtype + assert len(empty) == 0 + + +def test_determinism_and_seeds(): + a1 = pat.RandomArrayGenerator(seed=123).array_of(pa.int64(), 100) + a2 = pat.RandomArrayGenerator(seed=123).array_of(pa.int64(), 100) + b = pat.RandomArrayGenerator(seed=456).array_of(pa.int64(), 100) + assert a1.equals(a2) + assert not a1.equals(b) + + # Sequential calls from the same generator advance its state + rng = pat.RandomArrayGenerator(seed=7) + x1 = rng.array_of(pa.int32(), 50) + x2 = rng.array_of(pa.int32(), 50) + assert not x1.equals(x2) + + # __new__ without __init__ still initializes the C++ generator via __cinit__ + direct = pat.RandomArrayGenerator.__new__(pat.RandomArrayGenerator) + assert len(direct.array_of(pa.int32(), 5)) == 5 + + +def test_null_probability(): + no_nulls = pat.RandomArrayGenerator(seed=1).array_of( + pa.int32(), 100, null_probability=0.0) + assert no_nulls.null_count == 0 + + all_nulls = pat.RandomArrayGenerator(seed=1).array_of( + pa.int32(), 100, null_probability=1.0) + assert all_nulls.null_count == 100 + + half_nulls = pat.RandomArrayGenerator(seed=1).array_of( + pa.int32(), 500, null_probability=0.5) + assert 0 < half_nulls.null_count < 500 + + +def test_field_metadata_options(): + int_field = pa.field( + "ints", pa.int32(), nullable=False, + metadata={"min": "10", "max": "20"} + ) + int_arr = pat.RandomArrayGenerator(seed=9).array_of(int_field, 200) + int_arr.validate(full=True) + assert int_arr.null_count == 0 + for val in int_arr.to_pylist(): + assert 10 <= val <= 20 + + bool_field = pa.field( + "bools", pa.bool_(), nullable=False, + metadata={"true_probability": "1.0"} + ) + bool_arr = pat.RandomArrayGenerator(seed=9).array_of(bool_field, 50) + assert bool_arr.to_pylist() == [True] * 50 + + float_field = pa.field( + "floats", pa.float64(), nullable=False, + metadata={"min": "-1.0", "max": "1.0", "nan_probability": "0.5"} + ) + float_arr = pat.RandomArrayGenerator(seed=9).array_of(float_field, 200) + float_arr.validate(full=True) + vals = float_arr.to_pylist() + assert any(math.isnan(v) for v in vals) + assert any(not math.isnan(v) and -1.0 <= v <= 1.0 for v in vals) + + str_field = pa.field( + "strs", pa.utf8(), nullable=False, + metadata={"min_length": "4", "max_length": "4", "unique": "3"} + ) + str_arr = pat.RandomArrayGenerator(seed=9).array_of(str_field, 50) + str_arr.validate(full=True) + py_strs = str_arr.to_pylist() + assert all(len(s) == 4 for s in py_strs) + assert len(set(py_strs)) <= 3 + + +def test_generate_batch_and_table(): + schema = pa.schema([ + pa.field("i", pa.int32(), nullable=False), + pa.field("s", pa.utf8()), + pa.field("f", pa.float64()), + ], metadata={"origin": "test"}) + + batch = pat.RandomArrayGenerator(seed=11).batch_of(schema, 50) + batch.validate(full=True) + assert batch.schema.equals(schema, check_metadata=True) + assert batch.num_rows == 50 + + table = pat.RandomArrayGenerator(seed=11).table_of(schema, 50) + table.validate(full=True) + assert table.schema.equals(schema, check_metadata=True) + assert table.num_rows == 50 + assert table.to_batches()[0].equals(batch) + + # Also accept an iterable of Fields + fields = [pa.field("a", pa.int8()), pa.field("b", pa.bool_())] + table2 = pat.RandomArrayGenerator(seed=11).table_of(fields, 0) + table2.validate(full=True) + assert table2.num_rows == 0 + assert table2.schema == pa.schema(fields) + + +def test_memory_pool(): + pool = pa.proxy_memory_pool(pa.default_memory_pool()) + arr = pat.RandomArrayGenerator(seed=1).array_of( + pa.int64(), 1000, memory_pool=pool) + assert len(arr) == 1000 + assert pool.bytes_allocated() > 0 + del arr + assert pool.bytes_allocated() == 0 + + +def test_invalid_inputs(): + rng = pat.RandomArrayGenerator(seed=0) + + with pytest.raises(TypeError): + pat.RandomArrayGenerator(seed=True) + with pytest.raises(TypeError): + pat.RandomArrayGenerator(seed="0") + with pytest.raises(OverflowError): + pat.RandomArrayGenerator(seed=2**31) + + with pytest.raises(ValueError): + rng.array_of(pa.int32(), -1) + + with pytest.raises(ValueError): + rng.array_of(pa.int32(), 10, null_probability=-0.1) + + with pytest.raises(ValueError): + rng.array_of(pa.int32(), 10, null_probability=1.5) + + with pytest.raises(ValueError): + rng.array_of(pa.int32(), 10, null_probability=float("nan")) + + with pytest.raises(TypeError): + rng.array_of(pa.int32(), 10, null_probability=True) + + with pytest.raises(ValueError, match="null_probability cannot be passed"): + rng.array_of(pa.field("x", pa.int32()), 10, null_probability=0.5) + + with pytest.raises(TypeError): + rng.batch_of([pa.int32()], 10) + + with pytest.raises(ValueError): + rng.batch_of([pa.field("x", pa.int32())], -1) + + +@pytest.mark.nonumpy +def test_works_without_numpy(): + table = pat.RandomArrayGenerator(seed=42).table_of( + [ + pa.field("i", pa.int64(), nullable=False), + pa.field("s", pa.utf8()), + pa.field("b", pa.bool_()), + ], + 20, + ) + table.validate(full=True) + assert table.num_rows == 20 diff --git a/python/pyarrow/tests/util.py b/python/pyarrow/tests/util.py index cf48ac807be1..4836c8da408b 100644 --- a/python/pyarrow/tests/util.py +++ b/python/pyarrow/tests/util.py @@ -38,6 +38,7 @@ import pyarrow as pa import pyarrow.fs +import pyarrow.testing as pat def randsign(): @@ -113,6 +114,16 @@ def random_ascii(length): return bytes([random.randint(65, 122) for i in range(length)]) +def random_array(dtype, size, *, seed=0, null_probability=0.0, **options): + """Generate a random Arrow array for testing.""" + metadata = {k: str(v) for k, v in options.items()} + if null_probability: + metadata["null_probability"] = str(null_probability) + field = pa.field("", dtype, nullable=bool(null_probability), + metadata=metadata or None) + return pat.RandomArrayGenerator(seed=seed).array_of(field, size) + + def rands(nchars): """ Generate one random string.