repo_id
stringlengths 21
96
| file_path
stringlengths 31
155
| content
stringlengths 1
92.9M
| __index_level_0__
int64 0
0
|
---|---|---|---|
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/src/addon.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-redeclare */
import {addon as CORE} from '@rapidsai/core';
import {addon as CUDA} from '@rapidsai/cuda';
import {addon as RMM} from '@rapidsai/rmm';
export const {
_cpp_exports,
Table,
Column,
Scalar,
GroupBy,
findCommonType,
} = require('bindings')('rapidsai_cudf.node').init(CORE, CUDA, RMM) as typeof import('./node_cudf');
export default {
_cpp_exports,
Table,
Column,
Scalar,
GroupBy,
findCommonType,
};
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/read_orc.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cudf/io/orc.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
namespace nv {
namespace {
cudf::io::orc_reader_options make_reader_options(Napi::Object const& options,
cudf::io::source_info const& source) {
auto env = options.Env();
auto is_null = [](Napi::Value const& val) {
return val.IsNull() || val.IsEmpty() || val.IsUndefined();
};
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto napi_opt = [&](std::string const& key) -> Napi::Value {
return has_opt(key) ? options.Get(key) : env.Undefined();
};
auto long_opt = [&](std::string const& key) {
return has_opt(key) ? options.Get(key).ToNumber().Int32Value() : -1;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
auto napi_stripes = napi_opt("stripes");
std::vector<std::vector<cudf::size_type>> stripes;
if (!is_null(napi_stripes) && napi_stripes.IsArray()) {
auto arr = napi_stripes.As<Napi::Array>();
for (size_t i = 0; i < arr.Length(); ++i) { stripes.push_back(NapiToCPP{arr.Get(i)}); }
}
auto opts = std::move(cudf::io::orc_reader_options::builder(source)
.num_rows(long_opt("numRows"))
.use_index(bool_opt("useIndex", true))
.build());
// These cannot be both set together (cudf exception), so we only set them depending on if
// the options contains a definition for them.
if (!stripes.empty()) { opts.set_stripes(stripes); }
if (has_opt("skipRows")) { opts.set_skip_rows(long_opt("skipRows")); }
auto decimal_cols = napi_opt("decimalColumns");
if (!is_null(decimal_cols) && decimal_cols.IsArray()) {
opts.set_decimal128_columns(NapiToCPP{decimal_cols});
}
auto columns = napi_opt("columns");
if (!is_null(columns) && columns.IsArray()) { opts.set_columns(NapiToCPP{columns}); }
return opts;
}
Napi::Value read_orc_files(Napi::Object const& options, std::vector<std::string> const& sources) {
auto env = options.Env();
auto result = cudf::io::read_orc(make_reader_options(options, cudf::io::source_info{sources}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
std::vector<cudf::io::host_buffer> get_host_buffers(std::vector<Span<uint8_t>> const& sources) {
std::vector<cudf::io::host_buffer> buffers;
buffers.reserve(sources.size());
std::transform(sources.begin(), sources.end(), std::back_inserter(buffers), [&](auto const& buf) {
return cudf::io::host_buffer{static_cast<Span<char>>(buf), buf.size()};
});
return buffers;
}
Napi::Value read_orc_sources(Napi::Object const& options,
std::vector<Span<uint8_t>> const& sources) {
auto env = options.Env();
auto result = cudf::io::read_orc(
make_reader_options(options, cudf::io::source_info{get_host_buffers(sources)}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
} // namespace
Napi::Value Table::read_orc(Napi::CallbackInfo const& info) {
auto env = info.Env();
NODE_CUDF_EXPECT(info[0].IsObject(), "readORC expects an Object of ReadORCOptions", env);
auto options = info[0].As<Napi::Object>();
auto sources = options.Get("sources");
NODE_CUDF_EXPECT(sources.IsArray(), "readORC expects an Array of paths or buffers", env);
try {
return (options.Get("sourceType").ToString().Utf8Value() == "files")
? read_orc_files(options, NapiToCPP{sources})
: read_orc_sources(options, NapiToCPP{sources});
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/arrow.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <arrow/gpu/cuda_api.h>
#include <arrow/io/memory.h>
#include <arrow/ipc/api.h>
#include <arrow/ipc/writer.h>
#include <arrow/result.h>
#include <cudf/interop.hpp>
#include <memory>
namespace nv {
namespace {
class CudaMessageReader : arrow::ipc::MessageReader {
public:
CudaMessageReader(arrow::cuda::CudaBufferReader* stream, arrow::io::BufferReader* schema)
: stream_(stream), host_schema_reader_(schema){};
static std::unique_ptr<arrow::ipc::MessageReader> Open(arrow::cuda::CudaBufferReader* stream,
arrow::io::BufferReader* schema) {
return std::unique_ptr<arrow::ipc::MessageReader>(new CudaMessageReader(stream, schema));
}
arrow::Result<std::unique_ptr<arrow::ipc::Message>> ReadNextMessage() override {
if (host_schema_reader_ != nullptr) {
auto message = arrow::ipc::ReadMessage(host_schema_reader_);
host_schema_reader_ = nullptr;
if (message.ok() && *message != nullptr) { return message; }
}
return arrow::ipc::ReadMessage(stream_, arrow::default_memory_pool());
}
private:
arrow::cuda::CudaBufferReader* stream_;
arrow::io::BufferReader* host_schema_reader_ = nullptr;
std::shared_ptr<arrow::cuda::CudaBufferReader> owned_stream_;
};
std::vector<cudf::column_metadata> gather_metadata(Napi::Array const& names) {
std::vector<cudf::column_metadata> metadata;
metadata.reserve(names.Length());
for (uint32_t i = 0; i < names.Length(); ++i) {
auto pair = names.Get(i).As<Napi::Array>();
metadata.push_back({pair.Get(0u).ToString()});
if (pair.Length() == 2 && pair.Get(1u).IsArray()) {
metadata[i].children_meta = gather_metadata(pair.Get(1u).As<Napi::Array>());
}
}
return metadata;
}
} // namespace
Napi::Value Table::to_arrow(Napi::CallbackInfo const& info) {
auto env = info.Env();
auto buffer = [&]() {
auto table = cudf::to_arrow(*this, gather_metadata(info[0].As<Napi::Array>()));
auto sink = arrow::io::BufferOutputStream::Create().ValueOrDie();
auto writer = arrow::ipc::MakeStreamWriter(sink.get(), table->schema()).ValueOrDie();
auto write_status = writer->WriteTable(*table);
if (!write_status.ok()) { NAPI_THROW(Napi::Error::New(env, write_status.message())); }
auto close_status = writer->Close();
if (!close_status.ok()) { NAPI_THROW(Napi::Error::New(env, close_status.message())); }
auto buffer = sink->Finish().ValueOrDie();
auto arybuf = Napi::ArrayBuffer::New(env, buffer->size());
memcpy(arybuf.Data(), buffer->data(), buffer->size());
return arybuf;
}();
return Napi::Uint8Array::New(env, buffer.ByteLength(), buffer, 0);
}
Napi::Value Table::from_arrow(Napi::CallbackInfo const& info) {
using namespace arrow::cuda;
using namespace arrow::io;
using namespace arrow::ipc;
CallbackArgs args{info};
auto env = info.Env();
auto source = args[0];
Span<uint8_t> span = args[0];
std::unique_ptr<InputStream> buffer_reader;
auto stream_reader =
RecordBatchStreamReader::Open([&] {
if (Memory::IsInstance(source) || DeviceBuffer::IsInstance(source)) {
auto device_manager = CudaDeviceManager::Instance().ValueOrDie();
auto device_context = device_manager->GetContext(Device::active_device_id()).ValueOrDie();
buffer_reader.reset(new CudaBufferReader(std::make_shared<CudaBuffer>(
span.data(), span.size(), device_context, false, IpcMemory::IsInstance(source))));
return nv::CudaMessageReader::Open(static_cast<CudaBufferReader*>(buffer_reader.get()),
nullptr);
}
// If the memory was not allocated via CUDA, assume host
buffer_reader.reset(
new BufferReader(std::make_shared<arrow::Buffer>(span.data(), span.size())));
return MessageReader::Open(buffer_reader.get());
}())
.ValueOrDie();
try {
auto arrow_table = stream_reader->ToTable().ValueOrDie();
auto output = Napi::Object::New(env);
output.Set("table", Table::New(env, cudf::from_arrow(*arrow_table)));
output.Set("fields", Napi::Value::From(env, stream_reader->schema()->fields()));
return output;
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(env, e.what())); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/copying.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <cudf/copying.hpp>
#include <cudf/table/table_view.hpp>
#include <functional>
#include <memory>
namespace nv {
Table::wrapper_t Table::gather(Column const& gather_map,
cudf::out_of_bounds_policy bounds_policy,
rmm::mr::device_memory_resource* mr) const {
return Table::New(Env(), cudf::gather(cudf::table_view{{*this}}, gather_map, bounds_policy, mr));
}
Table::wrapper_t Table::scatter(
std::vector<std::reference_wrapper<const cudf::scalar>> const& source,
Column const& indices,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::scatter(source, indices, *this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Table::wrapper_t Table::scatter(Table const& source,
Column const& indices,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::scatter(source, indices, *this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::gather(Napi::CallbackInfo const& info) {
using namespace cudf;
CallbackArgs args{info};
if (!Column::IsInstance(args[0])) {
throw Napi::Error::New(info.Env(), "gather selection argument expects a Column");
}
Column::wrapper_t selection = args[0].ToObject();
auto oob_policy =
args[1].ToBoolean() ? out_of_bounds_policy::NULLIFY : out_of_bounds_policy::DONT_CHECK;
rmm::mr::device_memory_resource* mr = args[2];
return this->gather(selection, oob_policy, mr);
}
Napi::Value Table::apply_boolean_mask(Napi::CallbackInfo const& info) {
using namespace cudf;
CallbackArgs args{info};
if (!Column::IsInstance(args[0])) {
throw Napi::Error::New(info.Env(), "apply_boolean_mask selection argument expects a Column");
}
Column::wrapper_t selection = args[0].ToObject();
rmm::mr::device_memory_resource* mr = args[1];
return this->apply_boolean_mask(selection, mr);
}
Napi::Value Table::scatter_scalar(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 3 and args.Length() != 4) {
NAPI_THROW(Napi::Error::New(info.Env(),
"scatter_scalar expects a vector of scalars, a Column, and "
"optionally a bool and memory resource"));
}
if (!args[0].IsArray()) {
throw Napi::Error::New(info.Env(), "scatter_scalar source argument expects an array");
}
auto const source_array = args[0].As<Napi::Array>();
std::vector<std::reference_wrapper<const cudf::scalar>> source{};
for (uint32_t i = 0; i < source_array.Length(); ++i) {
if (!Scalar::IsInstance(source_array.Get(i))) {
throw Napi::Error::New(info.Env(),
"scatter_scalar source argument expects an array of scalars");
}
source.push_back(std::ref<const cudf::scalar>(*Scalar::Unwrap(source_array.Get(i).ToObject())));
}
if (!Column::IsInstance(args[1])) {
throw Napi::Error::New(info.Env(), "scatter_scalar indices argument expects a Column");
}
auto& indices = *Column::Unwrap(args[1]);
rmm::mr::device_memory_resource* mr = args[2];
return scatter(source, indices, mr)->Value();
}
Napi::Value Table::scatter_table(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 3 and args.Length() != 4) {
NAPI_THROW(Napi::Error::New(
info.Env(),
"scatter_table expects a Table, a Column, and optionally a bool and memory resource"));
}
if (!Table::IsInstance(args[0])) {
throw Napi::Error::New(info.Env(), "scatter_table source argument expects a Table");
}
auto& source = *Table::Unwrap(args[0]);
if (!Column::IsInstance(args[1])) {
throw Napi::Error::New(info.Env(), "scatter_table indices argument expects a Column");
}
auto& indices = *Column::Unwrap(args[1]);
rmm::mr::device_memory_resource* mr = args[2];
return scatter(source, indices, mr)->Value();
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/concatenate.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cudf/concatenate.hpp>
#include <node_cudf/table.hpp>
namespace nv {
Napi::Value Table::concat(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
std::vector<Table::wrapper_t> tables = args[0];
rmm::mr::device_memory_resource* mr = args[1];
NODE_CUDF_EXPECT(
tables.size() > 0, "Table concat requires non-empty array of tables", args.Env());
std::vector<cudf::table_view> table_views;
table_views.reserve(tables.size());
std::transform(tables.begin(),
tables.end(),
std::back_inserter(table_views),
[](const Table::wrapper_t& t) -> cudf::table_view { return t->view(); });
try {
return Table::New(info.Env(), cudf::concatenate(table_views, mr));
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/write_csv.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/io/csv.hpp>
#include <cudf/io/data_sink.hpp>
#include <cudf/io/types.hpp>
namespace nv {
namespace {
cudf::io::table_metadata make_csv_writer_metadata(Napi::Object const& options,
cudf::table_view const& table) {
auto env = options.Env();
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto napi_opt = [&](std::string const& key) -> Napi::Value {
return has_opt(key) ? options.Get(key) : env.Undefined();
};
auto str_opt = [&](std::string const& key, std::string const& default_val) {
return has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
cudf::io::table_metadata metadata{};
auto null_value = str_opt("nullValue", "N/A");
if (bool_opt("header", true)) {
Napi::Array column_names = napi_opt("columnNames").IsArray()
? napi_opt("columnNames").As<Napi::Array>()
: Napi::Array::New(env, table.num_columns());
metadata.column_names.reserve(table.num_columns());
for (auto i = 0u; i < column_names.Length(); ++i) {
auto name = column_names.Has(i) ? column_names.Get(i) : env.Null();
metadata.column_names.push_back(
name.IsString() || name.IsNumber() ? name.ToString().Utf8Value() : null_value);
}
}
return metadata;
}
cudf::io::csv_writer_options make_writer_options(Napi::Object const& options,
cudf::io::sink_info const& sink,
cudf::table_view const& table,
cudf::io::table_metadata* metadata) {
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto str_opt = [&](std::string const& key, std::string const& default_val) {
return has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val;
};
auto long_opt = [&](std::string const& key, long default_val) {
return has_opt(key) ? options.Get(key).ToNumber().Int32Value() : default_val;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
return std::move(cudf::io::csv_writer_options::builder(sink, table)
.names(metadata->column_names)
.na_rep(str_opt("nullValue", "N/A"))
.include_header(bool_opt("includeHeader", true))
.rows_per_chunk(long_opt("rowsPerChunk", 8))
.line_terminator(str_opt("lineTerminator", "\n"))
.inter_column_delimiter(str_opt("delimiter", ",")[0])
.true_value(str_opt("trueValue", "true"))
.false_value(str_opt("falseValue", "false"))
.build());
}
struct callback_sink : public cudf::io::data_sink {
callback_sink(Napi::Function const& emit)
: cudf::io::data_sink(), //
env_(emit.Env()),
emit_(Napi::Persistent(emit)) {}
size_t bytes_written() override { return bytes_written_; }
void host_write(void const* data, size_t size) override {
bytes_written_ += size;
emit_({Napi::Buffer<char>::Copy(env_, static_cast<char const*>(data), size)});
}
void flush() override {}
private:
Napi::Env env_;
size_t bytes_written_{0};
Napi::FunctionReference emit_;
};
} // namespace
void Table::write_csv(Napi::CallbackInfo const& info) {
auto env = info.Env();
NODE_CUDF_EXPECT(info[0].IsObject(), "writeCSV expects an Object of WriteCSVOptions", env);
auto options = info[0].As<Napi::Object>();
NODE_CUDF_EXPECT(options.Has("next"), "writeCSV expects a 'next' callback", env);
NODE_CUDF_EXPECT(options.Has("complete"), "writeCSV expects a 'complete' callback", env);
auto next = options.Get("next");
NODE_CUDF_EXPECT(next.IsFunction(), "writeCSV expects 'next' to be a function", env);
auto complete = options.Get("complete");
NODE_CUDF_EXPECT(complete.IsFunction(), "writeCSV expects 'complete' to be a function", env);
cudf::table_view table = *this;
callback_sink sink{next.As<Napi::Function>()};
auto metadata = make_csv_writer_metadata(options, table);
cudf::io::write_csv(make_writer_options(options, cudf::io::sink_info{&sink}, table, &metadata));
complete.As<Napi::Function>()({});
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/write_parquet.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
#include <cudf/io/data_sink.hpp>
#include <cudf/io/parquet.hpp>
namespace nv {
namespace {
cudf::io::parquet_writer_options make_writer_options(Napi::Object const& options,
cudf::io::sink_info const& sink,
cudf::table_view const& table,
cudf::io::table_input_metadata* metadata) {
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto str_opt = [&](std::string const& key, std::string const& default_val) {
return has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
return std::move(cudf::io::parquet_writer_options::builder(sink, table)
.metadata(metadata)
.compression(str_opt("compression", "snappy") == "snappy"
? cudf::io::compression_type::SNAPPY
: cudf::io::compression_type::NONE)
.int96_timestamps(bool_opt("int96Timestamps", false))
.build());
}
} // namespace
void Table::write_parquet(Napi::CallbackInfo const& info) {
auto env = info.Env();
CallbackArgs args{info};
NODE_CUDF_EXPECT(
args[1].IsObject(), "writeParquet expects an Object of WriteParquetOptions", env);
std::string file_path = args[0];
auto options = args[1].As<Napi::Object>();
cudf::table_view table = *this;
auto metadata = make_writer_columns_metadata(options, table);
auto writer_opts = make_writer_options(options, cudf::io::sink_info{file_path}, table, &metadata);
cudf::io::write_parquet(writer_opts);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/read_parquet.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cudf/io/datasource.hpp>
#include <cudf/io/parquet.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
namespace nv {
namespace {
cudf::io::parquet_reader_options make_reader_options(Napi::Object const& options,
cudf::io::source_info const& source) {
auto env = options.Env();
auto is_null = [](Napi::Value const& val) {
return val.IsNull() || val.IsEmpty() || val.IsUndefined();
};
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto napi_opt = [&](std::string const& key) -> Napi::Value {
return has_opt(key) ? options.Get(key) : env.Undefined();
};
auto long_opt = [&](std::string const& key) {
return has_opt(key) ? options.Get(key).ToNumber().Int32Value() : -1;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
auto napi_row_groups = napi_opt("rowGroups");
std::vector<std::vector<cudf::size_type>> row_groups;
if (!is_null(napi_row_groups) && napi_row_groups.IsArray()) {
auto arr = napi_row_groups.As<Napi::Array>();
for (size_t i = 0; i < arr.Length(); ++i) { row_groups.push_back(NapiToCPP{arr.Get(i)}); }
}
auto opts = std::move(cudf::io::parquet_reader_options::builder(source)
.num_rows(long_opt("numRows"))
.convert_strings_to_categories(bool_opt("stringsToCategorical", false))
.use_pandas_metadata(bool_opt("usePandasMetadata", true))
.build());
// These cannot be both set together (cudf exception), so we only set them depending on if
// the options contains a definition for them.
if (!row_groups.empty()) { opts.set_row_groups(row_groups); }
if (has_opt("skipRows")) { opts.set_skip_rows(long_opt("skipRows")); }
auto columns = napi_opt("columns");
if (!is_null(columns) && columns.IsArray()) { opts.set_columns(NapiToCPP{columns}); }
return opts;
}
Napi::Value read_parquet_files(Napi::Object const& options,
std::vector<std::string> const& sources) {
auto env = options.Env();
auto result =
cudf::io::read_parquet(make_reader_options(options, cudf::io::source_info{sources}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
std::vector<cudf::io::host_buffer> get_host_buffers(std::vector<Span<uint8_t>> const& sources) {
std::vector<cudf::io::host_buffer> buffers;
buffers.reserve(sources.size());
std::transform(sources.begin(), sources.end(), std::back_inserter(buffers), [&](auto const& buf) {
return cudf::io::host_buffer{static_cast<Span<char>>(buf), buf.size()};
});
return buffers;
}
Napi::Value read_parquet_sources(Napi::Object const& options,
std::vector<Span<uint8_t>> const& sources) {
auto env = options.Env();
auto result = cudf::io::read_parquet(
make_reader_options(options, cudf::io::source_info{get_host_buffers(sources)}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
} // namespace
Napi::Value Table::read_parquet(Napi::CallbackInfo const& info) {
auto env = info.Env();
NODE_CUDF_EXPECT(info[0].IsObject(), "readParquet expects an Object of ReadParquetOptions", env);
auto options = info[0].As<Napi::Object>();
auto sources = options.Get("sources");
NODE_CUDF_EXPECT(sources.IsArray(), "readParquet expects an Array of paths or buffers", env);
try {
return (options.Get("sourceType").ToString().Utf8Value() == "files")
? read_parquet_files(options, NapiToCPP{sources})
: read_parquet_sources(options, NapiToCPP{sources});
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/write_orc.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
#include <cudf/io/data_sink.hpp>
#include <cudf/io/orc.hpp>
namespace nv {
namespace {
cudf::io::orc_writer_options make_writer_options(Napi::Object const& options,
cudf::io::sink_info const& sink,
cudf::table_view const& table,
cudf::io::table_input_metadata* metadata) {
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto str_opt = [&](std::string const& key, std::string const& default_val) {
return has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
return std::move(cudf::io::orc_writer_options::builder(sink, table)
.metadata(metadata)
.enable_statistics(bool_opt("enableStatistics", true)
? cudf::io::statistics_freq::STATISTICS_PAGE
: cudf::io::statistics_freq::STATISTICS_NONE)
.compression(str_opt("compression", "none") == "snappy"
? cudf::io::compression_type::SNAPPY
: cudf::io::compression_type::NONE)
.build());
}
} // namespace
void Table::write_orc(Napi::CallbackInfo const& info) {
auto env = info.Env();
CallbackArgs args{info};
NODE_CUDF_EXPECT(args[1].IsObject(), "writeORC expects an Object of WriteORCOptions", env);
std::string file_path = args[0];
auto options = args[1].As<Napi::Object>();
cudf::table_view table = *this;
auto metadata = make_writer_columns_metadata(options, table);
auto writer_opts = make_writer_options(options, cudf::io::sink_info{file_path}, table, &metadata);
cudf::io::write_orc(writer_opts);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/join.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <cudf/join.hpp>
#include <cudf/table/table_view.hpp>
namespace nv {
namespace detail {
void check_join_args(std::string const& func_name, Napi::CallbackInfo const& info) {
if (info.Length() != 3 and info.Length() != 4) {
NAPI_THROW(Napi::Error::New(
info.Env(),
func_name + "expects a left, right, null_eqaulity and optionally a memory resource"));
}
if (!Table::IsInstance(info[0])) {
throw Napi::Error::New(info.Env(), func_name + " left argument expects a Table");
}
if (!Table::IsInstance(info[1])) {
throw Napi::Error::New(info.Env(), func_name + " right argument expects a Table");
}
if (!info[2].IsBoolean()) {
throw Napi::Error::New(info.Env(), func_name + " null_equality argument expects an bool");
}
}
Napi::Value make_gather_maps(
Napi::Env const& env,
std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>> gathers) {
using namespace cudf;
auto& lhs_map = gathers.first;
auto& rhs_map = gathers.second;
auto lhs_size = static_cast<size_type>(lhs_map->size());
auto rhs_size = static_cast<size_type>(rhs_map->size());
auto result = Napi::Array::New(env, 2);
result.Set(
0u,
Column::New(env,
std::make_unique<column>(data_type{type_id::INT32}, lhs_size, lhs_map->release())));
result.Set(
1u,
Column::New(env,
std::make_unique<column>(data_type{type_id::INT32}, rhs_size, rhs_map->release())));
return result;
}
} // namespace detail
std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
Table::full_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr) {
auto compare_nulls = null_equality ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return cudf::full_join(left, right, compare_nulls, mr);
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
Table::inner_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr) {
auto compare_nulls = null_equality ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return cudf::inner_join(left, right, compare_nulls, mr);
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
Table::left_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr) {
auto compare_nulls = null_equality ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return cudf::left_join(left, right, compare_nulls, mr);
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
std::unique_ptr<rmm::device_uvector<cudf::size_type>> Table::left_semi_join(
Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr) {
auto compare_nulls = null_equality ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return cudf::left_semi_join(left, right, compare_nulls, mr);
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
std::unique_ptr<rmm::device_uvector<cudf::size_type>> Table::left_anti_join(
Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr) {
auto compare_nulls = null_equality ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return cudf::left_anti_join(left, right, compare_nulls, mr);
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
Napi::Value Table::full_join(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
detail::check_join_args("full_join", info);
Table::wrapper_t lhs = args[0];
Table::wrapper_t rhs = args[1];
bool null_equality = args[2];
rmm::mr::device_memory_resource* mr = args[3];
return detail::make_gather_maps(info.Env(),
Table::full_join(info.Env(), lhs, rhs, null_equality, mr));
}
Napi::Value Table::inner_join(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
detail::check_join_args("inner_join", info);
Table::wrapper_t lhs = args[0];
Table::wrapper_t rhs = args[1];
bool null_equality = args[2];
rmm::mr::device_memory_resource* mr = args[3];
return detail::make_gather_maps(info.Env(),
Table::inner_join(info.Env(), lhs, rhs, null_equality, mr));
}
Napi::Value Table::left_join(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
detail::check_join_args("left_join", info);
Table::wrapper_t lhs = args[0];
Table::wrapper_t rhs = args[1];
bool null_equality = args[2];
rmm::mr::device_memory_resource* mr = args[3];
return detail::make_gather_maps(info.Env(),
Table::left_join(info.Env(), lhs, rhs, null_equality, mr));
}
Napi::Value Table::left_semi_join(Napi::CallbackInfo const& info) {
using namespace cudf;
CallbackArgs const args{info};
detail::check_join_args("left_semi_join", info);
Table::wrapper_t lhs = args[0];
Table::wrapper_t rhs = args[1];
bool null_equality = args[2];
rmm::mr::device_memory_resource* mr = args[3];
auto map = Table::left_semi_join(info.Env(), lhs, rhs, null_equality, mr);
auto map_size = static_cast<size_type>(map->size());
return Column::New(info.Env(),
std::make_unique<column>(data_type{type_id::INT32}, map_size, map->release()));
}
Napi::Value Table::left_anti_join(Napi::CallbackInfo const& info) {
using namespace cudf;
CallbackArgs const args{info};
detail::check_join_args("left_anti_join", info);
Table::wrapper_t lhs = args[0];
Table::wrapper_t rhs = args[1];
bool null_equality = args[2];
rmm::mr::device_memory_resource* mr = args[3];
auto map = Table::left_anti_join(info.Env(), lhs, rhs, null_equality, mr);
auto map_size = static_cast<size_type>(map->size());
return Column::New(info.Env(),
std::make_unique<column>(data_type{type_id::INT32}, map_size, map->release()));
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/explode.cpp
|
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/lists/explode.hpp>
namespace nv {
Table::wrapper_t Table::explode(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::explode(*this, explode_column_idx, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::explode(Napi::CallbackInfo const& info) {
return explode(info[0].ToNumber(),
NapiToCPP(info[1]).operator rmm::mr::device_memory_resource*());
}
Table::wrapper_t Table::explode_position(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::explode_position(*this, explode_column_idx, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::explode_position(Napi::CallbackInfo const& info) {
return explode_position(info[0].ToNumber(),
NapiToCPP(info[1]).operator rmm::mr::device_memory_resource*());
}
Table::wrapper_t Table::explode_outer(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::explode_outer(*this, explode_column_idx, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::explode_outer(Napi::CallbackInfo const& info) {
return explode_outer(info[0].ToNumber(),
NapiToCPP(info[1]).operator rmm::mr::device_memory_resource*());
}
Table::wrapper_t Table::explode_outer_position(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::explode_outer_position(*this, explode_column_idx, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::explode_outer_position(Napi::CallbackInfo const& info) {
return explode_outer_position(info[0].ToNumber(),
NapiToCPP(info[1]).operator rmm::mr::device_memory_resource*());
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/reshape.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/reshape.hpp>
namespace nv {
Column::wrapper_t Table::interleave_columns(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::interleave_columns(*this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::interleave_columns(Napi::CallbackInfo const& info) {
return interleave_columns(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/stream_compaction.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <nv_node/utilities/args.hpp>
#include <nv_node/utilities/napi_to_cpp.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <memory>
#include <vector>
namespace nv {
Table::wrapper_t Table::apply_boolean_mask(Column const& boolean_mask,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::apply_boolean_mask(cudf::table_view{{*this}}, boolean_mask, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Table::wrapper_t Table::drop_nulls(std::vector<cudf::size_type> keys,
cudf::size_type threshold,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::drop_nulls(*this, keys, threshold, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::drop_nulls(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return drop_nulls(args[0], args[1], args[2]);
}
Table::wrapper_t Table::drop_nans(std::vector<cudf::size_type> keys,
cudf::size_type threshold,
rmm::mr::device_memory_resource* mr) const {
try {
return Table::New(Env(), cudf::drop_nans(*this, keys, threshold, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::drop_nans(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return drop_nans(args[0], args[1], args[2]);
}
Table::wrapper_t Table::unique(std::vector<cudf::size_type> keys,
cudf::duplicate_keep_option keep,
bool is_nulls_equal,
rmm::mr::device_memory_resource* mr) const {
cudf::null_equality nulls_equal =
is_nulls_equal ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
try {
return Table::New(Env(), cudf::unique(*this, keys, keep, nulls_equal, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::unique(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return unique(args[0], args[1], args[2], args[3]);
}
Table::wrapper_t Table::distinct(std::vector<cudf::size_type> keys,
bool is_nulls_equal,
rmm::mr::device_memory_resource* mr) const {
cudf::null_equality nulls_equal =
is_nulls_equal ? cudf::null_equality::EQUAL : cudf::null_equality::UNEQUAL;
cudf::nan_equality nans_equal =
is_nulls_equal ? cudf::nan_equality::ALL_EQUAL : cudf::nan_equality::UNEQUAL;
try {
return Table::New(
Env(),
cudf::distinct(
*this, keys, cudf::duplicate_keep_option::KEEP_ANY, nulls_equal, nans_equal, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Table::distinct(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return unique(args[0], args[1], args[2]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/table/read_csv.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/io/csv.hpp>
#include <cudf/io/datasource.hpp>
#include <cudf/io/types.hpp>
#include <node_cudf/utilities/metadata.hpp>
namespace nv {
namespace {
cudf::io::csv_reader_options make_reader_options(Napi::Object const& options,
cudf::io::source_info const& source) {
auto env = options.Env();
auto is_null = [](Napi::Value const& val) {
return val.IsNull() || val.IsEmpty() || val.IsUndefined();
};
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto napi_opt = [&](std::string const& key) -> Napi::Value {
return has_opt(key) ? options.Get(key) : env.Undefined();
};
auto char_opt = [&](std::string const& key, std::string const& default_val) {
return (has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val)[0];
};
auto long_opt = [&](std::string const& key) {
return has_opt(key) ? options.Get(key).ToNumber().Int32Value() : -1;
};
auto byte_opt = [&](std::string const& key) {
return has_opt(key) ? options.Get(key).ToNumber() : 0;
};
auto bool_opt = [&](std::string const& key, bool default_val) {
return has_opt(key) ? options.Get(key).ToBoolean() == true : default_val;
};
auto to_upper = [](std::string const& str) {
std::string out = str;
std::transform(
str.begin(), str.end(), out.begin(), [](char const& c) { return std::toupper(c); });
return out;
};
auto compression_type = [&](std::string const& key) {
if (has_opt(key)) {
auto type = to_upper(options.Get(key).ToString());
if (type == "INFER") { return cudf::io::compression_type::AUTO; }
if (type == "SNAPPY") { return cudf::io::compression_type::SNAPPY; }
if (type == "GZIP") { return cudf::io::compression_type::GZIP; }
if (type == "BZ2") { return cudf::io::compression_type::BZIP2; }
if (type == "BROTLI") { return cudf::io::compression_type::BROTLI; }
if (type == "ZIP") { return cudf::io::compression_type::ZIP; }
if (type == "XZ") { return cudf::io::compression_type::XZ; }
}
return cudf::io::compression_type::NONE;
};
auto quote_style = [&](std::string const& key) {
if (has_opt(key)) {
auto style = to_upper(options.Get(key).ToString());
if (style == "ALL") { return cudf::io::quote_style::ALL; }
if (style == "NONE") { return cudf::io::quote_style::NONE; }
if (style == "NONNUMERIC") { return cudf::io::quote_style::NONNUMERIC; }
}
return cudf::io::quote_style::MINIMAL;
};
auto names_and_types = [&](std::string const& key) {
std::vector<std::string> names;
std::vector<cudf::data_type> types;
auto dtypes = napi_opt(key);
if (is_null(dtypes) || !dtypes.IsObject()) {
names.resize(0);
types.resize(0);
} else {
auto data_types = dtypes.ToObject();
auto type_names = data_types.GetPropertyNames();
names.reserve(type_names.Length());
types.reserve(type_names.Length());
for (uint32_t i = 0; i < type_names.Length(); ++i) {
auto name = type_names.Get(i).ToString().Utf8Value();
auto _type = data_types.Get(name).As<Napi::Object>();
auto type = arrow_to_cudf_type(_type);
names.push_back(name);
types.push_back(type);
}
}
names.shrink_to_fit();
types.shrink_to_fit();
return std::make_pair(std::move(names), std::move(types));
};
std::vector<std::string> names;
std::vector<cudf::data_type> types;
std::tie(names, types) = names_and_types("dataTypes");
auto opts = std::move(cudf::io::csv_reader_options::builder(source)
.byte_range_offset(byte_opt("byteOffset"))
.byte_range_size(byte_opt("byteRange"))
.compression(compression_type("compression"))
.mangle_dupe_cols(bool_opt("renameDuplicateColumns", true))
.nrows(long_opt("numRows"))
.skiprows(long_opt("skipHead"))
.skipfooter(long_opt("skipTail"))
.quoting(quote_style("quoteStyle"))
.lineterminator(char_opt("lineTerminator", "\n"))
.quotechar(char_opt("quoteCharacter", "\""))
.decimal(char_opt("decimalCharacter", "."))
.delim_whitespace(bool_opt("whitespaceAsDelimiter", false))
.skipinitialspace(bool_opt("skipInitialSpaces", false))
.skip_blank_lines(bool_opt("skipBlankLines", true))
.doublequote(bool_opt("allowDoubleQuoting", true))
.keep_default_na(bool_opt("keepDefaultNA", true))
.na_filter(bool_opt("autoDetectNullValues", true))
.dayfirst(bool_opt("inferDatesWithDayFirst", false))
.delimiter(char_opt("delimiter", ","))
.thousands(char_opt("thousands", "\0"))
.comment(char_opt("comment", "\0"))
.build());
auto header = napi_opt("header");
auto prefix = napi_opt("prefix");
auto null_values = napi_opt("nullValues");
auto true_values = napi_opt("trueValues");
auto false_values = napi_opt("falseValues");
auto dt_columns = napi_opt("datetimeColumns");
auto cols_to_return = napi_opt("columnsToReturn");
// Set the column names/dtypes and header inference flag
if (names.size() > 0 && types.size() > 0) {
opts.set_names(names);
opts.set_dtypes(types);
}
if (header.IsNumber()) {
// Pass header row index down if provided
opts.set_header(std::max(-1, header.ToNumber().Int32Value()));
} else if (names.size() > 0 || header.IsNull()) {
// * If header is `null` or names were explicitly provided, treat row 0 as data
opts.set_header(-1);
} else if (header.IsUndefined() ||
(header.IsString() && header.ToString().Utf8Value() == "infer")) {
// If header is `undefined` or "infer", try to parse row 0 as the header row
opts.set_header(0);
}
// set the prefix
if (!is_null(prefix) && prefix.IsString()) { opts.set_prefix(prefix.ToString().Utf8Value()); }
// set the column names to return
if (!is_null(cols_to_return) && cols_to_return.IsArray()) {
auto const names_or_indices = cols_to_return.As<Napi::Array>();
auto const string_col_names = [&]() {
for (uint32_t i = 0; i < names_or_indices.Length(); ++i) {
if (names_or_indices.Get(i).IsString()) { return true; }
}
return false;
}();
if (string_col_names) {
opts.set_use_cols_names(NapiToCPP{names_or_indices});
} else {
opts.set_use_cols_indexes(NapiToCPP{names_or_indices});
}
}
// set the column names or indices to infer as datetime columns
if (!is_null(dt_columns) && dt_columns.IsArray()) {
auto dt_cols = dt_columns.As<Napi::Array>();
for (uint32_t i = 0; i < dt_cols.Length(); ++i) {
std::vector<int32_t> date_indexes;
std::vector<std::string> date_names;
if (dt_cols.Get(i).IsString()) {
date_names.push_back(dt_cols.Get(i).ToString());
} else if (dt_cols.Get(i).IsNumber()) {
date_indexes.push_back(dt_cols.Get(i).ToNumber());
}
opts.set_parse_dates(date_names);
opts.set_parse_dates(date_indexes);
}
}
if (!is_null(null_values) && null_values.IsArray()) {
opts.set_na_values(NapiToCPP{null_values});
}
if (!is_null(true_values) && true_values.IsArray()) {
opts.set_true_values(NapiToCPP{true_values});
}
if (!is_null(false_values) && false_values.IsArray()) {
opts.set_false_values(NapiToCPP{false_values});
}
return opts;
}
std::vector<cudf::io::host_buffer> get_host_buffers(std::vector<Span<char>> const& sources) {
std::vector<cudf::io::host_buffer> buffers;
buffers.reserve(sources.size());
std::transform(sources.begin(), sources.end(), std::back_inserter(buffers), [&](auto const& buf) {
return cudf::io::host_buffer{buf.data(), buf.size()};
});
return buffers;
}
Napi::Value read_csv_files(Napi::Object const& options, std::vector<std::string> const& sources) {
auto env = options.Env();
auto result = cudf::io::read_csv(make_reader_options(options, cudf::io::source_info{sources}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
Napi::Value read_csv_strings(Napi::Object const& options, std::vector<Span<char>> const& sources) {
auto env = options.Env();
auto result = cudf::io::read_csv(
make_reader_options(options, cudf::io::source_info{get_host_buffers(sources)}));
auto output = Napi::Object::New(env);
output.Set("names", get_output_names_from_metadata(env, result));
output.Set("table", Table::New(env, get_output_cols_from_metadata(env, result)));
return output;
}
} // namespace
Napi::Value Table::read_csv(Napi::CallbackInfo const& info) {
auto env = info.Env();
NODE_CUDF_EXPECT(info[0].IsObject(), "readCSV expects an Object of ReadCSVOptions", env);
auto options = info[0].As<Napi::Object>();
auto sources = options.Get("sources");
NODE_CUDF_EXPECT(sources.IsArray(), "readCSV expects an Array of paths or buffers", env);
try {
return (options.Get("sourceType").ToString().Utf8Value() == "files")
? read_csv_files(options, NapiToCPP{sources})
: read_csv_strings(options, NapiToCPP{sources});
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/dataframe/join.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {DataFrame, SeriesMap} from '../data_frame';
import {Series} from '../series';
import {Table} from '../table';
import {ColumnsMap, CommonType, findCommonType, TypeMap} from '../types/mappings';
export type JoinKey<
P extends string,
T extends TypeMap,
TOn extends string,
Suffix extends string,
> = P extends TOn ? `${P}` : P extends keyof T ? `${P}${Suffix}` : `${P}`;
// clang-format off
export type JoinResult<
Lhs extends TypeMap,
Rhs extends TypeMap,
TOn extends(string & keyof Lhs & keyof Rhs),
LSuffix extends string,
RSuffix extends string
> = {
[P in keyof Lhs as JoinKey<string & P, Rhs, TOn, LSuffix>]: Lhs[P]
} & {
[P in keyof Rhs as JoinKey<string & P, Lhs, TOn, RSuffix>]: Rhs[P]
};
// clang-format on
interface JoinProps<
// clang-format off
Lhs extends TypeMap,
Rhs extends TypeMap,
TOn extends(string & keyof Lhs & keyof Rhs),
LSuffix extends string,
RSuffix extends string
// clang-format on
> {
lhs: DataFrame<Lhs>;
rhs: DataFrame<Rhs>;
on: TOn[];
lsuffix?: LSuffix;
rsuffix?: RSuffix;
nullEquality?: boolean;
memoryResource?: MemoryResource;
}
// clang-format off
export class Join<
Lhs extends TypeMap,
Rhs extends TypeMap,
TOn extends (string & keyof Lhs & keyof Rhs),
LSuffix extends string,
RSuffix extends string
> {
// clang-format on
private lhs: DataFrame<Lhs>;
private rhs: DataFrame<Rhs>;
private on: TOn[];
private lsuffix: LSuffix|'';
private rsuffix: RSuffix|'';
private nullEquality: boolean;
private memoryResource?: MemoryResource;
constructor(props: JoinProps<Lhs, Rhs, TOn, LSuffix, RSuffix>) {
const {lsuffix = '', rsuffix = '', nullEquality = true} = props;
this.lhs = props.lhs;
this.rhs = props.rhs;
this.on = props.on;
this.lsuffix = lsuffix;
this.rsuffix = rsuffix;
this.nullEquality = nullEquality;
this.memoryResource = props.memoryResource;
this.on.forEach((name) => {
const lhs_col = this.lhs.get(name);
const rhs_col = this.rhs.get(name);
if (!compareTypes(lhs_col.type, rhs_col.type)) {
const type = findCommonType(lhs_col.type, rhs_col.type);
this.lhs = this.lhs.assign({[name]: lhs_col.cast(type)}) as any as DataFrame<Lhs>;
this.rhs = this.rhs.assign({[name]: rhs_col.cast(type)}) as any as DataFrame<Rhs>;
}
});
}
public left() {
const {on} = this;
// clang-format off
const [lhsMap, rhsMap] = Table.leftJoin(
this.lhs.select(on).asTable(),
this.rhs.select(on).asTable(),
this.nullEquality,
this.memoryResource
).map((col) => Series.new(col));
// clang-format on
const lhs = this.lhs.gather(lhsMap, true);
const rhs = this.rhs.drop(on).gather(rhsMap, true);
const result = mergeResults(lhs, rhs, on, this.lsuffix, this.rsuffix);
return new DataFrame(result);
}
public right() {
return new Join({
on: this.on,
lhs: this.rhs,
rhs: this.lhs,
lsuffix: this.rsuffix,
rsuffix: this.lsuffix
})
.left();
}
public inner() {
const {on} = this;
// clang-format off
const [lhsMap, rhsMap] = Table.innerJoin(
this.lhs.select(on).asTable(),
this.rhs.select(on).asTable(),
this.nullEquality,
this.memoryResource
).map((col) => Series.new(col));
// clang-format on
const lhs = this.lhs.gather(lhsMap, true);
const rhs = this.rhs.drop(on).gather(rhsMap, true);
const result = mergeResults(lhs, rhs, on, this.lsuffix, this.rsuffix);
return new DataFrame(result);
}
public outer() {
const {on} = this;
// clang-format off
const [lhsMap, rhsMap] = Table.fullJoin(
this.lhs.select(on).asTable(),
this.rhs.select(on).asTable(),
this.nullEquality,
this.memoryResource
).map((col) => Series.new(col));
// clang-format on
const lhs = this.lhs.gather(lhsMap, true);
const rhs = this.rhs.gather(rhsMap, true);
// clang-format off
// replace lhs nulls with rhs valids for each common column name
const lhsValids = lhs.assign(on.reduce((cols, name) => ({
...cols, [name]: lhs.get(name).replaceNulls(rhs.get(name) as any)
}), <any>{}) as SeriesMap<Lhs>);
// clang-format on
const result = mergeResults(lhsValids, rhs.drop(on), on, this.lsuffix, this.rsuffix);
return new DataFrame(result);
}
public leftSemi() {
const {on} = this;
// clang-format off
const lhsMap = Series.new(Table.leftSemiJoin(
this.lhs.select(on).asTable(),
this.rhs.select(on).asTable(),
this.nullEquality,
this.memoryResource
));
// clang-format on
return this.lhs.gather(lhsMap, true);
}
public leftAnti() {
const {on} = this;
// clang-format off
const lhsMap = Series.new(Table.leftAntiJoin(
this.lhs.select(on).asTable(),
this.rhs.select(on).asTable(),
this.nullEquality,
this.memoryResource
));
// clang-format on
return this.lhs.gather(lhsMap, true);
}
}
// clang-format off
function mergeResults<
Lhs extends TypeMap,
Rhs extends TypeMap,
TOn extends string,
LSuffix extends string,
RSuffix extends string
>(lhs: DataFrame<Lhs>, rhs: DataFrame<Rhs>, on: TOn[], lsuffix: LSuffix, rsuffix: RSuffix) {
type TResult = JoinResult<Lhs, Rhs, TOn, LSuffix, RSuffix>;
// clang-format on
function getColumns<T extends TypeMap>(
lhs: DataFrame<T>, rhsNames: readonly string[], suffix: string) {
return lhs.names.reduce((cols, name) => {
const newName = on.includes(name as TOn) ? name
: rhsNames.includes(name) ? `${name}${suffix}`
: name;
cols[newName] = lhs.get(name)._col;
return cols;
}, <any>{}) as ColumnsMap<{
[P in keyof TResult]: //
P extends TOn ? CommonType<Lhs[P], Rhs[P]>: TResult[P]
}>;
}
const lhsCols = getColumns(lhs, rhs.names, lsuffix);
const rhsCols = getColumns(rhs, lhs.names, rsuffix);
return (
lsuffix == '' && rsuffix == '' // <<< If no suffixes and overlapping names,
? {...rhsCols, ...lhsCols} // <<< prefer the lhs cols over the rhs cols,
: {...lhsCols, ...rhsCols} // <<< otherwise prefer the right cols.
);
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/dataframe/print.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DataFrame} from '../data_frame';
import {Series} from '../series';
import {Int32, Utf8String} from '../types/dtypes';
import {TypeMap} from '../types/mappings';
export type DisplayOptions = {
/**
* The maximum number of columns to display before truncation. Truncation may also occur
* if the total printed width in characters exceeds `width`
* (default: 20)
*
*/
maxColumns?: number,
/**
* The maximum width in characters of a column when printing a DataFrame. When the column *
* overflows, a "..." placeholder is embedded in the output. A value of zero means unlimited.
* (default: 50)
*/
maxColWidth?: number,
/**
* The maximum number of rows to output when printing a DataFrame. A value of zero means
* unlimited. (default: 60)
*/
maxRows?: number,
/**
* Width of the display in characters. A value of zero means unlimited. (default: 0)
*/
width?: number,
}
const SEP = ' ';
const SEP_WIDTH = SEP.length;
export class DataFrameFormatter<T extends TypeMap> {
private frame: DataFrame;
private maxColumns: number;
private maxColWidth: number;
private maxRows: number;
private width: number;
private htrunc: boolean;
private vtrunc: boolean;
private measuredWidths: {[key: string]: number};
constructor(options: DisplayOptions, frame: DataFrame<T>) {
this.maxColumns = options.maxColumns ?? 20;
this.maxColWidth = options.maxColWidth ?? 50;
this.maxRows = options.maxRows ?? 60;
this.width = options.width ?? 0;
this.htrunc = false;
this.vtrunc = false;
if (this.maxColWidth < 4) { throw Error('maxColWidth must be at least 4'); }
let tmp = this._preprocess(frame);
this.measuredWidths = this._measureWidths(tmp);
while (this.width > 0 && this._totalWidth(tmp) > this.width) {
this.htrunc = true;
const names = [...tmp.names];
const N = Math.ceil((names.length - 1) / 2);
tmp = tmp.drop([names[N]]);
}
this.frame = tmp;
}
private _preprocess(frame: DataFrame<T>) {
let tmp: DataFrame = frame;
if (this.maxColumns > 0 && tmp.numColumns > this.maxColumns) {
this.htrunc = true;
const half = this.maxColumns / 2;
const first = Math.ceil(half);
const last = this.maxColumns - first;
const last_names = last == 0 ? [] : tmp.names.slice(-last);
const trunc_names = [...tmp.names.slice(0, first), ...last_names];
tmp = tmp.select(trunc_names);
}
if (this.maxRows > 0 && tmp.numRows > this.maxRows - 1) {
this.vtrunc = true;
const half = (this.maxRows - 1) / 2;
const first = Math.ceil(half);
const last = this.maxRows - first - 1;
tmp = tmp.head(first).concat(tmp.tail(last));
}
return tmp.castAll(new Utf8String).replaceNulls('null');
}
render(): string {
const headers: string[] = [...this.frame.names];
const widths: number[] = this._computeWidthsForColumns(headers);
const lines = [];
lines.push(this._formatFields(headers, widths, ' '));
for (let i = 0; i < this.frame.numRows; ++i) {
const fields = headers.map((name: string) => this.frame.get(name).getValue(i));
lines.push(this._formatFields(fields, widths));
}
if (this.vtrunc) {
const N = 1 + Math.floor((lines.length - 1) / 2); // 1+ for header row
const dots = Array(headers.length).fill('...');
lines.splice(N, 1, this._formatFields(dots, widths));
}
lines.push('');
return lines.join('\n');
}
private _totalWidth(frame: DataFrame) {
const widths = this._computeWidthsForColumns([...frame.names]);
return widths.reduce((x, y) => x + y, 0) + (widths.length - 1) * SEP_WIDTH;
}
private _computeWidthsForColumns(headers: string[]) {
const widths = [];
for (const name of headers) { widths.push(this.measuredWidths[name]); }
return widths;
}
private _measureWidths(frame: DataFrame) {
const inds = Series.sequence({type: new Int32, size: frame.numRows, init: 0});
const widths: {[key: string]: number} = {};
for (const name of [...frame.names]) {
const lengths = (frame.get(name) as Series<Utf8String>).len();
const truncated = lengths.scatter(3, inds.filter(lengths.gt(this.maxColWidth))); // '...'
widths[name] = Math.max(name.length, Number(truncated.max()));
}
return widths;
}
_formatFields(rawFields: string[], rawWidths: number[], placeholder = '...') {
const fields = [...rawFields];
const widths = [...rawWidths];
if (this.htrunc) {
const N = Math.ceil(rawFields.length / 2);
fields.splice(N, 0, placeholder);
widths.splice(N, 0, 3);
}
const truncated = fields.map((val: string) => val.length > this.maxColWidth ? '...' : val);
return truncated.map((val: string, i: number) => val.padStart(widths[i], ' ')).join(SEP);
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/dataframe/concat.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {Column} from '../column';
import {DataFrame, SeriesMap} from '../data_frame';
import {Series} from '../series';
import {Table} from '../table';
import {DataType} from '../types/dtypes';
import {CommonTypes, findCommonType} from '../types/mappings';
// clang-format off
export type ConcatTypeMap<D extends DataFrame, T extends unknown[]> =
T extends [] ? D['types'] :
T extends [DataFrame] ? CommonTypes<D['types'], T[0]['types']> :
T extends [DataFrame, ...infer U] ? CommonTypes<D['types'], ConcatTypeMap<T[0], U>> :
D['types'] ;
// clang-format on
export function concat<TFirst extends DataFrame, TRest extends DataFrame[]>(first: TFirst,
...others: TRest) {
const dfs = ([first, ...others] as [TFirst, ...TRest]).filter((df) => df.numColumns > 0);
const names =
[...new Set(dfs.reduce((names: string[], df) => names.concat(df.names), [])).keys()];
/**
* Array<Array<(Column|null)>> -- If a DF has a Column for a given name, it will be in the list
* otherwise there will be a null in that slot. For example:
* ```
* concat(new DataFrame({a, b}), new DataFrame({b, c}))
*
* columnsPerDF == [
* [dfs[0].get("a"), dfs[0].get("b"), null],
* [ null, dfs[1].get("b"), dfs[1].get("c")]
* ]
* ```
*/
const rows = dfs.map((df) => { //
return names.map((name) => { //
return df.has(name) //
? df.get(name)._col as Column<DataType> //
: null;
});
});
/**
* Array<DataType> -- Find the common dtype for each column in the final table.
* ```
* [Float64, Int32, Float64]
* ```
*/
const commonDtypes = names.map((_, colIdx) => {
return rows.reduce((commonDtype: DataType|null, columns) => {
const column = columns[colIdx];
return !column ? commonDtype ///< If Column is null, return the latest common dtype
: !commonDtype ? column.type ///< If this is the first non-null Column, use its dtype
: findCommonType(commonDtype, column.type); ///< find the common dtype
}, null)!;
});
/**
* If any columns are null, create an empty column with type of common dtype
* Otherwise cast the column using the common dtype (if it isn't already the correct type).
*/
const tables = dfs.map((df, rowIdx) => {
// Function to create an empty Column
const makeEmptyColumn = (() => {
let data: any[]|undefined;
return (type: DataType) => {
// Lazily create and reuse the empty data Array
data = data || new Array(df.numRows).fill(null);
return Series.new({type, data})._col;
};
})();
// 1. Create empty Columns for any null slots
// 2. Cast non-null Columns to the common dtype
const columns = rows[rowIdx].map((column, colIdx) => {
const commonDtype = commonDtypes[colIdx];
if (column === null) { // 1.
return makeEmptyColumn(commonDtype);
} else if (!compareTypes(column.type, commonDtype)) { // 2.
return column.cast(commonDtype);
}
return column;
});
// Return each DataFrame to concatenate
return new DataFrame(
names.reduce((map, name, index) => ({...map, [name]: columns[index]}), {}));
});
const constructChild = (tables[0] as any).__constructChild.bind(tables[0]);
const result = Table.concat(tables.map((df) => df.asTable()));
type TResultTypeMap = ConcatTypeMap<TFirst, TRest>;
// clang-format off
return new DataFrame(
names.reduce((map, name, index) =>
({...map, [name]: constructChild(name, result.getColumnByIndex(index))}),
{} as SeriesMap<{[P in keyof TResultTypeMap]: TResultTypeMap[P]}>)
) as TResultTypeMap[keyof TResultTypeMap] extends never
? never
: DataFrame<{[P in keyof TResultTypeMap]: TResultTypeMap[P]}>;
// clang-format on
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/groupby.hpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/table.hpp>
#include <nv_node/objectwrap.hpp>
#include <nv_node/utilities/args.hpp>
#include <cudf/groupby.hpp>
#include <napi.h>
namespace nv {
/**
* @brief An owning wrapper around a cudf::groupy::groupby.
*
*/
struct GroupBy : public EnvLocalObjectWrap<GroupBy> {
/**
* @brief Initialize and export the Groupby JavaScript constructor and prototype.
*
* @param env The active JavaScript environment.
* @param exports The exports object to decorate.
* @return Napi::Function The GroupBy constructor function.
*/
static Napi::Function Init(Napi::Env const& env, Napi::Object exports);
/**
* @brief Construct a new Groupby instance
*
*/
static wrapper_t New(Napi::Env const& env);
/**
* @brief Construct a new Groupby instance from JavaScript.
*
*/
GroupBy(CallbackArgs const& args);
private:
std::unique_ptr<cudf::groupby::groupby> groupby_;
Napi::Value get_groups(Napi::CallbackInfo const& info);
Napi::Value argmax(Napi::CallbackInfo const& info);
Napi::Value argmin(Napi::CallbackInfo const& info);
Napi::Value count(Napi::CallbackInfo const& info);
Napi::Value max(Napi::CallbackInfo const& info);
Napi::Value mean(Napi::CallbackInfo const& info);
Napi::Value median(Napi::CallbackInfo const& info);
Napi::Value min(Napi::CallbackInfo const& info);
Napi::Value nth(Napi::CallbackInfo const& info);
Napi::Value nunique(Napi::CallbackInfo const& info);
Napi::Value std(Napi::CallbackInfo const& info);
Napi::Value sum(Napi::CallbackInfo const& info);
Napi::Value var(Napi::CallbackInfo const& info);
Napi::Value quantile(Napi::CallbackInfo const& info);
Napi::Value collect_list(Napi::CallbackInfo const& info);
Napi::Value collect_set(Napi::CallbackInfo const& info);
std::pair<Table::wrapper_t, rmm::mr::device_memory_resource*> _get_basic_args(
Napi::CallbackInfo const& info);
template <typename MakeAggregation>
Napi::Value _single_aggregation(Napi::CallbackInfo const& info,
Table::wrapper_t const& values_table,
rmm::mr::device_memory_resource* const mr,
MakeAggregation const& make_aggregation);
};
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/table.hpp
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/column.hpp>
#include <node_rmm/device_buffer.hpp>
#include <nv_node/objectwrap.hpp>
#include <nv_node/utilities/args.hpp>
#include <cudf/copying.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <napi.h>
namespace nv {
/**
* @brief An owning wrapper around a cudf::Table.
*
*/
struct Table : public EnvLocalObjectWrap<Table> {
/**
* @brief Initialize and export the Table JavaScript constructor and prototype.
*
* @param env The active JavaScript environment.
* @param exports The exports object to decorate.
* @return Napi::Function The Table constructor function.
*/
static Napi::Function Init(Napi::Env const& env, Napi::Object exports);
/**
* @brief Construct a new Table instance from existing device memory.
*
* @param children Array of child columns
* @return wrapper_t The new Table instance
*/
static wrapper_t New(Napi::Env const& env, Napi::Array const& columns = {});
/**
* @brief Construct a new Table instance from an existing libcudf Table
*
* @param table The libcudf Table to adapt
* @return wrapper_t The new Table instance
*/
static wrapper_t New(Napi::Env const& env, std::unique_ptr<cudf::table> table);
/**
* @brief Construct a new Column instance from JavaScript.
*
*/
Table(CallbackArgs const& args);
/**
* @brief Destructor called when the JavaScript VM garbage collects this Table
* instance.
*
* @param env The active JavaScript environment.
*/
void Finalize(Napi::Env) override;
/**
* @brief Explicitly free the device memory associated with this Table.
*
* @param env The active JavaScript environment.
*/
void dispose(Napi::Env);
/**
* @brief Returns the number of columns in the table
*/
inline cudf::size_type num_columns() const noexcept { return num_columns_; }
/**
* @brief Returns the number of columns in the table
*/
inline cudf::size_type num_rows() const noexcept { return num_rows_; }
/**
* @brief Creates an immutable, non-owning view of the table
*
* @return cudf::table_view The immutable, non-owning view
*/
cudf::table_view view() const;
/**
* @brief Creates a mutable, non-owning view of the table
*
* @return cudf::mutable_table_view The mutable, non-owning view
*/
cudf::mutable_table_view mutable_view();
/**
* @brief Implicit conversion operator to a `table_view`.
*
* This allows passing a `table` object directly into a function that
* requires a `table_view`. The conversion is automatic.
*
* @return cudf::table_view Immutable, non-owning `table_view`
*/
inline operator cudf::table_view() const { return this->view(); };
/**
* @brief Implicit conversion operator to a `mutable_table_view`.
*
* This allows pasing a `table` object into a function that accepts a
*`mutable_table_view `. The conversion is automatic.
* @return cudf::mutable_table_view Mutable, non-owning `mutable_table_view`
*/
inline operator cudf::mutable_table_view() { return this->mutable_view(); };
/**
* @brief Returns a const reference to the specified column
*
* @throws std::out_of_range
* If i is out of the range [0, num_columns)
*
* @param i Index of the desired column
* @return A const reference to the desired column
*/
inline Column const& get_column(cudf::size_type i) const { return *(columns_[i].Value()); }
// table/copying.cpp
Table::wrapper_t gather(
Column const& gather_map,
cudf::out_of_bounds_policy bounds_policy = cudf::out_of_bounds_policy::DONT_CHECK,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t scatter(
std::vector<std::reference_wrapper<const cudf::scalar>> const& source,
Column const& indices,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t scatter(
Table const& source,
Column const& indices,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// table/join.cpp
static std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
full_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
static std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
inner_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
static std::pair<std::unique_ptr<rmm::device_uvector<cudf::size_type>>,
std::unique_ptr<rmm::device_uvector<cudf::size_type>>>
left_join(Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
static std::unique_ptr<rmm::device_uvector<cudf::size_type>> left_semi_join(
Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
static std::unique_ptr<rmm::device_uvector<cudf::size_type>> left_anti_join(
Napi::Env const& env,
Table const& left,
Table const& right,
bool null_equality,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// table/explode.cpp
Table::wrapper_t explode(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const;
Table::wrapper_t explode_position(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const;
Table::wrapper_t explode_outer(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const;
Table::wrapper_t explode_outer_position(cudf::size_type explode_column_idx,
rmm::mr::device_memory_resource* mr) const;
// table/reshape.cpp
Column::wrapper_t interleave_columns(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// table/stream_compaction.cpp
Table::wrapper_t apply_boolean_mask(
Column const& boolean_mask,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t drop_nulls(
std::vector<cudf::size_type> keys,
cudf::size_type threshold,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t drop_nans(
std::vector<cudf::size_type> keys,
cudf::size_type threshold,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t unique(
std::vector<cudf::size_type> keys,
cudf::duplicate_keep_option keep,
bool nulls_equal,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Table::wrapper_t distinct(
std::vector<cudf::size_type> keys,
bool nulls_equal,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
private:
cudf::size_type num_columns_{}; ///< The number of columns in the table
cudf::size_type num_rows_{}; ///< The number of rows
std::vector<Napi::Reference<Column::wrapper_t>> columns_{}; ///< columns of table
bool disposed_{false}; ///< Flag indicating this table has been disposed
void dispose(Napi::CallbackInfo const&);
Napi::Value num_columns(Napi::CallbackInfo const& info);
Napi::Value num_rows(Napi::CallbackInfo const& info);
Napi::Value select(Napi::CallbackInfo const& info);
Napi::Value get_column(Napi::CallbackInfo const& info);
// table/concatenate.cpp
static Napi::Value concat(Napi::CallbackInfo const& info);
// table/copying.cpp
Napi::Value gather(Napi::CallbackInfo const& info);
Napi::Value scatter_scalar(Napi::CallbackInfo const& info);
Napi::Value scatter_table(Napi::CallbackInfo const& info);
Napi::Value apply_boolean_mask(Napi::CallbackInfo const& info);
// table/join.cpp
static Napi::Value full_join(Napi::CallbackInfo const& info);
static Napi::Value inner_join(Napi::CallbackInfo const& info);
static Napi::Value left_join(Napi::CallbackInfo const& info);
static Napi::Value left_semi_join(Napi::CallbackInfo const& info);
static Napi::Value left_anti_join(Napi::CallbackInfo const& info);
// table/explode.cpp
Napi::Value explode(Napi::CallbackInfo const& info);
Napi::Value explode_position(Napi::CallbackInfo const& info);
Napi::Value explode_outer(Napi::CallbackInfo const& info);
Napi::Value explode_outer_position(Napi::CallbackInfo const& info);
// table/reshape.cpp
Napi::Value interleave_columns(Napi::CallbackInfo const& info);
// table/stream_compaction.cpp
Napi::Value drop_nulls(Napi::CallbackInfo const& info);
Napi::Value drop_nans(Napi::CallbackInfo const& info);
Napi::Value unique(Napi::CallbackInfo const& info);
Napi::Value distinct(Napi::CallbackInfo const& info);
static Napi::Value read_csv(Napi::CallbackInfo const& info);
void write_csv(Napi::CallbackInfo const& info);
static Napi::Value read_parquet(Napi::CallbackInfo const& info);
void write_parquet(Napi::CallbackInfo const& info);
static Napi::Value read_orc(Napi::CallbackInfo const& info);
void write_orc(Napi::CallbackInfo const& info);
static Napi::Value from_arrow(Napi::CallbackInfo const& info);
Napi::Value to_arrow(Napi::CallbackInfo const& info);
Napi::Value order_by(Napi::CallbackInfo const& info);
};
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/column.hpp
|
// Copyright (c) 2020-2023, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/scalar.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <node_rmm/device_buffer.hpp>
#include <nv_node/objectwrap.hpp>
#include <nv_node/utilities/args.hpp>
#include <cudf/aggregation.hpp>
#include <cudf/binaryop.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/reduction.hpp>
#include <cudf/replace.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/strings/combine.hpp>
#include <cudf/strings/json.hpp>
#include <cudf/strings/padding.hpp>
#include <cudf/strings/regex/flags.hpp>
#include <cudf/types.hpp>
#include <cudf/unary.hpp>
#include <rmm/device_buffer.hpp>
#include <napi.h>
namespace nv {
/**
* @brief An owning wrapper around a cudf::Column.
*
*/
struct Column : public EnvLocalObjectWrap<Column> {
/**
* @brief Initialize and export the Column JavaScript constructor and prototype.
*
* @param env The active JavaScript environment.
* @param exports The exports object to decorate.
* @return Napi::Function The Column constructor function.
*/
static Napi::Function Init(Napi::Env const& env, Napi::Object exports);
/**
* @brief Construct a new Column instance from a cudf::column.
*
* @param column The column in device memory.
*/
static wrapper_t New(Napi::Env const& env, std::unique_ptr<cudf::column> column);
/**
* @brief Construct a new Column instance from JavaScript.
*
*/
Column(CallbackArgs const& args);
/**
* @brief Destructor called when the JavaScript VM garbage collects this Column
* instance.
*
* @param env The active JavaScript environment.
*/
void Finalize(Napi::Env) override;
/**
* @brief Explicitly free the device memory associated with this Column.
*
* @param env The active JavaScript environment.
*/
void dispose(Napi::Env);
/**
* @brief Returns the column's logical element type
*/
inline cudf::data_type type() const noexcept { return arrow_to_cudf_type(type_.Value()); }
/**
* @brief Returns the number of elements
*/
inline cudf::size_type size() const noexcept { return size_; }
/**
* @brief Returns the data element offset
*/
inline cudf::size_type offset() const noexcept { return offset_; }
/**
* @brief Return a const pointer to the data buffer
*/
inline DeviceBuffer::wrapper_t data() const { return data_.Value(); }
/**
* @brief Return a const pointer to the null bitmask buffer
*/
inline DeviceBuffer::wrapper_t null_mask() const { return null_mask_.Value(); }
/**
* @brief Sets the column's null value indicator bitmask to `new_null_mask`.
*
* @throw cudf::logic_error if new_null_count is larger than 0 and the size
* of `new_null_mask` does not match the size of this column.
*
* @param new_null_mask New null value indicator bitmask (lvalue overload &
* copied) to set the column's null value indicator mask. May be empty if
* `new_null_count` is 0 or `UNKOWN_NULL_COUNT`.
* @param new_null_count Optional, the count of null elements. If unknown,
* specify `UNKNOWN_NULL_COUNT` to indicate that the null count should be
* computed on the first invocation of `null_count()`.
*/
void set_null_mask(Napi::Value const& new_null_mask,
cudf::size_type new_null_count = cudf::UNKNOWN_NULL_COUNT);
/**
* @brief Updates the count of null elements.
*
* @note `UNKNOWN_NULL_COUNT` can be specified as `new_null_count` to force
* the next invocation of `null_count()` to recompute the null count from the
* null mask.
*
* @throw cudf::logic_error if `new_null_count > 0 and nullable() == false`
*
* @param new_null_count The new null count.
*/
void set_null_count(cudf::size_type new_null_count);
/**
* @brief Indicates whether it is possible for the column to contain null
* values, i.e., it has an allocated null mask.
*
* This may return `false` iff `null_count() == 0`.
*
* May return true even if `null_count() == 0`. This function simply indicates
* whether the column has an allocated null mask.
*
* @return true The column can hold null values
* @return false The column cannot hold null values
*/
inline bool nullable() const { return null_mask()->size() > 0; }
/**
* @brief Returns the count of null elements.
*
* @note If the column was constructed with `UNKNOWN_NULL_COUNT`, or if at any
* point `set_null_count(UNKNOWN_NULL_COUNT)` was invoked, then the
* first invocation of `null_count()` will compute and store the count of null
* elements indicated by the `null_mask` (if it exists).
*/
cudf::size_type null_count() const;
/**
* @brief Creates an immutable, non-owning view of the column's data and
* children.
*
* @return cudf::column_view The immutable, non-owning view
*/
cudf::column_view view() const;
/**
* @brief Returns the number of child columns
*/
inline cudf::size_type num_children() const { return children_.size(); }
/**
* @brief Returns a const reference to the specified child
*
* @param child_index Index of the desired child
* @return column const& Const reference to the desired child
*/
inline Column::wrapper_t child(cudf::size_type child_index) const noexcept {
return children_[child_index].Value();
};
/**
* @brief Returns aa vector of the column's childre
*
* @return Array of children
*/
inline Napi::Array children() const noexcept {
uint32_t idx = 0;
auto arr = Napi::Array::New(Env(), num_children());
std::for_each(children_.begin(),
children_.end(),
[&](Napi::Reference<Column::wrapper_t> const& val) mutable {
arr.Set((idx++), (val.Value()));
});
return arr;
}
/**
* @brief Creates a mutable, non-owning view of the column's data and
* children.
*
* @note Creating a mutable view of a `column` invalidates the `column`'s
* `null_count()` by setting it to `UNKNOWN_NULL_COUNT`. The user can
* either explicitly update the null count with `set_null_count()`, or
* if not, the null count will be recomputed on the next invocation of
*`null_count()`.
*
* @return cudf::mutable_column_view The mutable, non-owning view
*/
cudf::mutable_column_view mutable_view();
/**
* @brief Implicit conversion operator to a `column_view`.
*
* This allows passing a `column` object directly into a function that
* requires a `column_view`. The conversion is automatic.
*
* @return cudf::column_view Immutable, non-owning `column_view`
*/
inline operator cudf::column_view() const { return this->view(); };
/**
* @brief Implicit conversion operator to a `mutable_column_view`.
*
* This allows pasing a `column` object into a function that accepts a
*`mutable_column_view`. The conversion is automatic.
* @note Creating a mutable view of a `column` invalidates the `column`'s
* `null_count()` by setting it to `UNKNOWN_NULL_COUNT`. For best performance,
* the user should explicitly update the null count with `set_null_count()`.
* Otherwise, the null count will be recomputed on the next invocation of
* `null_count()`.
*
* @return cudf::mutable_column_view Mutable, non-owning `mutable_column_view`
*/
inline operator cudf::mutable_column_view() { return this->mutable_view(); };
// column/reductions.cpp
/**
* @copydoc cudf::minmax(cudf::column_view const& col, rmm::mr::device_memory_resource* mr)
*
* @return std::pair<Scalar, Scalar>
*/
std::pair<Scalar::wrapper_t, Scalar::wrapper_t> minmax(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @copydoc cudf::reduce(cudf::column_view const &col, std::unique_ptr<aggregation> const &agg,
* data_type output_dtype, rmm::mr::device_memory_resource* mr)
*
* @return Scalar
*/
Scalar::wrapper_t reduce(
std::unique_ptr<cudf::reduce_aggregation> const& agg,
cudf::data_type const& output_dtype,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @copydoc cudf::scan(cudf::column_view const &col, std::unique_ptr<aggregation> const &agg,
* cudf::scan_type inclusive, cudf::null_policy null_handling, rmm::mr::device_memory_resource*
* mr)
*
* @return Column
*/
Column::wrapper_t scan(
std::unique_ptr<cudf::scan_aggregation> const& agg,
cudf::scan_type inclusive,
cudf::null_policy null_handling = cudf::null_policy::EXCLUDE,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @copydoc cudf::sum(rmm::mr::device_memory_resource* mr)
*
* @return Scalar
*/
Scalar::wrapper_t sum(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @copydoc cudf::product(rmm::mr::device_memory_resource* mr)
*
* @return Scalar
*/
Scalar::wrapper_t product(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @copydoc cudf::sum_of_squares(rmm::mr::device_memory_resource* mr)
*
* @return Scalar
*/
Scalar::wrapper_t sum_of_squares(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_mean_aggregation()
*
* @param rmm::mr::device_memory_resource* mr
*
* @return Scalar
*/
Scalar::wrapper_t mean(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_median_aggregation()
*
* @param rmm::mr::device_memory_resource* mr
*
* @return Scalar
*/
Scalar::wrapper_t median(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_nunique_aggregation()
*
* @param bool dropna if true, compute using cudf::null_policy::EXCLUDE, else use
* cudf::null_policy::INCLUDE
* @param rmm::mr::device_memory_resource* mr
* @return Scalar
*/
Scalar::wrapper_t nunique(
bool dropna = true,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_variance_aggregation(ddof)
*
* @param cudf::size_type ddof Delta Degrees of Freedom. The divisor used in calculations is
* N - ddof, where N represents the number of elements. default is 1
* @param rmm::mr::device_memory_resource* mr
* @return Scalar
*/
Scalar::wrapper_t variance(
cudf::size_type ddof = 1,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_std_aggregation(ddof)
*
* @param cudf::size_type ddof Delta Degrees of Freedom. The divisor used in calculations is
* N - ddof, where N represents the number of elements. default is 1
* @param rmm::mr::device_memory_resource* mr
* @return Scalar
*/
Scalar::wrapper_t std(
cudf::size_type ddof = 1,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Returns a reduce computation based on cudf::make_quantile_aggregation(q, i)
*
* @param double q the quantile(s) to compute, 0<=q<=1, default 0.5
* @param rmm::mr::device_memory_resource* mr
* @return Scalar
*/
Scalar::wrapper_t quantile(
double q = 0.5,
cudf::interpolation i = cudf::interpolation::LINEAR,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Return the cumulative max
*
* @return Scalar
*/
Column::wrapper_t cumulative_max(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Return the cumulative minimum
*
* @return Scalar
*/
Column::wrapper_t cumulative_min(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Return the cumulative product
*
* @return Scalar
*/
Column::wrapper_t cumulative_product(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
/**
* @brief Return the cumulative sum
*
* @return Scalar
*/
Column::wrapper_t cumulative_sum(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/binaryop.cpp
// cudf::binary_operator::ADD
Column::wrapper_t operator+(Column const& other) const;
Column::wrapper_t operator+(Scalar const& other) const;
Column::wrapper_t add(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t add(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::SUB
Column::wrapper_t operator-(Column const& other) const;
Column::wrapper_t operator-(Scalar const& other) const;
Column::wrapper_t sub(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t sub(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::MUL
Column::wrapper_t operator*(Column const& other) const;
Column::wrapper_t operator*(Scalar const& other) const;
Column::wrapper_t mul(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t mul(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::DIV
Column::wrapper_t operator/(Column const& other) const;
Column::wrapper_t operator/(Scalar const& other) const;
Column::wrapper_t div(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t div(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::TRUE_DIV
Column::wrapper_t true_div(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t true_div(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::FLOOR_DIV
Column::wrapper_t floor_div(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t floor_div(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::MOD
Column::wrapper_t operator%(Column const& other) const;
Column::wrapper_t operator%(Scalar const& other) const;
Column::wrapper_t mod(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t mod(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::POW
Column::wrapper_t pow(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t pow(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::EQUAL
Column::wrapper_t operator==(Column const& other) const;
Column::wrapper_t operator==(Scalar const& other) const;
Column::wrapper_t eq(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t eq(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::NOT_EQUAL
Column::wrapper_t operator!=(Column const& other) const;
Column::wrapper_t operator!=(Scalar const& other) const;
Column::wrapper_t ne(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t ne(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::LESS
Column::wrapper_t operator<(Column const& other) const;
Column::wrapper_t operator<(Scalar const& other) const;
Column::wrapper_t lt(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t lt(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::GREATER
Column::wrapper_t operator>(Column const& other) const;
Column::wrapper_t operator>(Scalar const& other) const;
Column::wrapper_t gt(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t gt(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::LESS_EQUAL
Column::wrapper_t operator<=(Column const& other) const;
Column::wrapper_t operator<=(Scalar const& other) const;
Column::wrapper_t le(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t le(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::GREATER_EQUAL
Column::wrapper_t operator>=(Column const& other) const;
Column::wrapper_t operator>=(Scalar const& other) const;
Column::wrapper_t ge(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t ge(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::BITWISE_AND
Column::wrapper_t operator&(Column const& other) const;
Column::wrapper_t operator&(Scalar const& other) const;
Column::wrapper_t bitwise_and(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t bitwise_and(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::BITWISE_OR
Column::wrapper_t operator|(Column const& other) const;
Column::wrapper_t operator|(Scalar const& other) const;
Column::wrapper_t bitwise_or(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t bitwise_or(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::BITWISE_XOR
Column::wrapper_t operator^(Column const& other) const;
Column::wrapper_t operator^(Scalar const& other) const;
Column::wrapper_t bitwise_xor(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t bitwise_xor(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::LOGICAL_AND
Column::wrapper_t operator&&(Column const& other) const;
Column::wrapper_t operator&&(Scalar const& other) const;
Column::wrapper_t logical_and(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t logical_and(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::LOGICAL_OR
Column::wrapper_t operator||(Column const& other) const;
Column::wrapper_t operator||(Scalar const& other) const;
Column::wrapper_t logical_or(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t logical_or(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::SHIFT_LEFT
Column::wrapper_t operator<<(Column const& other) const;
Column::wrapper_t operator<<(Scalar const& other) const;
Column::wrapper_t shift_left(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t shift_left(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::SHIFT_RIGHT
Column::wrapper_t operator>>(Column const& other) const;
Column::wrapper_t operator>>(Scalar const& other) const;
Column::wrapper_t shift_right(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t shift_right(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::SHIFT_RIGHT_UNSIGNED
Column::wrapper_t shift_right_unsigned(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t shift_right_unsigned(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::LOG_BASE
Column::wrapper_t log_base(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t log_base(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::ATAN2
Column::wrapper_t atan2(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t atan2(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::NULL_EQUALS
Column::wrapper_t null_equals(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t null_equals(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::NULL_MAX
Column::wrapper_t null_max(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t null_max(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// cudf::binary_operator::NULL_MIN
Column::wrapper_t null_min(
Column const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t null_min(
Scalar const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t operator[](Column const& gather_map) const;
Column::wrapper_t binary_operation(
Column const& rhs,
cudf::binary_operator op,
cudf::type_id output_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t binary_operation(
Scalar const& rhs,
cudf::binary_operator op,
cudf::type_id output_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/concatenate.cpp
Column::wrapper_t concat(
cudf::column_view const& other,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// column/stream_compaction.cpp
Column::wrapper_t apply_boolean_mask(
Column const& boolean_mask,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t drop_nulls(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t drop_nans(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/filling.cpp
static Column::wrapper_t sequence(
Napi::Env const& env,
cudf::size_type size,
cudf::scalar const& init,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
static Column::wrapper_t sequence(
Napi::Env const& env,
cudf::size_type size,
cudf::scalar const& init,
cudf::scalar const& step,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
inline static Column::wrapper_t sequence(
Napi::Env const& env,
cudf::size_type size,
Scalar::wrapper_t const& init,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
return sequence(env, size, init->operator cudf::scalar&(), mr);
}
inline static Column::wrapper_t sequence(
Napi::Env const& env,
cudf::size_type size,
Scalar::wrapper_t const& init,
Scalar::wrapper_t const& step,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
return sequence(env, size, init->operator cudf::scalar&(), step->operator cudf::scalar&(), mr);
}
inline static Column::wrapper_t zeros(
Napi::Env const& env,
cudf::type_id type,
cudf::size_type size,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
auto zero = Scalar::New(env, Napi::Number::New(env, 0), cudf::data_type{type});
return sequence(env, size, zero->operator cudf::scalar&(), zero->operator cudf::scalar&(), mr);
}
// column/transform.cpp
std::pair<std::unique_ptr<rmm::device_buffer>, cudf::size_type> nans_to_nulls(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
std::pair<std::unique_ptr<rmm::device_buffer>, cudf::size_type> bools_to_mask(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/copying.cpp
Column::wrapper_t gather(
Column const& gather_map,
cudf::out_of_bounds_policy bounds_policy = cudf::out_of_bounds_policy::DONT_CHECK,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/filling.cpp
Column::wrapper_t fill(
cudf::size_type begin,
cudf::size_type end,
cudf::scalar const& value,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// column/replace.cpp
Column::wrapper_t replace_nulls(
cudf::column_view const& replacement,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
Column::wrapper_t replace_nulls(
cudf::scalar const& replacement,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
Column::wrapper_t replace_nulls(
cudf::replace_policy const& replace_policy,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
Column::wrapper_t replace_nans(
cudf::column_view const& replacement,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
Column::wrapper_t replace_nans(
cudf::scalar const& replacement,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// column/unaryop.cpp
Column::wrapper_t cast(
cudf::data_type out_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t is_null(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t is_valid(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t is_nan(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t is_not_nan(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t unary_operation(
cudf::unary_operator op,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/strings/attributes.cpp
Column::wrapper_t count_bytes(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t count_characters(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/strings/combine.cpp
static Column::wrapper_t concatenate(
Napi::Env const& env,
cudf::table_view const& columns,
cudf::string_scalar const& separator,
cudf::string_scalar const& narep,
cudf::strings::separator_on_nulls separator_on_nulls,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// column/strings/contains.cpp
Column::wrapper_t contains_re(
std::string const& pattern,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t count_re(
std::string const& pattern,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t matches_re(
std::string const& pattern,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/strings/json.cpp
Column::wrapper_t get_json_object(
std::string const& json_path,
cudf::strings::get_json_object_options const& opts,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
// column/strings/padding.cpp
Column::wrapper_t pad(
cudf::size_type width,
cudf::strings::side_type pad_side,
std::string const& fill_char,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t zfill(
cudf::size_type width,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/strings/replace_re.cpp
Column::wrapper_t replace_re(
std::string const& pattern,
std::string const& replacement,
cudf::size_type max_replace_count = -1,
cudf::strings::regex_flags const flags = cudf::strings::regex_flags::DEFAULT,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/strings/replace_slice.cpp
Column::wrapper_t replace_slice(
std::string const& repl = "",
cudf::size_type start = 0,
cudf::size_type stop = -1,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
// column/convert.cpp
Column::wrapper_t strings_from_booleans(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t strings_to_booleans(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t string_is_timestamp(std::string_view format,
rmm::mr::device_memory_resource* mr) const;
Column::wrapper_t strings_from_timestamps(std::string_view format,
rmm::mr::device_memory_resource* mr) const;
Column::wrapper_t strings_to_timestamps(cudf::data_type timestamp_type,
std::string_view format,
rmm::mr::device_memory_resource* mr) const;
Column::wrapper_t string_is_float(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t strings_from_floats(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t strings_to_floats(
cudf::data_type out_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t string_is_integer(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t strings_from_integers(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t strings_to_integers(
cudf::data_type out_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t string_is_hex(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t hex_from_integers(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t hex_to_integers(
cudf::data_type out_type,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t string_is_ipv4(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t ipv4_from_integers(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
Column::wrapper_t ipv4_to_integers(
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) const;
private:
cudf::size_type size_{}; ///< The number of elements in the column
cudf::size_type offset_{}; ///< The offset of elements in the data
Napi::Reference<Napi::Object> type_; ///< Logical type of elements in the column
Napi::Reference<DeviceBuffer::wrapper_t> data_; ///< Dense, contiguous, type erased device memory
///< buffer containing the column elements
Napi::Reference<DeviceBuffer::wrapper_t> null_mask_; ///< Bitmask used to represent null values.
///< May be empty if `null_count() == 0`
mutable cudf::size_type null_count_{cudf::UNKNOWN_NULL_COUNT}; ///< The number of null elements
std::vector<Napi::Reference<Column::wrapper_t>>
children_; ///< Depending on element type, child
///< columns may contain additional data
bool disposed_{false}; ///< Flag indicating this column has been disposed
Napi::Value type(Napi::CallbackInfo const& info);
void type(Napi::CallbackInfo const& info, Napi::Value const& value);
Napi::Value offset(Napi::CallbackInfo const& info);
Napi::Value size(Napi::CallbackInfo const& info);
Napi::Value data(Napi::CallbackInfo const& info);
Napi::Value null_mask(Napi::CallbackInfo const& info);
Napi::Value disposed(Napi::CallbackInfo const& info);
Napi::Value has_nulls(Napi::CallbackInfo const& info);
Napi::Value null_count(Napi::CallbackInfo const& info);
Napi::Value is_nullable(Napi::CallbackInfo const& info);
Napi::Value num_children(Napi::CallbackInfo const& info);
void dispose(Napi::CallbackInfo const&);
Napi::Value gather(Napi::CallbackInfo const& info);
Napi::Value apply_boolean_mask(Napi::CallbackInfo const& info);
Napi::Value copy(Napi::CallbackInfo const& info);
Napi::Value get_child(Napi::CallbackInfo const& info);
Napi::Value get_value(Napi::CallbackInfo const& info);
void set_null_mask(Napi::CallbackInfo const& info);
void set_null_count(Napi::CallbackInfo const& info);
// column/binaryop.cpp
Napi::Value add(Napi::CallbackInfo const& info);
Napi::Value sub(Napi::CallbackInfo const& info);
Napi::Value mul(Napi::CallbackInfo const& info);
Napi::Value div(Napi::CallbackInfo const& info);
Napi::Value true_div(Napi::CallbackInfo const& info);
Napi::Value floor_div(Napi::CallbackInfo const& info);
Napi::Value mod(Napi::CallbackInfo const& info);
Napi::Value pow(Napi::CallbackInfo const& info);
Napi::Value eq(Napi::CallbackInfo const& info);
Napi::Value ne(Napi::CallbackInfo const& info);
Napi::Value lt(Napi::CallbackInfo const& info);
Napi::Value gt(Napi::CallbackInfo const& info);
Napi::Value le(Napi::CallbackInfo const& info);
Napi::Value ge(Napi::CallbackInfo const& info);
Napi::Value bitwise_and(Napi::CallbackInfo const& info);
Napi::Value bitwise_or(Napi::CallbackInfo const& info);
Napi::Value bitwise_xor(Napi::CallbackInfo const& info);
Napi::Value logical_and(Napi::CallbackInfo const& info);
Napi::Value logical_or(Napi::CallbackInfo const& info);
Napi::Value shift_left(Napi::CallbackInfo const& info);
Napi::Value shift_right(Napi::CallbackInfo const& info);
Napi::Value shift_right_unsigned(Napi::CallbackInfo const& info);
Napi::Value log_base(Napi::CallbackInfo const& info);
Napi::Value atan2(Napi::CallbackInfo const& info);
Napi::Value null_equals(Napi::CallbackInfo const& info);
Napi::Value null_max(Napi::CallbackInfo const& info);
Napi::Value null_min(Napi::CallbackInfo const& info);
// column/concatenate.cpp
Napi::Value concat(Napi::CallbackInfo const& info);
// column/filling.cpp
Napi::Value fill(Napi::CallbackInfo const& info);
void fill_in_place(Napi::CallbackInfo const& info);
// column/stream_compaction.cpp
Napi::Value drop_nulls(Napi::CallbackInfo const& info);
Napi::Value drop_nans(Napi::CallbackInfo const& info);
// column/filling.cpp
static Napi::Value sequence(Napi::CallbackInfo const& info);
// column/transform.cpp
Napi::Value bools_to_mask(Napi::CallbackInfo const& info);
Napi::Value nans_to_nulls(Napi::CallbackInfo const& info);
// column/reductions.cpp
Napi::Value min(Napi::CallbackInfo const& info);
Napi::Value max(Napi::CallbackInfo const& info);
Napi::Value minmax(Napi::CallbackInfo const& info);
Napi::Value sum(Napi::CallbackInfo const& info);
Napi::Value product(Napi::CallbackInfo const& info);
Napi::Value any(Napi::CallbackInfo const& info);
Napi::Value all(Napi::CallbackInfo const& info);
Napi::Value sum_of_squares(Napi::CallbackInfo const& info);
Napi::Value mean(Napi::CallbackInfo const& info);
Napi::Value median(Napi::CallbackInfo const& info);
Napi::Value nunique(Napi::CallbackInfo const& info);
Napi::Value variance(Napi::CallbackInfo const& info);
Napi::Value std(Napi::CallbackInfo const& info);
Napi::Value quantile(Napi::CallbackInfo const& info);
Napi::Value cumulative_max(Napi::CallbackInfo const& info);
Napi::Value cumulative_min(Napi::CallbackInfo const& info);
Napi::Value cumulative_product(Napi::CallbackInfo const& info);
Napi::Value cumulative_sum(Napi::CallbackInfo const& info);
// column/replace.cpp
Napi::Value replace_nulls(Napi::CallbackInfo const& info);
Napi::Value replace_nans(Napi::CallbackInfo const& info);
// column/unaryop.cpp
Napi::Value cast(Napi::CallbackInfo const& info);
Napi::Value is_null(Napi::CallbackInfo const& info);
Napi::Value is_valid(Napi::CallbackInfo const& info);
Napi::Value is_nan(Napi::CallbackInfo const& info);
Napi::Value is_not_nan(Napi::CallbackInfo const& info);
Napi::Value sin(Napi::CallbackInfo const& info);
Napi::Value cos(Napi::CallbackInfo const& info);
Napi::Value tan(Napi::CallbackInfo const& info);
Napi::Value arcsin(Napi::CallbackInfo const& info);
Napi::Value arccos(Napi::CallbackInfo const& info);
Napi::Value arctan(Napi::CallbackInfo const& info);
Napi::Value sinh(Napi::CallbackInfo const& info);
Napi::Value cosh(Napi::CallbackInfo const& info);
Napi::Value tanh(Napi::CallbackInfo const& info);
Napi::Value arcsinh(Napi::CallbackInfo const& info);
Napi::Value arccosh(Napi::CallbackInfo const& info);
Napi::Value arctanh(Napi::CallbackInfo const& info);
Napi::Value exp(Napi::CallbackInfo const& info);
Napi::Value log(Napi::CallbackInfo const& info);
Napi::Value sqrt(Napi::CallbackInfo const& info);
Napi::Value cbrt(Napi::CallbackInfo const& info);
Napi::Value ceil(Napi::CallbackInfo const& info);
Napi::Value floor(Napi::CallbackInfo const& info);
Napi::Value abs(Napi::CallbackInfo const& info);
Napi::Value rint(Napi::CallbackInfo const& info);
Napi::Value bit_invert(Napi::CallbackInfo const& info);
Napi::Value unary_not(Napi::CallbackInfo const& info);
// column/strings/attributes.cpp
Napi::Value count_bytes(Napi::CallbackInfo const& info);
Napi::Value count_characters(Napi::CallbackInfo const& info);
// column/filling.cpp
static Napi::Value concatenate(Napi::CallbackInfo const& info);
// column/strings/contains.cpp
Napi::Value contains_re(Napi::CallbackInfo const& info);
Napi::Value count_re(Napi::CallbackInfo const& info);
Napi::Value matches_re(Napi::CallbackInfo const& info);
// column/strings/json.cpp
Napi::Value get_json_object(Napi::CallbackInfo const& info);
// column/strings/padding.cpp
Napi::Value pad(Napi::CallbackInfo const& info);
Napi::Value zfill(Napi::CallbackInfo const& info);
// column/strings/partition.cpp
Napi::Value string_partition(Napi::CallbackInfo const& info);
// column/strings/replace_re.cpp
Napi::Value replace_re(Napi::CallbackInfo const& info);
// column/strings/replace.cpp
Napi::Value replace_slice(Napi::CallbackInfo const& info);
// column/convert.hpp
Napi::Value strings_from_lists(Napi::CallbackInfo const& info);
Napi::Value strings_from_booleans(Napi::CallbackInfo const& info);
Napi::Value strings_to_booleans(Napi::CallbackInfo const& info);
Napi::Value string_is_timestamp(Napi::CallbackInfo const& info);
Napi::Value strings_from_timestamps(Napi::CallbackInfo const& info);
Napi::Value strings_to_timestamps(Napi::CallbackInfo const& info);
Napi::Value string_is_float(Napi::CallbackInfo const& info);
Napi::Value strings_from_floats(Napi::CallbackInfo const& info);
Napi::Value strings_to_floats(Napi::CallbackInfo const& info);
Napi::Value string_is_integer(Napi::CallbackInfo const& info);
Napi::Value strings_from_integers(Napi::CallbackInfo const& info);
Napi::Value strings_to_integers(Napi::CallbackInfo const& info);
Napi::Value string_is_hex(Napi::CallbackInfo const& info);
Napi::Value hex_from_integers(Napi::CallbackInfo const& info);
Napi::Value hex_to_integers(Napi::CallbackInfo const& info);
Napi::Value string_is_ipv4(Napi::CallbackInfo const& info);
Napi::Value ipv4_from_integers(Napi::CallbackInfo const& info);
Napi::Value ipv4_to_integers(Napi::CallbackInfo const& info);
// io/text.hpp
static Napi::Value read_text(Napi::CallbackInfo const& info);
Napi::Value split(Napi::CallbackInfo const& info);
};
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/scalar.hpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/utilities/dtypes.hpp>
#include <node_cudf/utilities/error.hpp>
#include <nv_node/objectwrap.hpp>
#include <nv_node/utilities/args.hpp>
#include <nv_node/utilities/cpp_to_napi.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/types.hpp>
#include <napi.h>
#include <memory>
namespace nv {
struct Scalar : public EnvLocalObjectWrap<Scalar> {
/**
* @brief Initialize and export the Scalar JavaScript constructor and prototype.
*
* @param env The active JavaScript environment.
* @param exports The exports object to decorate.
* @return Napi::Function The Scalar constructor function.
*/
static Napi::Function Init(Napi::Env const& env, Napi::Object exports);
/**
* @brief Construct a new Scalar instance from a scalar in device memory.
*
* @param scalar The scalar in device memory.
*/
static wrapper_t New(Napi::Env const& env, std::unique_ptr<cudf::scalar> scalar);
/**
* @brief Construct a new Scalar instance from a Number.
*
* @param value The Number to use.
*/
static wrapper_t New(Napi::Env const& env, Napi::Number const& value);
/**
* @brief Construct a new Scalar instance from a BigInt.
*
* @param value The BigInt to use.
*/
static wrapper_t New(Napi::Env const& env, Napi::BigInt const& value);
/**
* @brief Construct a new Scalar instance from a String.
*
* @param value The String to use.
*/
static wrapper_t New(Napi::Env const& env, Napi::String const& value);
/**
* @brief Construct a new Scalar instance from a Value and data type.
*
* @param value The Value to use.
* @param type The cudf::data_type for the scalar.
*/
static wrapper_t New(Napi::Env const& env, Napi::Value const& value, cudf::data_type type);
/**
* @brief Construct a new Scalar instance from JavaScript.
*
*/
Scalar(CallbackArgs const& args);
/**
* @brief Move a unique scalar pointer so it's owned by this Scalar wrapper.
*
* @param other The scalar to move.
*/
inline Scalar& operator=(std::unique_ptr<cudf::scalar>&& other) {
scalar_ = std::move(other);
return *this;
}
/**
* @brief Returns the scalar's logical value type
*/
inline cudf::data_type type() const { return arrow_to_cudf_type(type_.Value()); }
/**
* @brief Updates the validity of the value
*
* @param is_valid true: set the value to valid. false: set it to null
* @param stream CUDA stream used for device memory operations.
*/
inline void set_valid_async(bool is_valid, cudaStream_t stream = 0) {
scalar_->set_valid_async(is_valid, stream);
}
/**
* @brief Indicates whether the scalar contains a valid value
*
* @note Using the value when `is_valid() == false` is undefined behaviour
*
* @param stream CUDA stream used for device memory operations.
* @return true Value is valid
* @return false Value is invalid/null
*/
inline bool is_valid(cudaStream_t stream = 0) const { return scalar_->is_valid(stream); };
template <typename scalar_type>
inline operator scalar_type*() const {
NODE_CUDF_EXPECT(cudf::type_to_id<typename scalar_type::value_type>() == type().id(),
"Invalid conversion from node_cudf::Scalar to cudf::scalar",
Env());
return static_cast<scalar_type*>(scalar_.get());
}
operator cudf::scalar&() const;
Napi::Value get_value() const;
void set_value(Napi::CallbackInfo const& info, Napi::Value const& value);
private:
Napi::Reference<Napi::Object> type_{}; ///< Logical type of elements in the column
std::unique_ptr<cudf::scalar> scalar_;
Napi::Value type(Napi::CallbackInfo const& info);
Napi::Value get_value(Napi::CallbackInfo const& info);
};
} // namespace nv
namespace Napi {
template <>
inline Value Value::From(napi_env env, nv::Scalar::wrapper_t const& scalar) {
return scalar->get_value();
}
} // namespace Napi
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/napi_to_cpp.hpp
|
// Copyright (c) 2020, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/scalar.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <nv_node/utilities/napi_to_cpp.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/strings/json.hpp>
#include <cudf/types.hpp>
#include <napi.h>
#include <memory>
#include <type_traits>
namespace nv {
template <>
inline NapiToCPP::operator cudf::data_type() const {
if (IsObject()) {
auto obj = ToObject();
if (obj.Has("typeId") && obj.Get("typeId").IsNumber()) { //
return arrow_to_cudf_type(obj);
}
}
NAPI_THROW(Napi::Error::New(Env()), "Expected value to be a DataType");
}
template <>
inline NapiToCPP::operator cudf::sorted() const {
if (IsBoolean()) { return ToBoolean() ? cudf::sorted::YES : cudf::sorted::NO; }
NAPI_THROW(Napi::Error::New(Env()), "Expected value to be a boolean");
}
template <>
inline NapiToCPP::operator cudf::null_policy() const {
if (IsBoolean()) { return ToBoolean() ? cudf::null_policy::INCLUDE : cudf::null_policy::EXCLUDE; }
NAPI_THROW(Napi::Error::New(Env()), "Expected value to be a boolean");
}
template <>
inline NapiToCPP::operator cudf::null_order() const {
if (IsNumber()) { return ToBoolean() ? cudf::null_order::BEFORE : cudf::null_order::AFTER; }
NAPI_THROW(Napi::Error::New(Env()), "Expected value to be a NullOrder");
}
template <>
inline NapiToCPP::operator cudf::order() const {
if (IsBoolean()) { return ToBoolean() ? cudf::order::ASCENDING : cudf::order::DESCENDING; }
NAPI_THROW(Napi::Error::New(Env()), "Expected value to be a boolean");
}
template <>
inline NapiToCPP::operator cudf::duration_D() const {
return cudf::duration_D{operator cudf::duration_D::rep()};
}
template <>
inline NapiToCPP::operator cudf::duration_s() const {
return cudf::duration_s{operator cudf::duration_s::rep()};
}
template <>
inline NapiToCPP::operator cudf::duration_ms() const {
return cudf::duration_ms{operator cudf::duration_ms::rep()};
}
template <>
inline NapiToCPP::operator cudf::duration_us() const {
return cudf::duration_us{operator cudf::duration_us::rep()};
}
template <>
inline NapiToCPP::operator cudf::duration_ns() const {
return cudf::duration_ns{operator cudf::duration_ns::rep()};
}
template <>
inline NapiToCPP::operator cudf::timestamp_D() const {
return cudf::timestamp_D{operator cudf::duration_D()};
}
template <>
inline NapiToCPP::operator cudf::timestamp_s() const {
return cudf::timestamp_s{operator cudf::duration_s()};
}
template <>
inline NapiToCPP::operator cudf::timestamp_ms() const {
return cudf::timestamp_ms{operator cudf::duration_ms()};
}
template <>
inline NapiToCPP::operator cudf::timestamp_us() const {
return cudf::timestamp_us{operator cudf::duration_us()};
}
template <>
inline NapiToCPP::operator cudf::timestamp_ns() const {
return cudf::timestamp_ns{operator cudf::duration_ns()};
}
template <>
inline NapiToCPP::operator cudf::interpolation() const {
return static_cast<cudf::interpolation>(operator int32_t());
}
template <>
inline NapiToCPP::operator cudf::duplicate_keep_option() const {
return static_cast<cudf::duplicate_keep_option>(operator int32_t());
}
template <>
inline NapiToCPP::operator cudf::strings::get_json_object_options() const {
cudf::strings::get_json_object_options opts{};
if (IsObject()) {
auto obj = ToObject();
opts.set_allow_single_quotes(obj.Get("allowSingleQuotes").ToBoolean());
opts.set_missing_fields_as_nulls(obj.Get("missingFieldsAsNulls").ToBoolean());
opts.set_strip_quotes_from_single_strings(obj.Get("stripQuotesFromSingleStrings").ToBoolean());
}
return opts;
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/scalar_to_value.hpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <cudf/wrappers/durations.hpp>
#include <cudf/wrappers/timestamps.hpp>
#include <napi.h>
namespace nv {
namespace detail {
struct get_scalar_value {
Napi::Env env;
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int8_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int16_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int32_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int64_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::BigInt::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint8_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint16_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint32_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint64_t>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::BigInt::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<cudf::is_floating_point<T>(), Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Number::New(env,
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, bool>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Boolean::New(
env, static_cast<cudf::numeric_scalar<bool>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::string_view>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Value::From(env,
static_cast<cudf::string_scalar*>(scalar.get())->to_string(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<cudf::is_duration<T>(), Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Value::From(env,
static_cast<cudf::duration_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<cudf::is_timestamp<T>(), Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Value::From(env,
static_cast<cudf::timestamp_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, numeric::decimal32>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Value::From(
env, static_cast<cudf::fixed_point_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, numeric::decimal64>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Napi::Value::From(
env, static_cast<cudf::fixed_point_scalar<T>*>(scalar.get())->value(stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::list_view>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Column::New(env,
std::make_unique<cudf::column>(
// The list_scalar's column_view is copied here because the underlying
// column cannot be moved.
static_cast<cudf::list_scalar*>(scalar.get())->view(),
stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::struct_view>, Napi::Value> operator()(
std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
return scalar->is_valid(stream)
? Table::New(env,
std::make_unique<cudf::table>(
// The struct_scalar's table_view is copied here because the underlying
// table cannot be moved.
static_cast<cudf::struct_scalar*>(scalar.get())->view(),
stream))
: env.Null();
}
template <typename T>
inline std::enable_if_t<!(cudf::is_chrono<T>() || //
cudf::is_index_type<T>() || //
cudf::is_floating_point<T>() || //
std::is_same_v<T, bool> || //
std::is_same_v<T, cudf::string_view> || //
std::is_same_v<T, numeric::decimal32> || //
std::is_same_v<T, numeric::decimal64> || //
std::is_same_v<T, cudf::list_view> || //
std::is_same_v<T, cudf::struct_view>),
Napi::Value>
operator()(std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
NAPI_THROW(Napi::Error::New(env, "Unsupported dtype"));
}
};
} // namespace detail
} // namespace nv
namespace Napi {
template <>
inline Value Value::From(napi_env env, std::unique_ptr<cudf::scalar> const& scalar) {
return cudf::type_dispatcher(scalar->type(), nv::detail::get_scalar_value{env}, scalar);
}
} // namespace Napi
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/value_to_scalar.hpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.hpp>
#include <napi.h>
namespace nv {
namespace detail {
namespace scalar {
inline int64_t get_int64(Napi::Value const& val) {
bool lossless = true;
return !val.IsBigInt() ? val.ToNumber().Int64Value()
: val.As<Napi::BigInt>().Int64Value(&lossless);
}
inline uint64_t get_uint64(Napi::Value const& val) {
bool lossless = true;
return !val.IsBigInt() ? static_cast<uint64_t>(val.ToNumber().Int64Value())
: val.As<Napi::BigInt>().Uint64Value(&lossless);
}
} // namespace scalar
struct set_scalar_value {
Napi::Value val;
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int8_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_int64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int16_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_int64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int32_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_int64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, int64_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_int64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint8_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_uint64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint16_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_uint64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint32_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_uint64(val)), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, uint64_t>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())
->set_value(static_cast<T>(scalar::get_uint64(val)), stream);
}
template <typename T>
inline std::enable_if_t<cudf::is_floating_point<T>(), void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->set_value(val.ToNumber(), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, bool>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::numeric_scalar<T>*>(scalar.get())->set_value(val.ToBoolean(), stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::string_view>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
scalar.reset(new cudf::string_scalar(val.ToString(), true, stream));
}
template <typename T>
inline std::enable_if_t<cudf::is_duration<T>() and std::is_same_v<typename T::rep, int32_t>, void>
operator()(std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::duration_scalar<T>*>(scalar.get())
->set_value(T{val.ToNumber().Int32Value()}, stream);
}
template <typename T>
inline std::enable_if_t<cudf::is_duration<T>() and std::is_same_v<typename T::rep, int64_t>, void>
operator()(std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::duration_scalar<T>*>(scalar.get())
->set_value(T{scalar::get_int64(val)}, stream);
}
template <typename T>
inline std::enable_if_t<cudf::is_timestamp<T>() and std::is_same_v<typename T::rep, int32_t>,
void>
operator()(std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::timestamp_scalar<T>*>(scalar.get())
->set_value(T{typename T::duration{val.ToNumber().Int32Value()}}, stream);
}
template <typename T>
inline std::enable_if_t<cudf::is_timestamp<T>() and std::is_same_v<typename T::rep, int64_t>,
void>
operator()(std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
static_cast<cudf::timestamp_scalar<T>*>(scalar.get())
->set_value(T{typename T::duration{scalar::get_int64(val)}}, stream);
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, numeric::decimal32>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
scalar.reset(new cudf::fixed_point_scalar<T>(val.ToNumber(), true, stream));
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, numeric::decimal64>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
scalar.reset(new cudf::fixed_point_scalar<T>(val.ToNumber(), true, stream));
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::list_view>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
scalar.reset(new cudf::list_scalar(*Column::Unwrap(val.ToObject()), true, stream));
}
template <typename T>
inline std::enable_if_t<std::is_same_v<T, cudf::struct_view>, void> operator()(
std::unique_ptr<cudf::scalar>& scalar, cudaStream_t stream = 0) {
scalar.reset(new cudf::struct_scalar(*Table::Unwrap(val.ToObject()), true, stream));
}
template <typename T>
inline std::enable_if_t<!(cudf::is_chrono<T>() || //
cudf::is_index_type<T>() || //
cudf::is_floating_point<T>() || //
std::is_same_v<T, bool> || //
std::is_same_v<T, cudf::string_view> || //
std::is_same_v<T, numeric::decimal32> || //
std::is_same_v<T, numeric::decimal64> || //
std::is_same_v<T, cudf::list_view> || //
std::is_same_v<T, cudf::struct_view>),
void>
operator()(std::unique_ptr<cudf::scalar> const& scalar, cudaStream_t stream = 0) {
NAPI_THROW(Napi::Error::New(val.Env(), "Unsupported dtype"));
}
};
} // namespace detail
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/dtypes.hpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <nv_node/utilities/args.hpp>
#include <cudf/types.hpp>
#include <arrow/type.h>
namespace nv {
cudf::type_id get_common_type(cudf::data_type const& lhs, cudf::data_type const& rhs);
cudf::data_type arrow_to_cudf_type(Napi::Object const& arrow_type);
Napi::Object column_to_arrow_type(Napi::Env const& env,
cudf::data_type const& cudf_type,
Napi::Array children);
Napi::Object cudf_to_arrow_type(Napi::Env const& env, cudf::data_type const& cudf_type);
Napi::Object cudf_scalar_type_to_arrow_type(Napi::Env const& env, cudf::data_type type);
Napi::Value find_common_type(CallbackArgs const& args);
} // namespace nv
namespace Napi {
template <>
inline Value Value::From(napi_env env, cudf::data_type const& type) {
return nv::cudf_to_arrow_type(env, type);
}
template <>
inline Value Value::From(napi_env env, arrow::DataType const& type);
template <>
inline Value Value::From(napi_env env, std::vector<std::shared_ptr<arrow::Field>> const& fields) {
auto n = fields.size();
auto fs = Array::New(env, n);
for (std::size_t i = 0; i < n; ++i) {
auto f = fields[i];
auto o = Object::New(env);
o["name"] = String::New(env, f->name());
o["type"] = Value::From(env, *f->type());
o["nullable"] = Boolean::New(env, f->nullable());
fs[i] = o;
}
return fs;
}
template <>
inline Value Value::From(napi_env env, arrow::DataType const& type) {
auto o = Napi::Object::New(env);
switch (type.id()) {
case arrow::Type::DICTIONARY: { //
o["typeId"] = -1;
o["idOrdered"] = dynamic_cast<arrow::DictionaryType const&>(type).ordered();
o["indices"] =
Value::From(env, *dynamic_cast<arrow::DictionaryType const&>(type).index_type());
o["dictionary"] =
Value::From(env, *dynamic_cast<arrow::DictionaryType const&>(type).value_type());
return o;
}
case arrow::Type::INT8: {
o["typeId"] = 2;
o["bitWidth"] = 8;
o["isSigned"] = true;
return o;
}
case arrow::Type::INT16: {
o["typeId"] = 2;
o["bitWidth"] = 16;
o["isSigned"] = true;
return o;
}
case arrow::Type::INT32: {
o["typeId"] = 2;
o["bitWidth"] = 32;
o["isSigned"] = true;
return o;
}
case arrow::Type::INT64: {
o["typeId"] = 2;
o["bitWidth"] = 64;
o["isSigned"] = true;
return o;
}
case arrow::Type::UINT8: {
o["typeId"] = 2;
o["bitWidth"] = 8;
o["isSigned"] = false;
return o;
}
case arrow::Type::UINT16: {
o["typeId"] = 2;
o["bitWidth"] = 16;
o["isSigned"] = false;
return o;
}
case arrow::Type::UINT32: {
o["typeId"] = 2;
o["bitWidth"] = 32;
o["isSigned"] = false;
return o;
}
case arrow::Type::UINT64: {
o["typeId"] = 2;
o["bitWidth"] = 64;
o["isSigned"] = false;
return o;
}
case arrow::Type::FLOAT: {
o["typeId"] = 3;
o["precision"] = 1;
return o;
}
case arrow::Type::DOUBLE: {
o["typeId"] = 3;
o["precision"] = 2;
return o;
}
case arrow::Type::STRING: {
o["typeId"] = 5;
return o;
}
case arrow::Type::BOOL: {
o["typeId"] = 6;
return o;
}
case arrow::Type::TIMESTAMP: {
o["typeId"] = 10;
o["unit"] = static_cast<int32_t>(dynamic_cast<arrow::TimestampType const&>(type).unit());
o["bitWidth"] =
static_cast<int32_t>(dynamic_cast<arrow::TimestampType const&>(type).bit_width());
return o;
}
case arrow::Type::LIST: {
o["typeId"] = 12;
o["children"] = Value::From(env, dynamic_cast<arrow::ListType const&>(type).fields());
return o;
}
case arrow::Type::STRUCT: {
o["typeId"] = 13;
o["children"] = Value::From(env, dynamic_cast<arrow::StructType const&>(type).fields());
return o;
}
default: {
throw Napi::Error::New(env, "Unrecognized Arrow type '" + type.ToString() + "");
}
}
return o;
}
} // namespace Napi
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/metadata.hpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <nv_node/utilities/args.hpp>
#include <cudf/io/parquet.hpp>
namespace nv {
cudf::io::table_input_metadata make_writer_columns_metadata(Napi::Object const& options,
cudf::table_view const& table);
Napi::Array get_output_names_from_metadata(Napi::Env const& env,
cudf::io::table_with_metadata const& result);
Napi::Array get_output_cols_from_metadata(Napi::Env const& env,
cudf::io::table_with_metadata const& result);
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/error.hpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifdef CHECK_CUDA
#undef CHECK_CUDA
#endif
#include <cudf/utilities/error.hpp>
#ifdef CHECK_CUDA
#undef CHECK_CUDA
#endif
#include <napi.h>
namespace nv {
inline cudf::logic_error cudfError(std::string const& message,
std::string const& file,
uint32_t line) {
return cudf::logic_error("cuDF failure:\n" + message + "\n at " + file + ":" +
std::to_string(line));
}
inline Napi::Error cudfError(std::string const& message,
std::string const& file,
uint32_t line,
Napi::Env const& env) {
return Napi::Error::New(env, cudfError(message, file, line).what());
}
} // namespace nv
#ifndef NODE_CUDF_EXPECT
#define NODE_CUDF_EXPECT(expr, message, ...) \
do { \
if (!(expr)) NAPI_THROW(nv::cudfError(message, __FILE__, __LINE__, ##__VA_ARGS__)); \
} while (0)
#endif
#ifndef NODE_CUDF_THROW
#define NODE_CUDF_THROW(message, ...) \
NAPI_THROW(nv::cudfError(message, __FILE__, __LINE__, ##__VA_ARGS__))
#endif
/**
* @brief Error checking macro for CUDA runtime API functions.
*
* Invokes a CUDA runtime API function call, if the call does not return
* cudaSuccess, invokes cudaGetLastError() to clear the error and throws an
* exception detailing the CUDA error that occurred.
*
**/
#ifndef NODE_CUDF_TRY
#define NODE_CUDF_TRY(expr, ...) \
do { \
cudaError_t const status = (expr); \
if (status != cudaSuccess) { \
cudaGetLastError(); \
NODE_CUDF_THROW(status, ##__VA_ARGS__); \
} \
} while (0)
#endif
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/cpp_to_napi.hpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "scalar_to_value.hpp"
#include <nv_node/utilities/cpp_to_napi.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <cudf/wrappers/durations.hpp>
#include <cudf/wrappers/timestamps.hpp>
#include <napi.h>
#include <cuda/std/chrono>
namespace nv {
template <>
inline Napi::Value CPPToNapi::operator()(cudf::type_id const& id) const {
return Napi::Number::New(Env(), static_cast<int32_t>(id));
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::duration_D const& val) const {
return (*this)(val.count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::duration_s const& val) const {
return Napi::BigInt::New(Env(), val.count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::duration_ms const& val) const {
return Napi::BigInt::New(Env(), val.count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::duration_us const& val) const {
return Napi::BigInt::New(Env(), val.count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::duration_ns const& val) const {
return Napi::BigInt::New(Env(), val.count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::timestamp_D const& val) const {
return Napi::Number::New(
Env(), cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::timestamp_s const& val) const {
return Napi::BigInt::New(
Env(), cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::timestamp_ms const& val) const {
return Napi::BigInt::New(
Env(), cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::timestamp_us const& val) const {
return Napi::BigInt::New(
Env(), cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Napi::Value CPPToNapi::operator()(cudf::timestamp_ns const& val) const {
return Napi::BigInt::New(
Env(), cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Napi::Value CPPToNapi::operator()(std::unique_ptr<cudf::scalar> const& scalar) const {
return cudf::type_dispatcher(scalar->type(), detail::get_scalar_value{Env()}, scalar);
}
} // namespace nv
namespace Napi {
template <>
inline Value Value::From(napi_env env, cudf::type_id const& id) {
return Value::From(env, static_cast<int32_t>(id));
}
template <>
inline Value Value::From(napi_env env, cudf::duration_D const& val) {
return Value::From(env, val.count());
}
template <>
inline Value Value::From(napi_env env, cudf::duration_s const& val) {
return Napi::BigInt::New(env, val.count());
}
template <>
inline Value Value::From(napi_env env, cudf::duration_ms const& val) {
return Napi::BigInt::New(env, val.count());
}
template <>
inline Value Value::From(napi_env env, cudf::duration_us const& val) {
return Napi::BigInt::New(env, val.count());
}
template <>
inline Value Value::From(napi_env env, cudf::duration_ns const& val) {
return Napi::BigInt::New(env, val.count());
}
template <>
inline Value Value::From(napi_env env, cudf::timestamp_D const& val) {
return Napi::Number::New(
env, cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Value Value::From(napi_env env, cudf::timestamp_s const& val) {
return Napi::BigInt::New(
env, cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Value Value::From(napi_env env, cudf::timestamp_ms const& val) {
return Napi::BigInt::New(
env, cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Value Value::From(napi_env env, cudf::timestamp_us const& val) {
return Napi::BigInt::New(
env, cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
template <>
inline Value Value::From(napi_env env, cudf::timestamp_ns const& val) {
return Napi::BigInt::New(
env, cuda::std::chrono::duration_cast<cudf::duration_ms>(val.time_since_epoch()).count());
}
} // namespace Napi
| 0 |
rapidsai_public_repos/node/modules/cudf/src/node_cudf
|
rapidsai_public_repos/node/modules/cudf/src/node_cudf/utilities/buffer.hpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <node_rmm/device_buffer.hpp>
#include <cudf/types.hpp>
namespace nv {
/**
* @brief Unwrap or create DeviceBuffer from an Napi::Value suitable as a Column's data buffer.
*
* * If `value` is already a DeviceBuffer, unwrap and return it.
* * If `value` is an Array of JavaScript numbers, construct a DeviceBuffer of `double` values.
* * If `value` is an Array of JavaScript bigints, construct a DeviceBuffer of `int64_t` values.
* * If `value` is an ArrayBuffer, ArrayBufferView, CUDA Memory, or CUDA MemoryView, copy-construct
* and return a DeviceBuffer.
*
* @param env The active JavaScript environment.
* @param value JavaScript value to unwrap or convert.
* @param dtype The expected dtype of the input values.
* @param mr Memory resource to use for the device memory allocation.
* @param stream CUDA stream on which memory may be allocated if the memory
* resource supports streams.
*/
DeviceBuffer::wrapper_t data_to_devicebuffer(
Napi::Env const& env,
Napi::Value const& value,
cudf::data_type const& dtype,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream = rmm::cuda_stream_default);
inline DeviceBuffer::wrapper_t data_to_devicebuffer(
Napi::Env const& env,
Napi::Value const& value,
cudf::data_type const& dtype,
rmm::cuda_stream_view stream = rmm::cuda_stream_default) {
return data_to_devicebuffer(env, value, dtype, MemoryResource::Current(env), stream);
}
/**
* @brief Unwrap or create DeviceBuffer from an Napi::Value suitable as a Column's null mask.
*
* * If `value` is already a DeviceBuffer, unwrap and return it.
* * If `value` is an Array, construct a DeviceBuffer of non-null values.
* * If `value` is a Boolean, construct a DeviceBuffer of all valid or invalid bits.
* * If `value` is an ArrayBuffer, ArrayBufferView, CUDA Memory, or CUDA MemoryView, copy-construct
* and return a DeviceBuffer.
*
* @param env The active JavaScript environment.
* @param value JavaScript value to unwrap or convert.
* @param size The number of elements to be represented by the mask.
* @param mr Memory resource to use for the device memory allocation.
* @param stream CUDA stream on which memory may be allocated if the memory
* resource supports streams.
*/
DeviceBuffer::wrapper_t mask_to_null_bitmask(
Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream = rmm::cuda_stream_default);
inline DeviceBuffer::wrapper_t mask_to_null_bitmask(
Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
rmm::cuda_stream_view stream = rmm::cuda_stream_default) {
return mask_to_null_bitmask(env, value, size, MemoryResource::Current(env), stream);
}
/**
* @brief Create a DeviceBuffer from an Napi::Value of input data values suitable as a Column's null
* mask. Sets null/undefined elements to false, everything else to true.
*
* * If `value` is already a DeviceBuffer, unwrap and return it.
* * If `value` is an Array, construct a DeviceBuffer of non-null values.
* * If `value` is a Boolean, construct a DeviceBuffer of all valid or invalid bits.
* * If `value` is an ArrayBuffer, ArrayBufferView, CUDA Memory, or CUDA MemoryView, copy-construct
* and return a DeviceBuffer.
*
* @param env The active JavaScript environment.
* @param value JavaScript value to unwrap or convert.
* @param size The number of elements to be represented by the mask.
* @param mr Memory resource to use for the device memory allocation.
* @param stream CUDA stream on which memory may be allocated if the memory
* resource supports streams.
*/
DeviceBuffer::wrapper_t data_to_null_bitmask(
Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream = rmm::cuda_stream_default);
inline DeviceBuffer::wrapper_t data_to_null_bitmask(
Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
rmm::cuda_stream_view stream = rmm::cuda_stream_default) {
return data_to_null_bitmask(env, value, size, MemoryResource::Current(env), stream);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/enums.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @summary The desired order of null compared to other elements for a column.
*/
export enum NullOrder {
after,
before
}
export enum DuplicateKeepOption {
any, // Keeps an unspecified occurrence.
first, // Keeps first duplicate row and unique rows.
last, // Keeps last duplicate row and unique rows.
none, // Keeps only unique rows are kept.
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/orc.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export interface ReadORCOptionsCommon {
/** The list of columns to read */
columns?: string[];
/** Only these stripes will be read from the file. */
stripes?: number[][];
/** The number of rows to skip from the start of the file */
skipRows?: number;
/** The total number of rows to read */
numRows?: number;
/** Use row index if available for faster seeking (default 'true') */
useIndex?: boolean;
/** Names of the columns that should be read as 128-bit Decimal */
decimalColumns?: string[];
}
export interface ReadORCFileOptions extends ReadORCOptionsCommon {
sourceType: 'files';
sources: string[];
}
export interface ReadORCBufferOptions extends ReadORCOptionsCommon {
sourceType: 'buffers';
sources: (Uint8Array|Buffer)[];
}
export type ReadORCOptions = ReadORCFileOptions|ReadORCBufferOptions;
export interface WriteORCOptions {
/** The name of compression to use (default 'None'). */
compression?: 'snappy'|'none';
/** Write timestamps in int96 format (default 'true'). */
enableStatistics?: boolean;
}
export interface TableWriteORCOptions {
/** Column names to write in the header. */
columnNames?: string[];
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/dtypes.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as arrow from 'apache-arrow';
import {Column} from '../column';
import {Table} from '../table';
import {TypeMap} from './mappings';
export type FloatingPoint = Float32|Float64;
export type IndexType = Int8|Int16|Int32|Uint8|Uint16|Uint32;
export type Integral = IndexType|Int64|Uint64;
export type Numeric = Integral|FloatingPoint|Bool8;
export type Timestamp =
TimestampDay|TimestampSecond|TimestampMillisecond|TimestampMicrosecond|TimestampNanosecond;
export type DataType = Numeric|Utf8String|List|Struct|Timestamp|Categorical;
export interface Int8 extends arrow.Int8 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Int8 extends arrow.Int8 {}
(Int8.prototype as any).BYTES_PER_ELEMENT = 1;
export interface Int16 extends arrow.Int16 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Int16 extends arrow.Int16 {}
(Int16.prototype as any).BYTES_PER_ELEMENT = 2;
export interface Int32 extends arrow.Int32 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Int32 extends arrow.Int32 {}
(Int32.prototype as any).BYTES_PER_ELEMENT = 4;
export interface Int64 extends arrow.Int64 {
TValue: bigint;
scalarType: bigint;
readonly BYTES_PER_ELEMENT: number;
}
export class Int64 extends arrow.Int64 {}
(Int64.prototype as any).BYTES_PER_ELEMENT = 8;
export interface Uint8 extends arrow.Uint8 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Uint8 extends arrow.Uint8 {}
(Uint8.prototype as any).BYTES_PER_ELEMENT = 1;
export interface Uint16 extends arrow.Uint16 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Uint16 extends arrow.Uint16 {}
(Uint16.prototype as any).BYTES_PER_ELEMENT = 2;
export interface Uint32 extends arrow.Uint32 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Uint32 extends arrow.Uint32 {}
(Uint32.prototype as any).BYTES_PER_ELEMENT = 4;
export interface Uint64 extends arrow.Uint64 {
TValue: bigint;
scalarType: bigint;
readonly BYTES_PER_ELEMENT: number;
}
export class Uint64 extends arrow.Uint64 {}
(Uint64.prototype as any).BYTES_PER_ELEMENT = 8;
export interface Float32 extends arrow.Float32 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Float32 extends arrow.Float32 {}
(Float32.prototype as any).BYTES_PER_ELEMENT = 4;
export interface Float64 extends arrow.Float64 {
scalarType: number;
readonly BYTES_PER_ELEMENT: number;
}
export class Float64 extends arrow.Float64 {}
(Float64.prototype as any).BYTES_PER_ELEMENT = 8;
export interface Bool8 extends arrow.Bool {
scalarType: boolean;
readonly BYTES_PER_ELEMENT: number;
}
export class Bool8 extends arrow.Bool {}
(Bool8.prototype as any).BYTES_PER_ELEMENT = 1;
export interface Utf8String extends arrow.Utf8 {
scalarType: string;
}
export class Utf8String extends arrow.Utf8 {}
export interface List<T extends DataType = any> extends arrow.List<T> {
scalarType: Column<T>;
}
export class List<T extends DataType = any> extends arrow.List<T> {}
export interface Struct<T extends TypeMap = any> extends arrow.Struct<T> {
scalarType: Table;
}
export class Struct<T extends TypeMap = any> extends arrow.Struct<T> {}
export interface TimestampDay extends arrow.DateDay {
scalarType: Date;
}
export class TimestampDay extends arrow.DateDay {}
export interface TimestampSecond extends arrow.TimestampSecond {
scalarType: Date;
}
export class TimestampSecond extends arrow.TimestampSecond {}
export interface TimestampMillisecond extends arrow.TimestampMillisecond {
scalarType: Date;
}
export class TimestampMillisecond extends arrow.TimestampMillisecond {}
export interface TimestampMicrosecond extends arrow.TimestampMicrosecond {
scalarType: Date;
}
export class TimestampMicrosecond extends arrow.TimestampMicrosecond {}
export interface TimestampNanosecond extends arrow.TimestampNanosecond {
scalarType: Date;
}
export class TimestampNanosecond extends arrow.TimestampNanosecond {}
export interface Categorical<T extends DataType = any> extends arrow.Dictionary<T, Uint32> {
scalarType: T['scalarType'];
}
export class Categorical<T extends DataType = any> extends arrow.Dictionary<T, Uint32> {
constructor(dictionary: T, _id?: number|null, isOrdered?: boolean|null) {
// we are overriding the id here so that Arrow dictionaries will always compare
super(dictionary, new Uint32, 0, isOrdered);
}
}
export const FloatTypes = [new Float32, new Float64];
export const IntegralTypes = [
new Int8,
new Int16,
new Int32,
new Int64,
new Uint8,
new Uint16,
new Uint32,
new Uint64,
];
export const NumericTypes = [new Bool8, ...FloatTypes, ...IntegralTypes];
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/mappings.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as arrow from 'apache-arrow';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import * as CUDF from '../addon';
import {Column} from '../column';
import {
Bool8,
Categorical,
DataType,
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
List,
Numeric,
Struct,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
Uint16,
Uint32,
Uint64,
Uint8,
Utf8String
} from './dtypes';
export enum Interpolation {
linear, ///< Linear interpolation between i and j
lower, ///< Lower data point (i)
higher, ///< Higher data point (j)
midpoint, ///< (i + j)/2
nearest ///< i or j, whichever is nearest
}
export type TypeMap = {
[key: string]: DataType
};
export type ColumnsMap<T extends TypeMap = any> = {
[P in keyof T]: Column<T[P]>
};
type CommonType_Bool8<T extends Numeric> = T;
type CommonType_Int8<T extends Numeric> = T extends Bool8 ? Int8 : T;
type CommonType_Int16<T extends Numeric> = T extends Bool8|Int8|Uint8 ? Int16 : T;
type CommonType_Int32<T extends Numeric> = T extends Bool8|Int8|Uint8|Int16|Uint16 ? Int32 : T;
type CommonType_Int64<T extends Numeric> =
T extends Bool8|Int8|Uint8|Int16|Uint16|Int32|Uint32 ? Int64 : T;
type CommonType_Uint8<T extends Numeric> = T extends Bool8|Int8 ? Uint16 : T;
type CommonType_Uint16<T extends Numeric> = T extends Bool8|Int8|Uint8 ? Uint16 : T;
type CommonType_Uint32<T extends Numeric> = T extends Bool8|Int8|Uint8|Int16|Uint16 ? Uint32 : T;
type CommonType_Uint64<T extends Numeric> =
T extends Bool8|Int8|Uint8|Int16|Uint16|Int32|Uint32|Int64 ? Uint64 : T;
type CommonType_Float32<T extends Numeric> =
T extends Bool8|Int8|Uint8|Int16|Uint16 ? Float32 : Float64;
type CommonType_Float64<T extends Numeric> =
T extends Bool8|Int8|Uint8|Int16|Uint16|Int32|Uint32|Float32 ? Float64 : T;
// clang-format off
export type CommonType<T extends DataType, R extends DataType> =
T extends R ? R extends T ? T : R :
R extends Numeric
? T extends Bool8 ? CommonType_Bool8<R>
: T extends Int8 ? CommonType_Int8<R>
: T extends Int16 ? CommonType_Int16<R>
: T extends Int32 ? CommonType_Int32<R>
: T extends Int64 ? CommonType_Int64<R>
: T extends Uint8 ? CommonType_Uint8<R>
: T extends Uint16 ? CommonType_Uint16<R>
: T extends Uint32 ? CommonType_Uint32<R>
: T extends Uint64 ? CommonType_Uint64<R>
: T extends Float32 ? CommonType_Float32<R>
: T extends Float64 ? CommonType_Float64<R>
: never :
T extends List ? R extends List ? List<CommonType<T['valueType'], R['valueType']>> : never :
T extends Struct ? R extends Struct ? Struct<CommonTypes<T['dataTypes'], R['dataTypes']>> : never :
T extends Categorical ? R extends Categorical ? Categorical<CommonType<T['dictionary'], R['dictionary']>> : never :
never;
export type CommonTypes<T extends TypeMap, R extends TypeMap> =
{
[P in keyof T]:
P extends keyof R
? CommonType<T[P], R[P]>
: T[P]
} & {
[P in keyof R]:
P extends keyof T
? CommonType<R[P], T[P]>
: R[P]
};
// clang-format on
export function findCommonType<T extends DataType, R extends DataType>(lhs: T,
rhs: R): CommonType<T, R> {
if (compareTypes(lhs, rhs)) {
if (!(rhs instanceof arrow.DataType)) { //
return arrowToCUDFType(rhs as any) as CommonType<T, R>;
}
return rhs as unknown as CommonType<T, R>;
}
return arrowToCUDFType(CUDF.findCommonType(lhs, rhs)) as CommonType<T, R>;
}
// clang-format off
/** @ignore */
export type ArrowToCUDFType<T extends arrow.DataType> =
// T extends arrow.Null ? never : // TODO
T extends arrow.Int8 ? Int8 :
T extends arrow.Int16 ? Int16 :
T extends arrow.Int32 ? Int32 :
T extends arrow.Int64 ? Int64 :
T extends arrow.Uint8 ? Uint8 :
T extends arrow.Uint16 ? Uint16 :
T extends arrow.Uint32 ? Uint32 :
T extends arrow.Uint64 ? Uint64 :
// T extends arrow.Int ? never :
// T extends arrow.Float16 ? never :
T extends arrow.Float32 ? Float32 :
T extends arrow.Float64 ? Float64 :
// T extends arrow.Float ? never :
// T extends arrow.Binary ? never :
T extends arrow.Utf8 ? Utf8String :
T extends arrow.Bool ? Bool8 :
// T extends arrow.Decimal ? never : // TODO
T extends arrow.DateDay ? TimestampDay :
T extends arrow.DateMillisecond ? TimestampMillisecond :
// T extends arrow.Date_ ? never : // TODO
// T extends arrow.TimeSecond ? never : // TODO
// T extends arrow.TimeMillisecond ? never : // TODO
// T extends arrow.TimeMicrosecond ? never : // TODO
// T extends arrow.TimeNanosecond ? never : // TODO
// T extends arrow.Time ? never : // TODO
T extends arrow.TimestampSecond ? TimestampSecond :
T extends arrow.TimestampMillisecond ? TimestampMillisecond :
T extends arrow.TimestampMicrosecond ? TimestampMicrosecond :
T extends arrow.TimestampNanosecond ? TimestampNanosecond :
// T extends arrow.Timestamp ? never : // TODO
// T extends arrow.IntervalDayTime ? never : // TODO
// T extends arrow.IntervalYearMonth ? never : // TODO
// T extends arrow.Interval ? never : // TODO
T extends arrow.List ? T extends List ? T : List<ArrowToCUDFType<T['valueType']>> :
T extends arrow.Struct ? T extends Struct ? T : Struct<{[P in keyof T['dataTypes']]: ArrowToCUDFType<T['dataTypes'][P]>}> :
// T extends arrow.Union ? never :
// T extends arrow.DenseUnion ? never :
// T extends arrow.SparseUnion ? never :
// T extends arrow.FixedSizeBinary ? never :
// T extends arrow.FixedSizeList ? never :
// T extends arrow.Map_ ? never :
T extends arrow.Dictionary ? T extends Categorical ? T : Categorical<ArrowToCUDFType<T['valueType']>> :
never;
// clang-format on
export const arrowToCUDFType = (() => {
interface ArrowToCUDFTypeVisitor extends arrow.Visitor {
visit<T extends arrow.DataType>(node: T): ArrowToCUDFType<T>;
visitMany<T extends arrow.DataType>(nodes: T[]): ArrowToCUDFType<T>[];
getVisitFn<T extends arrow.DataType>(node: T): () => ArrowToCUDFType<T>;
}
// clang-format off
/* eslint-disable @typescript-eslint/no-unused-vars */
class ArrowToCUDFTypeVisitor extends arrow.Visitor {
getVisitFn<T extends arrow.DataType>(type: T): (type: T) => ArrowToCUDFType<T> {
if (!(type instanceof arrow.DataType)) {
type = {...(<any>type), __proto__: arrow.DataType.prototype};
}
return super.getVisitFn(type);
}
// public visitNull <T extends arrow.Null>(type: T) { return new Null; }
public visitBool <T extends arrow.Bool>(_type: T) { return new Bool8; }
public visitInt8 <T extends arrow.Int8>(_type: T) { return new Int8; }
public visitInt16 <T extends arrow.Int16>(_type: T) { return new Int16; }
public visitInt32 <T extends arrow.Int32>(_type: T) { return new Int32; }
public visitInt64 <T extends arrow.Int64>(_type: T) { return new Int64; }
public visitUint8 <T extends arrow.Uint8>(_type: T) { return new Uint8; }
public visitUint16 <T extends arrow.Uint16>(_type: T) { return new Uint16; }
public visitUint32 <T extends arrow.Uint32>(_type: T) { return new Uint32; }
public visitUint64 <T extends arrow.Uint64>(_type: T) { return new Uint64; }
// public visitFloat16 <T extends arrow.Float16>(_type: T) { return new Float16; }
public visitFloat32 <T extends arrow.Float32>(_type: T) { return new Float32; }
public visitFloat64 <T extends arrow.Float64>(_type: T) { return new Float64; }
public visitUtf8 <T extends arrow.Utf8>(_type: T) { return new Utf8String; }
// public visitBinary <T extends arrow.Binary>(_type: T) { return new Binary; }
// public visitFixedSizeBinary <T extends arrow.FixedSizeBinary>(type: T) { return new FixedSizeBinary(type); }
public visitDateDay <T extends arrow.DateDay>(_type: T) { return new TimestampDay; }
public visitDateMillisecond <T extends arrow.DateMillisecond>(_type: T) { return new TimestampMillisecond; }
public visitTimestampSecond <T extends arrow.TimestampSecond>(_type: T) { return new TimestampSecond; }
public visitTimestampMillisecond <T extends arrow.TimestampMillisecond>(_type: T) { return new TimestampMillisecond; }
public visitTimestampMicrosecond <T extends arrow.TimestampMicrosecond>(_type: T) { return new TimestampMicrosecond; }
public visitTimestampNanosecond <T extends arrow.TimestampNanosecond>(_type: T) { return new TimestampNanosecond; }
// public visitTimeSecond <T extends arrow.TimeSecond>(_type: T) { return new TimeSecond; }
// public visitTimeMillisecond <T extends arrow.TimeMillisecond>(_type: T) { return new TimeMillisecond; }
// public visitTimeMicrosecond <T extends arrow.TimeMicrosecond>(_type: T) { return new TimeMicrosecond; }
// public visitTimeNanosecond <T extends arrow.TimeNanosecond>(_type: T) { return new TimeNanosecond; }
// public visitDecimal <T extends arrow.Decimal>(_type: T) { return new Decimal(type); }
public visitList <T extends arrow.List>(type: T) {
const { name, type: childType } = type.children[0];
return new List(arrow.Field.new({ name, type: this.visit(childType) }));
}
public visitStruct <T extends arrow.Struct>(type: T) {
return new Struct(type.children.map(({ name, type: childType }) => {
return arrow.Field.new({ name, type: this.visit(childType) });
}));
}
// public visitDenseUnion <T extends arrow.DenseUnion>(type: T) { return new DenseUnion(type); }
// public visitSparseUnion <T extends arrow.SparseUnion>(type: T) { return new SparseUnion(type); }
public visitDictionary <T extends arrow.Dictionary>({dictionary, id, isOrdered}: T) {
return new Categorical(this.visit(dictionary), id, isOrdered);
}
// public visitIntervalDayTime <T extends arrow.IntervalDayTime>(type: T) { return new IntervalDayTime; }
// public visitIntervalYearMonth <T extends arrow.IntervalYearMonth>(type: T) { return new IntervalYearMonth; }
// public visitFixedSizeList <T extends arrow.FixedSizeList>(type: T) { return new FixedSizeList(type); }
// public visitMap <T extends arrow.Map>(type: T) { return new Map(type); }
}
/* eslint-enable @typescript-eslint/no-unused-vars */
// clang-format on
const visitor = new ArrowToCUDFTypeVisitor();
return function arrowToCUDFType<T extends arrow.DataType>(type: T): ArrowToCUDFType<T> {
return visitor.visit(type);
};
})();
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/json.ts
|
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export interface GetJSONObjectOptions {
/* Whether to allow single quotes to represent strings in JSON. */
allowSingleQuotes?: boolean;
/* Whether to return nulls when an object does not contain the requested field. */
missingFieldsAsNulls?: boolean;
/* Whether to return individual string values with quotes stripped. */
stripQuotesFromSingleStrings?: boolean;
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/csv.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {TypeMap} from './mappings';
export interface ReadCSVOptionsCommon<T extends TypeMap = any> {
/**
Names and types of all the columns; if empty then names and types are inferred/auto-generated
*/
dataTypes?: T;
/** The compression format of the source, or infer from file extension */
compression?: 'infer'|'snappy'|'gzip'|'bz2'|'brotli'|'zip'|'xz';
/** Whether to rename duplicate column names */
renameDuplicateColumns?: boolean;
/** Rows to read; -1 is all */
numRows?: number;
/** Rows to skip from the start */
skipHead?: number;
/** Rows to skip from the end */
skipTail?: number;
/** Treatment of quoting behavior */
quoteStyle?: 'all'|'none'|'nonnumeric'|'minimal';
/** Line terminator */
lineTerminator?: string;
/** Quoting character (if `allowDoubleQuoting` is true) */
quoteCharacter?: string;
/** Decimal point character; cannot match delimiter */
decimalCharacter?: string;
/** Treat whitespace as field delimiter; overrides character delimiter */
whitespaceAsDelimiter?: boolean;
/** Whether to skip whitespace after the delimiter */
skipInitialSpaces?: boolean;
/** Ignore empty lines or parse line values as invalid */
skipBlankLines?: boolean;
/** Whether a quote inside a value is double-quoted */
allowDoubleQuoting?: boolean;
/** Whether to keep the built-in default NA values */
keepDefaultNA?: boolean;
/** Whether to disable null filter; disabling can improve performance */
autoDetectNullValues?: boolean;
/** Whether to parse dates as DD/MM versus MM/DD */
inferDatesWithDayFirst?: boolean;
/** Field delimiter */
delimiter?: string;
/** Numeric data thousands separator; cannot match delimiter */
thousands?: string;
/** Comment line start character */
comment?: string;
/** Header row index */
header?: 'infer'|null|number;
/** String used as prefix for each column name if no header or names are provided. */
prefix?: string;
/** Additional values to recognize as null values */
nullValues?: string[];
/** Additional values to recognize as boolean true values */
trueValues?: string[];
/** Additional values to recognize as boolean false values */
falseValues?: string[];
/** Names of columns to read as datetime */
datetimeColumns?: string[];
/** Names of columns to read; empty/null is all columns */
columnsToReturn?: string[];
/** The number of bytes to skip from source start */
byteOffset?: number;
/** The number of bytes to read */
byteRange?: number;
}
export interface ReadCSVFileOptions<T extends TypeMap = any> extends ReadCSVOptionsCommon<T> {
sourceType: 'files';
sources: string[];
}
export interface ReadCSVBufferOptions<T extends TypeMap = any> extends ReadCSVOptionsCommon<T> {
sourceType: 'buffers';
sources: (Uint8Array|Buffer)[];
}
export type ReadCSVOptions<T extends TypeMap = any> = ReadCSVFileOptions<T>|ReadCSVBufferOptions<T>;
export interface WriteCSVOptions {
/** The field delimiter to write. */
delimiter?: string; // = ",";
/** String to use for null values. */
nullValue?: string;
/** String to use for boolean true values (default 'true'). */
trueValue?: string;
/** String to use for boolean false values (default 'false'). */
falseValue?: string;
/** Indicates whether to write headers to csv. */
includeHeader?: boolean;
/** Character to use for separating lines, */
lineTerminator?: string;
/** Maximum number of rows to write in each chunk (limits memory use). */
rowsPerChunk?: number;
}
export interface TableWriteCSVOptions extends WriteCSVOptions {
/** Callback invoked for each CSV chunk. */
next: (chunk: Buffer) => void;
/** Callback invoked when writing is finished. */
complete: () => void;
/** Column names to write in the header. */
columnNames?: string[];
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/types/parquet.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export interface ReadParquetOptionsCommon {
/** The list of columns to read */
columns?: string[];
/** Specifies for each input file, which row groups to read. */
rowGroups?: number[][];
/** The number of rows to skip from the start of the file */
skipRows?: number;
/** The total number of rows to read */
numRows?: number;
/** Return string columns as GDF_CATEGORY dtype (default 'false') */
stringsToCategorical?: boolean;
/**
* If true and dataset has custom PANDAS schema metadata, ensure that index columns are also
* loaded (default 'true').
*/
usePandasMetadata?: boolean;
}
export interface ReadParquetFileOptions extends ReadParquetOptionsCommon {
sourceType: 'files';
sources: string[];
}
export interface ReadParquetBufferOptions extends ReadParquetOptionsCommon {
sourceType: 'buffers';
sources: (Uint8Array|Buffer)[];
}
export type ReadParquetOptions = ReadParquetFileOptions|ReadParquetBufferOptions;
export interface WriteParquetOptions {
/** The name of compression to use (default 'snappy'). */
compression?: 'snappy'|'none';
/** Write timestamps in int96 format (default 'false'). */
int96Timestamps?: boolean;
}
export interface TableWriteParquetOptions extends WriteParquetOptions {
/** Column names to write in the header. */
columnNames?: string[];
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/groupby/multiple.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {Field} from 'apache-arrow';
import {Column} from '../column';
import {DataFrame} from '../data_frame';
import {GroupByBaseProps} from '../groupby';
import {Series} from '../series';
import {Table} from '../table';
import {DataType, Int32, List, Struct} from '../types/dtypes';
import {ColumnsMap, Interpolation, TypeMap} from '../types/mappings';
import {GroupByBase} from './base';
export interface GroupByMultipleProps<
T extends TypeMap, R extends keyof T, IndexKey extends string> extends GroupByBaseProps {
by: R[];
index_key: IndexKey;
}
export class GroupByMultiple<T extends TypeMap, R extends keyof T, IndexKey extends string> extends
GroupByBase<T, R> {
private index_key: IndexKey;
constructor(obj: DataFrame<T>, props: GroupByMultipleProps<T, R, IndexKey>) {
super(props, props.by, obj);
this.index_key = props.index_key;
}
protected prepare_results<U extends {[P in keyof T]: DataType}>(results:
{keys: Table, cols: Column[]}) {
const {index_key, _values: {names}} = this;
const {keys, cols} = results;
const rest_map =
names.reduce((xs, key, index) => ({...xs, [key]: cols[index]}), {} as ColumnsMap<Omit<U, R>>);
if (index_key in rest_map) {
throw new Error(`Groupby column name ${index_key} already exists`);
}
const fields = [];
const children = [];
for (const [index, name] of this._by.entries()) {
const series = Series.new(keys.getColumnByIndex(index));
fields.push(Field.new({name: name as string, type: series.type}));
children.push(series);
}
const index_map: any = {
[index_key]: Series.new({type: new Struct(fields), children: children})._col,
};
return new DataFrame(
{...index_map, ...rest_map} as ColumnsMap< //
{[P in IndexKey]: Struct<{[P in keyof Pick<U, R>]: Pick<U, R>[P]}>}& //
Omit<U, R>> //
)
.select([index_key, ...names]);
}
/**
* Compute the index of the maximum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
argmax(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._argmax(this._values.asTable(), memoryResource));
}
/**
* Compute the index of the minimum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
argmin(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._argmin(this._values.asTable(), memoryResource));
}
/**
* Compute the size of each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
count(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._count(this._values.asTable(), memoryResource));
}
/**
* Compute the maximum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
max(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._max(this._values.asTable(), memoryResource));
}
/**
* Compute the average value each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
mean(memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._mean(this._values.asTable(), memoryResource));
}
/**
* Compute the median value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
median(memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._median(this._values.asTable(), memoryResource));
}
/**
* Compute the minimum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
min(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._min(this._values.asTable(), memoryResource));
}
/**
* Return the nth value from each group
*
* @param n the index of the element to return
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
nth(n: number, include_nulls = true, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._nth(this._values.asTable(), memoryResource, n, include_nulls));
}
/**
* Compute the number of unique values in each group
*
* @param {boolean} [include_nulls=false] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
nunique(include_nulls = false, memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._nunique(this._values.asTable(), memoryResource, include_nulls));
}
/**
* Compute the standard deviation for each group
*
* @param {number} [ddof=1] Delta Degrees of Freedom. The divisor used in calculations is N -
* ddof, where N represents the number of elements in each group.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
std(ddof = 1, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._std(this._values.asTable(), memoryResource, ddof));
}
/**
* Compute the sum of values in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
sum(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._sum(this._values.asTable(), memoryResource));
}
/**
* Compute the variance for each group
*
* @param {number} [ddof=1] Delta Degrees of Freedom. The divisor used in calculations is N -
* ddof, where N represents the number of elements in each group.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
var(ddof = 1, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._var(this._values.asTable(), memoryResource, ddof));
}
/**
* Return values at the given quantile.
*
* @param q the quantile to compute, 0 <= q <= 1
* @param interpolation This optional parameter specifies the interpolation method to use,
* when the desired quantile lies between two data points i and j.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
quantile(q = 0.5,
interpolation: keyof typeof Interpolation = 'linear',
memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._quantile(
this._values.asTable(), memoryResource, q, Interpolation[interpolation]));
}
/**
* Returns a list column of all included elements in the group.
*
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
collectList(include_nulls = true, memoryResource?: MemoryResource) {
const {keys, cols} =
this._cudf_groupby._collect_list(this._values.asTable(), memoryResource, include_nulls);
this._values.names.forEach((name, index) => { //
cols[index] = this._propagateListFieldNames(name, cols[index]);
});
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : List<T[P]>}>({keys, cols});
}
/**
* Returns a lists column of all included elements in the group/series. Within each list, the
* duplicated entries are dropped out such that each entry appears only once.
*
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param {boolean} [nulls_equal=true] Whether null entries within each list should be considered
* equal.
* @param {boolean} [nans_equal=false] Whether `NaN` values in floating point column should be
* considered equal.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
collectSet(include_nulls = true,
nulls_equal = true,
nans_equal = false,
memoryResource?: MemoryResource) {
const {keys, cols} = this._cudf_groupby._collect_set(
this._values.asTable(), memoryResource, include_nulls, nulls_equal, nans_equal);
this._values.names.forEach((name, index) => { //
cols[index] = this._propagateListFieldNames(name, cols[index]);
});
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : List<T[P]>}>({keys, cols});
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/groupby/base.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import * as CUDF from '../addon';
import {Column} from '../column';
import {DataFrame, SeriesMap} from '../data_frame';
import {GroupByBaseProps, GroupByProps} from '../groupby';
import {Series} from '../series';
import {Int32, List} from '../types/dtypes';
import {TypeMap} from '../types/mappings';
export type Groups<KeysMap extends TypeMap, ValuesMap extends TypeMap> = {
keys: DataFrame<KeysMap>,
offsets: Int32Array,
values?: DataFrame<ValuesMap>,
}
export class GroupByBase<T extends TypeMap, R extends keyof T> {
protected _by: R[];
protected _values: DataFrame<Omit<T, R>>;
protected _cudf_groupby: InstanceType<typeof CUDF.GroupBy>;
constructor(props: GroupByBaseProps, by: R[], obj: DataFrame<T>) {
const table = obj.select(by).asTable();
const {
include_nulls = false,
keys_are_sorted = false,
column_order = [],
null_precedence = []
} = props;
const cudf_props: GroupByProps = {
keys: table,
include_nulls: include_nulls,
keys_are_sorted: keys_are_sorted,
column_order: column_order,
null_precedence: null_precedence,
};
this._cudf_groupby = new CUDF.GroupBy(cudf_props);
this._by = by;
this._values = obj.drop(by);
}
/**
* Return the Groups for this GroupBy
*
* @param memoryResource The optional MemoryResource used to allocate the result's
* device memory.
*/
getGroups(memoryResource?: MemoryResource) {
const {keys, offsets, values} =
this._cudf_groupby._getGroups(this._values.asTable(), memoryResource);
const results = {
offsets,
keys: new DataFrame(
this._by.reduce((keys_map, name, index) =>
({...keys_map, [name]: Series.new(keys.getColumnByIndex(index))}),
{} as SeriesMap<Pick<T, R>>))
} as Groups<Pick<T, R>, Omit<T, R>>;
if (values !== undefined) {
results.values = new DataFrame(this._values.names.reduce(
(values_map, name, index) =>
({...values_map, [name]: Series.new(values.getColumnByIndex(index))}),
{} as SeriesMap<Omit<T, R>>));
}
return results;
}
protected _propagateListFieldNames(name: string&keyof Omit<T, R>, col: Column<List>) {
(col.type.children[0] as any).name = '0';
return Series
.new({
type: col.type,
length: col.length,
nullMask: col.mask,
nullCount: col.nullCount,
children: [
col.getChild<Int32>(0),
(this._values.get(name) as any).__construct(col.getChild(1))._col
]
})
._col;
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/groupby/single.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {Column} from '../column';
import {DataFrame, SeriesMap} from '../data_frame';
import {GroupByBaseProps} from '../groupby';
import {Series} from '../series';
import {Table} from '../table';
import {DataType, Int32, List} from '../types/dtypes';
import {Interpolation, TypeMap} from '../types/mappings';
import {GroupByBase} from './base';
export interface GroupBySingleProps<T extends TypeMap, R extends keyof T> extends GroupByBaseProps {
by: R;
}
export class GroupBySingle<T extends TypeMap, R extends keyof T> extends GroupByBase<T, R> {
constructor(obj: DataFrame<T>, props: GroupBySingleProps<T, R>) { super(props, [props.by], obj); }
protected prepare_results<U extends {[P in keyof T]: DataType}>(results:
{keys: Table, cols: Column[]}) {
const {keys, cols} = results;
const series_map = {} as SeriesMap<U>;
series_map[this._by[0]] = Series.new(keys.getColumnByIndex(0));
this._values.names.forEach((name, index) => { series_map[name] = Series.new(cols[index]); });
return new DataFrame(series_map);
}
/**
* Compute the index of the maximum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
argmax(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._argmax(this._values.asTable(), memoryResource));
}
/**
* Compute the index of the minimum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
argmin(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._argmin(this._values.asTable(), memoryResource));
}
/**
* Compute the size of each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
count(memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._count(this._values.asTable(), memoryResource));
}
/**
* Compute the maximum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
max(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._max(this._values.asTable(), memoryResource));
}
/**
* Compute the average value each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
mean(memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._mean(this._values.asTable(), memoryResource));
}
/**
* Compute the median value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
median(memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._median(this._values.asTable(), memoryResource));
}
/**
* Compute the minimum value in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
min(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._min(this._values.asTable(), memoryResource));
}
/**
* Return the nth value from each group
*
* @param n the index of the element to return
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
nth(n: number, include_nulls = true, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._nth(this._values.asTable(), memoryResource, n, include_nulls));
}
/**
* Compute the number of unique values in each group
*
* @param {boolean} [include_nulls=false] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
nunique(include_nulls = false, memoryResource?: MemoryResource) {
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : Int32}>(
this._cudf_groupby._nunique(this._values.asTable(), memoryResource, include_nulls));
}
/**
* Compute the standard deviation for each group
*
* @param {number} [ddof=1] Delta Degrees of Freedom. The divisor used in calculations is N -
* ddof, where N represents the number of elements in each group.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
std(ddof = 1, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._std(this._values.asTable(), memoryResource, ddof));
}
/**
* Compute the sum of values in each group
*
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
sum(memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._sum(this._values.asTable(), memoryResource));
}
/**
* Compute the variance for each group
*
* @param {number} [ddof=1] Delta Degrees of Freedom. The divisor used in calculations is N -
* ddof, where N represents the number of elements in each group.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
var(ddof = 1, memoryResource?: MemoryResource) {
return this.prepare_results<T>(
this._cudf_groupby._var(this._values.asTable(), memoryResource, ddof));
}
/**
* Return values at the given quantile.
*
* @param q the quantile to compute, 0 <= q <= 1
* @param interpolation This optional parameter specifies the interpolation method to use,
* when the desired quantile lies between two data points i and j.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
quantile(q = 0.5,
interpolation: keyof typeof Interpolation = 'linear',
memoryResource?: MemoryResource) {
return this.prepare_results<T>(this._cudf_groupby._quantile(
this._values.asTable(), memoryResource, q, Interpolation[interpolation]));
}
/**
* Returns a list column of all included elements in the group.
*
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
collectList(include_nulls = true, memoryResource?: MemoryResource) {
const {keys, cols} =
this._cudf_groupby._collect_list(this._values.asTable(), memoryResource, include_nulls);
this._values.names.forEach((name, index) => { //
cols[index] = this._propagateListFieldNames(name, cols[index]);
});
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : List<T[P]>}>({keys, cols});
}
/**
* Returns a lists column of all included elements in the group/series. Within each list, the
* duplicated entries are dropped out such that each entry appears only once.
*
* @param {boolean} [include_nulls=true] Whether to include/exclude nulls in list elements.
* @param {boolean} [nulls_equal=true] Whether null entries within each list should be considered
* equal.
* @param {boolean} [nans_equal=false] Whether `NaN` values in floating point column should be
* considered equal.
* @param memoryResource The optional MemoryResource used to allocate the result's device memory.
*/
collectSet(include_nulls = true,
nulls_equal = true,
nans_equal = false,
memoryResource?: MemoryResource) {
const {keys, cols} = this._cudf_groupby._collect_set(
this._values.asTable(), memoryResource, include_nulls, nulls_equal, nans_equal);
this._values.names.forEach((name, index) => { //
cols[index] = this._propagateListFieldNames(name, cols[index]);
});
return this.prepare_results<{[P in keyof T]: P extends R ? T[P] : List<T[P]>}>({keys, cols});
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/bool.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Uint8ClampedBuffer} from '@rapidsai/cuda';
import {MemoryResource} from '@rapidsai/rmm';
import {Series, StringSeries} from '../series';
import {Bool8, Int64, Uint8} from '../types/dtypes';
import {NumericSeries} from './numeric';
/**
* A Series of 1-byte boolean values in GPU memory.
*/
export class Bool8Series extends NumericSeries<Bool8> {
_castAsString(memoryResource?: MemoryResource): StringSeries {
return StringSeries.new(this._col.stringsFromBooleans(memoryResource));
}
/**
* A Uint8 view of the values in GPU memory.
*/
get data() {
return new Uint8ClampedBuffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
toBitMask() { return this._col.boolsToMask()[0]; }
/**
* Compute the cumulative max of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative max of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([true, false, true])
*
* a.cumulativeMax() // {true, true, true}
* ```
*/
cumulativeMax(skipNulls = true, memoryResource?: MemoryResource) {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMax(memoryResource));
}
/**
* Compute the cumulative min of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative min of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([true, false, true])
*
* a.cumulativeMin() // {true, false, false}
* ```
*/
cumulativeMin(skipNulls = true, memoryResource?: MemoryResource) {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMin(memoryResource));
}
/**
* Compute the cumulative product of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative product of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([true, false, true])
*
* a.cumulativeProduct() // {1, 0, 0}
* ```
*/
cumulativeProduct(skipNulls = true, memoryResource?: MemoryResource) {
return Series.new(
this._prepare_scan_series(skipNulls).cast(new Uint8).cumulativeProduct(memoryResource));
}
/**
* Compute the cumulative sum of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative sum of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([true, false, true])
*
* a.cumulativeSum() // {1n, 1n, 2n}
* ```
*/
cumulativeSum(skipNulls = true, memoryResource?: MemoryResource) {
return Series.new(
this._prepare_scan_series(skipNulls).cast(new Int64).cumulativeSum(memoryResource));
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as boolean;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as boolean;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [boolean, boolean];
}
/** @inheritdoc */
sum(skipNulls = true, memoryResource?: MemoryResource) {
return super.sum(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
product(skipNulls = true, memoryResource?: MemoryResource) {
return super.product(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
sumOfSquares(skipNulls = true, memoryResource?: MemoryResource) {
return super.sumOfSquares(skipNulls, memoryResource) as number;
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/timestamp.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Int32Buffer, Int64Buffer} from '@rapidsai/cuda';
import {MemoryResource} from '@rapidsai/rmm';
import {Series} from '../series';
import {
Timestamp,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
Utf8String
} from '../types/dtypes';
export abstract class TimestampSeries<T extends Timestamp> extends Series<T> {
/** @ignore */
_castAsString(memoryResource?: MemoryResource): Series<Utf8String> {
return Series.new(this._col.stringsFromTimestamps('%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/** @ignore */
_castAsTimeStampDay(memoryResource?: MemoryResource): Series<TimestampDay> {
return Series.new(this._col.cast(new TimestampDay, memoryResource));
}
/** @ignore */
_castAsTimeStampSecond(memoryResource?: MemoryResource): Series<TimestampSecond> {
return Series.new(this._col.cast(new TimestampSecond, memoryResource));
}
/** @ignore */
_castAsTimeStampMillisecond(memoryResource?: MemoryResource): Series<TimestampMillisecond> {
return Series.new(this._col.cast(new TimestampMillisecond, memoryResource));
}
/** @ignore */
_castAsTimeStampMicrosecond(memoryResource?: MemoryResource): Series<TimestampMicrosecond> {
return Series.new(this._col.cast(new TimestampMicrosecond, memoryResource));
}
/** @ignore */
_castAsTimeStampNanosecond(memoryResource?: MemoryResource): Series<TimestampNanosecond> {
return Series.new(this._col.cast(new TimestampNanosecond, memoryResource));
}
}
export class TimestampDaySeries extends TimestampSeries<TimestampDay> {
get data() {
return new Int32Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series, TimestampDay} from "@rapidsai/cudf";
*
* // TimestampDaySeries
* const s = Series.new({
* type: new TimestampDay,
* data: [new Date('May 13, 2021 16:38:30:100 GMT+00:00')]
* });
*
* s.getValue(0) // 2021-05-13T00:00:00.000Z
* ```
*/
getValue(index: number) {
const val = this._col.getValue(index);
return val === null ? null : new Date(val);
}
}
export class TimestampSecondSeries extends TimestampSeries<TimestampSecond> {
get data() {
return new Int64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series, TimestampSecond} from "@rapidsai/cudf";
*
* // TimestampSecondSeries
* const s = Series.new({
* type: new TimestampSecond,
* data: [new Date('May 13, 2021 16:38:30:100 GMT+00:00')]
* });
*
* s.getValue(0) // 2021-05-13T16:38:30.000Z
* ```
*/
getValue(index: number) {
const val = this._col.getValue(index);
return val === null ? null : new Date(Number(val));
}
}
export class TimestampMicrosecondSeries extends TimestampSeries<TimestampMicrosecond> {
get data() {
return new Int64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series, TimestampMicrosecond} from "@rapidsai/cudf";
*
* // TimestampMicrosecondSeries
* const s = Series.new({
* type: new TimestampMicrosecond,
* data: [new Date('May 13, 2021 16:38:30:100 GMT+00:00')]
* });
*
* s.getValue(0) // 2021-05-13T16:38:30.100Z
* ```
*/
getValue(index: number) {
const val = this._col.getValue(index);
return val === null ? null : new Date(Number(val));
}
}
export class TimestampMillisecondSeries extends TimestampSeries<TimestampMillisecond> {
get data() {
return new Int64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series, TimestampMillisecond} from "@rapidsai/cudf";
*
* // TimestampMillisecondSeries
* const s = Series.new({
* type: new TimestampMillisecond,
* data: [new Date('May 13, 2021 16:38:30:100 GMT+00:00')]
* });
*
* s.getValue(0) // 2021-05-13T16:38:30.100Z
* ```
*/
getValue(index: number) {
const val = this._col.getValue(index);
return val === null ? null : new Date(Number(val));
}
}
export class TimestampNanosecondSeries extends TimestampSeries<TimestampNanosecond> {
get data() {
return new Int64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series, TimestampNanosecond} from "@rapidsai/cudf";
*
* // TimestampNanosecondSeries
* const s = Series.new({
* type: new TimestampNanosecond,
* data: [new Date('May 13, 2021 16:38:30:100 GMT+00:00')]
* });
*
* s.getValue(0) // 2021-05-13T16:38:30.100Z
* ```
*/
getValue(index: number) {
const val = this._col.getValue(index);
return val === null ? null : new Date(Number(val));
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/list.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {Series} from '../series';
import {Table} from '../table';
import {DataType, Int32, List, Utf8String} from '../types/dtypes';
let _separators: Series<Utf8String>|undefined;
/**
* A Series of lists of values.
*/
export class ListSeries<T extends DataType> extends Series<List<T>> {
/** @ignore */
_castAsString(memoryResource?: MemoryResource): Series<Utf8String> {
if (!_separators) {
// Lazily initialize the default separators
_separators = Series.new([',', '[', ']']);
}
if (compareTypes(this.elements.type, new Utf8String)) {
return Series.new(this._col.stringsFromLists('null', _separators._col, memoryResource));
}
const elements = this.elements.cast(new Utf8String)._col;
const type = new List(this.type.valueField.clone({type: elements.type}));
return Series
.new({
type,
length: this.length,
nullMask: this.mask,
nullCount: this.nullCount,
children: [this._col.getChild<Int32>(0), elements]
})
._castAsString(memoryResource);
}
/**
* Series of integer offsets for each list
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* import * as arrow from 'apache-arrow';
*
* const vec = arrow.vectorFromArray(
* [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
* new arrow.List(arrow.Field.new({ name: 'ints', type: new arrow.Int32 })),
* );
* const a = Series.new(vec);
*
* a.offsets // Int32Series [0, 3, 6, 9]
* ```
*/
// TODO: account for this.offset
get offsets() { return Series.new(this._col.getChild<Int32>(0)); }
/**
* Series containing the elements of each list
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* import * as arrow from 'apache-arrow';
*
* const vec = arrow.vectorFromArray(
* [[0, 1, 2], [3, 4, 5], [6, 7, 8]],
* new arrow.List(arrow.Field.new({ name: 'ints', type: new arrow.Int32 })),
* );
* const a = Series.new(vec);
*
* a.elements // Int32Series [0, 1, 2, 3, 4, 5, 6, 7, 8]
* ```
*/
// TODO: account for this.offset
get elements(): Series<T> { return Series.new(this._col.getChild<T>(1)); }
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // Series<List<Float64>>
* Series.new([[1, 2], [3]]).getValue(0) // Series([1, 2])
*
* // Series<List<Utf8String>>
* Series.new([["foo", "bar"], ["test"]]).getValue(1) // Series(["test"])
*
* // Series<List<Bool8>>
* Series.new([[false, true], [true]]).getValue(2) // throws index out of bounds error
* ```
*/
getValue(index: number) {
const value = this._col.getValue(index);
return value === null ? null : (this.elements as any).__construct(value);
}
/**
* @summary Flatten the list elements.
*/
flatten(memoryResource?: MemoryResource): Series<T> {
return (this.elements as any)
.__construct(
new Table({columns: [this._col]}).explode(0, memoryResource).getColumnByIndex(0));
}
/**
* @summary Flatten the list elements and return a Series of each element's position in
* its original list.
*/
flattenIndices(memoryResource?: MemoryResource): Series<Int32> {
return Series.new<Int32>(
new Table({columns: [this._col]}).explodePosition(0, memoryResource).getColumnByIndex(0));
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/string.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {Column, PadSideType} from '../column';
import {Series} from '../series';
import {Table} from '../table';
import {
Bool8,
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
Integral,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
Uint16,
Uint32,
Uint64,
Uint8,
Utf8String,
} from '../types/dtypes';
import {GetJSONObjectOptions} from '../types/json';
export type ConcatenateOptions = {
/** String that should inserted between each string from each row. Default is an empty string. */
separator?: string,
/**
String that should be used in place of any null strings found in any column. Default makes a
null entry in any produces a null result for that row.
*/
nullRepr?: string,
/**
If true, then the separator is included for null rows if nullRepr is valid. Default is true.
*/
separatorOnNulls?: boolean,
/** Device memory resource used to allocate the returned column's device memory. */
memoryResource?: MemoryResource
};
/**
* A Series of utf8-string values in GPU memory.
*/
export class StringSeries extends Series<Utf8String> {
/**
* Row-wise concatenates the given list of strings series and returns a single string series
* result.
*
* @param series List of string series to concatenate.
* @param opts Options for the concatenation
* @returns New series with concatenated results.
*
* @example
* ```typescript
* import {StringSeries} from '@rapidsai/cudf';
* const s = StringSeries.new(['a', 'b', null])
* const t = StringSeries.new(['foo', null, 'bar'])
* [...StringSeries.concatenate([s, t])] // ["afoo", null, null]
* ```
*/
public static concatenate(series: StringSeries[],
opts: ConcatenateOptions = {}): Series<Utf8String> {
const columns: Column[] = [];
for (const s of series) { columns.push(s._col); }
const separator = opts.separator ?? '';
const nullRepr = opts.nullRepr ?? null;
const separatorOnNulls = opts.separatorOnNulls ?? true;
return Series.new(Column.concatenate(
new Table({columns: columns}), separator, nullRepr, separatorOnNulls, opts.memoryResource));
}
/** @ignore */
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
_castAsString(_memoryResource?: MemoryResource): StringSeries {
return StringSeries.new(this._col);
}
/** @ignore */
_castAsInt8(memoryResource?: MemoryResource): Series<Int8> {
return Series.new(this._col.stringsToIntegers(new Int8, memoryResource));
}
/** @ignore */
_castAsInt16(memoryResource?: MemoryResource): Series<Int16> {
return Series.new(this._col.stringsToIntegers(new Int16, memoryResource));
}
/** @ignore */
_castAsInt32(memoryResource?: MemoryResource): Series<Int32> {
return Series.new(this._col.stringsToIntegers(new Int32, memoryResource));
}
/** @ignore */
_castAsInt64(memoryResource?: MemoryResource): Series<Int64> {
return Series.new(this._col.stringsToIntegers(new Int64, memoryResource));
}
/** @ignore */
_castAsUint8(memoryResource?: MemoryResource): Series<Uint8> {
return Series.new(this._col.stringsToIntegers(new Uint8, memoryResource));
}
/** @ignore */
_castAsUint16(memoryResource?: MemoryResource): Series<Uint16> {
return Series.new(this._col.stringsToIntegers(new Uint16, memoryResource));
}
/** @ignore */
_castAsUint32(memoryResource?: MemoryResource): Series<Uint32> {
return Series.new(this._col.stringsToIntegers(new Uint32, memoryResource));
}
/** @ignore */
_castAsUint64(memoryResource?: MemoryResource): Series<Uint64> {
return Series.new(this._col.stringsToIntegers(new Uint64, memoryResource));
}
/** @ignore */
_castAsFloat32(memoryResource?: MemoryResource): Series<Float32> {
return Series.new(this._col.stringsToFloats(new Float32, memoryResource));
}
/** @ignore */
_castAsFloat64(memoryResource?: MemoryResource): Series<Float64> {
return Series.new(this._col.stringsToFloats(new Float64, memoryResource));
}
/** @ignore */
_castAsTimeStampDay(memoryResource?: MemoryResource): Series<TimestampDay> {
return Series.new(
this._col.stringsToTimestamps(new TimestampDay, '%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/** @ignore */
_castAsTimeStampSecond(memoryResource?: MemoryResource): Series<TimestampSecond> {
return Series.new(
this._col.stringsToTimestamps(new TimestampSecond, '%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/** @ignore */
_castAsTimeStampMillisecond(memoryResource?: MemoryResource): Series<TimestampMillisecond> {
return Series.new(this._col.stringsToTimestamps(
new TimestampMillisecond, '%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/** @ignore */
_castAsTimeStampMicrosecond(memoryResource?: MemoryResource): Series<TimestampMicrosecond> {
return Series.new(this._col.stringsToTimestamps(
new TimestampMicrosecond, '%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/** @ignore */
_castAsTimeStampNanosecond(memoryResource?: MemoryResource): Series<TimestampNanosecond> {
return Series.new(
this._col.stringsToTimestamps(new TimestampNanosecond, '%Y-%m-%dT%H:%M:%SZ', memoryResource));
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // StringSeries
* Series.new(["foo", "bar", "test"]).getValue(0) // "foo"
* Series.new(["foo", "bar", "test"]).getValue(2) // "test"
* Series.new(["foo", "bar", "test"]).getValue(3) // throws index out of bounds error
* ```
*/
getValue(index: number) { return this._col.getValue(index); }
/**
* set value at the specified index
*
* @param index the index in this Series to set a value for
* @param value the value to set at `index`
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // StringSeries
* const a = Series.new(["foo", "bar", "test"])
* a.setValue(2, "test1") // inplace update -> Series(["foo", "bar", "test1"])
* ```
*/
setValue(index: number, value: string): void { this._col = this.scatter(value, [index])._col; }
/**
* Series of integer offsets for each string
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(["foo", "bar"]);
*
* a.offsets // Int32Array(3) [ 0, 3, 6 ]
* ```
*/
// TODO: Account for this.offset
get offsets() { return Series.new(this._col.getChild<Int32>(0)); }
/**
* Series containing the utf8 characters of each string
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(["foo", "bar"]);
*
* a.data // Uint8Array(6) [ 102, 111, 111, 98, 97, 114 ]
* ```
*/
// TODO: Account for this.offset
get data() { return Series.new(this._col.getChild<Uint8>(1)); }
/**
* Returns a boolean series identifying rows which match the given regex pattern.
*
* @param pattern Regex pattern to match to each string.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* The regex pattern strings accepted are described here:
*
* https://docs.rapids.ai/api/libcudf/stable/md_regex.html
*
* A RegExp may also be passed, however all flags are ignored (only `pattern.source` is used)
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['Finland','Colombia','Florida', 'Russia','france']);
*
* // items starting with F (only upper case)
* a.containsRe(/^F/) // [true, false, true, false, false]
* // items starting with F or f
* a.containsRe(/^[Ff]/) // [true, false, true, false, true]
* // items ending with a
* a.containsRe("a$") // [false, true, true, true, false]
* // items containing "us"
* a.containsRe("us") // [false, false, false, true, false]
* ```
*/
containsRe(pattern: string|RegExp, memoryResource?: MemoryResource): Series<Bool8> {
const pat_string = pattern instanceof RegExp ? pattern.source : pattern;
return Series.new(this._col.containsRe(pat_string, memoryResource));
}
/**
* Returns an Int32 series the number of bytes of each string in the Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['Hello', 'Bye', 'Thanks 😊', null]);
*
* a.byteCount() // [5, 3, 11, null]
* ```
*/
byteCount(memoryResource?: MemoryResource): Series<Int32> {
return Series.new(this._col.countBytes(memoryResource));
}
/**
* Returns an Int32 series the number of times the given regex pattern matches
* in each string.
*
* @param pattern Regex pattern to match to each string.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* The regex pattern strings accepted are described here:
*
* https://docs.rapids.ai/api/libcudf/stable/md_regex.html
*
* A RegExp may also be passed, however all flags are ignored (only `pattern.source` is used)
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['Finland','Colombia','Florida', 'Russia','france']);
*
* // count occurences of "o"
* a.countRe(/o/) // [0, 2, 1, 0, 0]
* // count occurences of "an"
* a.countRe('an') // [1, 0, 0, 0, 1]
*
* // get number of countries starting with F or f
* a.countRe(/^[fF]).count() // 3
* ```
*/
countRe(pattern: string|RegExp, memoryResource?: MemoryResource): Series<Int32> {
const pat_string = pattern instanceof RegExp ? pattern.source : pattern;
return Series.new(this._col.countRe(pat_string, memoryResource));
}
/**
* Returns a boolean column identifying strings in which all characters are valid for conversion
* to integers from hex.
*
* The output row entry will be set to true if the corresponding string element has at least one
* character in [0-9A-Za-z]. Also, the string may start with '0x'.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['123', '-456', '', 'AGE', '0x9EF']);
*
* a.isHex() // [true, false, false, false, true]
* ```
*/
isHex(memoryResource?: MemoryResource): Series<Bool8> {
return Series.new(this._col.stringIsHex(memoryResource));
}
/**
* Returns a new integer numeric series parsing hexadecimal values.
*
* Any null entries will result in corresponding null entries in the output series.
*
* Only characters [0-9] and [A-F] are recognized. When any other character is encountered,
* the parsing ends for that string. No interpretation is made on the sign of the integer.
*
* Overflow of the resulting integer type is not checked. Each string is converted using an
* int64 type and then cast to the target integer type before storing it into the output series.
* If the resulting integer type is too small to hold the value, the stored value will be
* undefined.
*
* @param dataType Type of integer numeric series to return.
* @param memoryResource The optional MemoryResource used to allocate the result Series' device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['04D2', 'FFFFFFFF', '00', '1B', '146D7719', null]);
*
* a.hexToIntegers() // [1234, -1, 0, 27, 342718233, null]
* ```
*/
hexToIntegers<R extends Integral>(dataType: R, memoryResource?: MemoryResource): Series<R> {
return Series.new(this._col.hexToIntegers(dataType, memoryResource));
}
/**
* Returns a boolean column identifying strings in which all characters are valid for conversion
* to integers from IPv4 format.
*
* The output row entry will be set to true if the corresponding string element has the following
* format xxx.xxx.xxx.xxx where xxx is integer digits between 0-255.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['123.255.0.7', '127.0.0.1', '', '1.2.34', '123.456.789.10', null]);
*
* a.isIpv4() // [true, true, false, false, false, null]
* ```
*/
isIpv4(memoryResource?: MemoryResource): Series<Bool8> {
return Series.new(this._col.stringIsIpv4(memoryResource));
}
/**
* Converts IPv4 addresses into integers.
*
* The IPv4 format is 1-3 character digits [0-9] between 3 dots (e.g. 123.45.67.890). Each section
* can have a value between [0-255].
*
* The four sets of digits are converted to integers and placed in 8-bit fields inside the
* resulting integer.
*
* i0.i1.i2.i3 -> (i0 << 24) | (i1 << 16) | (i2 << 8) | (i3)
*
* No checking is done on the format. If a string is not in IPv4 format, the resulting integer is
* undefined.
*
* The resulting 32-bit integer is placed in an int64_t to avoid setting the sign-bit in an
* int32_t type. This could be changed if cudf supported a UINT32 type in the future.
*
* Any null entries will result in corresponding null entries in the output column.Returns a new
* Int64 numeric series parsing hexadecimal values from the provided string series.
*
* @param dataType Type of integer numeric series to return.
* @param memoryResource The optional MemoryResource used to allocate the result Series' device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['123.255.0.7', '127.0.0.1', null]);
*
* a.ipv4ToIntegers() // [2080309255n, 2130706433n, null]
* ```
*/
ipv4ToIntegers(memoryResource?: MemoryResource): Series<Int64> {
return Series.new(this._col.ipv4ToIntegers(memoryResource));
}
/**
* Returns an Int32 series the length of each string in the Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['dog', '', '\n', null]);
*
* a.len() // [3, 0, 1 null]
* ```
*/
len(memoryResource?: MemoryResource): Series<Int32> {
return Series.new(this._col.countCharacters(memoryResource));
}
/**
* Returns a boolean series identifying rows which match the given regex pattern
* only at the beginning of the string
*
* @param pattern Regex pattern to match to each string.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* The regex pattern strings accepted are described here:
*
* https://docs.rapids.ai/api/libcudf/stable/md_regex.html
*
* A RegExp may also be passed, however all flags are ignored (only `pattern.source` is used)
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['Finland','Colombia','Florida', 'Russia','france']);
*
* // start of item contains "C"
* a.matchesRe(/C/) // [false, true, false, false, false]
* // start of item contains "us", returns false since none of the items start with "us"
* a.matchesRe('us') // [false, false, false, false, false]
* ```
*/
matchesRe(pattern: string|RegExp, memoryResource?: MemoryResource): Series<Bool8> {
const pat_string = pattern instanceof RegExp ? pattern.source : pattern;
return Series.new(this._col.matchesRe(pat_string, memoryResource));
}
/**
* Add padding to each string using a provided character.
*
* If the string is already width or more characters, no padding is performed. No strings are
* truncated.
*
* Null string entries result in null entries in the output column.
*
* @param width The minimum number of characters for each string.
* @param side Where to place the padding characters. Default is pad right (left justify).
* @param fill_char Single UTF-8 character to use for padding. Default is the space character.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['aa','bbb','cccc','ddddd', null]);
*
* a.pad(4) // ['aa ','bbb ','cccc','ddddd', null]
* ```
*/
pad(width: number, side: PadSideType = 'right', fill_char = ' ', memoryResource?: MemoryResource):
Series<Utf8String> {
return this.__construct(this._col.pad(width, side, fill_char, memoryResource));
}
/**
* Add '0' as padding to the left of each string.
*
* If the string is already width or more characters, no padding is performed. No strings are
* truncated.
*
* This equivalent to `pad(width, 'left', '0')` but is more optimized for this special case.
*
* Null string entries result in null entries in the output column.
*
* @param width The minimum number of characters for each string.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new(['1234','-9876','+0.34','-342567', null]);
*
* a.zfill(6) // ['001234','0-9876','0+0.34','-342567', null]
* ```
*/
zfill(width: number, memoryResource?: MemoryResource): Series<Utf8String> {
return this.__construct(this._col.zfill(width, memoryResource));
}
/**
* For each string in the column, replaces any character sequence matching the given pattern with
* the provided replacement string.
*
* Null string entries will return null output string entries.
*
* Position values are 0-based meaning position 0 is the first character of each string.
*
* This function can be used to insert a string into specific position by specifying the same
* position value for start and stop. The repl string can be appended to each string by specifying
* -1 for both start and stop.
*
* @param pattern The regular expression pattern to search within each string.
* @param replacement The string used to replace the matched sequence in each string.
* Default is an empty string.
* @param maxReplaceCount The maximum number of times to replace the matched pattern within each
* string. Default replaces every substring that is matched.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns New strings column with matching elements replaced.
*/
replaceRe(pattern: RegExp,
replacement = '',
maxReplaceCount = -1,
memoryResource?: MemoryResource): Series<Utf8String> {
return this.__construct(
this._col.replaceRe(pattern.source, replacement, maxReplaceCount, pattern, memoryResource));
}
/**
* Replaces each string in the column with the provided repl string within the [start,stop)
* character position range.
*
* Null string entries will return null output string entries.
*
* Position values are 0-based meaning position 0 is the first character of each string.
*
* This function can be used to insert a string into specific position by specifying the same
* position value for start and stop. The repl string can be appended to each string by specifying
* -1 for both start and stop.
*
* @param repl Replacement string for specified positions found.
* @param start Start position where repl will be added. Default is 0, first character position.
* @param stop End position (exclusive) to use for replacement. Default of -1 specifies the end of
* each string.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*/
replaceSlice(repl: string, start: number, stop: number, memoryResource?: MemoryResource):
Series<Utf8String> {
return this.__construct(this._col.replaceSlice(repl, start, stop, memoryResource));
}
/**
* Splits a StringSeries along the delimiter.
*
* @note If delimiter is omitted, the default is ''.
*
* @param delimiter Optional delimiter.
*
* @returns Series with new splits determined by the delimiter.
*/
split(delimiter = '', memoryResource?: MemoryResource): Series<Utf8String> {
return this.__construct(this._col.split(delimiter, memoryResource));
}
/**
* Returns a set of 3 columns by splitting each string using the specified delimiter.
*
* The number of rows in the output columns will be the same as the input column. The first column
* will contain the first tokens of each string as a result of the split. The second column will
* contain the delimiter. The third column will contain the remaining characters of each string
* after the delimiter.
*
* Any null string entries return corresponding null output columns.
*
* @note If delimiter is omitted, the default is ''.
*
* @param delimiter UTF-8 encoded string indicating where to split each string. Default of empty
* string indicates split on whitespace.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns 3 new string columns representing before the delimiter, the delimiter, and after the
* delimiter.
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
*
* const strs = Series.new(["a_b", "c_d"]);
* const [before, delim, after] = strs.partition('_');
*
* new DataFrame({ before, delim, after }).toString();
* // before delim after
* // a _ b
* // c _ d
* ```
*/
partition(delimiter = '', memoryResource?: MemoryResource):
[Series<Utf8String>, Series<Utf8String>, Series<Utf8String>] {
const [before, delim, after] = this._col.partitionStrings(delimiter, memoryResource);
return [this.__construct(before), this.__construct(delim), this.__construct(after)];
}
/**
* Applies a JSONPath(string) where each row in the series is a valid json string. Returns New
* StringSeries containing the retrieved json object strings
*
* @param jsonPath The JSONPath string to be applied to each row of the input column
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = const lines = Series.new([
* {foo: {bar: "baz"}},
* {foo: {baz: "bar"}},
* ].map(JSON.stringify)); // StringSeries ['{"foo":{"bar":"baz"}}', '{"foo":{"baz":"bar"}}']
*
* a.getJSONObject("$.foo") // StringSeries ['{"bar":"baz"}', '{"baz":"bar"}']
* a.getJSONObject("$.foo.bar") // StringSeries ["baz", null]
*
* // parse the resulting strings using JSON.parse
* [...a.getJSONObject("$.foo").map(JSON.parse)] // object [{ bar: 'baz' }, { baz: 'bar' }]
* ```
*/
getJSONObject(jsonPath: string,
options: GetJSONObjectOptions = {
allowSingleQuotes: false,
missingFieldsAsNulls: false,
stripQuotesFromSingleStrings: true,
},
memoryResource?: MemoryResource): Series<Utf8String> {
let col = this._col.getJSONObject(jsonPath, options, memoryResource);
// Work around a bug where libcudf can return String columns with no offsets or data children
if (col.numChildren === 0) {
({_col: col} = Series.new({
type: new Utf8String,
length: col.length,
nullMask: col.mask,
nullCount: col.nullCount,
children: [
new Int32Array(col.length + 1).fill(0),
new Uint8Array(0),
],
}));
}
return this.__construct(col);
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/float.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float32Buffer, Float64Buffer} from '@rapidsai/cuda';
import {MemoryResource} from '@rapidsai/rmm';
import {Column} from '../column';
import {Scalar} from '../scalar';
import {Series} from '../series';
import {Float32, Float64, FloatingPoint} from '../types/dtypes';
import {NumericSeries} from './numeric';
import {StringSeries} from './string';
/**
* A base class for Series of 32 or 64-bit floating-point values in GPU memory.
*/
export abstract class FloatSeries<T extends FloatingPoint> extends NumericSeries<T> {
_castAsString(memoryResource?: MemoryResource): StringSeries {
return StringSeries.new(this._col.stringsFromFloats(memoryResource));
}
/**
* Creates a Series of `BOOL8` elements where `true` indicates the value is `NaN` and `false`
* indicates the value is valid.
*
* @param memoryResource Memory resource used to allocate the result Column's device memory.
* @returns A non-nullable Series of `BOOL8` elements with `true` representing `NaN` values.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* // Float64Series
* Series.new([1, NaN, 3]).isNaN() // [false, true, false]
* ```
*/
isNaN(memoryResource?: MemoryResource) { return Series.new(this._col.isNaN(memoryResource)); }
/**
* Creates a Series of `BOOL8` elements indicating the absence of `NaN` values in a
* column of floating point values. The output element at row `i` is `false` if the element in
* `input` at row i is `NaN`, else `true`
*
* @param memoryResource Memory resource used to allocate the result Series's device memory.
* @returns A non-nullable Series of `BOOL8` elements with `true` representing `NAN`
* values
*/
isNotNaN(memoryResource?: MemoryResource) {
return Series.new(this._col.isNotNaN(memoryResource));
}
/**
* Round each floating-point value in this Series to the nearest integer.
*
* @param memoryResource Memory resource used to allocate the result Series's device memory.
* @returns A Series of the same number of elements containing the result of the operation.
*/
rint(memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._col.rint(memoryResource));
}
protected _process_reduction(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
if (skipNulls == true) {
return this.__construct(this._col.nansToNulls(memoryResource).dropNulls());
}
return this.__construct(this._col);
}
/**
* convert NaN values in the series with Null values,
* while also updating the nullMask and nullCount values
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns updated Series with Null values
*/
nansToNulls(memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._col.nansToNulls(memoryResource));
}
/**
* drop NaN values from the column if column is of floating-type
* values and contains NA values
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns column without NaN values
*/
dropNaNs(memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._col.dropNans(memoryResource));
}
/**
* Replace NaN values with a scalar value.
*
* @param value The value to use in place of NaNs.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*/
replaceNaNs(value: T['scalarType'], memoryResource?: MemoryResource): Series<T>;
/**
* Replace NaN values with the corresponding elements from another Series.
*
* @param value The Series to use in place of NaNs.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*/
replaceNaNs(value: Series<T>, memoryResource?: MemoryResource): Series<T>;
replaceNaNs(value: T['scalarType']|Series<T>, memoryResource?: MemoryResource): Series<T> {
if (value instanceof Series) {
return this.__construct(this._col.replaceNaNs(value._col as Column<T>, memoryResource));
} else {
return this.__construct(
this._col.replaceNaNs(new Scalar<T>({type: this.type, value}), memoryResource));
}
}
/**
* Return whether all elements are true in Series.
*
* @param skipNulls bool
* Exclude NA/null values. If the entire row/column is NA and skipNulls is true, then the result
* will be true, as for an empty row/column. If skipNulls is false, then NA are treated as true,
* because these are not equal to zero.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @returns true if all elements are true in Series, else false.
*/
all(skipNulls = true, memoryResource?: MemoryResource) {
if (skipNulls) {
const ser_result = this.nansToNulls(memoryResource);
if (ser_result.length == ser_result.nullCount) { return true; }
}
return this._col.all(memoryResource);
}
/**
* Return whether any elements are true in Series.
*
* @param skipNulls bool
* Exclude NA/null values. If the entire row/column is NA and skipNulls is true, then the result
* will be true, as for an empty row/column. If skipNulls is false, then NA are treated as true,
* because these are not equal to zero.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @returns true if any elements are true in Series, else false.
*/
any(skipNulls = true, memoryResource?: MemoryResource) {
if (this.length == 0) { return false; }
if (skipNulls) {
const ser_result = this.nansToNulls(memoryResource);
if (ser_result.length == ser_result.nullCount) { return false; }
}
return this._col.any(memoryResource);
}
/**
* Compute the cumulative max of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative max of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1])
*
* a.cumulativeMax() // {4, 4, 5, 5, 5}
* ```
*/
cumulativeMax(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMax(memoryResource));
}
/**
* Compute the cumulative min of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative min of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1])
*
* a.cumulativeMin() // {4, 2, 2, 1, 1}
* ```
*/
cumulativeMin(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMin(memoryResource));
}
/**
* Compute the cumulative product of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative product of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1])
*
* a.cumulativeProduct() // {4, 8, 40, 40, 40}
* ```
*/
cumulativeProduct(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeProduct(memoryResource));
}
/**
* Compute the cumulative sum of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative sum of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1])
*
* a.cumulativeSum() // {4, 6, 11, 12, 13}
* ```
*/
cumulativeSum(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeSum(memoryResource));
}
/**
* Compute the mean of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The mean of all the values in this Series.
*/
mean(skipNulls = true, memoryResource?: MemoryResource) {
if (!skipNulls && this.nansToNulls().nullCount > 0) { return NaN; }
return this._process_reduction(skipNulls, memoryResource)._col.mean(memoryResource);
}
/**
* Compute the median of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The median of all the values in this Series.
*/
median(skipNulls = true, memoryResource?: MemoryResource) {
if (!skipNulls && this.nansToNulls().nullCount > 0) { return NaN; }
return this._process_reduction(skipNulls, memoryResource)._col.median(memoryResource);
}
/**
* Compute the nunique of all values in this Series.
*
* @param dropna
* If true, NA/null values will not contribute to the count of unique values. If false, they
* will be included in the count.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The number of unqiue values in this Series.
*/
nunique(dropna = true, memoryResource?: MemoryResource) {
return (dropna ? this._col.nansToNulls(memoryResource) : this._col)
.nunique(dropna, memoryResource);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this.nansToNulls())
._col.min(memoryResource);
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this.nansToNulls())
._col.max(memoryResource);
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this.nansToNulls())
._col.minmax(memoryResource) as [number, number];
}
/** @inheritdoc */
sum(skipNulls = true, memoryResource?: MemoryResource) {
return super.sum(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
product(skipNulls = true, memoryResource?: MemoryResource) {
return super.product(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
sumOfSquares(skipNulls = true, memoryResource?: MemoryResource) {
return super.sumOfSquares(skipNulls, memoryResource) as number;
}
}
/**
* A Series of 32-bit floating-point values in GPU memory.
*/
export class Float32Series extends FloatSeries<Float32> {
/**
* A Float32 view of the values in GPU memory.
*/
get data() {
return new Float32Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
}
/**
* A Series of 64-bit floating-point values in GPU memory.
*/
export class Float64Series extends FloatSeries<Float64> {
/**
* A Float64 view of the values in GPU memory.
*/
get data() {
return new Float64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/categorical.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {Column} from '../column';
import {DataFrame} from '../data_frame';
import {scope} from '../scope';
import {Series} from '../series';
import {
Categorical,
DataType,
Int16,
Int32,
Int64,
Int8,
Integral,
Uint16,
Uint32,
Uint64,
Uint8,
Utf8String
} from '../types/dtypes';
/**
* A Series of dictionary-encoded values in GPU memory.
*/
export class CategoricalSeries<T extends DataType> extends Series<Categorical<T>> {
/**
* @summary The Series of codes.
*/
public get codes() { return Series.new(this._col.getChild<Int32>(0)); }
/**
* @summary The Series of categories.
*/
public get categories() { return Series.new(this._col.getChild<T>(1)); }
/**
* @inheritdoc
*/
public encodeLabels<R extends Integral = Uint32>(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_categories: Series<Categorical<T>> = this,
type: R = new Uint32 as R,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_nullSentinel: R['scalarType'] = -1,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_memoryResource?: MemoryResource): Series<R> {
return compareTypes(this.type.indices, type) ? this.codes as Series<R> //
: this.codes.cast(type);
}
/**
* @summary Get a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // StringSeries
* Series.new(["foo", "bar", "test"]).getValue(0) // "foo"
* Series.new(["foo", "bar", "test"]).getValue(2) // "test"
* Series.new(["foo", "bar", "test"]).getValue(3) // throws index out of bounds error
* ```
*/
public getValue(index: number) { return this._col.getValue(index); }
/**
* @summary Set a value at the specified index.
*
* @param index the index in this Series to set a value for
* @param value the value to set at `index`
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // StringSeries
* const a = Series.new(["foo", "bar", "test"])
* a.setValue(2, "test1") // inplace update -> Series(["foo", "bar", "test1"])
* ```
*/
public setValue(index: number, value: T['scalarType']): void {
this._col = this.scatter(value, [index])._col;
}
_castAsInt8(memoryResource?: MemoryResource): Series<Int8> {
return this._castCategories(new Int8, memoryResource);
}
_castAsInt16(memoryResource?: MemoryResource): Series<Int16> {
return this._castCategories(new Int16, memoryResource);
}
_castAsInt32(memoryResource?: MemoryResource): Series<Int32> {
return this._castCategories(new Int32, memoryResource);
}
_castAsInt64(memoryResource?: MemoryResource): Series<Int64> {
return this._castCategories(new Int64, memoryResource);
}
_castAsUint8(memoryResource?: MemoryResource): Series<Uint8> {
return this._castCategories(new Uint8, memoryResource);
}
_castAsUint16(memoryResource?: MemoryResource): Series<Uint16> {
return this._castCategories(new Uint16, memoryResource);
}
_castAsUint32(memoryResource?: MemoryResource): Series<Uint32> {
return this._castCategories(new Uint32, memoryResource);
}
_castAsUint64(memoryResource?: MemoryResource): Series<Uint64> {
return this._castCategories(new Uint64, memoryResource);
}
_castAsString(memoryResource?: MemoryResource): Series<Utf8String> {
return this._castCategories(new Utf8String, memoryResource);
}
_castAsCategorical<R extends Categorical>(type: R, memoryResource?: MemoryResource): Series<R> {
return Series.new({
type,
length: this.length,
nullMask: this.mask,
children: [this.codes, this.categories.cast(type, memoryResource)]
});
}
protected _castCategories<R extends DataType>(type: R,
memoryResource?: MemoryResource): Series<R> {
const result = this.categories.gather(this.codes).cast(type, memoryResource);
result.setNullMask(this.mask);
return result;
}
/**
* @summary Create a new CategoricalColumn with the categories set to the specified `categories`.
*
* @param categories The new categories
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns CategoricalSeries of same size as the current Series with the new categories.
*/
public setCategories(categories: Series<T>|(T['scalarType'][]),
memoryResource?: MemoryResource): Series<Categorical<T>> {
return scope(() => {
const new_cats = scope(() => {
const uniq = scope(() => {
return new DataFrame({
value: Series.new<T>(<any>categories),
order: Series.sequence({size: categories.length})
})
.groupBy({by: 'value'})
.nth(0);
});
return uniq.sortValues({order: {ascending: true}}, memoryResource).get('value');
});
const new_codes = scope(() => {
// 1. Join the old and new categories to align their codes
const aligned = scope(() => {
const cur_cats = this.categories;
const old_codes = Series.sequence({size: cur_cats.length});
const new_codes = Series.sequence({size: new_cats.length});
const old_df = new DataFrame({old_codes, categories: cur_cats});
const new_df = new DataFrame({new_codes, categories: new_cats});
return old_df.join({how: 'left', on: ['categories'], other: new_df});
});
// 2. Join the old and new codes to "recode" the new categories
const cur_index = Series.sequence({size: this.codes.length});
const cur_df = new DataFrame({old_codes: this.codes, cur_index});
return cur_df.join({how: 'left', on: ['old_codes'], other: aligned})
.drop(['old_codes'])
.sortValues({cur_index: {ascending: true}}, memoryResource)
.get('new_codes');
}, [new_cats]);
return this.__construct(new Column({
type: this.type,
length: this.length,
nullMask: this.mask,
children: [new_codes._col, new_cats._col]
}));
}, [this.codes, this.categories, categories]);
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/struct.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {Series} from '../series';
import {Struct, Utf8String} from '../types/dtypes';
import {TypeMap} from '../types/mappings';
/**
* A Series of structs.
*/
export class StructSeries<T extends TypeMap> extends Series<Struct<T>> {
/** @ignore */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_castAsString(_memoryResource?: MemoryResource): Series<Utf8String> {
return Series.new(this.toArray().map((x) => JSON.stringify(x)));
}
/**
* Return a child series by name.
*
* @param name Name of the Series to return.
*
* @example
* ```typescript
* import {Series} = require('@rapidsai/cudf');
* import * as arrow from 'apache-arrow';
*
* const vec = arrow.vectorFromArray(
* [{ x: 0, y: 3 }, { x: 1, y: 4 }, { x: 2, y: 5 }],
* new arrow.Struct([
* arrow.Field.new({ name: 'x', type: new arrow.Int32 }),
* arrow.Field.new({ name: 'y', type: new arrow.Int32 })
* ]),
* );
* const a = Series.new(vec);
*
* a.getChild('x') // Int32Series [0, 1, 2]
* a.getChild('y') // Int32Series [3, 4, 5]
* ```
*/
// TODO: Account for this.offset
getChild<P extends keyof T>(name: P): Series<T[P]> {
return Series.new(
this._col.getChild<T[P]>(this.type.children.findIndex((f) => f.name === name)));
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // Series<Struct<{a: Float64, b: Float64}>>
* Series.new([{a: 0, b: 1}]).getValue(0) // {a: 0, b: 1}
* ```
*/
getValue(index: number) {
const value = this._col.getValue(index);
return value === null
? null
: this.type.children.reduce(
(xs, f, i) => ({...xs, [f.name]: value.getColumnByIndex(i).getValue(0)}), {});
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/numeric.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {MemoryResource} from '@rapidsai/rmm';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {Column} from '../column';
import {Scalar} from '../scalar';
import {Series} from '../series';
import {
Bool8,
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
Numeric,
Uint16,
Uint32,
Uint64,
Uint8
} from '../types/dtypes';
import {CommonType, Interpolation} from '../types/mappings';
import {Float64Series} from './float';
import {Int64Series} from './integral';
/**
* A base class for Series of fixed-width numeric values.
*/
export abstract class NumericSeries<T extends Numeric> extends Series<T> {
/** @ignore */
_castAsBool8(memoryResource?: MemoryResource): Series<Bool8> { //
return this._castNumeric(new Bool8, memoryResource);
}
/** @ignore */
_castAsInt8(memoryResource?: MemoryResource): Series<Int8> { //
return this._castNumeric(new Int8, memoryResource);
}
/** @ignore */
_castAsInt16(memoryResource?: MemoryResource): Series<Int16> { //
return this._castNumeric(new Int16, memoryResource);
}
/** @ignore */
_castAsInt32(memoryResource?: MemoryResource): Series<Int32> { //
return this._castNumeric(new Int32, memoryResource);
}
/** @ignore */
_castAsInt64(memoryResource?: MemoryResource): Series<Int64> { //
return this._castNumeric(new Int64, memoryResource);
}
/** @ignore */
_castAsUint8(memoryResource?: MemoryResource): Series<Uint8> { //
return this._castNumeric(new Uint8, memoryResource);
}
/** @ignore */
_castAsUint16(memoryResource?: MemoryResource): Series<Uint16> { //
return this._castNumeric(new Uint16, memoryResource);
}
/** @ignore */
_castAsUint32(memoryResource?: MemoryResource): Series<Uint32> { //
return this._castNumeric(new Uint32, memoryResource);
}
/** @ignore */
_castAsUint64(memoryResource?: MemoryResource): Series<Uint64> { //
return this._castNumeric(new Uint64, memoryResource);
}
/** @ignore */
_castAsFloat32(memoryResource?: MemoryResource): Series<Float32> { //
return this._castNumeric(new Float32, memoryResource);
}
/** @ignore */
_castAsFloat64(memoryResource?: MemoryResource): Series<Float64> { //
return this._castNumeric(new Float64, memoryResource);
}
protected _castNumeric<R extends Numeric>(type: R, memoryResource?: MemoryResource): Series<R> {
return Series.new<R>(compareTypes(this.type, type) ? this._col as any as Column<R>
: this._col.cast(type, memoryResource));
}
protected _prepare_scan_series(skipNulls: boolean) {
const self = this.nansToNulls();
if (skipNulls || !self.hasNulls) { return self._col as Column<T>; }
const index = Series.sequence({size: self.length});
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const first = index.filter(self.isNull()).getValue(0)!;
const slice = Series.sequence({size: self.length - first, init: first});
const [nullMask, nullCount] =
index.cast(new Bool8).fill(true).scatter(false, slice)._col.boolsToMask();
return new Column({
type: this._col.type,
data: self._col.data,
offset: self._col.offset,
length: self._col.length,
nullMask,
nullCount,
});
}
/** @ignore */
/* eslint-disable @typescript-eslint/no-unused-vars */
nansToNulls(_memoryResource?: MemoryResource): Series<T> { return this.__construct(this._col); }
/* eslint-enable @typescript-eslint/no-unused-vars */
/**
* View the data underlying this Series as a new dtype (similar to `reinterpret_cast` in C++).
*
* @note The length of this Series must divide evenly into the size of the desired data type.
* @note Series with nulls may only be viewed as dtypes of the same element width.
*
* @returns Series of same size as the current Series containing result of the `cast` operation.
*/
view<R extends Numeric>(dataType: R): Series<R> {
if (this.type.BYTES_PER_ELEMENT === dataType.BYTES_PER_ELEMENT) {
return Series.new({
type: dataType,
data: this._col.data,
length: this.length,
nullMask: this.mask,
nullCount: this.nullCount,
});
}
if (this.nullCount > 0) {
throw new Error('Cannot view a Series with nulls as a dtype of a different element width');
}
const byteLength = this.length * this.type.BYTES_PER_ELEMENT;
if (0 !== (byteLength % dataType.BYTES_PER_ELEMENT)) {
throw new Error(
`Can not divide ${this.length * this.type.BYTES_PER_ELEMENT} total bytes into ${
String(dataType)} with element width ${dataType.BYTES_PER_ELEMENT}`);
}
const newLength = byteLength / dataType.BYTES_PER_ELEMENT;
return Series.new({type: dataType, data: this._col.data, length: newLength});
}
/**
* Return a value at the specified index to host memory
*
* @param index the index in this Series to return a value for
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // Float64Series
* Series.new([1, 2, 3]).getValue(0) // 1
* Series.new([1, 2, 3]).getValue(2) // 3
* Series.new([1, 2, 3]).getValue(3) // throws index out of bounds error
* ```
*/
getValue(index: number) { return this._col.getValue(index); }
/**
* set value at the specified index
*
* @param index the index in this Series to set a value for
* @param value the value to set at `index`
*
* @example
* ```typescript
* import {Series} from "@rapidsai/cudf";
*
* // Float64Series
* const a = Series.new([1, 2, 3]);
* a.setValue(0, -1) // inplace update -> Series([-1, 2, 3])
* ```
*/
setValue(index: number, value: T['scalarType']): void {
this._col = this.scatter(value, [index])._col as Column<T>;
}
/**
* Add this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to add to this Series.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.add(3); // [13, 15, 17, 23]
* a.add(b); // [13, 14, 15, 23]
* ```
*/
add(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
add(rhs: number, memoryResource?: MemoryResource): Float64Series;
add<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
add<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
add(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.add(rhs, memoryResource));
case 'number': return Series.new(this._col.add(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.add(rhs, memoryResource))
: Series.new(this._col.add(rhs._col, memoryResource));
}
/**
* Subtract this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to subtract from this Series.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.sub(3); // [7, 9, 11, 17]
* a.sub(b); // [7, 10, 13, 17]
* ```
*/
sub(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
sub(rhs: number, memoryResource?: MemoryResource): Float64Series;
sub<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
sub<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
sub(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.sub(rhs, memoryResource));
case 'number': return Series.new(this._col.sub(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.sub(rhs, memoryResource))
: Series.new(this._col.sub(rhs._col, memoryResource));
}
/**
* Multiply this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to multiply this column by.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.mul(3); // [30, 36, 42, 60]
* a.mul(b); // [30, 24, 14, 60]
* ```
*/
mul(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
mul(rhs: number, memoryResource?: MemoryResource): Float64Series;
mul<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
mul<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
mul(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.mul(rhs, memoryResource));
case 'number': return Series.new(this._col.mul(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.mul(rhs, memoryResource))
: Series.new(this._col.mul(rhs._col, memoryResource));
}
/**
* Divide this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to divide this Series by.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.div(3); // [3.3333333333333335, 4, 4.666666666666667, 6.666666666666667]
* a.div(b); // [3.3333333333333335, 6, 14, 6.666666666666667]
* ```
*/
div(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
div(rhs: number, memoryResource?: MemoryResource): Float64Series;
div<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
div<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
div(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.div(rhs, memoryResource));
case 'number': return Series.new(this._col.div(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.div(rhs, memoryResource))
: Series.new(this._col.div(rhs._col, memoryResource));
}
/**
* True-divide this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to true-divide this Series by.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.trueDiv(3); // [3.3333333333333335, 4, 4.666666666666667, 6.666666666666667]
* a.trueDiv(b); // [3.3333333333333335, 6, 14, 6.666666666666667]
* ```
*/
trueDiv(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
trueDiv(rhs: number, memoryResource?: MemoryResource): Float64Series;
trueDiv<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
trueDiv<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
trueDiv(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.trueDiv(rhs, memoryResource));
case 'number': return Series.new(this._col.trueDiv(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.trueDiv(rhs, memoryResource))
: Series.new(this._col.trueDiv(rhs._col, memoryResource));
}
/**
* Floor-divide this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to floor-divide this Series by.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.floorDiv(3); // [ 3, 4, 4, 6 ]
* a.floorDiv(b); // [ 3, 6, 14, 6 ]
* ```
*/
floorDiv(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
floorDiv(rhs: number, memoryResource?: MemoryResource): Float64Series;
floorDiv<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
floorDiv<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
floorDiv(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.floorDiv(rhs, memoryResource));
case 'number': return Series.new(this._col.floorDiv(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.floorDiv(rhs, memoryResource))
: Series.new(this._col.floorDiv(rhs._col, memoryResource));
}
/**
* Modulo this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to mod with this Series.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([10, 12, 14, 20]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.mod(3); // [ 1, 0, 2, 2 ]
* a.mod(b); // [ 1, 0, 0, 2 ]
* ```
*/
mod(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
mod(rhs: number, memoryResource?: MemoryResource): Float64Series;
mod<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
mod<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
mod(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.mod(rhs, memoryResource));
case 'number': return Series.new(this._col.mod(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.mod(rhs, memoryResource))
: Series.new(this._col.mod(rhs._col, memoryResource));
}
/**
* Power this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use as the exponent for the power operation.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.pow(2); // [ 0, 1, 4, 9 ]
* a.pow(b); // [ 0, 1, 2, 27 ]
* ```
*/
pow(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
pow(rhs: number, memoryResource?: MemoryResource): Float64Series;
pow<R extends Scalar<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
pow<R extends Series<Numeric>>(rhs: R,
memoryResource?: MemoryResource): Series<CommonType<T, R['type']>>;
pow(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.pow(rhs, memoryResource));
case 'number': return Series.new(this._col.pow(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.pow(rhs, memoryResource))
: Series.new(this._col.pow(rhs._col, memoryResource));
}
/**
* Perform the binary '==' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.eq(1); // [ false, true, false, false ]
* a.eq(b); // [ false, false, false, true ]
* ```
*/
eq(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
eq(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
eq<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
eq<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
eq(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.eq(rhs, memoryResource));
case 'number': return Series.new(this._col.eq(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.eq(rhs, memoryResource))
: Series.new(this._col.eq(rhs._col, memoryResource));
}
/**
* Perform the binary '!=' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.ne(1); // [true, false, true, true]
* a.ne(b); // [true, true, true, false]
* ```
*/
ne(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
ne(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
ne<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
ne<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
ne(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.ne(rhs, memoryResource));
case 'number': return Series.new(this._col.ne(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.ne(rhs, memoryResource))
: Series.new(this._col.ne(rhs._col, memoryResource));
}
/**
* Perform the binary '<' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.lt(1); // [true, false, false, false]
* a.lt(b); // [true, true, false, false]
* ```
*/
lt(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
lt(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
lt<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
lt<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
lt(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.lt(rhs, memoryResource));
case 'number': return Series.new(this._col.lt(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.lt(rhs, memoryResource))
: Series.new(this._col.lt(rhs._col, memoryResource));
}
/**
* Perform the binary '<=' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.le(1); // [true, true, false, false]
* a.le(b); // [true, true, false, true]
* ```
*/
le(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
le(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
le<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
le<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
le(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.le(rhs, memoryResource));
case 'number': return Series.new(this._col.le(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.le(rhs, memoryResource))
: Series.new(this._col.le(rhs._col, memoryResource));
}
/**
* Perform the binary '>' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.gt(1); // [false, false, true, true]
* a.gt(b); // [false, false, true, false]
* ```
*/
gt(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
gt(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
gt<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
gt<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
gt(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.gt(rhs, memoryResource));
case 'number': return Series.new(this._col.gt(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.gt(rhs, memoryResource))
: Series.new(this._col.gt(rhs._col, memoryResource));
}
/**
* Perform the binary '>=' operation between this column and another Series or scalar value.
*
* @rhs The other Series or scalar to compare with this column.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of booleans with the comparison result.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([0, 1, 2, 3]);
* const b = Series.new([3, 2, 1, 3]);
*
* a.ge(1); // [false, true, true, true]
* a.ge(b); // [false, false, true, true]
* ```
*/
ge(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
ge(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
ge<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
ge<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
ge(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.ge(rhs, memoryResource));
case 'number': return Series.new(this._col.ge(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.ge(rhs, memoryResource))
: Series.new(this._col.ge(rhs._col, memoryResource));
}
/**
* Perform a binary `&&` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series, Bool8} from '@rapidsai/cudf';
* const a = Series.new([false, true, true, false]);
* const b = Series.new([false, false, false, false]);
*
* a.logicalAnd(0); // Float64Series [ 0, 0, 0, 0 ]
* a.logicalAnd(0).view(new Bool8); // Bool8Series [ false, false, false, false ]
* a.logicalAnd(b); // [false, false, false, false]
* ```
*/
logicalAnd(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
logicalAnd(rhs: number, memoryResource?: MemoryResource): Float64Series;
logicalAnd<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logicalAnd<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logicalAnd(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.logicalAnd(rhs, memoryResource));
case 'number': return Series.new(this._col.logicalAnd(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.logicalAnd(rhs, memoryResource))
: Series.new(this._col.logicalAnd(rhs._col, memoryResource));
}
/**
* Perform a binary `||` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series, Bool8} from '@rapidsai/cudf';
* const a = Series.new([false, true, true, false]);
* const b = Series.new([false, false, false, false]);
*
* a.logicalOr(0); // Float64Series [ 0, 1, 1, 0 ]
* a.logicalOr(0).cast(new Bool8); // Bool8Series [ false, true, true, false ]
* a.logicalOr(b); // [false, true, true, false]
* ```
*/
logicalOr(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
logicalOr(rhs: number, memoryResource?: MemoryResource): Float64Series;
logicalOr<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logicalOr<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logicalOr(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.logicalOr(rhs, memoryResource));
case 'number': return Series.new(this._col.logicalOr(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.logicalOr(rhs, memoryResource))
: Series.new(this._col.logicalOr(rhs._col, memoryResource));
}
/**
* Perform a binary `logBase` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 10, 100]);
* const b = Series.new([2, 10, 20]);
*
* a.logBase(10); // [0, 1, 2]
* a.logBase(b); // [0, 1, 1.537243573680482]
* ```
*/
logBase(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
logBase(rhs: number, memoryResource?: MemoryResource): Float64Series;
logBase<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logBase<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
logBase(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.logBase(rhs, memoryResource));
case 'number': return Series.new(this._col.logBase(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.logBase(rhs, memoryResource))
: Series.new(this._col.logBase(rhs._col, memoryResource));
}
/**
* Perform a binary `atan2` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 3, 5, null, 7]);
* const b = Series.new([1, 3, 3, null, 9]);
*
* a.atan2(3);
* // [0.3217505543966422, 0.7853981633974483, 1.0303768265243125, 0, 1.1659045405098132]
*
* a.atan2(b);
* // [0.7853981633974483, 0.7853981633974483, 1.0303768265243125, 0, 0.6610431688506869]
* ```
*/
atan2(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
atan2(rhs: number, memoryResource?: MemoryResource): Float64Series;
atan2<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
atan2<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
atan2(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.atan2(rhs, memoryResource));
case 'number': return Series.new(this._col.atan2(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.atan2(rhs, memoryResource))
: Series.new(this._col.atan2(rhs._col, memoryResource));
}
/**
* Perform a binary `nullEquals` operation between this Series and another Series or scalar
* value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 3, 5, null, 7]);
* const b = Series.new([1, 3, 3, null, 9]);
*
* a.nullEquals(3); // [false, true, false, false, false]
* a.nullEquals(b); // [true, true, false, true, false]
* ```
*/
nullEquals(rhs: bigint, memoryResource?: MemoryResource): Series<Bool8>;
nullEquals(rhs: number, memoryResource?: MemoryResource): Series<Bool8>;
nullEquals<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
nullEquals<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource): Series<Bool8>;
nullEquals(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.nullEquals(rhs, memoryResource));
case 'number': return Series.new(this._col.nullEquals(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.nullEquals(rhs, memoryResource))
: Series.new(this._col.nullEquals(rhs._col, memoryResource));
}
/**
* Perform a binary `nullMax` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 3, 5, null, 7]);
* const b = Series.new([6, 6, 6, 6, 6]);
*
* a.nullMax(4); // [4, 4, 5, 4, 7]
* a.nullMax(b); // [6, 6, 6, 6, 7]
* ```
*/
nullMax(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
nullMax(rhs: number, memoryResource?: MemoryResource): Float64Series;
nullMax<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
nullMax<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
nullMax(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.nullMax(rhs, memoryResource));
case 'number': return Series.new(this._col.nullMax(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.nullMax(rhs, memoryResource))
: Series.new(this._col.nullMax(rhs._col, memoryResource));
}
/**
* Perform a binary `nullMin` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns A Series of a common numeric type with the results of the binary operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 3, 5, null, 7]);
* const c = Series.new([6, 6, 6, 6, 6]);
*
* a.nullMin(4); // [1, 3, 4, 4, 4]
* a.nullMin(b); // [1, 3, 5, 6, 6]
* ```
*/
nullMin(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
nullMin(rhs: number, memoryResource?: MemoryResource): Float64Series;
nullMin<R extends Scalar<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
nullMin<R extends Series<Numeric>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
nullMin(rhs: any, memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.nullMin(rhs, memoryResource));
case 'number': return Series.new(this._col.nullMin(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar ? Series.new(this._col.nullMin(rhs, memoryResource))
: Series.new(this._col.nullMin(rhs._col, memoryResource));
}
/**
* Compute the trigonometric sine for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).sin(); // [0, 0.8509035245341184, 0.8414709848078965]
* ```
*/
sin(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.sin(memoryResource));
}
/**
* Compute the trigonometric cosine for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).cos(); // [1, 0.5253219888177297, 0.5403023058681398]
* ```
*/
cos(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.cos(memoryResource));
}
/**
* Compute the trigonometric tangent for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).tan(); // [0, 1.6197751905438615, 1.557407724654902]
* ```
*/
tan(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.tan(memoryResource));
}
/**
* Compute the trigonometric sine inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).asin(); // [0, NaN, 1.5707963267948966]
* ```
*/
asin(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.asin(memoryResource));
}
/**
* Compute the trigonometric cosine inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).acos(); // [1.5707963267948966, NaN, 0]
* ```
*/
acos(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.acos(memoryResource));
}
/**
* Compute the trigonometric tangent inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).atan(); // [0, 1.5485777614681775, 0.7853981633974483]
* ```
*/
atan(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.atan(memoryResource));
}
/**
* Compute the hyperbolic sine for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).sinh(); // [0, 17467135528742547000, 1.1752011936438014]
* ```
*/
sinh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.sinh(memoryResource));
}
/**
* Compute the hyperbolic cosine for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).cosh(); // [1, 17467135528742547000, 1.5430806348152437]
* ```
*/
cosh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.cosh(memoryResource));
}
/**
* Compute the hyperbolic tangent for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).tanh(); // [0, 1, 0.7615941559557649]
* ```
*/
tanh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.tanh(memoryResource));
}
/**
* Compute the hyperbolic sine inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, 45, 1]).asinh(); // [0, 4.49993310426429, 0.8813735870195429]
* ```
*/
asinh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.asinh(memoryResource));
}
/**
* Compute the hyperbolic cosine inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([7, 56, 1]).acosh(); // [2.6339157938496336, 4.71841914237288, 0]
* ```
*/
acosh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.acosh(memoryResource));
}
/**
* Compute the hyperbolic tangent inverse for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([0, -0.5]).atanh(); // [0, -0.5493061443340549]
* ```
*/
atanh(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.atanh(memoryResource));
}
/**
* Compute the exponential (base e, euler number) for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5]).exp(); // [0.30119421191220214, 12.182493960703473]
* ```
*/
exp(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.exp(memoryResource));
}
/**
* Compute the natural logarithm (base e) for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5, 4]).log(); // [NaN, 0.9162907318741551, 1.3862943611198906]
* ```
*/
log(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.log(memoryResource));
}
/**
* Compute the square-root (x^0.5) for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5, 4]).sqrt(); // [NaN, 1.5811388300841898, 2]
* ```
*/
sqrt(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.sqrt(memoryResource));
}
/**
* Compute the cube-root (x^(1.0/3)) for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5]).cbrt(); // [-1.0626585691826111, 1.3572088082974534]
* ```
*/
cbrt(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.cbrt(memoryResource));
}
/**
* Compute the smallest integer value not less than arg for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5, -3, 4.6, 5]).ceil(); // [-1, 3, -3, 5, 5]
* ```
*/
ceil(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.ceil(memoryResource));
}
/**
* Compute the largest integer value not greater than arg for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1.2, 2.5, -3, 4.6, 5]).floor(); // [-2, 2, -3, 4, 5]
* ```
*/
floor(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.floor(memoryResource));
}
/**
* Compute the absolute value for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* Series.new([-1, 2, -3, 4, 5]).abs(); // [1, 2, 3, 4, 5]
* ```
*/
abs(memoryResource?: MemoryResource): Series<T> {
return Series.new(this._col.abs(memoryResource));
}
/**
* Compute the logical not (!) for each value in this Series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns A Series of the same number of elements containing the result of the operation.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([true, false, true, true, false])
* const b = Series.new([0, 1, 2, 3, 4])
*
* a.not() // [false, true, false, false, true]
* b.not() // [true, false, false, false, false]
*/
not(memoryResource?: MemoryResource): Series<Bool8> {
return Series.new(this._col.not(memoryResource));
}
/**
* Compute the min of all values in this Column.
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns The min of all the values in this Column.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.min() // [1]
*/
min(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.min(memoryResource);
}
/**
* Compute the max of all values in this Column.
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns The max of all the values in this Column.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.max() // 5
*/
max(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.max(memoryResource);
}
/**
* Compute a pair of [min,max] of all values in this Column.
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
* @returns The pair of [min,max] of all the values in this Column.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.minmax() // [1,5]
*/
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.minmax(memoryResource);
}
/**
* Compute the sum of all values in this Series.
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The sum of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.sum() // 20
* ```
*/
sum(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.sum(memoryResource);
}
/**
* Compute the product of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The product of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.product() // 20
* ```
*/
product(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.product(memoryResource);
}
/**
* Compute the sumOfSquares of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The sumOfSquares of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.sumOfSquares() // 44
* ```
*/
sumOfSquares(skipNulls = true, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.sumOfSquares(memoryResource);
}
/**
* Compute the mean of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The mean of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.mean() // 2.4
* ```
*/
mean(skipNulls = true, memoryResource?: MemoryResource) {
if (!skipNulls && this.nullCount > 0) { return NaN; }
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.mean(memoryResource);
}
/**
* Compute the median of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The median of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([5, 4, 1, 1, 1])
*
* a.median() // 1
* ```
*/
median(skipNulls = true, memoryResource?: MemoryResource) {
if (!skipNulls && this.nullCount > 0) { return NaN; }
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.median(memoryResource);
}
/**
* Compute the nunique of all values in this Series.
*
* @param dropna The optional dropna if true drops NA and null values before computing reduction,
* else if dropna is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The number of unqiue values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 2, 3, 4, 4, 5, null, null]);
*
* a.nunique() // 5
* a.nunique(false) // 6
* ```
*/
nunique(dropna = true, memoryResource?: MemoryResource) {
return this.nullCount === this.length ? dropna ? 0 : 1
: this._col.nunique(dropna, memoryResource);
}
/**
* Return unbiased variance of the Series.
* Normalized by N-1 by default. This can be changed using the `ddof` argument
*
* @param skipNulls Exclude NA/null values. If an entire row/column is NA, the result will be NA.
* @param ddof Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
* where N represents the number of elements.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The unbiased variance of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 2, 3, 4, 5, null]);
*
* a.var() // 2.5
* a.var(true, 2) // 3.333333333333332
* a.var(true, 5) // NaN, ddof>=a.length results in NaN
* ```
*/
var(skipNulls = true, ddof = 1, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.var(ddof, memoryResource);
}
/**
* Return Fisher’s unbiased kurtosis of a sample.
* Kurtosis obtained using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized
* by N-1.
*
* @param skipNulls Exclude NA/null values. If an entire row/column is NA, the result will be NA.
* @returns The unbiased kurtosis of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 2, 3, 4]);
*
* a.kurtosis() // -1.1999999999999904
* ```
*/
kurtosis(skipNulls = true) {
if (this.length == 0 || (this.hasNulls && !skipNulls)) { return NaN; }
const data = skipNulls ? this.nansToNulls().dropNulls() : this;
const n = data.length;
if (n < 4) { return NaN; }
const V = data.var(skipNulls, 1); // ddof = 1
if (V == 0) { return 0; }
const mu = data.mean(skipNulls);
const m4 = (data.sub(mu).pow(4).sum(skipNulls)) / (V ** 2);
// This is modeled after the cudf kurtosis implementation, it would be
// nice to be able to point to a reference for this specific formula
const a = (n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3)) * m4;
const b = ((n - 1) ** 2) / ((n - 2) * (n - 3));
return a - 3 * b;
}
/**
* Return unbiased Fisher-Pearson skew of a sample.
*
* @param skipNulls Exclude NA/null values. If an entire row/column is NA, the result will be NA.
* @returns The unbiased skew of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([1, 2, 3, 4, 5, 6, 6]);
*
* a.skew() // -0.288195490292614
* ```
*/
skew(skipNulls = true) {
if (this.length == 0 || (this.hasNulls && !skipNulls)) { return NaN; }
const data = skipNulls ? this.nansToNulls().dropNulls() : this;
const n = data.length;
if (data.length < 3) { return NaN; }
const V = data.var(skipNulls, 0); // ddof = 0
if (V == 0) { return 0; }
const mu = data.mean(skipNulls);
const m3 = (data.sub(mu).pow(3).sum(skipNulls)) / n;
return ((n * (n - 1)) ** 0.5) / (n - 2) * m3 / (V ** (3 / 2));
}
/**
* Return sample standard deviation of the Series.
* Normalized by N-1 by default. This can be changed using the `ddof` argument
*
* @param skipNulls Exclude NA/null values. If an entire row/column is NA, the result will be NA.
* @param ddof Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
* where N represents the number of elements.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The standard deviation of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* const a = Series.new([1, 2, 3, 4, 5]);
*
* //skipNulls=true, ddof=1
* a.std() // 1.5811388300841898
* a.std(true, 2) // 1.8257418583505534
* a.std(true, 5) // NaN, ddof>=a.length results in NaN
* ```
*/
std(skipNulls = true, ddof = 1, memoryResource?: MemoryResource) {
return (skipNulls ? this.nansToNulls().dropNulls() : this)._col.std(ddof, memoryResource);
}
/**
* Return values at the given quantile.
*
* @param q the quantile(s) to compute, 0 <= q <= 1
* @param interpolation This optional parameter specifies the interpolation method to use,
* when the desired quantile lies between two data points i and j.
* Valid values: ’linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns values at the given quantile.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* const a = Series.new([1, 2, 3, 4, 5])
*
* a.quantile(0.3, "linear") // 2.2
* a.quantile(0.3, "lower") // 2
* a.quantile(0.3, "higher") // 3
* a.quantile(0.3, "midpoint") // 2.5
* a.quantile(0.3, "nearest") // 2
* ```
*/
quantile(q = 0.5,
interpolation: keyof typeof Interpolation = 'linear',
memoryResource?: MemoryResource) {
return this.nansToNulls().dropNulls()._col.quantile(
q, Interpolation[interpolation], memoryResource);
}
/**
* Return whether all elements are true in Series.
*
* @param skipNulls bool
* Exclude null values. If the entire row/column is NA and skipNulls is true, then the result will
* be true, as for an empty row/column. If skipNulls is false, then NA are treated as true,
* because these are not equal to zero.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @returns true if all elements are true in Series, else false.
*
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* //boolean series
* Series.new([true, false, true]).all() // false
* Series.new([true, true, true]).all() // true
* ```
*/
all(skipNulls = true, memoryResource?: MemoryResource) {
if (skipNulls) {
if (this.length == this.nullCount) { return true; }
}
return this._col.all(memoryResource);
}
/**
* Return whether any elements are true in Series.
*
* @param skipNulls bool
* Exclude NA/null values. If the entire row/column is NA and skipNulls is true, then the result
* will be true, as for an empty row/column. If skipNulls is false, then NA are treated as true,
* because these are not equal to zero.
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @returns true if any elements are true in Series, else false.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
*
* //boolean series
* Series.new([false, false, false]).any() // false
* Series.new([true, false, true]).any() // true
* ```
*/
any(skipNulls = true, memoryResource?: MemoryResource) {
if (this.length == 0) { return false; }
if (skipNulls) {
if (this.length == this.nullCount) { return false; }
}
return this._col.any(memoryResource);
}
/**
* @summary Scale values to [0, 1] in float64
*
* @param memoryResource The optional MemoryResource used to allocate the result Column's device
* memory.
*
* @returns Series with values scaled between [0, 1].
*/
scale(memoryResource?: MemoryResource): Series<Float64> {
const [min, max] = this.minmax() as [any, any];
return this.sub(min).div(max - min, memoryResource);
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/series/integral.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
Int16Buffer,
Int32Buffer,
Int64Buffer,
Int8Buffer,
Uint16Buffer,
Uint32Buffer,
Uint64Buffer,
Uint8Buffer,
} from '@rapidsai/cuda';
import {MemoryResource} from '@rapidsai/rmm';
import {Column} from '../column';
import {Scalar} from '../scalar';
import {Series} from '../series';
import {
Int16,
Int32,
Int64,
Int8,
Integral,
Uint16,
Uint32,
Uint64,
Uint8,
Utf8String
} from '../types/dtypes';
import {CommonType} from '../types/mappings';
import {Float64Series} from './float';
import {NumericSeries} from './numeric';
import {StringSeries} from './string';
/**
* A base class for Series of 8, 16, 32, or 64-bit integral values in GPU memory.
*/
abstract class IntSeries<T extends Integral> extends NumericSeries<T> {
_castAsString(memoryResource?: MemoryResource): StringSeries {
return StringSeries.new(this._col.stringsFromIntegers(memoryResource));
}
/**
* Returns a new string Series converting integer columns to hexadecimal characters.
*
* Any null entries will result in corresponding null entries in the output series.
*
* The output character set is '0'-'9' and 'A'-'F'. The output string width will be a multiple of
* 2 depending on the size of the integer type. A single leading zero is applied to the first
* non-zero output byte if it less than 0x10.
*
* Leading zeros are suppressed unless filling out a complete byte as in 1234 -> 04D2 instead of
* 000004D2 or 4D2.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series' device
* memory.
*/
toHexString(memoryResource?: MemoryResource): Series<Utf8String> {
return Series.new(this._col.hexFromIntegers(memoryResource));
}
/**
* Perform a binary `&` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
bitwiseAnd(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
bitwiseAnd(rhs: number, memoryResource?: MemoryResource): Float64Series;
bitwiseAnd<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseAnd<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseAnd<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.bitwiseAnd(rhs, memoryResource));
case 'number': return Series.new(this._col.bitwiseAnd(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.bitwiseAnd(rhs, memoryResource))
: Series.new(this._col.bitwiseAnd(rhs._col as Column<R>, memoryResource));
}
/**
* Perform a binary `|` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
bitwiseOr(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
bitwiseOr(rhs: number, memoryResource?: MemoryResource): Float64Series;
bitwiseOr<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseOr<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseOr<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.bitwiseOr(rhs, memoryResource));
case 'number': return Series.new(this._col.bitwiseOr(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.bitwiseOr(rhs, memoryResource))
: Series.new(this._col.bitwiseOr(rhs._col as Column<R>, memoryResource));
}
/**
* Perform a binary `^` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
bitwiseXor(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
bitwiseXor(rhs: number, memoryResource?: MemoryResource): Float64Series;
bitwiseXor<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseXor<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
bitwiseXor<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.bitwiseXor(rhs, memoryResource));
case 'number': return Series.new(this._col.bitwiseXor(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.bitwiseXor(rhs, memoryResource))
: Series.new(this._col.bitwiseXor(rhs._col as Column<R>, memoryResource));
}
/**
* Perform a binary `<<` operation between this Series and another Series or scalar value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
shiftLeft(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
shiftLeft(rhs: number, memoryResource?: MemoryResource): Float64Series;
shiftLeft<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftLeft<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftLeft<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.shiftLeft(rhs, memoryResource));
case 'number': return Series.new(this._col.shiftLeft(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.shiftLeft(rhs, memoryResource))
: Series.new(this._col.shiftLeft(rhs._col as Column<R>, memoryResource));
}
/**
* Perform a binary `>>` operation between this Series and another Series or scalar
* value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
shiftRight(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
shiftRight(rhs: number, memoryResource?: MemoryResource): Float64Series;
shiftRight<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftRight<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftRight<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.shiftRight(rhs, memoryResource));
case 'number': return Series.new(this._col.shiftRight(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.shiftRight(rhs, memoryResource))
: Series.new(this._col.shiftRight(rhs._col as Column<R>, memoryResource));
}
/**
* Perform a binary `shiftRightUnsigned` operation between this Series and another Series or
* scalar value.
*
* @param rhs The other Series or scalar to use.
* @returns A Series of a common numeric type with the results of the binary operation.
*/
shiftRightUnsigned(rhs: bigint, memoryResource?: MemoryResource): Int64Series;
shiftRightUnsigned(rhs: number, memoryResource?: MemoryResource): Float64Series;
shiftRightUnsigned<R extends Scalar<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftRightUnsigned<R extends Series<Integral>>(rhs: R, memoryResource?: MemoryResource):
Series<CommonType<T, R['type']>>;
shiftRightUnsigned<R extends Integral>(rhs: bigint|number|Scalar<R>|Series<R>,
memoryResource?: MemoryResource) {
switch (typeof rhs) {
case 'bigint': return Series.new(this._col.shiftRightUnsigned(rhs, memoryResource));
case 'number': return Series.new(this._col.shiftRightUnsigned(rhs, memoryResource));
default: break;
}
return rhs instanceof Scalar
? Series.new(this._col.shiftRightUnsigned(rhs, memoryResource))
: Series.new(this._col.shiftRightUnsigned(rhs._col as Column<R>, memoryResource));
}
/**
* Compute the bitwise not (~) for each value in this Series.
*
* @param memoryResource Memory resource used to allocate the result Series's device memory.
* @returns A Series of the same number of elements containing the result of the operation.
*/
bitInvert(memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._col.bitInvert(memoryResource));
}
/**
* Compute the cumulative max of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative max of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1]).cast(new Int32)
*
* a.cumulativeMax() // {4, 4, 5, 5, 5}
* ```
*/
cumulativeMax(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMax(memoryResource));
}
/**
* Compute the cumulative min of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative min of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1]).cast(new Int32)
*
* a.cumulativeMin() // {4, 2, 2, 1, 1}
* ```
*/
cumulativeMin(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeMin(memoryResource));
}
/**
* Compute the cumulative product of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative product of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1]).cast(new Int32)
*
* a.cumulativeProduct() // {4, 8, 40, 40, 40}
* ```
*/
cumulativeProduct(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeProduct(memoryResource));
}
/**
* Compute the cumulative sum of all values in this Series.
*
* @param skipNulls The optional skipNulls if true drops NA and null values before computing
* reduction,
* else if skipNulls is false, reduction is computed directly.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns The cumulative sum of all the values in this Series.
* @example
* ```typescript
* import {Series} from '@rapidsai/cudf';
* const a = Series.new([4, 2, 5, 1, 1]).cast(new Int32)
*
* a.cumulativeSum() // {4, 6, 11, 12, 13}
* ```
*/
cumulativeSum(skipNulls = true, memoryResource?: MemoryResource): Series<T> {
return this.__construct(this._prepare_scan_series(skipNulls).cumulativeSum(memoryResource));
}
/** @inheritdoc */
sum(skipNulls = true, memoryResource?: MemoryResource) {
return super.sum(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
product(skipNulls = true, memoryResource?: MemoryResource) {
return super.product(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
sumOfSquares(skipNulls = true, memoryResource?: MemoryResource) {
return super.sumOfSquares(skipNulls, memoryResource) as bigint;
}
}
/**
* A Series of 8-bit signed integer values in GPU memory.
*/
export class Int8Series extends IntSeries<Int8> {
/**
* A Int8 view of the values in GPU memory.
*/
get data() {
return new Int8Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 16-bit signed integer values in GPU memory.
*/
export class Int16Series extends IntSeries<Int16> {
/**
* A Int16 view of the values in GPU memory.
*/
get data() {
return new Int16Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 32-bit signed integer values in GPU memory.
*/
export class Int32Series extends IntSeries<Int32> {
/**
* A Int32 view of the values in GPU memory.
*/
get data() {
return new Int32Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 64-bit signed integer values in GPU memory.
*/
export class Int64Series extends IntSeries<Int64> {
* [Symbol.iterator]() {
for (const x of super[Symbol.iterator]()) { yield x === null ? x : 0n + x; }
}
/**
* A Int64 view of the values in GPU memory.
*/
get data() {
return new Int64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/**
* Converts integers into IPv4 addresses as strings.
*
* The IPv4 format is 1-3 character digits [0-9] between 3 dots (e.g. 123.45.67.890). Each section
* can have a value between [0-255].
*
* Each input integer is dissected into four integers by dividing the input into 8-bit sections.
* These sub-integers are then converted into [0-9] characters and placed between '.' characters.
*
* No checking is done on the input integer value. Only the lower 32-bits are used.
*
* Any null entries will result in corresponding null entries in the output series.
*
* @param memoryResource The optional MemoryResource used to allocate the result Series' device
* memory.
*/
toIpv4String(memoryResource?: MemoryResource): Series<Utf8String> {
return Series.new(this._col.ipv4FromIntegers(memoryResource));
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [bigint, bigint];
}
}
/**
* A Series of 8-bit unsigned integer values in GPU memory.
*/
export class Uint8Series extends IntSeries<Uint8> {
/**
* A Uint8 view of the values in GPU memory.
*/
get data() {
return new Uint8Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 16-bit unsigned integer values in GPU memory.
*/
export class Uint16Series extends IntSeries<Uint16> {
/**
* A Uint16 view of the values in GPU memory.
*/
get data() {
return new Uint16Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 32-bit unsigned integer values in GPU memory.
*/
export class Uint32Series extends IntSeries<Uint32> {
/**
* A Uint32 view of the values in GPU memory.
*/
get data() {
return new Uint32Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as number;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [number, number];
}
}
/**
* A Series of 64-bit unsigned integer values in GPU memory.
*/
export class Uint64Series extends IntSeries<Uint64> {
* [Symbol.iterator]() {
for (const x of super[Symbol.iterator]()) { yield x === null ? x : 0n + x; }
}
/**
* A Uint64 view of the values in GPU memory.
*/
get data() {
return new Uint64Buffer(this._col.data).subarray(this.offset, this.offset + this.length);
}
/** @inheritdoc */
min(skipNulls = true, memoryResource?: MemoryResource) {
return super.min(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
max(skipNulls = true, memoryResource?: MemoryResource) {
return super.max(skipNulls, memoryResource) as bigint;
}
/** @inheritdoc */
minmax(skipNulls = true, memoryResource?: MemoryResource) {
return super.minmax(skipNulls, memoryResource) as [bigint, bigint];
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/reduction.cpp
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/scalar.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <nv_node/utilities/args.hpp>
#include <nv_node/utilities/napi_to_cpp.hpp>
#include <cudf/aggregation.hpp>
#include <cudf/reduction.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <memory>
#include <string>
namespace nv {
namespace {
cudf::data_type _compute_dtype(cudf::type_id id) {
switch (id) {
case cudf::type_id::INT8:
case cudf::type_id::INT16:
case cudf::type_id::INT32:
case cudf::type_id::INT64: return cudf::data_type{cudf::type_id::INT64};
case cudf::type_id::UINT8:
case cudf::type_id::UINT16:
case cudf::type_id::UINT32:
case cudf::type_id::UINT64: return cudf::data_type{cudf::type_id::UINT64};
default: return cudf::data_type{cudf::type_id::FLOAT64};
}
}
} // namespace
std::pair<Scalar::wrapper_t, Scalar::wrapper_t> Column::minmax(
rmm::mr::device_memory_resource* mr) const {
try {
auto result = cudf::minmax(*this, mr);
return {Scalar::New(Env(), std::move(result.first)), //
Scalar::New(Env(), std::move(result.second))};
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::min(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), minmax(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()).first);
}
Napi::Value Column::max(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), minmax(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()).second);
}
Napi::Value Column::minmax(Napi::CallbackInfo const& info) {
return Napi::Value::From(info.Env(),
minmax(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Scalar::wrapper_t Column::reduce(std::unique_ptr<cudf::reduce_aggregation> const& agg,
cudf::data_type const& output_dtype,
rmm::mr::device_memory_resource* mr) const {
try {
return Scalar::New(Env(), cudf::reduce(*this, *agg, output_dtype, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::scan(std::unique_ptr<cudf::scan_aggregation> const& agg,
cudf::scan_type inclusive,
cudf::null_policy null_handling,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::scan(*this, *agg, inclusive, null_handling, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Scalar::wrapper_t Column::sum(rmm::mr::device_memory_resource* mr) const {
return reduce(
cudf::make_sum_aggregation<cudf::reduce_aggregation>(), _compute_dtype(this->type().id()), mr);
}
Napi::Value Column::sum(Napi::CallbackInfo const& info) {
return Napi::Value::From(info.Env(),
sum(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Scalar::wrapper_t Column::product(rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_product_aggregation<cudf::reduce_aggregation>(),
_compute_dtype(this->type().id()),
mr);
}
Napi::Value Column::product(Napi::CallbackInfo const& info) {
return Napi::Value::From(info.Env(),
product(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Scalar::wrapper_t Column::sum_of_squares(rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_sum_of_squares_aggregation<cudf::reduce_aggregation>(),
_compute_dtype(this->type().id()),
mr);
}
Napi::Value Column::sum_of_squares(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), sum_of_squares(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Napi::Value Column::any(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(),
reduce(cudf::make_any_aggregation<cudf::reduce_aggregation>(),
cudf::data_type(cudf::type_id::BOOL8),
args[0]));
}
Napi::Value Column::all(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(),
reduce(cudf::make_all_aggregation<cudf::reduce_aggregation>(),
cudf::data_type(cudf::type_id::BOOL8),
args[0]));
}
Scalar::wrapper_t Column::mean(rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_mean_aggregation<cudf::reduce_aggregation>(),
cudf::data_type(cudf::type_id::FLOAT64),
mr);
}
Napi::Value Column::mean(Napi::CallbackInfo const& info) {
return Napi::Value::From(info.Env(),
mean(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Scalar::wrapper_t Column::median(rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_median_aggregation<cudf::reduce_aggregation>(),
cudf::data_type(cudf::type_id::FLOAT64),
mr);
}
Napi::Value Column::median(Napi::CallbackInfo const& info) {
return Napi::Value::From(info.Env(),
median(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Scalar::wrapper_t Column::nunique(bool dropna, rmm::mr::device_memory_resource* mr) const {
cudf::null_policy null_policy =
(dropna == true) ? cudf::null_policy::EXCLUDE : cudf::null_policy::INCLUDE;
return reduce(cudf::make_nunique_aggregation<cudf::reduce_aggregation>(null_policy),
cudf::data_type{cudf::type_to_id<cudf::size_type>()},
mr);
}
Napi::Value Column::nunique(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(), nunique(args[0], args[1]));
}
Scalar::wrapper_t Column::variance(cudf::size_type ddof,
rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_variance_aggregation<cudf::reduce_aggregation>(ddof),
cudf::data_type(cudf::type_id::FLOAT64),
mr);
}
Napi::Value Column::variance(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(), variance(args[0], args[1]));
}
Scalar::wrapper_t Column::std(cudf::size_type ddof, rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_std_aggregation<cudf::reduce_aggregation>(ddof),
cudf::data_type(cudf::type_id::FLOAT64),
mr);
}
Napi::Value Column::std(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(), std(args[0], args[1]));
}
Scalar::wrapper_t Column::quantile(double q,
cudf::interpolation i,
rmm::mr::device_memory_resource* mr) const {
return reduce(cudf::make_quantile_aggregation<cudf::reduce_aggregation>({q}, i),
cudf::data_type(cudf::type_id::FLOAT64),
mr);
}
Napi::Value Column::quantile(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Napi::Value::From(info.Env(), quantile(args[0], args[1], args[2]));
}
Column::wrapper_t Column::cumulative_max(rmm::mr::device_memory_resource* mr) const {
return scan(cudf::make_max_aggregation<cudf::scan_aggregation>(),
// following cudf, scan type and null policy always use these values
cudf::scan_type::INCLUSIVE,
cudf::null_policy::EXCLUDE,
mr);
}
Napi::Value Column::cumulative_max(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), cumulative_max(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Column::wrapper_t Column::cumulative_min(rmm::mr::device_memory_resource* mr) const {
return scan(cudf::make_min_aggregation<cudf::scan_aggregation>(),
// following cudf, scan type and null policy always use these values
cudf::scan_type::INCLUSIVE,
cudf::null_policy::EXCLUDE,
mr);
}
Napi::Value Column::cumulative_min(Napi::CallbackInfo const& info) {
return cumulative_min(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*())->Value();
}
Column::wrapper_t Column::cumulative_product(rmm::mr::device_memory_resource* mr) const {
return scan(cudf::make_product_aggregation<cudf::scan_aggregation>(),
// following cudf, scan type and null policy always use these values
cudf::scan_type::INCLUSIVE,
cudf::null_policy::EXCLUDE,
mr);
}
Napi::Value Column::cumulative_product(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), cumulative_product(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
Column::wrapper_t Column::cumulative_sum(rmm::mr::device_memory_resource* mr) const {
return scan(cudf::make_sum_aggregation<cudf::scan_aggregation>(),
// following cudf, scan type and null policy always use these values
cudf::scan_type::INCLUSIVE,
cudf::null_policy::EXCLUDE,
mr);
}
Napi::Value Column::cumulative_sum(Napi::CallbackInfo const& info) {
return Napi::Value::From(
info.Env(), cumulative_sum(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*()));
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/convert.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/convert/convert_booleans.hpp>
#include <cudf/strings/convert/convert_datetime.hpp>
#include <cudf/strings/convert/convert_floats.hpp>
#include <cudf/strings/convert/convert_integers.hpp>
#include <cudf/strings/convert/convert_ipv4.hpp>
#include <cudf/strings/convert/convert_lists.hpp>
#include <cudf/unary.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
namespace {
Column::wrapper_t lists_to_strings(
Napi::Env const& env,
cudf::lists_column_view const& input,
std::string const& na_rep,
cudf::strings_column_view const& separators,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
try {
return Column::New(
env, cudf::strings::format_list_column(input, cudf::string_scalar(na_rep), separators, mr));
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
} // namespace
Column::wrapper_t Column::strings_from_booleans(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
cudf::strings::from_booleans(
this->view(), cudf::string_scalar("true"), cudf::string_scalar("false"), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::strings_to_booleans(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(),
cudf::strings::to_booleans(this->view(), cudf::string_scalar("true"), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::string_is_timestamp(std::string_view format,
rmm::mr::device_memory_resource* mr) const {
return Column::New(Env(), cudf::strings::is_timestamp(this->view(), format, mr));
}
Column::wrapper_t Column::strings_from_timestamps(std::string_view format,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
cudf::strings::from_timestamps(this->view(),
format,
cudf::strings_column_view(cudf::column_view{
cudf::data_type{cudf::type_id::STRING}, 0, nullptr}),
mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::strings_to_timestamps(cudf::data_type timestamp_type,
std::string_view format,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(),
cudf::strings::to_timestamps(this->view(), timestamp_type, format, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::string_is_float(rmm::mr::device_memory_resource* mr) const {
return Column::New(Env(), cudf::strings::is_float(this->view(), mr));
}
Column::wrapper_t Column::strings_from_floats(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::from_floats(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::strings_to_floats(cudf::data_type out_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::to_floats(this->view(), out_type, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::string_is_integer(rmm::mr::device_memory_resource* mr) const {
return Column::New(Env(), cudf::strings::is_integer(this->view(), mr));
}
Column::wrapper_t Column::strings_from_integers(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::from_integers(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::strings_to_integers(cudf::data_type out_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::to_integers(this->view(), out_type, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::string_is_hex(rmm::mr::device_memory_resource* mr) const {
return Column::New(Env(), cudf::strings::is_hex(this->view(), mr));
}
Column::wrapper_t Column::hex_from_integers(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::integers_to_hex(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::hex_to_integers(cudf::data_type out_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::hex_to_integers(this->view(), out_type, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::string_is_ipv4(rmm::mr::device_memory_resource* mr) const {
return Column::New(Env(), cudf::strings::is_ipv4(this->view(), mr));
}
Column::wrapper_t Column::ipv4_from_integers(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::integers_to_ipv4(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::ipv4_to_integers(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::ipv4_to_integers(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::strings_from_lists(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string const na_rep = args[0];
Column::wrapper_t const separators = args[1];
rmm::mr::device_memory_resource* mr = args[2];
return nv::lists_to_strings(info.Env(), view(), na_rep, separators->view(), mr);
}
Napi::Value Column::strings_from_booleans(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return strings_from_booleans(mr);
}
Napi::Value Column::strings_to_booleans(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return strings_to_booleans(mr);
}
Napi::Value Column::string_is_timestamp(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string format = args[0];
return string_is_timestamp(format, args[1]);
}
Napi::Value Column::strings_from_timestamps(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string format = args[0];
return strings_from_timestamps(format, args[1]);
}
Napi::Value Column::strings_to_timestamps(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string format = args[1];
return strings_to_timestamps(args[0], format, args[2]);
}
Napi::Value Column::string_is_float(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return string_is_float(mr);
}
Napi::Value Column::strings_from_floats(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return strings_from_floats(mr);
}
Napi::Value Column::strings_to_floats(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column to_float expects an output type and optional MemoryResource",
info.Env());
}
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[1];
return strings_to_floats(args[0], mr);
}
Napi::Value Column::string_is_integer(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return string_is_integer(mr);
}
Napi::Value Column::strings_from_integers(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return strings_from_integers(mr);
}
Napi::Value Column::strings_to_integers(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column to_integers expects an output type and optional MemoryResource",
info.Env());
}
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[1];
return strings_to_integers(args[0], mr);
}
Napi::Value Column::string_is_hex(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return string_is_hex(mr);
}
Napi::Value Column::hex_from_integers(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return hex_from_integers(mr);
}
Napi::Value Column::hex_to_integers(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column hex_to_integers expects an output type and optional MemoryResource",
info.Env());
}
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[1];
return hex_to_integers(args[0], mr);
}
Napi::Value Column::string_is_ipv4(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return string_is_ipv4(mr);
}
Napi::Value Column::ipv4_from_integers(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return ipv4_from_integers(mr);
}
Napi::Value Column::ipv4_to_integers(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
rmm::mr::device_memory_resource* mr = args[0];
return ipv4_to_integers(mr);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/json.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_cudf/column.hpp>
#include <node_cudf/scalar.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/strings/json.hpp>
namespace nv {
Column::wrapper_t Column::get_json_object(std::string const& json_path,
cudf::strings::get_json_object_options const& opts,
rmm::mr::device_memory_resource* mr) {
try {
auto obj = cudf::strings::get_json_object(view(), json_path, opts, mr);
auto null_count = cudf::detail::count_unset_bits(
obj->view().null_mask(), 0, obj->size(), rmm::cuda_stream_default);
obj->set_null_count(null_count);
return Column::New(Env(), std::move(obj));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::get_json_object(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return get_json_object(args[0], args[1], args[2]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/copying.cpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <cudf/copying.hpp>
#include <cudf/table/table_view.hpp>
#include <memory>
namespace nv {
Column::wrapper_t Column::gather(Column const& gather_map,
cudf::out_of_bounds_policy bounds_policy,
rmm::mr::device_memory_resource* mr) const {
return Column::New(
Env(),
std::move(
cudf::gather(cudf::table_view{{*this}}, gather_map, bounds_policy, mr)->release()[0]));
}
Napi::Value Column::copy(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return Column::New(
args.Env(), std::make_unique<cudf::column>(this->view(), rmm::cuda_stream_default, args[0]));
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/unaryop.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/unary.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::cast(cudf::data_type out_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::cast(*this, out_type, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::is_null(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::is_null(*this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::is_valid(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::is_valid(*this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::is_nan(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::is_nan(*this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::is_not_nan(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::is_not_nan(*this, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::unary_operation(cudf::unary_operator op,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::unary_operation(*this, op, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::cast(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column cast expects a DataType and optional MemoryResource", info.Env());
}
return cast(NapiToCPP{info[0]}, NapiToCPP(info[1]));
}
Napi::Value Column::is_null(Napi::CallbackInfo const& info) {
return is_null(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Napi::Value Column::is_valid(Napi::CallbackInfo const& info) {
return is_valid(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Napi::Value Column::is_nan(Napi::CallbackInfo const& info) {
return is_nan(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Napi::Value Column::is_not_nan(Napi::CallbackInfo const& info) {
return is_not_nan(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Napi::Value Column::sin(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::SIN, NapiToCPP(info[0]));
}
Napi::Value Column::cos(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::COS, NapiToCPP(info[0]));
}
Napi::Value Column::tan(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::TAN, NapiToCPP(info[0]));
}
Napi::Value Column::arcsin(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCSIN, NapiToCPP(info[0]));
}
Napi::Value Column::arccos(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCCOS, NapiToCPP(info[0]));
}
Napi::Value Column::arctan(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCTAN, NapiToCPP(info[0]));
}
Napi::Value Column::sinh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::SINH, NapiToCPP(info[0]));
}
Napi::Value Column::cosh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::COSH, NapiToCPP(info[0]));
}
Napi::Value Column::tanh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::TANH, NapiToCPP(info[0]));
}
Napi::Value Column::arcsinh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCSINH, NapiToCPP(info[0]));
}
Napi::Value Column::arccosh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCCOSH, NapiToCPP(info[0]));
}
Napi::Value Column::arctanh(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ARCTANH, NapiToCPP(info[0]));
}
Napi::Value Column::exp(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::EXP, NapiToCPP(info[0]));
}
Napi::Value Column::log(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::LOG, NapiToCPP(info[0]));
}
Napi::Value Column::sqrt(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::SQRT, NapiToCPP(info[0]));
}
Napi::Value Column::cbrt(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::CBRT, NapiToCPP(info[0]));
}
Napi::Value Column::ceil(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::CEIL, NapiToCPP(info[0]));
}
Napi::Value Column::floor(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::FLOOR, NapiToCPP(info[0]));
}
Napi::Value Column::abs(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::ABS, NapiToCPP(info[0]));
}
Napi::Value Column::rint(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::RINT, NapiToCPP(info[0]));
}
Napi::Value Column::bit_invert(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::BIT_INVERT, NapiToCPP(info[0]));
}
Napi::Value Column::unary_not(Napi::CallbackInfo const& info) {
return unary_operation(cudf::unary_operator::NOT, NapiToCPP(info[0]));
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/concatenate.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cudf/concatenate.hpp>
#include <node_cudf/column.hpp>
namespace nv {
Column::wrapper_t Column::concat(cudf::column_view const& other,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::concatenate(std::vector{this->view(), other}, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::concat(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
return concat(*Column::Unwrap(args[0]), args[1]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/filling.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/scalar.hpp>
#include <node_rmm/device_buffer.hpp>
#include <cudf/column/column.hpp>
#include <cudf/filling.hpp>
#include <cudf/types.hpp>
#include <rmm/device_buffer.hpp>
#include <napi.h>
namespace nv {
Column::wrapper_t Column::fill(cudf::size_type begin,
cudf::size_type end,
cudf::scalar const& value,
rmm::mr::device_memory_resource* mr) {
return Column::New(Env(), cudf::fill(*this, begin, end, value, mr));
}
Napi::Value Column::fill(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
auto scalar = Scalar::Unwrap(args[0].ToObject());
cudf::size_type begin = args.Length() > 1 ? args[1] : 0;
cudf::size_type end = args.Length() > 2 ? args[2] : size();
try {
return fill(begin, end, *scalar, args[3]);
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
}
void Column::fill_in_place(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
Scalar::wrapper_t scalar = args[0].ToObject();
cudf::size_type begin = args.Length() > 1 ? args[1] : 0;
cudf::size_type end = args.Length() > 2 ? args[2] : size();
try {
cudf::mutable_column_view view = *this;
cudf::fill_in_place(view, begin, end, scalar->operator cudf::scalar&());
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
}
Column::wrapper_t Column::sequence(Napi::Env const& env,
cudf::size_type size,
cudf::scalar const& init,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(env, cudf::sequence(size, init, mr));
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
Column::wrapper_t Column::sequence(Napi::Env const& env,
cudf::size_type size,
cudf::scalar const& init,
cudf::scalar const& step,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(env, cudf::sequence(size, init, step, mr));
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
Napi::Value Column::sequence(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 3 and args.Length() != 4) {
NAPI_THROW(Napi::Error::New(
info.Env(), "sequence expects a size, init, and optionally a step and/or memory resource"));
}
if (!args[0].IsNumber()) {
throw Napi::Error::New(info.Env(), "sequence size argument expects a number");
}
cudf::size_type size = args[0];
if (!Scalar::IsInstance(args[1])) {
throw Napi::Error::New(info.Env(), "sequence init argument expects a scalar");
}
Scalar::wrapper_t init = args[1].As<Napi::Object>();
if (args.Length() == 3) {
rmm::mr::device_memory_resource* mr = args[2];
return Column::sequence(info.Env(), size, init, mr);
} else {
if (!Scalar::IsInstance(args[2])) {
throw Napi::Error::New(info.Env(), "sequence step argument expects a scalar");
}
Scalar::wrapper_t step = args[2].As<Napi::Object>();
rmm::mr::device_memory_resource* mr = args[3];
return Column::sequence(info.Env(), size, init, step, mr);
}
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/from_arrow.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as arrow from 'apache-arrow';
import {Column} from '../column';
import {Table} from '../table';
import {
Bool8,
Categorical,
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
List,
Struct,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
Uint16,
Uint32,
Uint64,
Uint8,
Utf8String,
} from '../types/dtypes';
import {ArrowToCUDFType} from '../types/mappings';
/** @ignore */
interface DataToColumnVisitor extends arrow.Visitor {
visit<T extends arrow.DataType>(node: arrow.Data<T>): Column<ArrowToCUDFType<T>>;
visitMany<T extends arrow.DataType>(nodes: readonly arrow.Data<T>[]):
Column<ArrowToCUDFType<T>>[];
getVisitFn<T extends arrow.DataType>(node: arrow.Data<T>): () => Column<ArrowToCUDFType<T>>;
}
class DataToColumnVisitor extends arrow.Visitor {
// visitNull<T extends arrow.Null>(data: arrow.Data<T>) {}
visitBool<T extends arrow.Bool>(data: arrow.Data<T>) {
const {values, nullBitmap: nullMask} = data;
return new Column({
type: new Bool8,
data:
// eslint-disable-next-line @typescript-eslint/unbound-method
new Uint8Array(new arrow.util.BitIterator(values, 0, data.length, null, arrow.util.getBit)),
nullMask
});
}
visitInt8<T extends arrow.Int8>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Int8, length, data: data.subarray(0, length), nullMask});
}
visitInt16<T extends arrow.Int16>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Int16, length, data: data.subarray(0, length), nullMask});
}
visitInt32<T extends arrow.Int32>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Int32, length, data: data.subarray(0, length), nullMask});
}
visitInt64<T extends arrow.Int64>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Int64, length, data: data.subarray(0, length * 2), nullMask});
}
visitUint8<T extends arrow.Uint8>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Uint8, length, data: data.subarray(0, length), nullMask});
}
visitUint16<T extends arrow.Uint16>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Uint16, length, data: data.subarray(0, length), nullMask});
}
visitUint32<T extends arrow.Uint32>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Uint32, length, data: data.subarray(0, length), nullMask});
}
visitUint64<T extends arrow.Uint64>({length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column({type: new Uint64, length, data: data.subarray(0, length * 2), nullMask});
}
// visitFloat16<T extends arrow.Float16>(data: arrow.Data<T>) {}
visitFloat32<T extends arrow.Float32>({length, values: data, nullBitmap: nullMask}:
arrow.Data<T>) {
return new Column({type: new Float32, length, data: data.subarray(0, length), nullMask});
}
visitFloat64<T extends arrow.Float64>({length, values: data, nullBitmap: nullMask}:
arrow.Data<T>) {
return new Column({type: new Float64, length, data: data.subarray(0, length), nullMask});
}
visitUtf8<T extends arrow.Utf8>({length, values, valueOffsets, nullBitmap: nullMask}:
arrow.Data<T>) {
return new Column({
length,
type: new Utf8String,
nullMask,
children: [
// offsets
new Column(
{type: new Int32, length: length + 1, data: valueOffsets.subarray(0, length + 1)}),
// data
new Column({
type: new Uint8,
length: valueOffsets[length],
data: values.subarray(0, valueOffsets[length])
}),
]
});
}
// visitBinary<T extends arrow.Binary>(data: arrow.Data<T>) {}
// visitFixedSizeBinary<T extends arrow.FixedSizeBinary>(data: arrow.Data<T>) {}
// visitDate<T extends arrow.Date_>(data: arrow.Data<T>) {}
visitDateDay<T extends arrow.DateDay>({length, values: data, nullBitmap: nullMask}:
arrow.Data<T>) {
return new Column({type: new TimestampDay, length, data: data.subarray(0, length), nullMask});
}
visitDateMillisecond<T extends arrow.DateMillisecond>(
{length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column(
{type: new TimestampMillisecond, length, data: data.subarray(0, length), nullMask});
}
visitTimestampSecond<T extends arrow.TimestampSecond>(
{length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column(
{type: new TimestampSecond, length, data: data.subarray(0, length * 2), nullMask});
}
visitTimestampMillisecond<T extends arrow.TimestampMillisecond>(
{length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column(
{type: new TimestampMillisecond, length, data: data.subarray(0, length * 2), nullMask});
}
visitTimestampMicrosecond<T extends arrow.TimestampMicrosecond>(
{length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column(
{type: new TimestampMicrosecond, length, data: data.subarray(0, length * 2), nullMask});
}
visitTimestampNanosecond<T extends arrow.TimestampNanosecond>(
{length, values: data, nullBitmap: nullMask}: arrow.Data<T>) {
return new Column(
{type: new TimestampNanosecond, length, data: data.subarray(0, length * 2), nullMask});
}
// visitTimeSecond<T extends arrow.TimeSecond>(data: arrow.Data<T>) {}
// visitTimeMillisecond<T extends arrow.TimeMillisecond>(data: arrow.Data<T>) {}
// visitTimeMicrosecond<T extends arrow.TimeMicrosecond>(data: arrow.Data<T>) {}
// visitTimeNanosecond<T extends arrow.TimeNanosecond>(data: arrow.Data<T>) {}
// visitDecimal<T extends arrow.Decimal>(data: arrow.Data<T>) {}
visitList<T extends arrow.List>(data: arrow.Data<T>) {
const {type, length, valueOffsets, nullBitmap: nullMask} = data;
const offsets =
new Column({type: new Int32, length: length + 1, data: valueOffsets.subarray(0, length + 1)});
const elements = this.visit(data.children[0] as arrow.Data<T['valueType']>);
return new Column({
length,
type: new List(type.children[0].clone({type: elements.type, nullable: elements.nullable})),
nullMask,
children: [
offsets,
elements,
]
});
}
visitStruct<T extends arrow.Struct>(data: arrow.Data<T>) {
const {type, length, nullBitmap: nullMask} = data;
const children = type.children.map((_, i) => this.visit(data.children[i]));
return new Column({
length,
type: new Struct(children.map(
(child, i) => type.children[i].clone({type: child.type, nullable: child.nullable}))),
nullMask,
children,
});
}
// visitDenseUnion<T extends arrow.DenseUnion>(data: arrow.Data<T>) {}
// visitSparseUnion<T extends arrow.SparseUnion>(data: arrow.Data<T>) {}
visitDictionary<T extends arrow.Dictionary>(data: arrow.Data<T>) {
const {type, length, nullBitmap: nullMask} = data;
const codes = this.visit(data.clone(type.indices)).cast(new Uint32);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const categories = fromArrow(data.dictionary!);
return new Column(
{length, type: new Categorical(categories.type), nullMask, children: [codes, categories]});
}
// visitIntervalDayTime<T extends arrow.IntervalDayTime>(data: arrow.Data<T>) {}
// visitIntervalYearMonth<T extends arrow.IntervalYearMonth>(data: arrow.Data<T>) {}
// visitFixedSizeList<T extends arrow.FixedSizeList>(data: arrow.Data<T>) {}
// visitMap<T extends arrow.Map_>(data: arrow.Data<T>) {}
}
const visitor = new DataToColumnVisitor();
export function fromArrow<T extends arrow.DataType>(vector: arrow.Vector<T>):
Column<ArrowToCUDFType<T>> {
const cols = visitor.visitMany(vector.data);
if (cols.length === 1) { return cols[0]; }
return Table.concat(cols.map((col) => new Table({columns: [col]}))).getColumnByIndex(0);
// return visitor.visit(vector);
}
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/replace.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/scalar.hpp>
#include <cudf/filling.hpp>
#include <cudf/replace.hpp>
namespace nv {
Column::wrapper_t Column::replace_nulls(cudf::column_view const& replacement,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::replace_nulls(*this, replacement, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::replace_nulls(cudf::scalar const& replacement,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::replace_nulls(*this, replacement, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::replace_nulls(cudf::replace_policy const& replace_policy,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::replace_nulls(*this, replace_policy, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::replace_nans(cudf::column_view const& replacement,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::replace_nans(*this, replacement, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::replace_nans(cudf::scalar const& replacement,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(Env(), cudf::replace_nans(*this, replacement, mr));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::replace_nulls(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
try {
if (Column::IsInstance(info[0])) { return replace_nulls(*Column::Unwrap(args[0]), args[1]); }
if (Scalar::IsInstance(info[0])) { return replace_nulls(*Scalar::Unwrap(args[0]), args[1]); }
if (args[0].IsBoolean()) {
cudf::replace_policy policy{static_cast<bool>(args[0])};
return replace_nulls(policy, args[1]);
}
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
throw Napi::Error::New(info.Env(), "replace_nulls requires a Column, Scalar, or Boolean");
}
Napi::Value Column::replace_nans(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
try {
if (Column::IsInstance(info[0])) { return replace_nans(*Column::Unwrap(args[0]), args[1]); }
if (Scalar::IsInstance(info[0])) { return replace_nans(*Scalar::Unwrap(args[0]), args[1]); }
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
throw Napi::Error::New(info.Env(), "replace_nans requires a Column or Scalar");
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/stream_compaction.cpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/device_buffer.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <rmm/device_buffer.hpp>
#include <napi.h>
#include <memory>
#include <utility>
namespace nv {
Column::wrapper_t Column::apply_boolean_mask(Column const& boolean_mask,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
std::move(
cudf::apply_boolean_mask(cudf::table_view{{*this}}, boolean_mask, mr)->release()[0]));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Column::wrapper_t Column::drop_nulls(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(), std::move(cudf::drop_nulls(cudf::table_view{{*this}}, {0}, mr)->release()[0]));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::drop_nulls(Napi::CallbackInfo const& info) {
return drop_nulls(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Column::wrapper_t Column::drop_nans(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(), std::move(cudf::drop_nans(cudf::table_view{{*this}}, {0}, mr)->release()[0]));
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::drop_nans(Napi::CallbackInfo const& info) {
return drop_nans(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/binaryop.cpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/binaryop.hpp>
#include <cudf/scalar/scalar_factories.hpp>
namespace nv {
namespace {
Column::wrapper_t auto_binary_operation(
Column const& lhs,
Column const& rhs,
cudf::binary_operator op,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
return lhs.binary_operation(rhs, op, get_common_type(lhs.type(), rhs.type()), mr);
}
Column::wrapper_t auto_binary_operation(
Column const& lhs,
Scalar const& rhs,
cudf::binary_operator op,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()) {
return lhs.binary_operation(rhs, op, get_common_type(lhs.type(), rhs.type()), mr);
}
} // namespace
Column::wrapper_t Column::binary_operation(Column const& rhs,
cudf::binary_operator op,
cudf::type_id output_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(rhs.Env(),
cudf::binary_operation(*this, rhs, op, cudf::data_type{output_type}, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::binary_operation(Scalar const& rhs,
cudf::binary_operator op,
cudf::type_id output_type,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(rhs.Env(),
cudf::binary_operation(*this, rhs, op, cudf::data_type{output_type}, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::operator+(Column const& other) const { return add(other); }
Column::wrapper_t Column::operator+(Scalar const& other) const { return add(other); }
Column::wrapper_t Column::add(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::ADD, mr);
}
Column::wrapper_t Column::add(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::ADD, mr);
}
Column::wrapper_t Column::operator-(Column const& other) const { return sub(other); }
Column::wrapper_t Column::operator-(Scalar const& other) const { return sub(other); }
Column::wrapper_t Column::sub(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SUB, mr);
}
Column::wrapper_t Column::sub(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SUB, mr);
}
Column::wrapper_t Column::operator*(Column const& other) const { return mul(other); }
Column::wrapper_t Column::operator*(Scalar const& other) const { return mul(other); }
Column::wrapper_t Column::mul(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::MUL, mr);
}
Column::wrapper_t Column::mul(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::MUL, mr);
}
Column::wrapper_t Column::operator/(Column const& other) const { return div(other); }
Column::wrapper_t Column::operator/(Scalar const& other) const { return div(other); }
Column::wrapper_t Column::div(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::DIV, mr);
}
Column::wrapper_t Column::div(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::DIV, mr);
}
Column::wrapper_t Column::true_div(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::TRUE_DIV, mr);
}
Column::wrapper_t Column::true_div(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::TRUE_DIV, mr);
}
Column::wrapper_t Column::floor_div(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::FLOOR_DIV, mr);
}
Column::wrapper_t Column::floor_div(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::FLOOR_DIV, mr);
}
Column::wrapper_t Column::operator%(Column const& other) const { return mod(other); }
Column::wrapper_t Column::operator%(Scalar const& other) const { return mod(other); }
Column::wrapper_t Column::mod(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::MOD, mr);
}
Column::wrapper_t Column::mod(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::MOD, mr);
}
Column::wrapper_t Column::pow(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::POW, mr);
}
Column::wrapper_t Column::pow(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::POW, mr);
}
Column::wrapper_t Column::operator==(Column const& other) const { return eq(other); }
Column::wrapper_t Column::operator==(Scalar const& other) const { return eq(other); }
Column::wrapper_t Column::eq(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::eq(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator!=(Column const& other) const { return ne(other); }
Column::wrapper_t Column::operator!=(Scalar const& other) const { return ne(other); }
Column::wrapper_t Column::ne(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::NOT_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::ne(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::NOT_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator<(Column const& other) const { return lt(other); }
Column::wrapper_t Column::operator<(Scalar const& other) const { return lt(other); }
Column::wrapper_t Column::lt(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::LESS, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::lt(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::LESS, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator<=(Column const& other) const { return le(other); }
Column::wrapper_t Column::operator<=(Scalar const& other) const { return le(other); }
Column::wrapper_t Column::le(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::LESS_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::le(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::LESS_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator>(Column const& other) const { return gt(other); }
Column::wrapper_t Column::operator>(Scalar const& other) const { return gt(other); }
Column::wrapper_t Column::gt(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::GREATER, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::gt(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(other, cudf::binary_operator::GREATER, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator>=(Column const& other) const { return ge(other); }
Column::wrapper_t Column::operator>=(Scalar const& other) const { return ge(other); }
Column::wrapper_t Column::ge(Column const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(
other, cudf::binary_operator::GREATER_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::ge(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(
other, cudf::binary_operator::GREATER_EQUAL, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator&(Column const& other) const { return bitwise_and(other); }
Column::wrapper_t Column::operator&(Scalar const& other) const { return bitwise_and(other); }
Column::wrapper_t Column::bitwise_and(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_AND, mr);
}
Column::wrapper_t Column::bitwise_and(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_AND, mr);
}
Column::wrapper_t Column::operator|(Column const& other) const { return bitwise_or(other); }
Column::wrapper_t Column::operator|(Scalar const& other) const { return bitwise_or(other); }
Column::wrapper_t Column::bitwise_or(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_OR, mr);
}
Column::wrapper_t Column::bitwise_or(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_OR, mr);
}
Column::wrapper_t Column::operator^(Column const& other) const { return bitwise_xor(other); }
Column::wrapper_t Column::operator^(Scalar const& other) const { return bitwise_xor(other); }
Column::wrapper_t Column::bitwise_xor(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_XOR, mr);
}
Column::wrapper_t Column::bitwise_xor(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::BITWISE_XOR, mr);
}
Column::wrapper_t Column::operator&&(Column const& other) const { return logical_and(other); }
Column::wrapper_t Column::operator&&(Scalar const& other) const { return logical_and(other); }
Column::wrapper_t Column::logical_and(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return binary_operation(other, cudf::binary_operator::LOGICAL_AND, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::logical_and(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return binary_operation(other, cudf::binary_operator::LOGICAL_AND, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator||(Column const& other) const { return logical_or(other); }
Column::wrapper_t Column::operator||(Scalar const& other) const { return logical_or(other); }
Column::wrapper_t Column::logical_or(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return binary_operation(other, cudf::binary_operator::LOGICAL_OR, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::logical_or(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return binary_operation(other, cudf::binary_operator::LOGICAL_OR, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::operator<<(Column const& other) const { return shift_left(other); }
Column::wrapper_t Column::operator<<(Scalar const& other) const { return shift_left(other); }
Column::wrapper_t Column::shift_left(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_LEFT, mr);
}
Column::wrapper_t Column::shift_left(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_LEFT, mr);
}
Column::wrapper_t Column::operator>>(Column const& other) const { return shift_right(other); }
Column::wrapper_t Column::operator>>(Scalar const& other) const { return shift_right(other); }
Column::wrapper_t Column::shift_right(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_RIGHT, mr);
}
Column::wrapper_t Column::shift_right(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_RIGHT, mr);
}
Column::wrapper_t Column::shift_right_unsigned(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_RIGHT_UNSIGNED, mr);
}
Column::wrapper_t Column::shift_right_unsigned(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::SHIFT_RIGHT_UNSIGNED, mr);
}
Column::wrapper_t Column::log_base(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::LOG_BASE, mr);
}
Column::wrapper_t Column::log_base(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::LOG_BASE, mr);
}
Column::wrapper_t Column::atan2(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::ATAN2, mr);
}
Column::wrapper_t Column::atan2(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::ATAN2, mr);
}
Column::wrapper_t Column::null_equals(Column const& other,
rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(
other, cudf::binary_operator::NULL_EQUALS, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::null_equals(Scalar const& other,
rmm::mr::device_memory_resource* mr) const {
return this->binary_operation(
other, cudf::binary_operator::NULL_EQUALS, cudf::type_id::BOOL8, mr);
}
Column::wrapper_t Column::null_max(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::NULL_MAX, mr);
}
Column::wrapper_t Column::null_max(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::NULL_MAX, mr);
}
Column::wrapper_t Column::null_min(Column const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::NULL_MIN, mr);
}
Column::wrapper_t Column::null_min(Scalar const& other, rmm::mr::device_memory_resource* mr) const {
return auto_binary_operation(*this, other, cudf::binary_operator::NULL_MIN, mr);
}
// Private (JS-facing) impls
Napi::Value Column::add(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return add(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return add(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return add(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return add(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.add expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::sub(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return sub(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return sub(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return sub(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return sub(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.sub expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::mul(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return mul(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return mul(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return mul(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return mul(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.mul expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::div(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return div(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return div(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return div(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return div(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.div expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::true_div(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return true_div(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return true_div(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return true_div(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return true_div(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.true_div expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::floor_div(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return floor_div(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return floor_div(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return floor_div(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return floor_div(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.floor_div expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::mod(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return mod(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return mod(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return mod(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return mod(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.mod expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::pow(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return pow(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return pow(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return pow(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return pow(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.pow expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::eq(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return eq(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return eq(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return eq(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return eq(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.eq expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::ne(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return ne(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return ne(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return ne(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return ne(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.ne expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::lt(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return lt(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return lt(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return lt(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return lt(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.lt expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::le(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return le(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return le(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return le(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return le(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.le expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::gt(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return gt(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return gt(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return gt(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return gt(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.gt expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::ge(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return ge(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return ge(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return ge(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return ge(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.ge expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::bitwise_and(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return bitwise_and(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return bitwise_and(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return bitwise_and(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return bitwise_and(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(Napi::Error::New(info.Env(),
"Column.bitwise_and expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::bitwise_or(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return bitwise_or(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return bitwise_or(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return bitwise_or(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return bitwise_or(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.bitwise_or expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::bitwise_xor(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return bitwise_xor(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return bitwise_xor(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return bitwise_xor(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return bitwise_xor(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(Napi::Error::New(info.Env(),
"Column.bitwise_xor expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::logical_and(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return logical_and(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return logical_and(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return logical_and(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return logical_and(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(Napi::Error::New(info.Env(),
"Column.logical_and expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::logical_or(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return logical_or(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return logical_or(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return logical_or(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return logical_or(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.logical_or expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::shift_left(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return shift_left(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return shift_left(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return shift_left(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return shift_left(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.shift_left expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::shift_right(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return shift_right(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return shift_right(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return shift_right(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return shift_right(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(Napi::Error::New(info.Env(),
"Column.shift_right expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::shift_right_unsigned(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return shift_right_unsigned(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return shift_right_unsigned(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return shift_right_unsigned(Scalar::New(info.Env(), rhs, type()), mr); }
if (rhs.IsNumber()) { return shift_right_unsigned(Scalar::New(info.Env(), rhs, type()), mr); }
NAPI_THROW(Napi::Error::New(
info.Env(), "Column.shift_right_unsigned expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::log_base(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return log_base(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return log_base(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return log_base(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return log_base(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.log_base expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::atan2(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return atan2(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return atan2(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return atan2(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return atan2(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.atan2 expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::null_equals(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return null_equals(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return null_equals(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return null_equals(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return null_equals(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(Napi::Error::New(info.Env(),
"Column.null_equals expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::null_max(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return null_max(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return null_max(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return null_max(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return null_max(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.null_max expects a Column, Scalar, bigint, or number."));
}
Napi::Value Column::null_min(Napi::CallbackInfo const& info) {
auto rhs = info[0];
rmm::mr::device_memory_resource* mr{NapiToCPP(info[1])};
if (Column::IsInstance(rhs)) { return null_min(*Column::Unwrap(rhs.ToObject()), mr); }
if (Scalar::IsInstance(rhs)) { return null_min(*Scalar::Unwrap(rhs.ToObject()), mr); }
if (rhs.IsBigInt()) { return null_min(Scalar::New(info.Env(), rhs.As<Napi::BigInt>()), mr); }
if (rhs.IsNumber()) { return null_min(Scalar::New(info.Env(), rhs.As<Napi::Number>()), mr); }
NAPI_THROW(
Napi::Error::New(info.Env(), "Column.null_min expects a Column, Scalar, bigint, or number."));
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/column/transform.cpp
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_rmm/device_buffer.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/transform.hpp>
#include <cudf/types.hpp>
#include <rmm/device_buffer.hpp>
#include <napi.h>
namespace nv {
std::pair<std::unique_ptr<rmm::device_buffer>, cudf::size_type> Column::bools_to_mask(
rmm::mr::device_memory_resource* mr) const {
try {
return cudf::bools_to_mask(*this, mr);
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::bools_to_mask(Napi::CallbackInfo const& info) {
rmm::mr::device_memory_resource* mr = CallbackArgs{info}[0];
auto result = bools_to_mask(mr);
auto ary = Napi::Array::New(Env(), 2);
ary.Set(0u, DeviceBuffer::New(Env(), std::move(result.first)));
ary.Set(1u, result.second);
return ary;
}
std::pair<std::unique_ptr<rmm::device_buffer>, cudf::size_type> Column::nans_to_nulls(
rmm::mr::device_memory_resource* mr) const {
try {
return cudf::nans_to_nulls(*this, mr);
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
}
Napi::Value Column::nans_to_nulls(Napi::CallbackInfo const& info) {
rmm::mr::device_memory_resource* mr = NapiToCPP(info[0]);
auto result = nans_to_nulls(mr);
try {
auto col =
Column::New(Env(), cudf::allocate_like(*this, cudf::mask_allocation_policy::RETAIN, mr));
[&](cudf::mutable_column_view view) {
cudf::copy_range_in_place(*this, view, 0, size(), 0);
}(col->mutable_view());
col->set_null_mask(DeviceBuffer::New(info.Env(), std::move(result.first)),
null_count() == cudf::UNKNOWN_NULL_COUNT ? cudf::UNKNOWN_NULL_COUNT
: null_count() + result.second);
return col;
} catch (std::exception const& e) { NAPI_THROW(Napi::Error::New(Env(), e.what())); }
} // namespace nv
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/attributes.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/strings/attributes.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::count_characters(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::count_characters(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::count_bytes(rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::count_bytes(this->view(), mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::count_characters(Napi::CallbackInfo const& info) {
return count_characters(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
Napi::Value Column::count_bytes(Napi::CallbackInfo const& info) {
return count_bytes(NapiToCPP(info[0]).operator rmm::mr::device_memory_resource*());
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/partition.cpp
|
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <cudf/strings/split/partition.hpp>
namespace nv {
Napi::Value Column::string_partition(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string const delimiter = args[0];
rmm::mr::device_memory_resource* mr = args[1];
try {
auto ary = Napi::Array::New(info.Env(), 3);
auto cols = cudf::strings::partition(view(), delimiter, mr)->release();
for (std::size_t i = 0; i < cols.size(); ++i) { //
ary[i] = Column::New(Env(), std::move(cols[i]));
}
return ary;
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/multibyte_split.cpp
|
// Copyright (c) 2022-2023, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
#include <cudf/io/text/data_chunk_source_factories.hpp>
#include <cudf/io/text/multibyte_split.hpp>
#include <cudf/utilities/span.hpp>
namespace nv {
namespace {
class device_span_data_chunk : public cudf::io::text::device_data_chunk {
public:
device_span_data_chunk(cudf::device_span<char const> data) : _data(data) {}
[[nodiscard]] char const* data() const override { return _data.data(); }
[[nodiscard]] std::size_t size() const override { return _data.size(); }
operator cudf::device_span<char const>() const override { return _data; }
private:
cudf::device_span<char const> _data;
};
/**
* @brief A reader which produces view of device memory which represent a subset of the input device
* span.
*/
class device_span_data_chunk_reader : public cudf::io::text::data_chunk_reader {
public:
device_span_data_chunk_reader(cudf::device_span<char const> data) : _data(data) {}
void skip_bytes(std::size_t read_size) override {
_position += std::min(read_size, _data.size() - _position);
}
std::unique_ptr<cudf::io::text::device_data_chunk> get_next_chunk(
std::size_t read_size, rmm::cuda_stream_view stream) override {
// limit the read size to the number of bytes remaining in the device_span.
read_size = std::min(read_size, _data.size() - _position);
// create a view over the device span
auto chunk_span = _data.subspan(_position, read_size);
// increment position
_position += read_size;
// return the view over device memory so it can be processed.
return std::make_unique<device_span_data_chunk>(chunk_span);
}
private:
cudf::device_span<char const> _data;
uint64_t _position = 0;
};
/**
* @brief A device span data source which creates an istream_data_chunk_reader.
*/
class device_span_data_chunk_source : public cudf::io::text::data_chunk_source {
public:
device_span_data_chunk_source(cudf::device_span<char const> data) : _data(data) {}
[[nodiscard]] std::unique_ptr<cudf::io::text::data_chunk_reader> create_reader() const override {
return std::make_unique<device_span_data_chunk_reader>(_data);
}
private:
cudf::device_span<char const> _data;
};
Column::wrapper_t split_string_column(Napi::CallbackInfo const& info,
cudf::mutable_column_view const& col,
std::string const& delimiter,
rmm::mr::device_memory_resource* mr) {
/* TODO: This only splits a string column. How to generalize */
// Check type
auto span = cudf::device_span<char const>(col.child(1).data<char const>(), col.child(1).size());
auto datasource = device_span_data_chunk_source(span);
return Column::New(info.Env(),
cudf::io::text::multibyte_split(datasource, delimiter, std::nullopt, mr));
}
Column::wrapper_t read_text_files(Napi::CallbackInfo const& info,
std::string const& filename,
std::string const& delimiter,
rmm::mr::device_memory_resource* mr) {
auto datasource = cudf::io::text::make_source_from_file(filename);
return Column::New(info.Env(),
cudf::io::text::multibyte_split(*datasource, delimiter, std::nullopt, mr));
}
} // namespace
Napi::Value Column::split(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
std::string const delimiter = args[0];
rmm::mr::device_memory_resource* mr = args[1];
try {
return split_string_column(info, *this, delimiter, mr);
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
}
Napi::Value Column::read_text(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
std::string const source = args[0];
std::string const delimiter = args[1];
rmm::mr::device_memory_resource* mr = args[2];
try {
return read_text_files(info, source, delimiter, mr);
} catch (std::exception const& e) { throw Napi::Error::New(info.Env(), e.what()); }
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/padding.cpp
|
// Copyright (c) 2021-2023, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/strings/padding.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::pad(cudf::size_type width,
cudf::strings::side_type pad_side,
std::string const& fill_char,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::pad(this->view(), width, pad_side, fill_char, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::zfill(cudf::size_type width, rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::zfill(this->view(), width, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::pad(Napi::CallbackInfo const& info) {
if (info.Length() < 3) {
NODE_CUDF_THROW("Column pad expects a width, pad_side, fill_char, and optional MemoryResource",
info.Env());
}
CallbackArgs const args{info};
const std::string pad_size_string = args[1];
const auto pad_side = [&pad_size_string, &info]() {
if (pad_size_string == "left") {
return cudf::strings::side_type::LEFT;
} else if (pad_size_string == "right") {
return cudf::strings::side_type::RIGHT;
} else if (pad_size_string == "both") {
return cudf::strings::side_type::BOTH;
} else {
NODE_CUDF_THROW("Invalid pad side " + pad_size_string, info.Env());
}
}();
const std::string fill_char = args[2];
if (fill_char.length() != 1) {
NODE_CUDF_THROW("fill_char must be exactly one character", info.Env());
}
return pad(args[0], pad_side, fill_char, args[3]);
}
Napi::Value Column::zfill(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column zfill expects a width and optional MemoryResource", info.Env());
}
CallbackArgs const args{info};
return zfill(args[0], args[1]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/replace.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/strings/replace.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::replace_slice(std::string const& repl,
cudf::size_type start,
cudf::size_type stop,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(), cudf::strings::replace_slice(this->view(), repl, start, stop, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::replace_slice(Napi::CallbackInfo const& info) {
if (info.Length() < 3) {
NODE_CUDF_THROW(
"Column replace_slice expects a replacement, start, stop, and optional MemoryResource",
info.Env());
}
CallbackArgs const args{info};
return replace_slice(args[0], args[1], args[2], args[3]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/combine.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/scalar.hpp>
#include <node_cudf/table.hpp>
#include <node_rmm/device_buffer.hpp>
#include <cudf/column/column.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/combine.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <rmm/device_buffer.hpp>
#include <napi.h>
namespace nv {
Column::wrapper_t Column::concatenate(Napi::Env const& env,
cudf::table_view const& columns,
cudf::string_scalar const& separator,
cudf::string_scalar const& narep,
cudf::strings::separator_on_nulls separator_on_nulls,
rmm::mr::device_memory_resource* mr) {
try {
return Column::New(
env, cudf::strings::concatenate(columns, separator, narep, separator_on_nulls, mr));
} catch (std::exception const& e) { throw Napi::Error::New(env, e.what()); }
}
Napi::Value Column::concatenate(Napi::CallbackInfo const& info) {
CallbackArgs args{info};
if (args.Length() != 5) {
NAPI_THROW(Napi::Error::New(info.Env(),
"concatenate expects a columns, separator, narep, "
"separator_on_nulls and optionally a memory resource"));
}
Table::wrapper_t columns = args[0];
const std::string separator_string = args[1];
const cudf::string_scalar separator{separator_string};
auto narep = [&args]() {
if (args[2].IsNull() or args[2].IsUndefined()) {
return cudf::string_scalar{"", false};
} else {
const std::string& narep_string = args[2];
return cudf::string_scalar{narep_string};
}
}();
auto separator_on_nulls = [&args]() {
bool separator_on_nulls_bool = args[3];
return separator_on_nulls_bool ? cudf::strings::separator_on_nulls::YES
: cudf::strings::separator_on_nulls::NO;
}();
rmm::mr::device_memory_resource* mr = args[4];
return concatenate(info.Env(), columns->view(), separator, narep, separator_on_nulls, mr);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/contains.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/strings/contains.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::contains_re(std::string const& pattern,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
cudf::strings::contains_re(this->view(), pattern, cudf::strings::regex_flags::DEFAULT, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::count_re(std::string const& pattern,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
cudf::strings::count_re(this->view(), pattern, cudf::strings::regex_flags::DEFAULT, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Column::wrapper_t Column::matches_re(std::string const& pattern,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(
Env(),
cudf::strings::matches_re(this->view(), pattern, cudf::strings::regex_flags::DEFAULT, mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::contains_re(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column contains_re expects a pattern and optional MemoryResource", info.Env());
}
CallbackArgs const args{info};
return contains_re(args[0], args[1]);
}
Napi::Value Column::count_re(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column contains_re expects a pattern and optional MemoryResource", info.Env());
}
CallbackArgs const args{info};
return count_re(args[0], args[1]);
}
Napi::Value Column::matches_re(Napi::CallbackInfo const& info) {
if (info.Length() < 1) {
NODE_CUDF_THROW("Column contains_re expects a pattern and optional MemoryResource", info.Env());
}
CallbackArgs const args{info};
return matches_re(args[0], args[1]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src/column
|
rapidsai_public_repos/node/modules/cudf/src/column/strings/replace_re.cpp
|
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <node_rmm/memory_resource.hpp>
#include <cudf/strings/replace_re.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace nv {
Column::wrapper_t Column::replace_re(std::string const& pattern,
std::string const& replacement,
cudf::size_type max_replace_count,
cudf::strings::regex_flags const flags,
rmm::mr::device_memory_resource* mr) const {
try {
return Column::New(Env(),
cudf::strings::replace_re(
this->view(),
pattern,
replacement,
max_replace_count < 0 ? std::nullopt : std::optional{max_replace_count},
flags,
mr));
} catch (std::exception const& e) { throw Napi::Error::New(Env(), e.what()); }
}
Napi::Value Column::replace_re(Napi::CallbackInfo const& info) {
CallbackArgs const args{info};
std::string const& pattern = args[0];
std::string const& replacement = args[1];
cudf::size_type const& count = args[2];
Napi::Object const& options = args[3];
uint32_t flags{cudf::strings::regex_flags::DEFAULT};
if (options.Get("dotAll").ToBoolean()) { flags |= cudf::strings::regex_flags::DOTALL; }
if (options.Get("multiline").ToBoolean()) { flags |= cudf::strings::regex_flags::MULTILINE; }
return replace_re(pattern, replacement, count, cudf::strings::regex_flags{flags}, args[4]);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/utilities/metadata.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/table.hpp>
#include <node_cudf/utilities/metadata.hpp>
namespace nv {
cudf::io::table_input_metadata make_writer_columns_metadata(Napi::Object const& options,
cudf::table_view const& table) {
auto env = options.Env();
auto has_opt = [&](std::string const& key) { return options.Has(key); };
auto napi_opt = [&](std::string const& key) -> Napi::Value {
return has_opt(key) ? options.Get(key) : env.Undefined();
};
auto str_opt = [&](std::string const& key, std::string const& default_val) {
return has_opt(key) ? options.Get(key).ToString().Utf8Value() : default_val;
};
auto null_value = str_opt("nullValue", "N/A");
cudf::io::table_input_metadata metadata{};
Napi::Array column_names = napi_opt("columnNames").IsArray()
? napi_opt("columnNames").As<Napi::Array>()
: Napi::Array::New(env, table.num_columns());
metadata.column_metadata.reserve(table.num_columns());
for (uint32_t i = 0; i < column_names.Length(); ++i) {
auto name = column_names.Has(i) ? column_names.Get(i) : env.Null();
auto column = cudf::io::column_in_metadata(
name.IsString() || name.IsNumber() ? name.ToString().Utf8Value() : null_value);
metadata.column_metadata.push_back(column);
}
return metadata;
};
Napi::Array get_output_names_from_metadata(Napi::Env const& env,
cudf::io::table_with_metadata const& result) {
auto const& column_names = result.metadata.column_names;
auto names = Napi::Array::New(env, column_names.size());
for (std::size_t i = 0; i < column_names.size(); ++i) { names.Set(i, column_names[i]); }
return names;
}
Napi::Array get_output_cols_from_metadata(Napi::Env const& env,
cudf::io::table_with_metadata const& result) {
auto contents = result.tbl->release();
auto columns = Napi::Array::New(env, contents.size());
for (std::size_t i = 0; i < contents.size(); ++i) {
columns.Set(i, Column::New(env, std::move(contents[i]))->Value());
}
return columns;
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/utilities/buffer.cpp
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/utilities/buffer.hpp>
#include <node_cudf/utilities/error.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/unary.hpp>
#include <cudf/utilities/bit.hpp>
namespace nv {
namespace {
bool is_device_memory(Napi::Object const& data) {
return data.Has("ptr") and data.Get("ptr").IsNumber();
}
bool is_device_buffer_wrapper(Napi::Object const& data) {
return data.Has("buffer") and data.Get("buffer").IsObject() and
DeviceBuffer::IsInstance(data.Get("buffer"));
}
bool is_device_memory_wrapper(Napi::Object const& data) {
return data.Has("buffer") and data.Get("buffer").IsObject() and
is_device_memory(data.Get("buffer").ToObject());
}
std::size_t get_size_type(Napi::Object const& data, std::string const& key) {
if (data.Has(key)) {
auto val = data.Get(key);
if (val.IsNumber()) { return val.ToNumber().Int64Value(); }
if (val.IsBigInt()) {
bool lossless{false};
return val.As<Napi::BigInt>().Uint64Value(&lossless);
}
}
return 0;
}
char* get_device_memory_ptr(Napi::Object const& buffer) {
return reinterpret_cast<char*>(buffer.Get("ptr").ToNumber().Int64Value());
}
DeviceBuffer::wrapper_t device_memory_to_device_buffer(Napi::Env const& env,
Napi::Object const& data,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
Napi::HandleScope scope{env};
auto dptr = get_device_memory_ptr(data);
auto length = get_size_type(data, "byteLength");
return DeviceBuffer::New(env, Span{dptr, length}, mr, stream);
}
DeviceBuffer::wrapper_t device_memory_wrapper_to_device_buffer(Napi::Env const& env,
Napi::Object const& data,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
Napi::HandleScope scope{env};
auto length = get_size_type(data, "byteLength");
auto offset = get_size_type(data, "byteOffset");
auto dptr = get_device_memory_ptr(data.Get("buffer").ToObject());
return DeviceBuffer::New(env, Span{dptr + offset, length}, mr, stream);
}
DeviceBuffer::wrapper_t data_view_to_device_buffer(Napi::Env const& env,
Napi::Object const& data,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
Napi::HandleScope scope{env};
auto dv = data.As<Napi::DataView>();
auto ary = Napi::Uint8Array::New(env, dv.ByteLength(), dv.ArrayBuffer(), dv.ByteOffset());
return DeviceBuffer::New(env, ary, mr, stream);
}
DeviceBuffer::wrapper_t array_buffer_to_device_buffer(Napi::Env const& env,
Napi::Object const& data,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
Napi::HandleScope scope{env};
auto buf = data.As<Napi::ArrayBuffer>();
auto ary = Napi::Uint8Array::New(env, buf.ByteLength(), buf, 0);
return DeviceBuffer::New(env, ary, mr, stream);
}
DeviceBuffer::wrapper_t typed_array_to_device_buffer(Napi::Env const& env,
Napi::Object const& data,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
Napi::HandleScope scope{env};
auto length = get_size_type(data, "byteLength");
auto offset = get_size_type(data, "byteOffset");
auto buf = data.Get("buffer").As<Napi::ArrayBuffer>();
auto ary = Napi::Uint8Array::New(env, length, buf, offset);
return DeviceBuffer::New(env, ary, mr, stream);
}
DeviceBuffer::wrapper_t array_to_device_buffer(Napi::Env const& env,
Napi::Array const& data,
cudf::data_type const& dtype,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
switch (dtype.id()) {
case cudf::type_id::INT64: return DeviceBuffer::New<int64_t>(env, data, mr);
case cudf::type_id::UINT64: return DeviceBuffer::New<uint64_t>(env, data, mr);
case cudf::type_id::FLOAT64: return DeviceBuffer::New<double>(env, data, mr);
case cudf::type_id::FLOAT32:
case cudf::type_id::INT8:
case cudf::type_id::INT16:
case cudf::type_id::INT32:
case cudf::type_id::UINT8:
case cudf::type_id::UINT16:
case cudf::type_id::UINT32:
case cudf::type_id::BOOL8: {
auto buffer = DeviceBuffer::New<double>(env, data, mr);
cudf::size_type size = buffer->size() / sizeof(double);
cudf::column_view view{cudf::data_type{cudf::type_id::FLOAT64}, size, buffer->data()};
return DeviceBuffer::New(env, std::move(cudf::cast(view, dtype)->release().data), mr);
}
default: return DeviceBuffer::New(env, mr, stream);
}
}
DeviceBuffer::wrapper_t bool_array_to_null_bitmask(Napi::Env const& env,
Napi::Array const& data,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
auto const mask_size = cudf::bitmask_allocation_size_bytes(size);
std::vector<cudf::bitmask_type> mask(mask_size / sizeof(cudf::bitmask_type), 0);
for (auto i = 0u; i < data.Length(); ++i) {
Napi::HandleScope scope{env};
// Set the valid bit if the value is "truthy" by JS standards
if (data.Get(i).ToBoolean().Value()) { cudf::set_bit_unsafe(mask.data(), i); }
}
return DeviceBuffer::New(env, mask.data(), mask_size, MemoryResource::Current(env));
}
DeviceBuffer::wrapper_t data_array_to_null_bitmask(Napi::Env const& env,
Napi::Array const& data,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
auto const mask_size = cudf::bitmask_allocation_size_bytes(size);
std::vector<cudf::bitmask_type> mask(mask_size / sizeof(cudf::bitmask_type), 0);
for (auto i = 0u; i < data.Length(); ++i) {
Napi::HandleScope scope{env};
auto const elt = data.Get(i);
// Set the valid bit if the value isn't `null` or `undefined`
if (!(elt.IsNull() or elt.IsUndefined() or elt.IsEmpty())) {
cudf::set_bit_unsafe(mask.data(), i);
}
}
return DeviceBuffer::New(env, mask.data(), mask_size, MemoryResource::Current(env));
}
} // namespace
DeviceBuffer::wrapper_t data_to_devicebuffer(Napi::Env const& env,
Napi::Value const& value,
cudf::data_type const& dtype,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
if (value.IsObject() and !(value.IsEmpty() || value.IsNull() || value.IsUndefined())) {
auto data = value.As<Napi::Object>();
if (DeviceBuffer::IsInstance(data)) { return data; }
if (is_device_buffer_wrapper(data)) { return data.Get("buffer").ToObject(); }
if (is_device_memory(data)) { return device_memory_to_device_buffer(env, data, mr, stream); }
if (is_device_memory_wrapper(data)) {
return device_memory_wrapper_to_device_buffer(env, data, mr, stream);
}
if (data.IsArrayBuffer()) { return array_buffer_to_device_buffer(env, data, mr, stream); }
if (data.IsDataView()) { return data_view_to_device_buffer(env, data, mr, stream); }
if (data.IsBuffer() || data.IsTypedArray()) {
return typed_array_to_device_buffer(env, data, mr, stream);
}
if (data.IsArray()) {
return array_to_device_buffer(env, data.As<Napi::Array>(), dtype, mr, stream);
}
}
return DeviceBuffer::New(env, mr, stream);
}
DeviceBuffer::wrapper_t mask_to_null_bitmask(Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
if (size <= 0 || value.IsEmpty() || value.IsNull() || value.IsUndefined()) {
// Return an empty bitmask indicating all-valid/non-nullable
return DeviceBuffer::New(env, mr, stream);
}
if (value.IsBoolean()) {
// Return a full bitmask indicating either all-valid or all-null
auto mask = cudf::create_null_mask(
size, value.ToBoolean() ? cudf::mask_state::ALL_VALID : cudf::mask_state::ALL_NULL);
return DeviceBuffer::New(value.Env(), std::make_unique<rmm::device_buffer>(std::move(mask)));
}
if (value.IsArray()) {
return bool_array_to_null_bitmask(env, value.As<Napi::Array>(), size, mr, stream);
}
if (value.IsObject()) {
auto mask = data_to_devicebuffer(
env, value.As<Napi::Object>(), cudf::data_type{cudf::type_id::BOOL8}, mr, stream);
if (mask->size() > 0 && mask->size() < cudf::bitmask_allocation_size_bytes(size)) {
mask->resize(cudf::bitmask_allocation_size_bytes(size), mask->stream());
}
NODE_CUDF_EXPECT(mask->size() == 0 || mask->size() >= cudf::bitmask_allocation_size_bytes(size),
"Null mask buffer size must match the size of the column.",
env);
return mask;
}
// Return an empty bitmask indicating all-valid/non-nullable
return DeviceBuffer::New(env, mr, stream);
}
DeviceBuffer::wrapper_t data_to_null_bitmask(Napi::Env const& env,
Napi::Value const& value,
cudf::size_type const& size,
MemoryResource::wrapper_t const& mr,
rmm::cuda_stream_view stream) {
if (size <= 0 || value.IsEmpty() || value.IsNull() || value.IsUndefined()) {
// Return an empty bitmask indicating all-valid/non-nullable
return DeviceBuffer::New(env, mr, stream);
}
if (value.IsArray()) {
return data_array_to_null_bitmask(env, value.As<Napi::Array>(), size, mr, stream);
}
// Return an empty bitmask indicating all-valid/non-nullable
return DeviceBuffer::New(env, mr, stream);
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf/src
|
rapidsai_public_repos/node/modules/cudf/src/utilities/dtypes.cpp
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <node_cudf/column.hpp>
#include <node_cudf/utilities/dtypes.hpp>
#include <node_cudf/utilities/error.hpp>
#include <node_cudf/utilities/napi_to_cpp.hpp>
#include <cudf/column/column.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
namespace nv {
namespace {
template <typename LHS, typename RHS, typename = void>
struct common_type_exists : std::false_type {};
template <typename LHS, typename RHS>
struct common_type_exists<LHS, RHS, std::void_t<std::common_type_t<LHS, RHS>>> : std::true_type {};
struct get_common_type_id {
template <typename LHS,
typename RHS,
typename std::enable_if_t<common_type_exists<LHS, RHS>::value>* = nullptr>
cudf::type_id operator()() {
return cudf::type_to_id<std::common_type_t<LHS, RHS>>();
}
template <typename LHS,
typename RHS,
typename std::enable_if_t<not common_type_exists<LHS, RHS>::value>* = nullptr>
cudf::type_id operator()() {
CUDF_FAIL("Cannot determine a logical common type between " +
cudf::type_to_name{}.operator()<LHS>() + " and " +
cudf::type_to_name{}.operator()<RHS>());
}
};
} // namespace
cudf::type_id get_common_type(cudf::data_type const& lhs, cudf::data_type const& rhs) {
return cudf::double_type_dispatcher(lhs, rhs, get_common_type_id{});
}
Napi::Value find_common_type(CallbackArgs const& args) {
try {
return cudf_to_arrow_type(args.Env(), cudf::data_type{get_common_type(args[0], args[1])});
} catch (std::exception const& e) { throw Napi::Error::New(args.Env(), e.what()); }
}
cudf::data_type arrow_to_cudf_type(Napi::Object const& type) {
using cudf::data_type;
using cudf::type_id;
switch (type.Get("typeId").ToNumber().Int32Value()) {
case -1 /*Arrow.Dictionary */: return data_type{type_id::DICTIONARY32};
case 0 /*Arrow.NONE */: return data_type{type_id::EMPTY};
case 1 /*Arrow.Null */: return data_type{type_id::EMPTY};
case 2 /*Arrow.Int */: {
switch (type.Get("bitWidth").ToNumber().Int32Value()) {
case 8:
return data_type{type.Get("isSigned").ToBoolean().Value() ? type_id::INT8
: type_id::UINT8};
case 16:
return data_type{type.Get("isSigned").ToBoolean().Value() ? type_id::INT16
: type_id::UINT16};
case 32:
return data_type{type.Get("isSigned").ToBoolean().Value() ? type_id::INT32
: type_id::UINT32};
case 64:
return data_type{type.Get("isSigned").ToBoolean().Value() ? type_id::INT64
: type_id::UINT64};
}
break;
}
case 3 /*Arrow.Float */: {
switch (type.Get("precision").ToNumber().Int32Value()) {
// case 0 /*Arrow.HALF */: return data_type{type_id::FLOAT16};
case 1 /*Arrow.SINGLE */: return data_type{type_id::FLOAT32};
case 2 /*Arrow.DOUBLE */: return data_type{type_id::FLOAT64};
}
break;
}
case 4 /*Arrow.Binary */: return data_type{type_id::STRING};
case 5 /*Arrow.Utf8 */: return data_type{type_id::STRING};
case 6 /*Arrow.Bool */: return data_type{type_id::BOOL8};
// case 7 /*Arrow.Decimal */:
case 8 /*Arrow.Date */: {
switch (type.Get("unit").ToNumber().Int32Value()) {
case 0: return data_type{type_id::TIMESTAMP_DAYS};
case 1: return data_type{type_id::TIMESTAMP_MILLISECONDS};
}
}
// case 9 /*Arrow.Time */:
case 10 /*Arrow.Timestamp */: {
switch (type.Get("unit").ToNumber().Int32Value()) {
case 0: return data_type{type_id::TIMESTAMP_SECONDS};
case 1: return data_type{type_id::TIMESTAMP_MILLISECONDS};
case 2: return data_type{type_id::TIMESTAMP_MICROSECONDS};
case 3: return data_type{type_id::TIMESTAMP_NANOSECONDS};
}
}
// case 11 /*Arrow.Interval */:
case 12 /*Arrow.List */: return data_type{type_id::LIST};
case 13 /*Arrow.Struct */:
return data_type{type_id::STRUCT};
// case 14 /*Arrow.Union */:
// case 15 /*Arrow.FixedSizeBinary */:
// case 16 /*Arrow.FixedSizeList */:
// case 17 /*Arrow.Map */:
}
throw Napi::Error::New(
type.Env(), "Unrecognized Arrow type '" + type.Get("typeId").ToString().Utf8Value() + "");
}
Napi::Object cudf_scalar_type_to_arrow_type(Napi::Env const& env, cudf::data_type type) {
auto arrow_type = Napi::Object::New(env);
switch (type.id()) {
case cudf::type_id::EMPTY: {
arrow_type.Set("typeId", 0);
break;
}
case cudf::type_id::INT8: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 8);
arrow_type.Set("isSigned", true);
break;
}
case cudf::type_id::INT16: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 16);
arrow_type.Set("isSigned", true);
break;
}
case cudf::type_id::INT32: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 32);
arrow_type.Set("isSigned", true);
break;
}
case cudf::type_id::INT64: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 64);
arrow_type.Set("isSigned", true);
break;
}
case cudf::type_id::UINT8: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 8);
arrow_type.Set("isSigned", false);
break;
}
case cudf::type_id::UINT16: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 16);
arrow_type.Set("isSigned", false);
break;
}
case cudf::type_id::UINT32: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 32);
arrow_type.Set("isSigned", false);
break;
}
case cudf::type_id::UINT64: {
arrow_type.Set("typeId", 2);
arrow_type.Set("bitWidth", 64);
arrow_type.Set("isSigned", false);
break;
}
case cudf::type_id::FLOAT32: {
arrow_type.Set("typeId", 3);
arrow_type.Set("precision", 1);
break;
}
case cudf::type_id::FLOAT64: {
arrow_type.Set("typeId", 3);
arrow_type.Set("precision", 2);
break;
}
case cudf::type_id::BOOL8: {
arrow_type.Set("typeId", 6);
break;
}
// case cudf::type_id::TIMESTAMP_DAYS: // TODO
case cudf::type_id::TIMESTAMP_SECONDS: {
arrow_type.Set("typeId", 10);
arrow_type.Set("unit", 0);
break;
}
case cudf::type_id::TIMESTAMP_MILLISECONDS: {
arrow_type.Set("typeId", 10);
arrow_type.Set("unit", 1);
break;
}
case cudf::type_id::TIMESTAMP_MICROSECONDS: {
arrow_type.Set("typeId", 10);
arrow_type.Set("unit", 2);
break;
}
case cudf::type_id::TIMESTAMP_NANOSECONDS: {
arrow_type.Set("typeId", 10);
arrow_type.Set("unit", 3);
break;
}
// case cudf::type_id::DURATION_DAYS: // TODO
// case cudf::type_id::DURATION_SECONDS: // TODO
// case cudf::type_id::DURATION_MILLISECONDS: // TODO
// case cudf::type_id::DURATION_MICROSECONDS: // TODO
// case cudf::type_id::DURATION_NANOSECONDS: // TODO
case cudf::type_id::STRING: {
arrow_type.Set("typeId", 5);
break;
}
// case cudf::type_id::DECIMAL32: // TODO
// case cudf::type_id::DECIMAL64: // TODO
default:
throw Napi::Error::New(env,
"cudf_scalar_type_to_arrow_type not implemented for type: " +
cudf::type_dispatcher(type, cudf::type_to_name{}));
}
return arrow_type;
}
Napi::Object cudf_to_arrow_type(Napi::Env const& env, cudf::data_type const& cudf_type) {
return cudf_scalar_type_to_arrow_type(env, cudf_type);
}
Napi::Object column_to_arrow_type(Napi::Env const& env,
cudf::data_type const& cudf_type,
Napi::Array children) {
auto arrow_type = Napi::Object::New(env);
switch (cudf_type.id()) {
case cudf::type_id::DICTIONARY32: {
arrow_type.Set("typeId", -1);
arrow_type.Set("indices", children.Get(0u).ToObject().Get("type"));
arrow_type.Set("dictionary", children.Get(1).ToObject().Get("type"));
arrow_type.Set("isOrdered", false);
break;
}
case cudf::type_id::LIST: {
auto list_children = Napi::Array::New(env, 1);
if (children.Length() > 1) {
auto field = Napi::Object::New(env);
field.Set("type", children.Get(1).ToObject().Get("type"));
list_children.Set(0u, field);
}
arrow_type.Set("typeId", 12);
arrow_type.Set("children", list_children);
break;
}
case cudf::type_id::STRUCT: {
auto struct_children = Napi::Array::New(env, children.Length());
for (uint32_t i = 0; i < children.Length(); ++i) {
Napi::HandleScope scope{env};
auto field = Napi::Object::New(env);
field.Set("type", children.Get(i).ToObject().Get("type"));
struct_children.Set(i, field);
}
arrow_type.Set("typeId", 13);
arrow_type.Set("children", struct_children);
break;
}
default: return cudf_scalar_type_to_arrow_type(env, cudf_type);
}
return arrow_type;
}
} // namespace nv
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-table-tests.ts
|
// Copyright (c) 2020, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float32Buffer, Int32Buffer, setDefaultAllocator, Uint8Buffer} from '@rapidsai/cuda';
import {
Bool8,
Column,
Float32,
Int32,
Table,
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength) => new DeviceBuffer(byteLength, mr));
test('Table initialization', () => {
const length = 100;
const col_0 = new Column({type: new Int32, data: new Int32Buffer(length)});
const col_1 = new Column({
type: new Bool8,
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const table_0 = new Table({columns: [col_0, col_1]});
expect(table_0.numColumns).toBe(2);
});
test('Table.getColumnByIndex', () => {
const length = 100;
const col_0 = new Column({type: new Int32, data: new Int32Buffer(length)});
const col_1 = new Column({
type: new Bool8,
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const table_0 = new Table({columns: [col_0, col_1]});
expect(table_0.getColumnByIndex(0).type).toBeInstanceOf(Int32);
expect(() => { table_0.getColumnByIndex(4); }).toThrow();
});
test('Table.gather (bad argument)', () => {
const col_0 = new Column({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5])});
const table_0 = new Table({columns: [col_0]});
const selection = [2, 4, 5];
expect(() => table_0.gather(<any>selection, false)).toThrow();
});
test('Table.gather (indices)', () => {
const col_0 = new Column({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5])});
const col_1 =
new Column({type: new Float32, data: new Float32Buffer([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])});
const table_0 = new Table({columns: [col_0, col_1]});
const selection = new Column({type: new Int32, data: new Int32Buffer([2, 4, 5])});
const result = table_0.gather(selection, false);
expect(result.numRows).toBe(3);
const r0 = result.getColumnByIndex(0);
const r1 = result.getColumnByIndex(1);
expect(r0.type.typeId).toBe(arrow.Type.Int);
expect(r0.type.bitWidth).toBe(32);
expect(r0.getValue(0)).toBe(2);
expect(r0.getValue(1)).toBe(4);
expect(r0.getValue(2)).toBe(5);
expect(r1.type.typeId).toBe(arrow.Type.Float);
expect(r1.type.precision).toBe(arrow.Precision.SINGLE);
expect(r1.getValue(0)).toBe(2.0);
expect(r1.getValue(1)).toBe(4.0);
expect(r1.getValue(2)).toBe(5.0);
});
test('Table.applyBooleanMask', () => {
const col_0 = new Column({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5])});
const col_1 =
new Column({type: new Float32, data: new Float32Buffer([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])});
const table_0 = new Table({columns: [col_0, col_1]});
const selection = new Column({
length: 6,
type: new Bool8,
data: new Uint8Buffer([0, 0, 1, 0, 1, 1]),
});
const result = table_0.applyBooleanMask(selection);
expect(result.numRows).toBe(3);
const r0 = result.getColumnByIndex(0);
const r1 = result.getColumnByIndex(1);
expect(r0.type.typeId).toBe(arrow.Type.Int);
expect(r0.type.bitWidth).toBe(32);
expect(r0.getValue(0)).toBe(2);
expect(r0.getValue(1)).toBe(4);
expect(r0.getValue(2)).toBe(5);
expect(r1.type.typeId).toBe(arrow.Type.Float);
expect(r1.type.precision).toBe(arrow.Precision.SINGLE);
expect(r1.getValue(0)).toBe(2.0);
expect(r1.getValue(1)).toBe(4.0);
expect(r1.getValue(2)).toBe(5.0);
});
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-scope-test.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DataFrame, scope, Series} from '@rapidsai/cudf';
test('basic disposes', () => {
let test: any = null;
const result = scope(() => {
test = Series.sequence({size: 20});
return Series.sequence({size: 30});
});
expect(test._col.disposed).toBe(true);
expect(result._col.disposed).toBe(false);
});
test('basic disposes promise', async () => {
let test: any = null;
// eslint-disable-next-line @typescript-eslint/require-await
const promise = scope(async () => {
test = Series.sequence({size: 20});
return Series.sequence({size: 30});
});
const resolver = async () => promise;
const result = await resolver();
expect(test._col.disposed).toBe(true);
expect(result._col.disposed).toBe(false);
});
test('explicit keep', () => {
let test: any = null;
const outer = Series.sequence({size: 30});
const result = scope(() => {
test = Series.sequence({size: 20});
const inner = Series.sequence({size: 30});
return new DataFrame({
outer: outer,
inner: inner,
});
}, [outer]);
expect(test._col.disposed).toBe(true);
expect(result.get('inner')._col.disposed).toBe(false);
expect(result.get('outer')._col.disposed).toBe(false);
});
test('nested disposes', () => {
const outer = Series.sequence({size: 30});
let test_inner: any = null;
let test_middle: any = null;
const result = scope(() => {
const middle = Series.sequence({size: 30});
test_middle = Series.sequence({size: 20});
const result = scope(() => {
test_inner = Series.sequence({size: 20});
const inner = Series.sequence({size: 30});
return new DataFrame({
inner: inner,
});
});
expect(test_inner._col.disposed).toBe(true);
expect(test_middle._col.disposed).toBe(false);
expect(result.get('inner')._col.disposed).toBe(false);
expect(middle._col.disposed).toBe(false);
return result.assign({middle: middle});
});
expect(test_inner._col.disposed).toBe(true);
expect(test_middle._col.disposed).toBe(true);
expect(result.get('middle')._col.disposed).toBe(false);
expect(result.get('inner')._col.disposed).toBe(false);
expect(outer._col.disposed).toBe(false);
});
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/tsconfig.json
|
{
"extends": "../tsconfig.json",
"include": [
"../src/**/*.ts",
"../test/**/*.ts"
],
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"allowJs": true,
"importHelpers": false,
"noEmitHelpers": false,
"noEmitOnError": false,
"sourceMap": false,
"inlineSources": false,
"inlineSourceMap": false,
"downlevelIteration": false,
"baseUrl": "../",
"paths": {
"@rapidsai/cudf": ["src/index"],
"@rapidsai/cudf/*": ["src/*"]
}
}
}
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-data-frame-tests.ts
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float32Buffer, Int32Buffer, setDefaultAllocator, Uint8Buffer} from '@rapidsai/cuda';
import {
Bool8,
DataFrame,
Float32,
GroupByMultiple,
GroupBySingle,
Int32,
Int8,
Series,
Table
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr));
test('DataFrame initialization', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const table_0 = new DataFrame({'col_0': col_0, 'col_1': col_1});
expect(table_0.numColumns).toBe(2);
expect(table_0.numRows).toBe(length);
expect(table_0.names).toStrictEqual(['col_0', 'col_1']);
expect(table_0.get('col_0').type.typeId).toBe(col_0.type.typeId);
expect(table_0.get('col_1').type.typeId).toBe(col_1.type.typeId);
});
test('Empty DataFrame initialization', () => {
const table_0 = new DataFrame({});
expect(table_0.numColumns).toBe(0);
expect(table_0.numRows).toBe(0);
expect(table_0.names).toStrictEqual([]);
const table_1 = new DataFrame();
expect(table_1.numColumns).toBe(0);
expect(table_1.numRows).toBe(0);
expect(table_1.names).toStrictEqual([]);
});
test('DataFrame asTable', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const table_0 = new DataFrame({'col_0': col_0, 'col_1': col_1});
expect(table_0.asTable()).toBeInstanceOf(Table);
});
test('DataFrame.get', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const table_0 = new DataFrame({'col_0': col_0, 'col_1': col_1});
expect(table_0.get('col_0').type.typeId).toBe(col_0.type.typeId);
expect(() => { (<any>table_0).get(2); }).toThrow();
expect(() => { (<any>table_0).get('junk'); }).toThrow();
});
test('DataFrame.select', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const col_2 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_3 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const table_0 = new DataFrame({'col_0': col_0, 'col_1': col_1, 'col_2': col_2, 'col_3': col_3});
expect(table_0.numColumns).toBe(4);
expect(table_0.numRows).toBe(length);
expect(table_0.names).toStrictEqual(['col_0', 'col_1', 'col_2', 'col_3']);
expect(table_0.select(['col_0'])).toStrictEqual(new DataFrame({'col_0': col_0}));
expect(table_0.select(['col_0', 'col_3']))
.toStrictEqual(new DataFrame({'col_0': col_0, 'col_3': col_3}));
});
test('DataFrame.assign', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const col_2 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_3 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_4 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const table_0 = new DataFrame({col_0, col_1, col_2, 'col_3': col_1});
const table_1 = table_0.assign({col_3});
expect(table_1.numColumns).toBe(4);
expect(table_1.numRows).toBe(length);
expect(table_1.names).toStrictEqual(['col_0', 'col_1', 'col_2', 'col_3']);
// testing DataFrame.assign(DataFrame)
const table_2 = new DataFrame({col_4});
const table_3 = table_0.assign(table_2);
expect(table_3.numColumns).toBe(5);
expect(table_3.numRows).toBe(length);
expect(table_3.names).toStrictEqual(['col_0', 'col_1', 'col_2', 'col_3', 'col_4']);
});
test('DataFrame.drop', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const col_2 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const table_0 = new DataFrame({'col_0': col_0, 'col_1': col_1, 'col_2': col_2});
const table_1 = table_0.drop(['col_1']);
expect(table_1.numColumns).toBe(2);
expect(table_1.numRows).toBe(length);
expect(table_1.names).toStrictEqual(['col_0', 'col_2']);
});
test('DataFrame.rename', () => {
const length = 100;
const col_0 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const col_1 = Series.new({
type: new Bool8(),
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64),
});
const col_2 = Series.new({type: new Int32(), data: new Int32Buffer(length)});
const table_0 = new DataFrame({col_0, col_1, col_2});
const table_1 = table_0.rename({col_1: 'col_1_renamed', col_2: 2});
expect(table_1.numColumns).toBe(3);
expect(table_1.numRows).toBe(length);
expect(table_1.names).toStrictEqual(['2', 'col_0', 'col_1_renamed']);
});
test('DataFrame.orderBy (ascending, non-null)', () => {
const col = Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: true, null_order: 'before'}});
const expected = [5, 0, 4, 1, 3, 2];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.orderBy (descending, non-null)', () => {
const col = Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: false, null_order: 'before'}});
const expected = [2, 3, 1, 4, 0, 5];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.orderBy (ascending, null before)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: true, null_order: 'before'}});
const expected = [1, 5, 0, 4, 3, 2];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.orderBy (ascending, null after)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: true, null_order: 'after'}});
const expected = [5, 0, 4, 3, 2, 1];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.orderBy (descendng, null before)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: false, null_order: 'before'}});
const expected = [2, 3, 4, 0, 5, 1];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.orderBy (descending, null after)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32(), data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const df = new DataFrame({'a': col});
const result = df.orderBy({'a': {ascending: false, null_order: 'after'}});
const expected = [1, 2, 3, 4, 0, 5];
expect([...result]).toEqual([...Buffer.from(expected)]);
});
test('DataFrame.gather (indices)', () => {
const a = Series.new({type: new Int32(), data: new Int32Buffer([0, 1, 2, 3, 4, 5])});
const b =
Series.new({type: new Float32(), data: new Float32Buffer([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])});
const df = new DataFrame({'a': a, 'b': b});
const selection = Series.new({type: new Int32(), data: new Int32Buffer([2, 4, 5])});
const result = df.gather(selection);
expect(result.numRows).toBe(3);
const ra = result.get('a');
const rb = result.get('b');
const expected_a = Series.new({type: new Int32(), data: new Int32Buffer([2, 4, 5])});
expect([...ra]).toEqual([...expected_a]);
const expected_b = Series.new({type: new Float32(), data: new Float32Buffer([2.0, 4.0, 5.0])});
expect([...rb]).toEqual([...expected_b]);
});
describe('Dataframe.head', () => {
const a = Series.new([0, 1, 2, 3, 4, 5, 6]);
const b = Series.new([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]);
const c = Series.new(['foo', null, null, 'bar', null, null, 'foo']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
test('default n', () => {
const result = df.head();
expect(result.numRows).toEqual(5);
expect([...result.get('a')]).toEqual([0, 1, 2, 3, 4]);
expect([...result.get('b')]).toEqual([0.0, 1.1, 2.2, 3.3, 4.4]);
expect([...result.get('c')]).toEqual(['foo', null, null, 'bar', null]);
});
test('invalid n', () => { expect(() => df.head(-1)).toThrowError(); });
test('providing n', () => {
const result = df.head(2);
expect(result.numRows).toEqual(2);
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([0.0, 1.1]);
expect([...result.get('c')]).toEqual(['foo', null]);
});
test('n longer than length of series', () => {
const result = df.head(25);
expect(result.numRows).toEqual(7);
expect([...result.get('a')]).toEqual([...a]);
expect([...result.get('b')]).toEqual([...b]);
expect([...result.get('c')]).toEqual([...c]);
});
});
describe('Dataframe.tail', () => {
const a = Series.new([0, 1, 2, 3, 4, 5, 6]);
const b = Series.new([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]);
const c = Series.new(['foo', null, null, 'bar', null, null, 'foo']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
test('default n', () => {
const result = df.tail();
expect(result.numRows).toEqual(5);
expect([...result.get('a')]).toEqual([2, 3, 4, 5, 6]);
expect([...result.get('b')]).toEqual([2.2, 3.3, 4.4, 5.5, 6.6]);
expect([...result.get('c')]).toEqual([null, 'bar', null, null, 'foo']);
});
test('invalid n', () => { expect(() => df.tail(-1)).toThrowError(); });
test('providing n', () => {
const result = df.tail(2);
expect(result.numRows).toEqual(2);
expect([...result.get('a')]).toEqual([5, 6]);
expect([...result.get('b')]).toEqual([5.5, 6.6]);
expect([...result.get('c')]).toEqual([null, 'foo']);
});
test('n longer than length of series', () => {
const result = df.tail(25);
expect(result.numRows).toEqual(7);
expect([...result.get('a')]).toEqual([...a]);
expect([...result.get('b')]).toEqual([...b]);
expect([...result.get('c')]).toEqual([...c]);
});
});
test('DataFrame groupBy (single)', () => {
const a = Series.new({type: new Int32, data: [1, 2, 3, 1, 2, 2, 1, 3, 3, 2]});
const b = Series.new({type: new Float32, data: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]});
const df = new DataFrame({'a': a, 'b': b});
const out = df.groupBy({by: 'a'});
expect(out instanceof GroupBySingle).toBe(true);
});
test('DataFrame groupBy (multiple)', () => {
const a = Series.new({type: new Int32, data: [1, 2, 3, 1, 2, 2, 1, 3, 3, 2]});
const aa = Series.new({type: new Int32, data: [1, 2, 3, 1, 2, 2, 1, 3, 3, 2]});
const b = Series.new({type: new Float32, data: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]});
const df = new DataFrame({'a': a, 'aa': aa, 'b': b});
const out = df.groupBy({by: ['a', 'aa'], index_key: 'ind'});
expect(out instanceof GroupByMultiple).toBe(true);
});
test('DataFrame filter', () => {
const a = Series.new({type: new Int32(), data: new Int32Buffer([0, 1, 2, 3, 4, 5])});
const b =
Series.new({type: new Float32(), data: new Float32Buffer([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])});
const df = new DataFrame({'a': a, 'b': b});
const mask =
Series.new({length: 6, type: new Bool8(), data: new Uint8Buffer([0, 0, 1, 0, 1, 1])});
const result = df.filter(mask);
expect(result.numRows).toBe(3);
const ra = result.get('a');
const rb = result.get('b');
const expected_a = Series.new({type: new Int32(), data: new Int32Buffer([2, 4, 5])});
expect([...ra]).toEqual([...expected_a]);
const expected_b = Series.new({type: new Float32(), data: new Float32Buffer([2.0, 4.0, 5.0])});
expect([...rb]).toEqual([...expected_b]);
});
test(
'dataframe.dropNulls(axis=0, thresh=df.numColumns), drop rows with non-null values < numColumn (drop row if atleast one null)',
() => {
const a = Series.new({
type: new Float32,
data: [null, 1, null, null, null, null],
});
const b = Series.new({
type: new Float32,
data: [null, 1, null, null, null, null],
});
const c = Series.new({
type: new Float32,
data: [1, null, 3, 4, 5, 6],
});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
// all rows are dropped, since every row contains atleast one Null value
const result = df.dropNulls(0, df.numColumns);
expect(result.numRows).toEqual(0);
});
test(
'dataframe.dropNulls(axis=0, thresh=1), drop rows with non-null values < 1 (drop row if all null)',
() => {
const a = Series.new({
type: new Float32,
data: [null, 1, null, null, null, null],
});
const b = Series.new({
type: new Float32,
data: [null, 1, null, null, null, null],
});
const c = Series.new({
type: new Float32,
data: [null, 2, 3, 4, 5, 6],
});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const expected_a = Series.new({type: new Float32, data: [1, null, null, null, null]});
const expected_c = Series.new({type: new Float32, data: [2, 3, 4, 5, 6]});
// row 1 is dropped as it contains all Nulls
const result = df.dropNulls(0, 1);
const ra = result.get('a');
const rc = result.get('c');
expect([...ra]).toEqual([...expected_a]);
expect([...rc]).toEqual([...expected_c]);
expect(result.numRows).toEqual(5);
});
test(
'dataframe.dropNulls(axis=1, thresh=1), drop columns with non-null values < 1 (drop if all null)',
() => {
const a = Series.new({
type: new Float32,
data: [null, 1, null, null, null, null],
});
const b = Series.new({
type: new Float32,
data: [null, 1, 2, 3, 4, null],
});
const c = Series.new({
type: new Float32,
data: [null, null, null, null, null, null],
});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.dropNulls(1, 1);
// column c is dropped as it contains all Null values
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(['a', 'b']);
});
test(
'dataframe.dropNulls(axis=1, thresh=df.numRows), drop columns with non-ull values < numRows (drop if atleast one null)',
() => {
const a = Series.new({type: new Float32, data: [0, 1, null, 3, 4, 4]});
const b = Series.new({type: new Float32, data: [0, 1, 3, 5, 5, null]});
const c = Series.new({type: new Float32, data: [1, 2, 3, null, 5, 6]});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.dropNulls(1, df.numRows);
// all columns are dropped as each one contains atleast one null value
expect(result.numColumns).toEqual(0);
expect(result.names).toEqual([]);
});
test(
'dataframe.dropNaNs(axis=0, thresh=df.numColumns), drop row with non-NaN values < numColumn (drop row if atleast one NaN)',
() => {
const a = Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]});
const d = Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]});
const b = Series.new({type: new Float32, data: [0, NaN, 3, 5, 5, 6]});
const c = Series.new({type: new Float32, data: [NaN, NaN, NaN, NaN, NaN, NaN]});
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
// all rows are dropped, since every row contains atleast one NaN value
const result = df.dropNaNs(0, df.numColumns);
expect(result.numRows).toEqual(0);
});
test('dataframe.dropNaNs(axis=0, thresh=1), drop row with non-NaN values < 1 (drop row if all NaN)',
() => {
const a = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const d = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const b = Series.new({type: new Float32, data: [0, NaN, 3, 5, 5, 6]});
const c = Series.new({type: new Float32, data: [NaN, NaN, NaN, NaN, NaN, NaN]});
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
const expected_a = Series.new({type: new Float32, data: [0, 2, 3, 4, 4]});
// row 1 is dropped as it contains all NaNs
const result = df.dropNaNs(0, 1);
const ra = result.get('a');
expect([...ra]).toEqual([...expected_a]);
expect(result.numRows).toEqual(5);
});
test('dataframe.dropNaNs(axis=1, thresh=1), drop columns with non-NaN values < 1 (drop if all NaN)',
() => {
const a = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const b = Series.new({type: new Float32, data: [0, NaN, 3, 5, 5, 6]});
const c = Series.new({type: new Float32, data: [NaN, NaN, NaN, NaN, NaN, NaN]});
const d = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
const result = df.dropNaNs(1, 1);
// column c is dropped as it contains all NaN values
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(['a', 'b', 'd']);
});
test(
'dataframe.dropNaNs(axis=1, thresh=df.numRows), drop columns with non-NaN values < numRows (drop if atleast one NaN)',
() => {
const a = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const b = Series.new({type: new Float32, data: [0, NaN, 3, 5, 5, 6]});
const c = Series.new({type: new Float32, data: [NaN, NaN, NaN, NaN, NaN, NaN]});
const d = Series.new({type: new Float32, data: [0, NaN, 2, 3, 4, 4]});
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
const result = df.dropNaNs(1, df.numRows);
// all columns are dropped as each one contains atleast one null value
expect(result.numColumns).toEqual(0);
expect(result.names).toEqual([]);
});
test('dataframe.cast', () => {
const a = Series.new({type: new Int32, data: [1, 2, 3, 4]});
const b = Series.new({type: new Float32, data: new Float32Buffer([1.5, 2.3, 3.1, 4])});
const df = new DataFrame({'a': a, 'b': b});
const result = df.cast({b: new Int32});
expect(result.get('a').type).toBeInstanceOf(Int32);
expect(result.get('b').type).toBeInstanceOf(Int32);
expect([...result.get('b')]).toEqual([1, 2, 3, 4]);
});
test('dataframe.castAll', () => {
const a = Series.new({type: new Int8, data: [1, 2, 3, 4]});
const b = Series.new({type: new Float32, data: new Float32Buffer([1.5, 2.3, 3.1, 4])});
const df = new DataFrame({'a': a, 'b': b});
const result = df.castAll(new Int32);
expect(result.get('a').type).toBeInstanceOf(Int32);
expect(result.get('b').type).toBeInstanceOf(Int32);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('b')]).toEqual([1, 2, 3, 4]);
});
describe('dataframe unaryops', () => {
const a = Series.new({type: new Int32, data: [-3, 0, 3]});
const b = Series.new({type: new Int8, data: [-3, 0, 3]});
const c = Series.new({type: new Float32, data: [-2.7, 0, 3.1]});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const d = Series.new(['foo', 'bar', 'foo']);
// If a unary op is performed on this df, the result will be `never`
// due to the df containing a string series.
// (unary ops only support numeric series)
const non_numeric_df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
test('dataframe.sin', () => {
const result = df.sin();
expect([...result.get('a')]).toEqual([0, 0, 0]);
expect([...result.get('b')]).toEqual([0, 0, 0]);
expect([...result.get('c')]).toEqual([...c.sin()]);
expect(() => _verifyIsNever(non_numeric_df.sin())).toThrow();
});
test('dataframe.cos', () => {
const result = df.cos();
expect([...result.get('a')]).toEqual([0, 1, 0]);
expect([...result.get('b')]).toEqual([0, 1, 0]);
expect([...result.get('c')]).toEqual([...c.cos()]);
expect(() => _verifyIsNever(non_numeric_df.cos())).toThrow();
});
test('dataframe.tan', () => {
const result = df.tan();
expect([...result.get('a')]).toEqual([0, 0, 0]);
expect([...result.get('b')]).toEqual([0, 0, 0]);
expect([...result.get('c')]).toEqual([...c.tan()]);
expect(() => _verifyIsNever(non_numeric_df.tan())).toThrow();
});
test('dataframe.asin', () => {
const result = df.asin();
expect([...result.get('a')]).toEqual([-2147483648, 0, -2147483648]);
expect([...result.get('b')]).toEqual([0, 0, 0]);
expect([...result.get('c')]).toEqual([...c.asin()]);
expect(() => _verifyIsNever(non_numeric_df.asin())).toThrow();
});
test('dataframe.acos', () => {
const result = df.acos();
expect([...result.get('a')]).toEqual([-2147483648, 1, -2147483648]);
expect([...result.get('b')]).toEqual([0, 1, 0]);
expect([...result.get('c')]).toEqual([...c.acos()]);
expect(() => _verifyIsNever(non_numeric_df.acos())).toThrow();
});
test('dataframe.atan', () => {
const result = df.atan();
expect([...result.get('a')]).toEqual([-1, 0, 1]);
expect([...result.get('b')]).toEqual([-1, 0, 1]);
expect([...result.get('c')]).toEqual([...c.atan()]);
expect(() => _verifyIsNever(non_numeric_df.atan())).toThrow();
});
test('dataframe.sinh', () => {
const result = df.sinh();
expect([...result.get('a')]).toEqual([-10, 0, 10]);
expect([...result.get('b')]).toEqual([-10, 0, 10]);
expect([...result.get('c')]).toEqual([...c.sinh()]);
expect(() => _verifyIsNever(non_numeric_df.sinh())).toThrow();
});
test('dataframe.cosh', () => {
const result = df.cosh();
expect([...result.get('a')]).toEqual([10, 1, 10]);
expect([...result.get('b')]).toEqual([10, 1, 10]);
expect([...result.get('c')]).toEqual([...c.cosh()]);
expect(() => _verifyIsNever(non_numeric_df.cosh())).toThrow();
});
test('dataframe.tanh', () => {
const result = df.tanh();
expect([...result.get('a')]).toEqual([0, 0, 0]);
expect([...result.get('b')]).toEqual([0, 0, 0]);
expect([...result.get('c')]).toEqual([...c.tanh()]);
expect(() => _verifyIsNever(non_numeric_df.tanh())).toThrow();
});
test('dataframe.asinh', () => {
const result = df.asinh();
expect([...result.get('a')]).toEqual([-1, 0, 1]);
expect([...result.get('b')]).toEqual([-1, 0, 1]);
expect([...result.get('c')]).toEqual([...c.asinh()]);
expect(() => _verifyIsNever(non_numeric_df.asinh())).toThrow();
});
test('dataframe.acosh', () => {
const result = df.acosh();
expect([...result.get('a')]).toEqual([-2147483648, -2147483648, 1]);
expect([...result.get('b')]).toEqual([0, 0, 1]);
expect([...result.get('c')]).toEqual([...c.acosh()]);
expect(() => _verifyIsNever(non_numeric_df.acosh())).toThrow();
});
test('dataframe.atanh', () => {
const result = df.atanh();
expect([...result.get('a')]).toEqual([-2147483648, 0, -2147483648]);
expect([...result.get('b')]).toEqual([0, 0, 0]);
expect([...result.get('c')]).toEqual([...c.atanh()]);
expect(() => _verifyIsNever(non_numeric_df.atanh())).toThrow();
});
test('dataframe.exp', () => {
const result = df.exp();
expect([...result.get('a')]).toEqual([0, 1, 20]);
expect([...result.get('b')]).toEqual([0, 1, 20]);
expect([...result.get('c')]).toEqual([...c.exp()]);
expect(() => _verifyIsNever(non_numeric_df.exp())).toThrow();
});
test('dataframe.log', () => {
const result = df.log();
expect([...result.get('a')]).toEqual([-2147483648, -2147483648, 1]);
expect([...result.get('b')]).toEqual([0, 0, 1]);
expect([...result.get('c')]).toEqual([...c.log()]);
expect(() => _verifyIsNever(non_numeric_df.log())).toThrow();
});
test('dataframe.sqrt', () => {
const result = df.sqrt();
expect([...result.get('a')]).toEqual([-2147483648, 0, 1]);
expect([...result.get('b')]).toEqual([0, 0, 1]);
expect([...result.get('c')]).toEqual([...c.sqrt()]);
expect(() => _verifyIsNever(non_numeric_df.sqrt())).toThrow();
});
test('dataframe.cbrt', () => {
const result = df.cbrt();
expect([...result.get('a')]).toEqual([-1, 0, 1]);
expect([...result.get('b')]).toEqual([-1, 0, 1]);
expect([...result.get('c')]).toEqual([...c.cbrt()]);
expect(() => _verifyIsNever(non_numeric_df.cbrt())).toThrow();
});
test('dataframe.ceil', () => {
const result = df.ceil();
expect([...result.get('a')]).toEqual([-3, 0, 3]);
expect([...result.get('b')]).toEqual([-3, 0, 3]);
expect([...result.get('c')]).toEqual([...c.ceil()]);
expect(() => _verifyIsNever(non_numeric_df.ceil())).toThrow();
});
test('dataframe.floor', () => {
const result = df.floor();
expect([...result.get('a')]).toEqual([-3, 0, 3]);
expect([...result.get('b')]).toEqual([-3, 0, 3]);
expect([...result.get('c')]).toEqual([...c.floor()]);
expect(() => _verifyIsNever(non_numeric_df.floor())).toThrow();
});
test('dataframe.abs', () => {
const result = df.abs();
expect([...result.get('a')]).toEqual([3, 0, 3]);
expect([...result.get('b')]).toEqual([3, 0, 3]);
expect([...result.get('c')]).toEqual([...c.abs()]);
expect(() => _verifyIsNever(non_numeric_df.abs())).toThrow();
});
test('dataframe.not', () => {
const result = df.not();
expect([...result.get('a')]).toEqual([-3, 0, 3].map((x) => !x));
expect([...result.get('b')]).toEqual([-3, 0, 3].map((x) => !x));
expect([...result.get('c')]).toEqual([...c.not()]);
expect(() => _verifyIsNever(non_numeric_df.not())).toThrow();
});
});
describe('dataframe.replaceNulls', () => {
test('replace with scalar', () => {
const a = Series.new([1, 2, 3, null]);
const b = Series.new([null, null, 7, null]);
const c = Series.new([null, null, null, null]);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.replaceNulls(4);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('b')]).toEqual([4, 4, 7, 4]);
expect([...result.get('c')]).toEqual([4, 4, 4, 4]);
// compare with series.replaceNulls result
expect([...result.get('a')]).toEqual([...a.replaceNulls(4)]);
expect([...result.get('b')]).toEqual([...b.replaceNulls(4)]);
expect([...result.get('c')]).toEqual([...c.replaceNulls(4)]);
});
test('replace with seriesmap', () => {
const a = Series.new([1, 2, 3, null]);
const b = Series.new(['foo', 'bar', null, null]);
const c = Series.new([null, false, null, true]);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.replaceNulls({
'a': Series.new([1, 2, 3, 4]),
'b': Series.new(['foo', 'bar', 'foo', 'bar']),
'c': Series.new([false, false, true, true])
});
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('b')]).toEqual(['foo', 'bar', 'foo', 'bar']);
expect([...result.get('c')]).toEqual([false, false, true, true]);
// compare with series.replaceNulls result
expect([...result.get('a')]).toEqual([...a.replaceNulls(Series.new([1, 2, 3, 4]))]);
expect([...result.get('b')]).toEqual([...b.replaceNulls(
Series.new(['foo', 'bar', 'foo', 'bar']))]);
expect([...result.get('c')]).toEqual([...c.replaceNulls(
Series.new([false, false, true, true]))]);
});
});
test('dataframe.kurtosis', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([7, 8, 9, 10]);
const df = new DataFrame({'a': a, 'b': b});
expect([...df.kurtosis()]).toEqual([-1.1999999999999904, -1.2000000000000686]);
const c = Series.new(['foo', 'bar', 'foo', 'bar']);
const invalid_kurtosis_df = new DataFrame({'a': a, 'b': b, 'c': c});
expect(() => _verifyIsNever(invalid_kurtosis_df.kurtosis())).toThrow();
});
test('dataframe.skew', () => {
const a = Series.new([1, 2, 3, 4, 5, 6, 6]);
const b = Series.new([7, 8, 9, 10, 11, 12, 12]);
const df = new DataFrame({'a': a, 'b': b});
expect([...df.skew()]).toEqual([-0.288195490292614, -0.2881954902926153]);
const c = Series.new(['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo']);
const invalid_skew_df = new DataFrame({'a': a, 'b': b, 'c': c});
expect(() => _verifyIsNever(invalid_skew_df.skew())).toThrow();
});
test('dataframe.nansToNulls', () => {
const a = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 4]});
const b = Series.new({type: new Float32, data: new Float32Buffer([0, NaN, 3, 5, 5, 6])});
const df = new DataFrame({'a': a, 'b': b});
expect(df.get('b').nullCount).toEqual(0);
const result = df.nansToNulls();
expect(result.get('b').nullCount).toEqual(1);
});
test('dataframe.isNaN', () => {
const a = Series.new({type: new Int32, data: [0, null, 2, 3, null]});
const b = Series.new({type: new Float32, data: [NaN, 0, 3, NaN, null]});
const c = Series.new([null, null, 'foo', 'bar', '']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.isNaN();
const expected_a = Series.new(a);
const expected_b = Series.new([true, false, false, true, false]);
const expected_c = Series.new(c);
expect([...result.get('a')]).toEqual([...expected_a]);
expect([...result.get('b')]).toEqual([...expected_b]);
expect([...result.get('c')]).toEqual([...expected_c]);
});
test('dataframe.isNull', () => {
const a = Series.new([0, null, 2, 3, null]);
const b = Series.new([NaN, 0, 3, NaN, null]);
const c = Series.new([null, null, 'foo', 'bar', '']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.isNull();
const expected_a = Series.new({type: new Bool8, data: [false, true, false, false, true]});
const expected_b = Series.new({type: new Bool8, data: [false, false, false, false, true]});
const expected_c = Series.new({type: new Bool8, data: [true, true, false, false, false]});
expect([...result.get('a')]).toEqual([...expected_a]);
expect([...result.get('b')]).toEqual([...expected_b]);
expect([...result.get('c')]).toEqual([...expected_c]);
});
test('dataframe.isNotNaN', () => {
const a = Series.new({type: new Float32, data: [0, NaN, 2, NaN, null]});
const b = Series.new({type: new Int32, data: [0, null, 2, 3, null]});
const c = Series.new([null, null, 'foo', 'bar', '']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.isNotNaN();
const expected_a = Series.new([true, false, true, false, true]);
const expected_b = Series.new(b);
const expected_c = Series.new(c);
expect([...result.get('a')]).toEqual([...expected_a]);
expect([...result.get('b')]).toEqual([...expected_b]);
expect([...result.get('c')]).toEqual([...expected_c]);
});
test('dataframe.isNotNull', () => {
const a = Series.new([null, 1, 2, 3, null]);
const b = Series.new([NaN, 0, 3, NaN, null]);
const c = Series.new(['foo', 'bar', null, null, '']);
const df = new DataFrame({'a': a, 'b': b, 'c': c});
const result = df.isNotNull();
const expected_a = Series.new({type: new Bool8, data: [false, true, true, true, false]});
const expected_b = Series.new({type: new Bool8, data: [true, true, true, true, false]});
const expected_c = Series.new({type: new Bool8, data: [true, true, false, false, true]});
expect([...result.get('a')]).toEqual([...expected_a]);
expect([...result.get('b')]).toEqual([...expected_b]);
expect([...result.get('c')]).toEqual([...expected_c]);
});
test.each`
keep | nullsEqual | nullsFirst | data | expected
${'first'} | ${true} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[null, 1, 3, 4], [null, 5, 8, 4]]}
${'last'} | ${true} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[null, 1, 3, 4], [null, 5, 8, 4]]}
${'none'} | ${true} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3], [5, 8]]}
${'first'} | ${false} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[null, null, 1, 3, 4], [null, null, 5, 8, 4]]}
${'last'} | ${false} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[null, null, 1, 3, 4], [null, null, 5, 8, 4]]}
${'none'} | ${false} | ${true} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[null, null, 1, 3], [null, null, 5, 8]]}
${'first'} | ${true} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3, 4, null], [5, 8, 4, null]]}
${'last'} | ${true} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3, 4, null], [5, 8, 4, null]]}
${'none'} | ${true} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3], [5, 8]]}
${'first'} | ${false} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3, 4, null, null], [5, 8, 4, null, null]]}
${'last'} | ${false} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3, 4, null, null], [5, 8, 4, null, null]]}
${'none'} | ${false} | ${false} | ${[[4, null, 1, null, 3, 4], [4, null, 5, null, 8, 4]]} | ${[[1, 3, null, null], [5, 8, null, null]]}
`('DataFrame.dropDuplicates($keep, $nullsEqual, $nullsFirst)', ({keep, nullsEqual, nullsFirst, data, expected}) => {
const a = Series.new(data[0]);
const b = Series.new(data[1]);
const df = new DataFrame({a, b});
const result = df.dropDuplicates(keep, nullsEqual, nullsFirst);
expect([...result.get('a')]).toEqual(expected[0]);
expect([...result.get('b')]).toEqual(expected[1]);
});
test(`DataFrame.dropDuplicates("first", true, true, ['a'])`, () => {
const a = Series.new([4, null, 1, null, 3, 4]);
const b = Series.new([2, null, 5, null, 8, 9]);
const df = new DataFrame({a, b});
const result = df.dropDuplicates('first', true, true, ['a']);
expect([...result.get('a')]).toEqual([null, 1, 3, 4]);
expect([...result.get('b')]).toEqual([null, 5, 8, 2]);
});
// Typescript does not allow us to throw a compile-time error if
// the result of a method is `never`. Instead, let's just verify
// the result is `never` by checking the parameter type.
function _verifyIsNever(_: never) { return _; }
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/jest-extensions.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {BigIntArray, TypedArray} from '@rapidsai/cuda';
import {zip} from 'ix/iterable';
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace jest {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Matchers<R> {
toEqualTypedArray<T extends TypedArray|BigIntArray>(expected: T): CustomMatcherResult;
}
}
}
expect.extend({
toEqualTypedArray,
});
function toEqualTypedArray<T extends TypedArray|BigIntArray>(
this: jest.MatcherUtils, actual: T, expected: T) {
const failures: Error[] = [];
if (actual instanceof Float32Array || actual instanceof Float64Array) {
for (const [x, y] of zip<number>(<any>actual, <any>expected)) {
try {
(isNaN(x) && isNaN(y)) ? expect(x).toBeNaN() : expect(x).toBeCloseTo(y);
} catch (e: any) { failures.push(e); }
}
} else {
try {
expect(actual).toEqual(expected);
} catch (e: any) { failures.push(e); }
}
return {
pass: failures.length === 0,
message: () => failures.join('\n'),
};
}
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-series-test.ts
|
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
Float32Buffer,
Float64Buffer,
Int16Buffer,
Int32Buffer,
Int64Buffer,
Int8Buffer,
setDefaultAllocator,
Uint16Buffer,
Uint32Buffer,
Uint64Buffer,
Uint8Buffer,
Uint8ClampedBuffer
} from '@rapidsai/cuda';
import {
Bool8,
Column,
Float32,
Float32Series,
Float64,
Float64Series,
Int16,
Int16Series,
Int32,
Int32Series,
Int64,
Int64Series,
Int8,
Int8Series,
Series,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
Uint16,
Uint16Series,
Uint32,
Uint32Series,
Uint64,
Uint64Series,
Uint8,
Uint8Series,
Utf8String
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {promises} from 'fs';
import * as Path from 'path';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr));
describe.each([
[Int8Series.name, Int8Series, Int8, Int8Array, Int8Buffer],
[Int16Series.name, Int16Series, Int16, Int16Array, Int16Buffer],
[Int32Series.name, Int32Series, Int32, Int32Array, Int32Buffer],
[Int64Series.name, Int64Series, Int64, BigInt64Array, Int64Buffer],
[Uint8Series.name, Uint8Series, Uint8, Uint8Array, Uint8Buffer],
[Uint16Series.name, Uint16Series, Uint16, Uint16Array, Uint16Buffer],
[Uint32Series.name, Uint32Series, Uint32, Uint32Array, Uint32Buffer],
[Uint64Series.name, Uint64Series, Uint64, BigUint64Array, Uint64Buffer],
[Float32Series.name, Float32Series, Float32, Float32Array, Float32Buffer],
[Float64Series.name, Float64Series, Float64, Float64Array, Float64Buffer],
[Uint8Series.name, Uint8Series, Uint8, Uint8ClampedArray, Uint8ClampedBuffer],
])(`%s initialization`,
(_: string, SeriesType: any, DType: any, ArrayType: any, BufferType: any) => {
const isBigInt = DType === Int64 || DType === Uint64;
const values = [1, 2, 3, 4, 5, 6].map(x => isBigInt ? BigInt(x) : x);
const nulls = values.slice() as any[];
nulls[2] = null;
nulls[4] = null;
const cases = [
[ArrayType.name, ArrayType],
[BufferType.name, BufferType],
];
test.each(cases)(`From %s`, (_: string, ArrayType: any) => {
const v = new ArrayType(values);
const s = Series.new(v);
expect(s).toBeInstanceOf(SeriesType);
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe((v.buffer instanceof DeviceBuffer) ? v.byteOffset / v.BYTES_PER_ELEMENT
: 0);
expect(s.nullCount).toBe(0);
expect(s.hasNulls).toBe(false);
expect(s.nullable).toBe(false);
});
test.each(cases)(`From %s (sliced)`, (_: string, ArrayType: any) => {
const v = new ArrayType(values).subarray(3);
const s = Series.new(v);
expect(s).toBeInstanceOf(SeriesType);
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe((v.buffer instanceof DeviceBuffer) ? v.byteOffset / v.BYTES_PER_ELEMENT
: 0);
expect(s.nullCount).toBe(0);
expect(s.hasNulls).toBe(false);
expect(s.nullable).toBe(false);
});
test.each(cases)(`From ColumnProps with data=%s (no nulls)`, (_: string, ArrayType: any) => {
const v = new ArrayType(values);
const s = Series.new({type: new DType, data: v});
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe((v.buffer instanceof DeviceBuffer) ? v.byteOffset / v.BYTES_PER_ELEMENT
: 0);
expect(s.nullCount).toBe(0);
expect(s.hasNulls).toBe(false);
expect(s.nullable).toBe(false);
});
test.each(cases)(`From ColumnProps with data=%s (with nulls)`, (_: string, ArrayType: any) => {
const v = new ArrayType(values);
const s = Series.new({type: new DType, data: v, nullMask: new Uint8Buffer([250])});
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe((v.buffer instanceof DeviceBuffer) ? v.byteOffset / v.BYTES_PER_ELEMENT
: 0);
expect(s.nullCount).toBe(2);
expect(s.hasNulls).toBe(true);
expect(s.nullable).toBe(true);
});
test.each(cases)(`From Column with data=%s`, (_: string, ArrayType: any) => {
const v = new ArrayType(values);
const s = Series.new(new Column({type: new DType, data: v}));
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe((v.buffer instanceof DeviceBuffer) ? v.byteOffset / v.BYTES_PER_ELEMENT
: 0);
expect(s.nullCount).toBe(0);
expect(s.hasNulls).toBe(false);
expect(s.nullable).toBe(false);
});
test(`From Array of mixed values`, () => {
const v = nulls.slice();
const s = Series.new({type: new DType, data: v});
expect(s.type).toBeInstanceOf(DType);
expect(s.length).toBe(v.length);
expect(s.offset).toBe(0);
expect(s.nullCount).toBe(2);
expect(s.hasNulls).toBe(true);
expect(s.nullable).toBe(true);
});
});
test('Series initialization with type inference', () => {
const a = Series.new([0, 1, 2, null]);
const b = Series.new(['foo', 'bar', 'test', null]);
const c = Series.new([0n, 1n, 2n, null]);
const d = Series.new([true, false, true, null]);
expect(a.type).toBeInstanceOf(Float64);
expect(b.type).toBeInstanceOf(Utf8String);
expect(c.type).toBeInstanceOf(Int64);
expect(d.type).toBeInstanceOf(Bool8);
});
test('test child(child_index), num_children', () => {
const utf8Col = Series.new({type: new Uint8, data: new Uint8Buffer(Buffer.from('hello'))});
const offsetsCol = Series.new({type: new Int32, data: new Int32Buffer([0, utf8Col.length])});
const stringsCol = Series.new({
type: new Utf8String(),
length: 1,
nullMask: new Uint8Buffer([255]),
children: [offsetsCol, utf8Col],
});
expect(stringsCol.type).toBeInstanceOf(Utf8String);
expect(stringsCol.numChildren).toBe(2);
expect(stringsCol.nullCount).toBe(0);
expect(stringsCol.getValue(0)).toBe('hello');
expect(stringsCol.offsets.length).toBe(offsetsCol.length);
expect(stringsCol.offsets.type).toBeInstanceOf(Int32);
expect(stringsCol.data.length).toBe(utf8Col.length);
expect(stringsCol.data.type).toBeInstanceOf(Uint8);
});
test('test mixed series/column children', () => {
const utf8Col = Series.new({type: new Uint8, data: new Uint8Buffer(Buffer.from('hello'))});
const offsetsCol = Series.new({type: new Int32, data: new Int32Buffer([0, utf8Col.length])});
const stringsCol = Series.new({
type: new Utf8String(),
length: 1,
nullMask: new Uint8Buffer([255]),
children: [offsetsCol, utf8Col._col],
});
expect(stringsCol.type).toBeInstanceOf(Utf8String);
expect(stringsCol.numChildren).toBe(2);
expect(stringsCol.nullCount).toBe(0);
expect(stringsCol.getValue(0)).toBe('hello');
expect(stringsCol.offsets.length).toBe(offsetsCol.length);
expect(stringsCol.offsets.type).toBeInstanceOf(Int32);
expect(stringsCol.data.length).toBe(utf8Col.length);
expect(stringsCol.data.type).toBeInstanceOf(Uint8);
});
test('Series.getValue', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
for (let i = 0; i < 10; i++) { expect(col.getValue(i)).toEqual(i); }
});
test('Series.setValue', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
col.setValue(2, 999);
col.setValue(4, 999);
col.setValue(5, 999);
col.setValue(8, 999);
expect([...col]).toEqual([0, 1, 999, 3, 999, 999, 6, 7, 999, 9]);
});
test('Series.setValues (series)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const values = Series.new({type: new Int32, data: [200, 400, 500, 800]});
const indices = Series.new({type: new Int32, data: [2, 4, 5, 8]});
col.setValues(indices, values);
expect([...col]).toEqual([0, 1, 200, 3, 400, 500, 6, 7, 800, 9]);
});
test('Series.setValues (scalar)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const indices = Series.new({type: new Int32, data: [2, 4, 5, 8]});
col.setValues(indices, 999);
expect([...col]).toEqual([0, 1, 999, 3, 999, 999, 6, 7, 999, 9]);
});
test('NumericSeries.cast', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4])});
expect(col.cast(new Int64).type).toBeInstanceOf(Int64);
expect(col.cast(new Float32).type).toBeInstanceOf(Float32);
expect(col.cast(new Float64).type).toBeInstanceOf(Float64);
const floatCol = Series.new({type: new Float32, data: new Float32Buffer([1.5, 2.8, 3.1, 4.2])});
const result = floatCol.cast(new Int32);
expect([...result]).toEqual([1, 2, 3, 4]);
});
test('NumericSeries.concat', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 2, 3, 4, 5])});
const colToConcat = Series.new({type: new Int32, data: new Int32Buffer([6, 7, 8, 9, 10])});
const result = col.concat(colToConcat);
expect([...result]).toEqual([...col, ...colToConcat]);
});
test('NumericSeries.concat up-casts to common dtype', () => {
const col = Series.new([1, 2, 3, 4, 5]).cast(new Int32);
const colToConcat = Series.new([6, 7, 8, 9, 10]);
const result = col.concat(colToConcat);
expect(result.type).toBeInstanceOf(Float64);
expect([...result]).toEqual([...col, ...colToConcat]);
});
test('Series.copy fixed width', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 2, 3, 4, 5])});
const result = col.copy();
expect([...result]).toEqual([...col]);
});
test('Series.copy String', () => {
const col = Series.new(['foo', 'bar', 'test', null]);
const result = col.copy();
expect([...result]).toEqual([...col]);
});
test('Series.gather', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
const selection = Series.new({type: new Int32, data: new Int32Buffer([2, 4, 5, 8])});
const result = col.gather(selection);
expect([...result]).toEqual([...selection]);
});
describe('Series.head', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
test('default n', () => { expect([...col.head()]).toEqual([0, 1, 2, 3, 4]); });
test('invalid n', () => { expect(() => col.head(-1)).toThrowError(); });
test('providing n', () => { expect([...col.head(8)]).toEqual([0, 1, 2, 3, 4, 5, 6, 7]); });
test('n longer than length of series', () => {
expect([...col.head(25)]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
});
describe('Series.tail', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
test('default n', () => { expect([...col.tail()]).toEqual([5, 6, 7, 8, 9]); });
test('invalid n', () => { expect(() => col.tail(-1)).toThrowError(); });
test('providing n', () => { expect([...col.tail(8)]).toEqual([2, 3, 4, 5, 6, 7, 8, 9]); });
test('n longer than length of series', () => {
expect([...col.tail(25)]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
});
describe('Series.nLargest', () => {
const col =
Series.new({type: new Int32, data: new Int32Buffer([9, 5, 0, 2, 1, 3, 4, 7, 6, 8, 0])});
test('default n', () => { expect([...col.nLargest()]).toEqual([9, 8, 7, 6, 5]); });
test('negative n', () => { expect([...col.nLargest(-1)]).toEqual([]); });
test('providing n', () => { expect([...col.nLargest(8)]).toEqual([9, 8, 7, 6, 5, 4, 3, 2]); });
test('n longer than length of series', () => {
expect([...col.nLargest(25)]).toEqual([9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0]);
});
test('keep last duplicate option', () => {
expect([...col.nLargest(25, 'last')]).toEqual([9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0]);
expect([...col.nLargest(-5, 'last')]).toEqual([]);
});
test('keep none duplicate option throws',
() => { expect(() => col.nLargest(25, 'none')).toThrow(); });
});
describe('Series.nSmallest', () => {
const col =
Series.new({type: new Int32, data: new Int32Buffer([9, 5, 0, 2, 1, 3, 4, 7, 6, 8, 0])});
test('default n', () => { expect([...col.nSmallest()]).toEqual([0, 0, 1, 2, 3]); });
test('negative n', () => { expect([...col.nSmallest(-1)]).toEqual([]); });
test('providing n', () => { expect([...col.nSmallest(8)]).toEqual([0, 0, 1, 2, 3, 4, 5, 6]); });
test('n longer than length of series', () => {
expect([...col.nSmallest(25)]).toEqual([0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
test('keep last duplicate option', () => {
expect([...col.nSmallest(25, 'last')]).toEqual([0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect([...col.nSmallest(-5, 'last')]).toEqual([]);
});
test('keep none duplicate option throws',
() => { expect(() => col.nSmallest(25, 'none')).toThrow(); });
});
test('Series.scatter (series)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const values = Series.new({type: new Int32, data: [200, 400, 500, 800]});
const indices = Series.new({type: new Int32, data: [2, 4, 5, 8]});
const result = col.scatter(values, indices);
expect([...result]).toEqual([0, 1, 200, 3, 400, 500, 6, 7, 800, 9]);
});
test('Series.scatter (series with array indices)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const values = Series.new({type: new Int32, data: [200, 400, 500, 800]});
const indices = [2, 4, 5, 8];
const result = col.scatter(values, indices);
expect([...result]).toEqual([0, 1, 200, 3, 400, 500, 6, 7, 800, 9]);
});
test('Series.scatter (scalar)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const indices = Series.new({type: new Int32, data: [2, 4, 5, 8]});
const result = col.scatter(999, indices);
expect([...result]).toEqual([0, 1, 999, 3, 999, 999, 6, 7, 999, 9]);
});
test('Series.scatter (scalar with array indicies)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const indices = [2, 4, 5, 8];
const result = col.scatter(999, indices);
expect([...result]).toEqual([0, 1, 999, 3, 999, 999, 6, 7, 999, 9]);
});
test('Series.scatter (scalar)', () => {
const col = Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const indices = Series.new({type: new Int32, data: [2, 4, 5, 8]});
const result = col.scatter(999, indices);
expect([...result]).toEqual([0, 1, 999, 3, 999, 999, 6, 7, 999, 9]);
});
test('Series.filter', () => {
const col = Series.new([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const mask = Series.new([false, false, true, false, true, true, false, false, true, false]);
const result = col.filter(mask);
const expected = Series.new({type: new Int32, data: new Int32Buffer([2, 4, 5, 8])});
expect([...result]).toEqual([...expected]);
});
describe('toArrow()', () => {
test('converts Uint8 Series to Uint8Vector', () => {
const uint8Col = Series.new({type: new Uint8, data: new Uint8Buffer(Buffer.from('hello'))});
const uint8Vec = uint8Col.toArrow();
expect(uint8Vec).toBeInstanceOf(arrow.Vector);
expect([...uint8Vec]).toEqual([...Buffer.from('hello')]);
});
test('converts String Series to Utf8Vector', () => {
const utf8Col = Series.new({type: new Uint8, data: new Uint8Buffer(Buffer.from('hello'))});
const offsetsCol = Series.new({type: new Int32, data: new Int32Buffer([0, utf8Col.length])});
const stringsCol = Series.new({
type: new Utf8String(),
length: 1,
nullMask: new Uint8Buffer([255]),
children: [offsetsCol, utf8Col],
});
const utf8Vec = stringsCol.toArrow();
expect(utf8Vec).toBeInstanceOf(arrow.Vector);
expect([...utf8Vec]).toEqual(['hello']);
});
});
test('Series.orderBy (ascending, non-null)', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const result = col.orderBy(true, 'before');
const expected = [5, 0, 4, 1, 3, 2];
expect([...result]).toEqual(expected);
});
test('Series.orderBy (descending, non-null)', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const result = col.orderBy(false, 'before');
const expected = [2, 3, 1, 4, 0, 5];
expect([...result]).toEqual(expected);
});
test('Series.orderBy (ascending, null before)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const result = col.orderBy(true, 'before');
const expected = [1, 5, 0, 4, 3, 2];
expect([...result]).toEqual(expected);
});
test('Series.orderBy (ascending, null after)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const result = col.orderBy(true, 'after');
const expected = [5, 0, 4, 3, 2, 1];
expect([...result]).toEqual(expected);
});
test('Series.orderBy (descendng, null before)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const result = col.orderBy(false, 'before');
const expected = [2, 3, 4, 0, 5, 1];
expect([...result]).toEqual(expected);
});
test('Series.orderBy (descending, null after)', () => {
const mask = arrow.vectorFromArray([1, 0, 1, 1, 1, 1], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0]), nullMask: mask});
const result = col.orderBy(false, 'after');
const expected = [1, 2, 3, 4, 0, 5];
expect([...result]).toEqual(expected);
});
test('Series.sortValues (ascending)', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const result = col.sortValues();
const expected = [0, 1, 2, 3, 4, 5];
expect([...result]).toEqual(expected);
});
test('Series.sortValues (descending)', () => {
const col = Series.new({type: new Int32, data: new Int32Buffer([1, 3, 5, 4, 2, 0])});
const result = col.sortValues(false);
const expected = [5, 4, 3, 2, 1, 0];
expect([...result]).toEqual(expected);
});
test('Series.isNull (numeric)', () => {
const col = Series.new({type: new Int32, data: [0, 1, null, 3, 4, null, 6, null]});
const result = col.isNull();
const expected = [false, false, true, false, false, true, false, true];
expect([...result]).toEqual(expected);
});
test('Series.isNotNull (numeric)', () => {
const col = Series.new({type: new Int32, data: [0, 1, null, 3, 4, null, 6, null]});
const result = col.isNotNull();
const expected = [true, true, false, true, true, false, true, false];
expect([...result]).toEqual(expected);
});
test('Series.dropNulls (drop nulls only)', () => {
const mask = arrow.vectorFromArray([0, 1, 1, 1, 1, 0], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Float32, data: new Float32Buffer([1, 3, NaN, 4, 2, 0]), nullMask: mask});
const result = col.dropNulls();
const expected = [3, NaN, 4, 2];
expect([...result]).toEqual(expected);
});
test('FloatSeries.dropNaNs (drop NaN values only)', () => {
const mask = arrow.vectorFromArray([0, 1, 1, 1, 1, 0], new arrow.Bool).data[0].values;
const col =
Series.new({type: new Float32, data: new Float32Buffer([1, 3, NaN, 4, 2, 0]), nullMask: mask});
const result = col.dropNaNs();
const expected = [null, 3, 4, 2, null];
expect([...result]).toEqual(expected);
});
test('Series.countNonNulls', () => {
const twoNonNulls = Series.new(['foo', null, 'bar']);
const fourNonNulls = Series.new([NaN, null, 10, 15, 17, null]);
const fiveNonNulls = Series.new([0, 1, null, 3, 4, null, 6, null]);
expect(twoNonNulls.countNonNulls()).toEqual(2);
expect(fourNonNulls.countNonNulls()).toEqual(4);
expect(fiveNonNulls.countNonNulls()).toEqual(5);
});
test('FloatSeries.nansToNulls', () => {
const col = Series.new({type: new Float32, data: new Float32Buffer([1, 3, NaN, 4, 2, 0])});
const result = col.nansToNulls();
const expected = [1, 3, null, 4, 2, 0];
expect([...result]).toEqual(expected);
expect(result.nullCount).toEqual(1);
expect(col.nullCount).toEqual(0);
});
test('Series.reverse', () => {
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const col = Series.new(array);
expect([...col.reverse()]).toEqual(array.reverse());
});
describe.each([new Int32, new Float32, new Float64])('Series.sequence({type=%p,, ...})', (typ) => {
test('no step', () => {
const col = Series.sequence({type: typ, size: 10, init: 0});
expect([...col]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
test('step=1', () => {
const col = Series.sequence({type: typ, size: 10, step: 1, init: 0});
expect([...col]).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
test('step=2', () => {
const col = Series.sequence({type: typ, size: 10, step: 2, init: 0});
expect([...col]).toEqual([0, 2, 4, 6, 8, 10, 12, 14, 16, 18]);
});
});
test('Series.valueCounts', () => {
const s = Series.new({type: new Int32, data: [110, 120, 100, 110, 120, 120]});
const result = s.valueCounts();
const count = [...result.count];
const value = [...result.value];
const countMap: Record<number, number> = {100: 1, 110: 2, 120: 3};
for (let i = 0; i < value.length; i++) {
const currentVal = value[i] as number;
const currentCount = count[i];
expect(currentCount).toBe(countMap[currentVal]);
}
});
test.each`
nullsEqual | data | expected
${true} | ${[null, null, 1, 2, 3, 4, 4]} | ${[null, 1, 2, 3, 4]}
${false} | ${[null, null, 1, 2, 3, 4, 4]} | ${[null, null, 1, 2, 3, 4]}
`('Series.unique($nullsEqual)', ({nullsEqual, data, expected}) => {
const s = Series.new({type: new Int32, data});
const result = s.unique(nullsEqual);
expect([...result]).toEqual(expected);
});
test.each`
data | replaceValue | expected
${[1, null, 3]} | ${Series.new([9, 9, 9])} | ${[1, 9, 3]}
${['foo', 'bar', null]} | ${Series.new(['test','test','test'])} | ${['foo', 'bar', 'test']}
${[true, false, null]} | ${Series.new([false, false, false])} | ${[true, false, false]}
${[1, null, 3]} | ${9} | ${[1, 9, 3]}
${['foo', 'bar', null]} | ${'test'} | ${['foo', 'bar', 'test']}
${[true, false, null]} | ${false} | ${[true, false, false]}
`('Series.replaceNulls', ({data, replaceValue, expected}) => {
const s = Series.new(data);
const result = s.replaceNulls(replaceValue);
expect([...result]).toEqual(expected);
});
test.each`
data | expected
${[1, null, 3]} | ${[1, 1, 3]}
${['foo', 'bar', null]} | ${['foo', 'bar', 'bar']}
${[true, false, null]} | ${[true, false, false]}
`('Series.replaceNullsPreceding', ({data, expected})=> {
const s = Series.new(data);
const result = s.replaceNullsPreceding();
expect([...result]).toEqual(expected);
});
test.each`
data | expected
${[1, null, 3]} | ${[1, 3, 3]}
${['foo', 'bar', null]} | ${['foo', 'bar', null]}
${[true, null, true]} | ${[true, true, true]}
`('Series.replaceNullsFollowing', ({data, expected})=> {
const s = Series.new(data);
const result = s.replaceNullsFollowing();
expect([...result]).toEqual(expected);
});
test('Series.TimestampDay (Int32Buffer)', () => {
const dateTime = Math.floor(new Date('May 13, 2021 16:38:30:100 GMT+00:00').getTime() / 86400000);
const s = Series.new({type: new TimestampDay, data: new Int32Buffer([dateTime])});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
});
test('Series.TimestampSecond (Int64Buffer)', () => {
const dateTime = Math.floor(new Date('May 13, 2021 16:38:30:100 GMT+00:00').getTime() / 1000);
const s = Series.new({type: new TimestampSecond, data: new Int64Buffer([dateTime].map(BigInt))});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
});
test('Series.TimestampMillisecond (Int64Buffer)', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00').getTime();
const s =
Series.new({type: new TimestampMillisecond, data: new Int64Buffer([dateTime].map(BigInt))});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series.TimestampNanosecond (Int64Buffer)', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00').getTime() * 1000;
const s =
Series.new({type: new TimestampMicrosecond, data: new Int64Buffer([dateTime].map(BigInt))});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series.TimestampMicrosecond (Int64Buffer)', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00').getTime() * 1000000;
const s =
Series.new({type: new TimestampNanosecond, data: new Int64Buffer([dateTime].map(BigInt))});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series.TimestampDay', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new({type: new TimestampDay, data: [dateTime]});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
});
test('Series.TimestampSecond', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new({type: new TimestampSecond, data: [dateTime]});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
});
test('Series.TimestampMillisecond', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new({type: new TimestampMillisecond, data: [dateTime]});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series.TimestampNanosecond', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new({type: new TimestampMicrosecond, data: [dateTime]});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series.TimestampMicrosecond', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new({type: new TimestampNanosecond, data: [dateTime]});
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test('Series initialization with Date', () => {
const dateTime = new Date('May 13, 2021 16:38:30:100 GMT+00:00');
const s = Series.new([dateTime]);
const val = s.getValue(0);
expect(val?.getUTCFullYear()).toBe(2021);
expect(val?.getUTCMonth()).toBe(4);
expect(val?.getUTCDate()).toBe(13);
expect(val?.getUTCHours()).toBe(16);
expect(val?.getUTCMinutes()).toBe(38);
expect(val?.getUTCSeconds()).toBe(30);
expect(val?.getUTCMilliseconds()).toBe(100);
});
test.each`
keep | nullsEqual | nullsFirst | data | expected
${true} | ${true} | ${true} | ${[4, null, 1, 2, null, 3, 4]} | ${[null, 1, 2, 3, 4]}
${false} | ${true} | ${true} | ${[4, null, 1, 2, null, 3, 4]} | ${[1, 2, 3]}
${true} | ${true} | ${false} | ${[4, null, 1, 2, null, 3, 4]} | ${[1, 2, 3, 4, null]}
${false} | ${true} | ${false} | ${[4, null, 1, 2, null, 3, 4]} | ${[1, 2, 3]}
${true} | ${false} | ${true} | ${[4, null, 1, 2, null, 3, 4]} | ${[null, null, 1, 2, 3, 4]}
${false} | ${false} | ${true} | ${[4, null, 1, 2, null, 3, 4]} | ${[null, null, 1, 2, 3]}
${true} | ${false} | ${false} | ${[4, null, 1, 2, null, 3, 4]} | ${[1, 2, 3, 4, null, null]}
${false} | ${false} | ${false} | ${[4, null, 1, 2, null, 3, 4]} | ${[1, 2, 3, null, null]}
`('Series.dropDuplicates($keep, $nullsEqual, $nullsFirst)', ({keep, nullsEqual, nullsFirst, data, expected}) => {
const s = Series.new({type: new Int32, data});
const result = s.dropDuplicates(keep, nullsEqual, nullsFirst);
expect([...result]).toEqual(expected);
});
describe('Series.readText', () => {
test('can read a json file', async () => {
const rows = [
{a: 0, b: 1.0, c: '2'},
{a: 1, b: 2.0, c: '3'},
{a: 2, b: 3.0, c: '4'},
];
const outputString = JSON.stringify(rows);
const path = Path.join(readTextTmpDir, 'simple.txt');
await promises.writeFile(path, outputString);
const text = Series.readText(path, '');
expect(text.toArray()).toEqual(outputString.split(''));
await new Promise<void>((resolve, reject) =>
rimraf(path, (err?: Error|null) => err ? reject(err) : resolve()));
});
test('can read a random file', async () => {
const outputString = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
const path = Path.join(readTextTmpDir, 'simple.txt');
await promises.writeFile(path, outputString);
const text = Series.readText(path, '');
expect(text.toArray()).toEqual(outputString.split(''));
await new Promise<void>((resolve, reject) =>
rimraf(path, (err?: Error|null) => err ? reject(err) : resolve()));
});
test('can read an empty file', async () => {
const outputString = '';
const path = Path.join(readTextTmpDir, 'simple.txt');
await promises.writeFile(path, outputString);
const text = Series.readText(path, '');
expect(text.toArray()).toEqual(outputString.split(''));
await new Promise<void>((resolve, reject) =>
rimraf(path, (err?: Error|null) => err ? reject(err) : resolve()));
});
});
describe('StringSeries split', () => {
test('split a basic string', () => {
const input = Series.new(['abcdefg']).split('d');
expect(input.toArray()).toEqual(['abcd', 'efg']);
});
test('split a string twice', () => {
const input = Series.new(['abcdefgdcba']).split('d');
expect(input.toArray()).toEqual(['abcd', 'efgd', 'cba']);
});
});
let readTextTmpDir = '';
const rimraf = require('rimraf');
beforeAll(async () => { //
readTextTmpDir = await promises.mkdtemp(Path.join('/tmp', 'node_cudf'));
});
afterAll(() => {
return new Promise<void>((resolve, reject) => { //
rimraf(readTextTmpDir, (err?: Error|null) => err ? reject(err) : resolve());
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-column-tests.ts
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
DeviceMemory,
Float32Buffer,
Int32Buffer,
setDefaultAllocator,
Uint8Buffer
} from '@rapidsai/cuda';
import {Bool8, Column, Float32, Float64, Int32, Series, Uint8, Utf8String} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength) => new DeviceBuffer(byteLength, mr));
test('Column initialization', () => {
const length = 100;
const col = new Column({type: new Int32, data: new Int32Buffer(length)});
expect(col.type).toBeInstanceOf(Int32);
expect(col.length).toBe(length);
expect(col.nullCount).toBe(0);
expect(col.hasNulls).toBe(false);
expect(col.nullable).toBe(false);
});
test('Column initialization with null_mask', () => {
const length = 100;
const col = new Column({
type: new Bool8,
data: new Uint8Buffer(length),
nullMask: new Uint8Buffer(64).fill(0),
});
expect(col.length).toBe(length);
expect(col.nullCount).toBe(100);
expect(col.hasNulls).toBe(true);
expect(col.nullable).toBe(true);
});
test('Column initialization with Array of mixed values', () => {
const col = new Column({type: new Bool8, data: [true, null, false, null]});
expect(col.type).toBeInstanceOf(Bool8);
expect(col.length).toBe(4);
expect(col.nullCount).toBe(2);
expect(col.hasNulls).toBe(true);
expect(col.nullable).toBe(true);
expect(col.getValue(0)).toEqual(true);
expect(col.getValue(1)).toEqual(null);
expect(col.getValue(2)).toEqual(false);
expect(col.getValue(3)).toEqual(null);
});
test('Column.gather', () => {
const col = new Column({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
const selection = new Column({type: new Int32, data: new Int32Buffer([2, 4, 5, 8])});
const result = col.gather(selection, false);
expect(result.getValue(0)).toBe(2);
expect(result.getValue(1)).toBe(4);
expect(result.getValue(2)).toBe(5);
expect(result.getValue(3)).toBe(8);
});
test('Column.gather (bad argument)', () => {
const col = new Column({type: new Int32, data: new Int32Buffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])});
const selection = [2, 4, 5];
expect(() => col.gather(<any>selection, false)).toThrow();
});
test('Column null_mask, null_count', () => {
const length = 32;
const col = new Column({
type: new Float32,
data: new Float32Buffer(length),
nullMask: new Uint8Buffer([254, 255, 255, 255])
});
expect(col.type).toBeInstanceOf(Float32);
expect(col.length).toBe(length);
expect(col.nullCount).toBe(1);
expect(col.hasNulls).toBe(true);
expect(col.nullable).toBe(true);
});
test('test child(child_index), num_children', () => {
const utf8Col = new Column({type: new Uint8, data: new Uint8Buffer(Buffer.from('hello'))});
const offsetsCol = new Column({type: new Int32, data: new Int32Buffer([0, utf8Col.length])});
const stringsCol = new Column({
type: new Utf8String,
length: 1,
nullMask: new Uint8Buffer([255]),
children: [offsetsCol, utf8Col],
});
expect(stringsCol.type).toBeInstanceOf(Utf8String);
expect(stringsCol.numChildren).toBe(2);
expect(stringsCol.getValue(0)).toBe('hello');
expect(stringsCol.getChild(0).length).toBe(offsetsCol.length);
expect(stringsCol.getChild(0).type).toBeInstanceOf(Int32);
expect(stringsCol.getChild(1).length).toBe(utf8Col.length);
expect(stringsCol.getChild(1).type).toBeInstanceOf(Uint8);
});
test('Column.dropNans', () => {
const col = new Column({type: new Float32(), data: new Float32Buffer([1, 3, NaN, 4, 2, 0])});
const result = col.dropNans();
const expected = [1, 3, 4, 2, 0];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.dropNulls', () => {
const mask = arrow.vectorFromArray([0, 1, 1, 1, 1, 0], new arrow.Bool).data[0].values;
const col = new Column(
{type: new Float32(), data: new Float32Buffer([1, 3, NaN, 4, 2, 0]), nullMask: mask});
const result = col.dropNulls();
const expected = [3, NaN, 4, 2];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.nansToNulls', () => {
const col = new Column({type: new Float32(), data: new Float32Buffer([1, 3, NaN, 4, 2, 0])});
const result = col.nansToNulls();
const expected = [1, 3, null, 4, 2, 0];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsFromBooleans', () => {
const col = Series.new([true, false, true, null, true])._col;
const result = col.stringsFromBooleans();
const expected = ['true', 'false', 'true', null, 'true'];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsToBooleans', () => {
const col = Series.new(['true', 'false', 'true', null, 'true'])._col;
const result = col.stringsToBooleans();
const expected = [true, false, true, null, true];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringIsFloat', () => {
const col = Series.new(['1.2', '12', 'abc', '-2.3', '-5', null, '2e+17', '0'])._col;
const result = col.stringIsFloat();
const expected = [true, true, false, true, true, null, true, true];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsFromFloats', () => {
const col = Series.new([1.2, 12, -2.3, -5, null, 2e+17, 0])._col;
const result = col.stringsFromFloats();
const expected = ['1.2', '12.0', '-2.3', '-5.0', null, '2.0e+17', '0.0'];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsToFloats', () => {
const col = Series.new(['1.2', '12', '-2.3', '-5', null, '2e+17', '0'])._col;
const result = col.stringsToFloats(new Float64);
const expected = [1.2, 12.0, -2.3, -5.0, null, 2.0e+17, 0.0];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringIsInteger', () => {
const col = Series.new(['1.2', '12', 'abc', '-2.3', '-5', null, '2e+17', '0'])._col;
const result = col.stringIsInteger();
const expected = [false, true, false, false, true, null, false, true];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsFromIntegers', () => {
const col = Series.new({type: new Int32, data: [12, -5, null, 0]})._col;
const result = col.stringsFromIntegers();
const expected = ['12', '-5', null, '0'];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringsToIntegers', () => {
const col = Series.new(['12', '-5', null, '0'])._col;
const result = col.stringsToIntegers(new Int32);
const expected = [12, -5, null, 0];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringIsHex', () => {
const col = Series.new(['123', '-456', '', 'AGE', '+17EA', '0x9EF', '123ABC', null])._col;
const result = col.stringIsHex();
const expected = [true, false, false, false, false, true, true, null];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.hexFromIntegers', () => {
const col = Series.new({type: new Int32, data: [1234, -1, 0, 27, 342718233, null]})._col;
const result = col.hexFromIntegers();
const expected = ['04D2', 'FFFFFFFF', '00', '1B', '146D7719', null];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.hexToIntegers', () => {
const col = Series.new(['04D2', 'FFFFFFFF', '00', '1B', '146D7719', null])._col;
const result = col.hexToIntegers(new Int32);
const expected = [1234, -1, 0, 27, 342718233, null];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.stringIsIpv4', () => {
const col = Series.new(['123.255.0.7', '127.0.0.1', '', '1.2.34', '123.456.789.10', null])._col;
const result = col.stringIsIpv4();
const expected = [true, true, false, false, false, null];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.ipv4FromIntegers', () => {
const col = Series.new([2080309255n, 2130706433n, null])._col;
const result = col.ipv4FromIntegers();
const expected = ['123.255.0.7', '127.0.0.1', null];
expect([...Series.new(result)]).toEqual(expected);
});
test('Column.ipv4ToIntegers', () => {
const col = Series.new(['123.255.0.7', '127.0.0.1', null])._col;
const result = col.ipv4ToIntegers();
const expected = [2080309255n, 2130706433n, null];
expect([...Series.new(result)]).toEqual(expected);
});
describe('Column.replaceSlice', () => {
test('prepend', () => {
const col = Series.new(['foo', 'bar', 'abcdef'])._col;
const result = col.replaceSlice('123', 0, 0);
const expected = ['123foo', '123bar', '123abcdef'];
expect([...Series.new(result)]).toEqual(expected);
});
test('append', () => {
const col = Series.new(['foo', 'bar', 'abcdef'])._col;
const result = col.replaceSlice('123', -1, -1);
const expected = ['foo123', 'bar123', 'abcdef123'];
expect([...Series.new(result)]).toEqual(expected);
});
test('insert', () => {
const col = Series.new(['foo', 'bar', 'abcdef'])._col;
const result = col.replaceSlice('123', 1, 1);
const expected = ['f123oo', 'b123ar', 'a123bcdef'];
expect([...Series.new(result)]).toEqual(expected);
});
test('replace middle', () => {
const col = Series.new(['foo', 'bar', 'abcdef'])._col;
const result = col.replaceSlice('123', 1, 2);
const expected = ['f123o', 'b123r', 'a123cdef'];
expect([...Series.new(result)]).toEqual(expected);
});
test('replace entire', () => {
const col = Series.new(['foo', 'bar', 'abcdef'])._col;
const result = col.replaceSlice('123', 0, -1);
const expected = ['123', '123', '123'];
expect([...Series.new(result)]).toEqual(expected);
});
});
describe('Column.setNullMask', () => {
const arange = (length: number) => Array.from({length}, (_, i) => i);
const makeTestColumn = (length: number) =>
new Column({type: new Int32, length, data: arange(length)});
const validateSetNullMask =
(col: Column, length: number, expectedNullCount: number, newNullMask: any, ...args: [any?]) => {
expect(col.length).toBe(length);
expect(col.nullCount).toBe(0);
col.setNullMask(newNullMask, ...args);
expect(col.length).toBe(length);
expect(col.nullCount).toBe(expectedNullCount);
expect(col.hasNulls).toBe(expectedNullCount > 0);
expect(col.nullable).toBe(newNullMask != null);
if (newNullMask == null) {
expect(col.mask.byteLength).toBe(0);
} else {
expect(col.mask.byteLength).toBe((((length >> 3) + 63) & ~63) || 64);
}
};
test('recomputes nullCount (all null)',
() => { validateSetNullMask(makeTestColumn(4), 4, 4, new Uint8Buffer(64).buffer); });
test('recomputes nullCount (all valid)',
() => { validateSetNullMask(makeTestColumn(4), 4, 0, new Uint8Buffer(8).fill(255)); });
test('uses the new nullCount',
() => { validateSetNullMask(makeTestColumn(4), 4, 4, new Uint8Buffer(8).buffer, 4); });
test('clamps the new nullCount to length',
() => { validateSetNullMask(makeTestColumn(4), 4, 4, new Uint8Buffer(8).buffer, 8); });
test('resizes when mask is smaller than 64 bytes',
() => { validateSetNullMask(makeTestColumn(4), 4, 4, new Uint8Buffer(4).buffer); });
test('Passing null resets to all valid',
() => { validateSetNullMask(makeTestColumn(4), 4, 0, null); });
test('accepts Arrays of numbers', () => {
validateSetNullMask(makeTestColumn(4), 4, 0, [1, 1, 1, 1]);
validateSetNullMask(makeTestColumn(4), 4, 2, [1, 1, 0, 0]);
validateSetNullMask(makeTestColumn(4), 4, 4, [0, 0, 0, 0]);
});
test('accepts Arrays of bigints', () => {
validateSetNullMask(makeTestColumn(4), 4, 0, [1n, 1n, 1n, 1n]);
validateSetNullMask(makeTestColumn(4), 4, 2, [1n, 1n, 0n, 0n]);
validateSetNullMask(makeTestColumn(4), 4, 4, [0n, 0n, 0n, 0n]);
});
test('accepts Arrays of booleans', () => {
validateSetNullMask(makeTestColumn(4), 4, 0, [true, true, true, true]);
validateSetNullMask(makeTestColumn(4), 4, 2, [true, true, false, false]);
validateSetNullMask(makeTestColumn(4), 4, 4, [false, false, false, false]);
});
test('accepts CUDA DeviceMemory', () => {
validateSetNullMask(
makeTestColumn(4), 4, 4, new Uint8Buffer(new DeviceMemory(8)).fill(0).buffer);
});
test('accepts CUDA MemoryView of DeviceMemory', () => {
validateSetNullMask(makeTestColumn(4), 4, 4, new Uint8Buffer(new DeviceMemory(8)).fill(0));
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf
|
rapidsai_public_repos/node/modules/cudf/test/cudf-groupby-tests.ts
|
// Copyright (c) 2020-2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import './jest-extensions';
import {setDefaultAllocator} from '@rapidsai/cuda';
import {
DataFrame,
DataType,
Float64,
GroupByMultiple,
GroupBySingle,
Int32,
Series,
// StructSeries
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr));
function makeBasicData(values: number[]) {
const a = Series.new({type: new Int32, data: [1, 2, 3, 1, 2, 2, 1, 3, 3, 2]});
const b = Series.new({type: new Float64, data: values});
const c = Series.new({type: new Float64, data: values});
return new DataFrame({a, b, 'c': c});
}
function basicAggCompare<T extends {a: DataType, b: DataType, c: DataType}, E extends any[]>(
result: DataFrame<T>, expected: E): void {
const ra = result.get('a');
const rb = result.get('b');
const rc = result.get('c');
const a_expected = Series.new({type: new Int32, data: [1, 2, 3]});
expect([...ra]).toEqual([...a_expected]);
const b_expected = Series.new({type: rb.type, data: expected});
expect(rb.type).toEqual(b_expected.type);
expect(rc.type).toEqual(b_expected.type);
if (arrow.DataType.isList(rb.type)) {
const isIterable = (x: any): x is Iterable<any> => //
(x && typeof x === 'object' && typeof x[Symbol.iterator]);
const unwrap = (xs: any[]): any[][] => //
xs.map((ys) => isIterable(ys) ? unwrap([...ys]) : ys);
const actual_rb_lists = unwrap([...rb]);
const actual_rc_lists = unwrap([...rc]);
const b_expected_lists = unwrap([...b_expected]);
expect(actual_rb_lists).toEqual(b_expected_lists);
expect(actual_rc_lists).toEqual(b_expected_lists);
} else {
expect(rb.toArray()).toEqualTypedArray(b_expected.toArray() as any);
expect(rc.toArray()).toEqualTypedArray(b_expected.toArray() as any);
}
}
test('getGroups basic', () => {
const a = Series.new({type: new Int32, data: [1, 1, 2, 1, 2, 3]});
const df = new DataFrame({'a': a});
const grp = new GroupBySingle(df, {by: 'a'});
const groups = grp.getGroups();
const keys_result = groups['keys'].get('a');
expect([...keys_result]).toEqual([1, 1, 1, 2, 2, 3]);
expect(groups.values).toBeUndefined();
expect([...groups['offsets']]).toEqual([0, 3, 5, 6]);
});
test('getGroups basic two columns', () => {
const a = Series.new({type: new Int32, data: [1, 1, 2, 1, 2, 3]});
const aa = Series.new({type: new Int32, data: [4, 5, 4, 4, 4, 3]});
const df = new DataFrame({'a': a, 'aa': aa});
const grp = new GroupByMultiple(df, {by: ['a', 'aa'], index_key: 'out'});
const groups = grp.getGroups();
const keys_result_a = groups['keys'].get('a');
expect([...keys_result_a]).toEqual([1, 1, 1, 2, 2, 3]);
const keys_result_aa = groups['keys'].get('aa');
expect([...keys_result_aa]).toEqual([4, 4, 5, 4, 4, 3]);
expect(groups.values).toBeUndefined();
expect([...groups['offsets']]).toEqual([0, 2, 3, 5, 6]);
});
test('getGroups empty', () => {
const a = Series.new({type: new Int32, data: []});
const df = new DataFrame({'a': a});
const grp = new GroupBySingle(df, {by: 'a'});
const groups = grp.getGroups();
const keys_result = groups['keys'].get('a');
expect(keys_result.length).toBe(0);
expect(groups.values).toBeUndefined();
expect([...groups['offsets']]).toEqual([0]);
});
test('getGroups basic with values', () => {
const a = Series.new({type: new Int32, data: [5, 4, 3, 2, 1, 0]});
const b = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const c = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const groups = grp.getGroups();
const keys_result = groups['keys'].get('a');
expect([...keys_result]).toEqual([0, 1, 2, 3, 4, 5]);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_b = groups.values?.get('b')!;
expect(values_result_b).toBeDefined();
expect([...values_result_b]).toEqual([2, 2, 1, 1, 0, 0]);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_c = groups.values?.get('c')!;
expect(values_result_c).toBeDefined();
expect([...values_result_c]).toEqual([2, 2, 1, 1, 0, 0]);
expect([...groups['offsets']]).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
test('getGroups basic two columns with values', () => {
const a = Series.new({type: new Int32, data: [5, 4, 3, 2, 1, 0]});
const aa = Series.new({type: new Int32, data: [4, 5, 4, 4, 4, 3]});
const b = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const c = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const df = new DataFrame({a, aa, b, c});
const grp = new GroupByMultiple(df, {by: ['a', 'aa'], index_key: 'out'});
const groups = grp.getGroups();
const keys_result_a = groups['keys'].get('a');
expect([...keys_result_a]).toEqual([0, 1, 2, 3, 4, 5]);
const keys_result_aa = groups['keys'].get('aa');
expect([...keys_result_aa]).toEqual([3, 4, 4, 4, 5, 4]);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_b = groups.values?.get('b')!;
expect(values_result_b).toBeDefined();
expect([...values_result_b]).toEqual([2, 2, 1, 1, 0, 0]);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_c = groups.values?.get('c')!;
expect(values_result_c).toBeDefined();
expect([...values_result_c]).toEqual([2, 2, 1, 1, 0, 0]);
expect([...groups['offsets']]).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
test('getGroups all nulls', () => {
const a = Series.new({type: new Int32, data: [null, null, null, null, null, null]});
const df = new DataFrame({'a': a});
const grp = new GroupBySingle(df, {by: 'a'});
const groups = grp.getGroups();
const keys_result = groups['keys'].get('a');
expect(keys_result.length).toBe(0);
expect(groups.values).toBeUndefined();
expect([...groups['offsets']]).toEqual([0]);
});
test('getGroups some nulls', () => {
const a = Series.new({type: new Int32, data: [1, null, 3, null, null, 2]});
const b = Series.new({type: new Int32, data: [1, 2, 3, 4, 5, 6]});
const c = Series.new({type: new Int32, data: [1, 2, 3, 4, 5, 6]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const groups = grp.getGroups();
const keys_result = groups['keys'].get('a');
expect([...keys_result]).toEqual([1, 2, 3]);
expect(keys_result.nullCount).toBe(0);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_b = groups.values?.get('b')!;
expect(values_result_b).toBeDefined();
expect([...values_result_b]).toEqual([1, 6, 3]);
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const values_result_c = groups.values?.get('c')!;
expect(values_result_c).toBeDefined();
expect([...values_result_c]).toEqual([1, 6, 3]);
expect([...groups['offsets']]).toEqual([0, 1, 2, 3]);
});
test('aggregation column name with two columns', () => {
const a = Series.new({type: new Int32, data: [5, 4, 3, 2, 1, 0]});
const aa = Series.new({type: new Int32, data: [4, 5, 4, 4, 4, 3]});
const b = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const df = new DataFrame({'a': a, 'aa': aa, 'b': b});
const grp = new GroupByMultiple(df, {by: ['a', 'aa'], index_key: 'out'});
const agg = grp.max();
const result_out = agg.get('out');
const keys_result_a = result_out.getChild('a');
const keys_result_aa = result_out.getChild('aa');
const sorter = [0, 1, 2, 3, 4, 5];
const ka = [...keys_result_a];
sorter.sort((i, j) => ka[i]! - ka[j]!);
const sorted_a =
keys_result_a.gather(Series.new({type: new Int32, data: new Int32Array(sorter)}));
expect([...sorted_a]).toEqual([0, 1, 2, 3, 4, 5]);
const sorted_aa =
keys_result_aa.gather(Series.new({type: new Int32, data: new Int32Array(sorter)}));
expect([...sorted_aa]).toEqual([3, 4, 4, 4, 5, 4]);
const sorted_b = agg.get('b').gather(Series.new({type: new Int32, data: new Int32Array(sorter)}));
expect([...sorted_b]).toEqual([2, 2, 1, 1, 0, 0]);
});
test('aggregation existing column name with two columns raises', () => {
const a = Series.new({type: new Int32, data: [5, 4, 3, 2, 1, 0]});
const aa = Series.new({type: new Int32, data: [4, 5, 4, 4, 4, 3]});
const b = Series.new({type: new Int32, data: [0, 0, 1, 1, 2, 2]});
const df = new DataFrame({'a': a, 'aa': aa, 'b': b});
const grp = new GroupByMultiple(df, {by: ['a', 'aa'], index_key: 'b'});
expect(() => grp.max()).toThrowError();
});
test('Groupby argmax basic', () => {
const df = makeBasicData([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.argmax(), [0, 1, 2]);
});
test('Groupby argmin basic', () => {
const df = makeBasicData([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.argmin(), [6, 9, 8]);
});
test('Groupby count basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.count(), [3, 4, 3]);
});
test('Groupby max basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.max(), [6, 9, 8]);
});
test('Groupby mean basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.mean(), [3, 19 / 4, 17 / 3]);
});
test('Groupby median basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.median(), [3, 4.5, 7]);
});
test('Groupby min basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.min(), [0, 1, 2]);
});
test('Groupby nth basic', () => {
const a = Series.new({type: new Int32, data: [1, 1, 1, 2, 2, 2, 3, 3, 3]});
const b = Series.new({type: new Float64, data: [1, 2, 3, 10, 20, 30, 100, 200, 300]});
const c = Series.new({type: new Float64, data: [1, 2, 3, 10, 20, 30, 100, 200, 300]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.nth(0), [1, 10, 100]);
basicAggCompare(grp.nth(1), [2, 20, 200]);
basicAggCompare(grp.nth(2), [3, 30, 300]);
});
test('Groupby nth uneven', () => {
const a = Series.new({type: new Int32, data: [1, 1, 1, 2, 2, 2, 3, 3]});
const b = Series.new({type: new Float64, data: [1, 2, 3, 10, 20, 30, 100, 200]});
const c = Series.new({type: new Float64, data: [1, 2, 3, 10, 20, 30, 100, 200]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.nth(2);
basicAggCompare(result, [3, 30, 0]);
expect(result.get('b').nullCount).toBe(1);
});
test('Groupby nunique basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.nunique(), [3, 4, 3]);
});
test('Groupby quantile uneven', () => {
const a = Series.new({type: new Int32, data: [1, 2, 3, 1, 2, 2, 1, 3, 3, 2]});
const b = Series.new({type: new Float64, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const c = Series.new({type: new Float64, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.quantile(0.5);
basicAggCompare(result, [3., 4.5, 7.]);
expect(result.get('b').nullCount).toBe(0);
});
test('Groupby std basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.std(), [3, Math.sqrt(131 / 12), Math.sqrt(31 / 3)]);
});
test('Groupby sum basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.sum(), [9, 19, 17]);
});
test('Groupby var basic', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.var(), [9, 131 / 12, 31 / 3]);
});
test('Groupby collectList basic', () => {
// keys=[[1, 1, 1], [2, 2, 2, 2], [3, 3, 3]]
// vals=[[0, 3, 6], [1, 4, 5, 9], [2, 7, 8]]
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.collectList(), [[0, 3, 6], [1, 4, 5, 9], [2, 7, 8]]);
});
test('Groupby collectSet all unique', () => {
const df = makeBasicData([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.collectSet(), [[0, 3, 6], [1, 4, 5, 9], [2, 7, 8]]);
});
test('Groupby collectSet with duplicates', () => {
const df = makeBasicData([0, 1, 2, 0, 1, 1, 6, 2, 8, 9]);
const grp = new GroupBySingle(df, {by: 'a'});
basicAggCompare(grp.collectSet(), [[0, 6], [1, 9], [2, 8]]);
});
export type BasicAggType =
'sum'|'min'|'max'|'argmin'|'argmax'|'mean'|'count'|'nunique'|'var'|'std'|'median';
const BASIC_AGGS: BasicAggType[] =
['sum', 'min', 'max', 'argmin', 'argmax', 'mean', 'count', 'nunique', 'var', 'std', 'median'];
for (const agg of BASIC_AGGS) {
test(`Groupby ${agg} empty`, () => {
const a = Series.new({type: new Int32, data: []});
const b = Series.new({type: new Float64, data: []});
const c = Series.new({type: new Float64, data: []});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp[agg]();
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
}
test(`Groupby nth empty`, () => {
const a = Series.new({type: new Int32, data: []});
const b = Series.new({type: new Float64, data: []});
const c = Series.new({type: new Float64, data: []});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.nth(0);
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
test(`Groupby quantile empty`, () => {
const a = Series.new({type: new Int32, data: []});
const b = Series.new({type: new Float64, data: []});
const c = Series.new({type: new Float64, data: []});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.quantile(0.5);
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
for (const agg of BASIC_AGGS) {
test(`Groupby ${agg} null keys`, () => {
const a = Series.new({type: new Int32, data: [null, null, null]});
const b = Series.new({type: new Float64, data: [3, 4, 5]});
const c = Series.new({type: new Float64, data: [3, 4, 5]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp[agg]();
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
}
test(`Groupby nth null keys`, () => {
const a = Series.new({type: new Int32, data: [null, null, null]});
const b = Series.new({type: new Float64, data: [3, 4, 5]});
const c = Series.new({type: new Float64, data: [3, 4, 5]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.nth(0);
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
test(`Groupby quantile null keys`, () => {
const a = Series.new({type: new Int32, data: [null, null, null]});
const b = Series.new({type: new Float64, data: [3, 4, 5]});
const c = Series.new({type: new Float64, data: [3, 4, 5]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.quantile(0.5);
expect(result.get('a').length).toBe(0);
expect(result.get('b').length).toBe(0);
expect(result.get('c').length).toBe(0);
});
for (const agg of BASIC_AGGS) {
test(`Groupby ${agg} null values`, () => {
const a = Series.new({type: new Int32, data: [1, 1, 1]});
const b = Series.new({type: new Float64, data: [null, null, null]});
const c = Series.new({type: new Float64, data: [null, null, null]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp[agg]();
expect([...result.get('a')]).toEqual([1]);
expect(result.get('a').nullCount).toBe(0);
expect(result.get('b').length).toBe(1);
expect(result.get('c').length).toBe(1);
if (agg == 'count' || agg == 'nunique') {
expect(result.get('b').nullCount).toBe(0);
expect(result.get('c').nullCount).toBe(0);
} else {
expect(result.get('b').nullCount).toBe(1);
expect(result.get('c').nullCount).toBe(1);
}
});
}
test(`Groupby nth null values`, () => {
const a = Series.new({type: new Int32, data: [1, 1, 1]});
const b = Series.new({type: new Float64, data: [null, null, null]});
const c = Series.new({type: new Float64, data: [null, null, null]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.nth(0);
expect([...result.get('a')]).toEqual([1]);
expect(result.get('a').nullCount).toBe(0);
expect(result.get('b').length).toBe(1);
expect(result.get('b').nullCount).toBe(1);
expect(result.get('c').length).toBe(1);
expect(result.get('c').nullCount).toBe(1);
});
test(`Groupby quantile null values`, () => {
const a = Series.new({type: new Int32, data: [1, 1, 1]});
const b = Series.new({type: new Float64, data: [null, null, null]});
const c = Series.new({type: new Float64, data: [null, null, null]});
const df = new DataFrame({a, b, c});
const grp = new GroupBySingle(df, {by: 'a'});
const result = grp.quantile(0.5);
expect([...result.get('a')]).toEqual([1]);
expect(result.get('a').nullCount).toBe(0);
expect(result.get('b').length).toBe(1);
expect(result.get('b').nullCount).toBe(1);
expect(result.get('c').length).toBe(1);
expect(result.get('c').nullCount).toBe(1);
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/utils.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {toArray} from 'ix/asynciterable';
export function makeCSVString(
opts: {rows?: any[], delimiter?: string, lineTerminator?: string, header?: boolean} = {}) {
const {rows = [], delimiter = ',', lineTerminator = '\n', header = true} = opts;
const names = Object.keys(rows.reduce(
(keys, row) => Object.keys(row).reduce((keys, key) => ({...keys, [key]: true}), keys), {}));
return [
...[header ? names.join(delimiter) : []],
...rows.map((row) =>
names.map((name) => row[name] === undefined ? '' : row[name]).join(delimiter))
].join(lineTerminator) +
lineTerminator;
}
export async function toStringAsync(source: AsyncIterable<string>) {
return (await toArray(source)).join('');
}
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/write-read-orc-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float64Buffer, Int32Buffer} from '@rapidsai/cuda';
import {DataFrame, Float64, Int32, Series} from '@rapidsai/cudf';
import {promises} from 'fs';
import * as Path from 'path';
test('writes and reads an ORC', () => {
const expected = new DataFrame({
a: Series.new({length: 3, type: new Int32, data: new Int32Buffer([1, 2, 3])}),
b: Series.new({length: 3, type: new Float64, data: new Float64Buffer([1.0, 2.0, 3.0])}),
c: Series.new(['2', '3', '4']),
});
const path = Path.join(tmpDir, 'simple.orc');
expected.toORC(path);
const result = DataFrame.readORC({
sourceType: 'files',
sources: [path],
});
expect(result.toString()).toEqual(expected.toString());
});
let tmpDir = '';
const rimraf = require('rimraf');
beforeAll(async () => { //
tmpDir = await promises.mkdtemp(Path.join('/tmp', 'node_cudf'));
});
afterAll(() => {
return new Promise<void>((resolve, reject) => { //
rimraf(tmpDir, (err?: Error|null) => err ? reject(err) : resolve());
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/read-csv-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DataFrame, Float64, Int32, Utf8String} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
import {promises} from 'fs';
import * as Path from 'path';
import {makeCSVString} from './utils';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
describe('DataFrame.readCSV', () => {
test('can read a CSV string', () => {
const rows = [
{a: 0, b: 1.0, c: '2'},
{a: 1, b: 2.0, c: '3'},
{a: 2, b: 3.0, c: '4'},
];
const df = DataFrame.readCSV({
header: 0,
sourceType: 'buffers',
sources: [Buffer.from(makeCSVString({rows}))],
dataTypes: {a: new Int32, b: new Float64, c: new Utf8String},
});
expect(df.get('a').data.toArray()).toEqual(new Int32Array([0, 1, 2]));
expect(df.get('b').data.toArray()).toEqual(new Float64Array([1.0, 2.0, 3.0]));
expect([...df.get('c')]).toEqual(['2', '3', '4']);
});
test('can read a CSV file', async () => {
const rows = [
{a: 0, b: 1.0, c: '2'},
{a: 1, b: 2.0, c: '3'},
{a: 2, b: 3.0, c: '4'},
];
const path = Path.join(csvTmpDir, 'simple.csv');
await promises.writeFile(path, makeCSVString({rows}));
const df = DataFrame.readCSV({
header: 0,
sourceType: 'files',
sources: [path],
dataTypes: {a: new Int32, b: new Float64, c: new Utf8String},
});
expect(df.get('a').data.toArray()).toEqual(new Int32Array([0, 1, 2]));
expect(df.get('b').data.toArray()).toEqual(new Float64Array([1.0, 2.0, 3.0]));
expect([...df.get('c')]).toEqual(['2', '3', '4']);
await new Promise<void>((resolve, reject) =>
rimraf(path, (err?: Error|null) => err ? reject(err) : resolve()));
});
});
let csvTmpDir = '';
const rimraf = require('rimraf');
beforeAll(async () => { //
csvTmpDir = await promises.mkdtemp(Path.join('/tmp', 'node_cudf'));
});
afterAll(() => {
return new Promise<void>((resolve, reject) => { //
rimraf(csvTmpDir, (err?: Error|null) => err ? reject(err) : resolve());
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/concat-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {Categorical, DataFrame, Float64, Int32, Series, Utf8String} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
describe('dataframe.concat', () => {
test('zero series in common same types', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([5, 6, 7, 8]);
const dfa = new DataFrame({'a': a});
const dfb = new DataFrame({'b': b});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([...a, null, null, null, null]);
expect([...result.get('b')]).toEqual([null, null, null, null, ...b]);
});
test('zero series in common different types', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new(['5', '6', '7', '8']);
const dfa = new DataFrame({'a': a});
const dfb = new DataFrame({'b': b});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([...a, null, null, null, null]);
expect([...result.get('b')]).toEqual([null, null, null, null, ...b]);
});
test('one Float64 series in common', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([5, 6, 7, 8]);
const c = Series.new([9, 10, 11, 12]);
const dfa = new DataFrame({'a': a, 'b': b});
const dfb = new DataFrame({'b': b, 'c': c});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([...a, null, null, null, null]);
expect([...result.get('b')]).toEqual([...b, ...b]);
expect([...result.get('c')]).toEqual([null, null, null, null, ...c]);
});
test('two Float64 series in common', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([5, 6, 7, 8]);
const dfa = new DataFrame({'a': a, 'b': b});
const dfb = new DataFrame({'a': a, 'b': b});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([...a, ...a]);
expect([...result.get('b')]).toEqual([...b, ...b]);
});
test('one String series in common', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new(['5', '6', '7', '8']);
const c = Series.new([9, 10, 11, 12]);
const dfa = new DataFrame({'a': a, 'b': b});
const dfb = new DataFrame({'b': b, 'c': c});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([...a, null, null, null, null]);
expect([...result.get('b')]).toEqual([...b, ...b]);
expect([...result.get('c')]).toEqual([null, null, null, null, ...c]);
});
test('up-casts Int32 to common Float64 dtype', () => {
const a1 = Series.new([1, 2, 3, 4, 5]).cast(new Int32);
const a2 = Series.new([6, 7, 8, 9, 10]);
const df1 = new DataFrame({'a': a1});
const df2 = new DataFrame({'a': a2});
const result = df1.concat(df2);
// Helper function to throw a compile error if `df.concat()` fails
// up-cast the `(Int32 | Float64)` type union to Float64, e.g.:
// ```ts
// expectFloat64(<Int32|Float64>new Float64());
// ```
function expectFloat64(type: Float64) { expect(type).toBeInstanceOf(Float64); }
expectFloat64(result.get('a').type);
expect([...result.get('a')]).toEqual([...a1, ...a2]);
});
test('fails to up-cast between Float64 and String', () => {
const a1 = Series.new([1, 2, 3, 4, 5]);
const a2 = Series.new(['6', '7', '8', '9', '10']);
const df1 = new DataFrame({'a': a1});
const df2 = new DataFrame({'a': a2});
expect(() => {
// This throws a runtime exception because it
// can't find a common dtype between Float64 and String.
// Ideally this should cause a compile-time error, but it
// TS has no generic equivalent of the C #error directive.
const result = df1.concat(df2);
// A compilation error does happen when someone tries to use the "a" Column:
// result.get('a').type; // `Property 'type' does not exist on type 'never'.ts(2339)`
// For now, we'll just verify that concat returns a DataFrame<{ a: never }>
verifyConcatResultType(result);
function verifyConcatResultType(_: never) { return _; }
}).toThrow();
});
test('array of dataframes', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([5, 6, 7, 8]);
const c = Series.new([9, 10, 11, 12]);
const dfa = new DataFrame({'a': a, 'b': b});
const dfb = new DataFrame({'b': b, 'c': c});
const dfc = new DataFrame({'a': a, 'c': c});
const result = dfa.concat(dfb, dfc);
expect([...result.get('a')]).toEqual([...a, null, null, null, null, ...a]);
expect([...result.get('b')]).toEqual([...b, ...b, null, null, null, null]);
expect([...result.get('c')]).toEqual([null, null, null, null, ...c, ...c]);
});
test('unique mismatched series length', () => {
const a = Series.new([1, 2, 3, 4]);
const b = Series.new([5, 6, 7, 8, 9]);
const dfa = new DataFrame({'a': a});
const dfb = new DataFrame({'b': b});
const result = dfa.concat(dfb);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, null, null, null, null, null]);
expect([...result.get('b')]).toEqual([null, null, null, null, 5, 6, 7, 8, 9]);
});
test('overlapping categorical columns', () => {
const a = Series.new(new Int32Array([1, 2, 3, 4])).cast(new Categorical(new Utf8String));
const aa = Series.new(new Int32Array([5, 6, 1, 3, 6, 5])).cast(new Categorical(new Utf8String));
const dfa = new DataFrame({'a': a});
const dfb = new DataFrame({'a': aa});
const result = dfa.concat(dfb).get('a');
expect([...result]).toEqual(['1', '2', '3', '4', '5', '6', '1', '3', '6', '5']);
expect([...result.codes]).toEqual([0, 1, 2, 3, 4, 5, 0, 2, 5, 4]);
expect([...result.categories]).toEqual(['1', '2', '3', '4', '5', '6']);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/write-csv-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float64Buffer, Int32Buffer, setDefaultAllocator} from '@rapidsai/cuda';
import {DataFrame, Float64, Int32, Series} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
import {makeCSVString, toStringAsync} from './utils';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
describe('DataFrame.toCSV', () => {
test('writes a CSV', async () => {
const rows = [
{a: 0, b: '1.0', c: '2'},
{a: 1, b: '2.0', c: '3'},
{a: 2, b: '3.0', c: '4'},
];
const df = new DataFrame({
a: Series.new({length: 3, type: new Int32, data: new Int32Buffer([0, 1, 2])}),
b: Series.new({length: 3, type: new Float64, data: new Float64Buffer([1.0, 2.0, 3.0])}),
c: Series.new(['2', '3', '4']),
});
expect((await toStringAsync(df.toCSV()))).toEqual(makeCSVString({rows}));
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/write-read-parquet-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Float64Buffer, Int32Buffer} from '@rapidsai/cuda';
import {DataFrame, Float64, Int32, Series} from '@rapidsai/cudf';
import {promises} from 'fs';
import * as Path from 'path';
test('writes and reads a Parquet', () => {
const expected = new DataFrame({
a: Series.new({length: 3, type: new Int32, data: new Int32Buffer([1, 2, 3])}),
b: Series.new({length: 3, type: new Float64, data: new Float64Buffer([1.0, 2.0, 3.0])}),
c: Series.new(['2', '3', '4']),
});
const path = Path.join(tmpDir, 'simple.parquet');
expected.toParquet(path);
const result = DataFrame.readParquet({
sourceType: 'files',
sources: [path],
});
expect(result.toString()).toEqual(expected.toString());
});
test('reading a Parquet file deserializes the types', () => {
const expected = new DataFrame({
a: Series.new([1, 2, 3]),
b: Series.new([1, 2, 3]),
c: Series.new([1, 2, 3]),
});
const path = Path.join(tmpDir, 'floats.parquet');
expected.toParquet(path);
const result = DataFrame.readParquet({
sourceType: 'files',
sources: [path],
});
expect(result.sum().sum()).toEqual(18);
});
let tmpDir = '';
const rimraf = require('rimraf');
beforeAll(async () => { //
tmpDir = await promises.mkdtemp(Path.join('/tmp', 'node_cudf'));
});
afterAll(() => {
return new Promise<void>((resolve, reject) => { //
rimraf(tmpDir, (err?: Error|null) => err ? reject(err) : resolve());
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/flatten-tests.ts
|
// Copyright (c) 2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DataFrame, Series} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
describe(`DataFrame.flatten`, () => {
const input = new DataFrame({
a: Series.new([100, 200, 300]),
b: Series.new([[1, 2, 7], [5, 6], [0, 3]]),
c: Series.new(['string0', 'string1', 'string2']),
d: Series.new([[1, 2, 7], [5, 6], [0, 3]]),
e: Series.new([{a: 0, b: '0'}, {a: 1, b: '1'}, {a: 2, b: '2'}]),
});
test(`doesn't flatten non-list columns`, () => {
const expected = input.assign({});
const actual = input.flatten(['a']);
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
test(`flattens a single list column`, () => {
const expected = new DataFrame({
a: Series.new([100, 100, 100, 200, 200, 300, 300]),
b: Series.new([1, 2, 7, 5, 6, 0, 3]),
c: Series.new(['string0', 'string0', 'string0', 'string1', 'string1', 'string2', 'string2']),
d: Series.new([[1, 2, 7], [1, 2, 7], [1, 2, 7], [5, 6], [5, 6], [0, 3], [0, 3]]),
e: Series.new([
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 2, b: '2'},
{a: 2, b: '2'},
]),
});
const actual = input.flatten(['b']);
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
test(`flattens multiple list columns`, () => {
const expected = new DataFrame({
a: Series.new(
[100, 100, 100, 100, 100, 100, 100, 100, 100, 200, 200, 200, 200, 300, 300, 300, 300]),
b: Series.new([1, 1, 1, 2, 2, 2, 7, 7, 7, 5, 5, 6, 6, 0, 0, 3, 3]),
c: Series.new([
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string1',
'string1',
'string1',
'string1',
'string2',
'string2',
'string2',
'string2'
]),
d: Series.new([1, 2, 7, 1, 2, 7, 1, 2, 7, 5, 6, 5, 6, 0, 3, 0, 3]),
e: Series.new([
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 2, b: '2'},
{a: 2, b: '2'},
{a: 2, b: '2'},
{a: 2, b: '2'},
]),
});
const actual = input.flatten();
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
});
describe(`DataFrame.flattenIndices`, () => {
const input = new DataFrame({
a: Series.new([100, 200, 300]),
b: Series.new([[1, 2, 7], [5, 6], [0, 3]]),
c: Series.new(['string0', 'string1', 'string2']),
d: Series.new([[1, 2, 7], [5, 6], [0, 3]]),
e: Series.new([{a: 0, b: '0'}, {a: 1, b: '1'}, {a: 2, b: '2'}]),
});
test(`doesn't flatten non-list columns`, () => {
const expected = input.assign({});
const actual = input.flattenIndices(['a']);
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
test(`flattens a single list column`, () => {
const expected = new DataFrame({
a: Series.new([100, 100, 100, 200, 200, 300, 300]),
b: Series.new([0, 1, 2, 0, 1, 0, 1]),
c: Series.new(['string0', 'string0', 'string0', 'string1', 'string1', 'string2', 'string2']),
d: Series.new([[1, 2, 7], [1, 2, 7], [1, 2, 7], [5, 6], [5, 6], [0, 3], [0, 3]]),
e: Series.new([
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 2, b: '2'},
{a: 2, b: '2'},
]),
});
const actual = input.flattenIndices(['b']);
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
test(`flattens multiple list columns`, () => {
const expected = new DataFrame({
a: Series.new(
[100, 100, 100, 100, 100, 100, 100, 100, 100, 200, 200, 200, 200, 300, 300, 300, 300]),
b: Series.new([0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1]),
c: Series.new([
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string0',
'string1',
'string1',
'string1',
'string1',
'string2',
'string2',
'string2',
'string2'
]),
d: Series.new([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1]),
e: Series.new([
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 0, b: '0'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 1, b: '1'},
{a: 2, b: '2'},
{a: 2, b: '2'},
{a: 2, b: '2'},
{a: 2, b: '2'},
]),
});
const actual = input.flattenIndices();
expect([...actual.get('a')]).toEqual([...expected.get('a')]);
expect([...actual.get('b')]).toEqual([...expected.get('b')]);
expect([...actual.get('c')]).toEqual([...expected.get('c')]);
expect([...actual.get('d')]).toEqual([...expected.get('d')]);
expect([...actual.get('e')]).toEqual([...expected.get('e')]);
compareTypes(actual.types['e'], expected.types['e']);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/join-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DataFrame, Float32, Float64, Int32, Series} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
const left = new DataFrame({
a: Series.new({type: new Int32, data: [1, 2, 3, 4, 5]}),
b: Series.new({type: new Int32, data: [0, 0, 1, 1, 2]})
});
const right = new DataFrame({
b: Series.new({type: new Int32, data: [0, 1, 3]}),
c: Series.new({type: new Int32, data: [0, 10, 30]})
});
const right_conflict = new DataFrame({
b: Series.new({type: new Int32, data: [0, 1, 3]}),
a: Series.new({type: new Int32, data: [0, 10, 30]})
});
const left_double = new DataFrame({
a: Series.new({type: new Int32, data: [0, 1, 1]}),
b: Series.new({type: new Int32, data: [10, 20, 10]}),
c: Series.new({type: new Float64, data: [1., 2., 3.]})
});
const right_double = new DataFrame({
a: Series.new({type: new Int32, data: [0, 0, 1]}),
b: Series.new({type: new Int32, data: [10, 20, 20]}),
d: Series.new({type: new Float64, data: [10, 20, 30]})
});
const right_double_conflict = new DataFrame({
a: Series.new({type: new Int32, data: [0, 0, 1]}),
b: Series.new({type: new Int32, data: [10, 20, 20]}),
c: Series.new({type: new Float64, data: [10, 20, 30]})
});
describe('DataFrame.join({how="inner"}) ', () => {
test('can join with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'inner'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10]);
});
test('discards right conflicts without suffices', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'inner'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
});
test('applies lsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'inner', lsuffix: '_L'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_L']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4]);
expect([...result.get('a')]).toEqual([0, 0, 10, 10]);
});
test('applies rsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'inner', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10]);
});
test('applies lsuffix and rsuffix', () => {
const result =
left.join({other: right_conflict, on: ['b'], how: 'inner', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a_L', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10]);
});
test('can join on multi-index', () => {
const result = left_double.join({other: right_double, on: ['a', 'b'], how: 'inner'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([10, 20]);
expect([...result.get('c')]).toEqual([1, 2]);
expect([...result.get('d')]).toEqual([10, 30]);
});
test('can join on multi-index with conflict, rsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'inner', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([10, 20]);
expect([...result.get('c')]).toEqual([1, 2]);
expect([...result.get('c_R')]).toEqual([10, 30]);
});
test('can join on multi-index with conflict, lsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'inner', lsuffix: '_L'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c']));
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([10, 20]);
expect([...result.get('c_L')]).toEqual([1, 2]);
expect([...result.get('c')]).toEqual([10, 30]);
});
test('can join on multi-index with conflict, lsuffix and rsuffix', () => {
const result = left_double.join(
{other: right_double_conflict, on: ['a', 'b'], how: 'inner', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([10, 20]);
expect([...result.get('c_L')]).toEqual([1, 2]);
expect([...result.get('c_R')]).toEqual([10, 30]);
});
test('can find common type for single-index join', () => {
const left_float =
new DataFrame({a: Series.new([1, 2, 3, 4, 5]), b: Series.new([0, 0, 1, 1, 2])});
const result = left_float.join({other: right, on: ['b'], how: 'inner'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10]);
});
test('can find common type on multi-index join', () => {
const left_double_float = new DataFrame({
a: Series.new([0, 1, 1]),
b: Series.new([10, 20, 10]),
c: Series.new({type: new Float32, data: [1., 2., 3.]})
});
const result = left_double_float.join({other: right_double, on: ['a', 'b'], how: 'inner'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1]);
expect([...result.get('b')]).toEqual([10, 20]);
expect([...result.get('c')]).toEqual([1, 2]);
expect([...result.get('d')]).toEqual([10, 30]);
});
});
describe('DataFrame.join({how="left"}) ', () => {
test('can join with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'left'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10, null]);
});
test('discards right conflicts without suffices', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'left'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5]);
});
test('applies lsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'left', lsuffix: '_L'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_L']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4, 5]);
expect([...result.get('a')]).toEqual([0, 0, 10, 10, null]);
});
test('applies rsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'left', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10, null]);
});
test('applies lsuffix and rsuffix', () => {
const result =
left.join({other: right_conflict, on: ['b'], how: 'left', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a_L', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4, 5]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10, null]);
});
test('can join on multi-index', () => {
const result = left_double.join({other: right_double, on: ['a', 'b'], how: 'left'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 1]);
expect([...result.get('b')]).toEqual([10, 20, 10]);
expect([...result.get('c')]).toEqual([1, 2, 3]);
expect([...result.get('d')]).toEqual([10, 30, null]);
});
test('can join on multi-index with conflict, rsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'left', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1, 1]);
expect([...result.get('b')]).toEqual([10, 20, 10]);
expect([...result.get('c')]).toEqual([1, 2, 3]);
expect([...result.get('c_R')]).toEqual([10, 30, null]);
});
test('can join on multi-index with conflict, lsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'left', lsuffix: '_L'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c']));
expect([...result.get('a')]).toEqual([0, 1, 1]);
expect([...result.get('b')]).toEqual([10, 20, 10]);
expect([...result.get('c_L')]).toEqual([1, 2, 3]);
expect([...result.get('c')]).toEqual([10, 30, null]);
});
test('can join on multi-index with conflict, lsuffix and rsuffix', () => {
const result = left_double.join(
{other: right_double_conflict, on: ['a', 'b'], how: 'left', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1, 1]);
expect([...result.get('b')]).toEqual([10, 20, 10]);
expect([...result.get('c_L')]).toEqual([1, 2, 3]);
expect([...result.get('c_R')]).toEqual([10, 30, null]);
});
test('can find common type for single-index join', () => {
const left_double =
new DataFrame({a: Series.new([1, 2, 3, 4, 5]), b: Series.new([0, 0, 1, 1, 2])});
const result = left_double.join({other: right, on: ['b'], how: 'left'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10, null]);
});
test('can find common type on multi-index join', () => {
const left_double_float = new DataFrame({
a: Series.new([0, 1, 1]),
b: Series.new([10, 20, 10]),
c: Series.new({type: new Float32, data: [1., 2., 3.]})
});
const result = left_double_float.join({other: right_double, on: ['a', 'b'], how: 'left'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 1]);
expect([...result.get('b')]).toEqual([10, 20, 10]);
expect([...result.get('c')]).toEqual([1, 2, 3]);
expect([...result.get('d')]).toEqual([10, 30, null]);
});
});
describe('DataFrame.join({how="outer"}) ', () => {
test('can join with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'outer'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5, null]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10, null, 30]);
});
test('discards right conflicts without suffices', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'outer'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5, null]);
});
test('applies lsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'outer', lsuffix: '_L'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_L']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4, 5, null]);
expect([...result.get('a')]).toEqual([0, 0, 10, 10, null, 30]);
});
test('applies rsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'outer', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5, null]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10, null, 30]);
});
test('applies lsuffix and rsuffix', () => {
const result =
left.join({other: right_conflict, on: ['b'], how: 'outer', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a_L', 'b', 'a_R']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a_L')]).toEqual([1, 2, 3, 4, 5, null]);
expect([...result.get('a_R')]).toEqual([0, 0, 10, 10, null, 30]);
});
test('can join on multi-index', () => {
const result = left_double.join({other: right_double, on: ['a', 'b'], how: 'outer'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 10, 20]);
expect([...result.get('c')]).toEqual([1, 2, 3, null]);
expect([...result.get('d')]).toEqual([10, 30, null, 20]);
});
test('can join on multi-index with conflict, rsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'outer', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 10, 20]);
expect([...result.get('c')]).toEqual([1, 2, 3, null]);
expect([...result.get('c_R')]).toEqual([10, 30, null, 20]);
});
test('can join on multi-index with conflict, lsuffix', () => {
const result =
left_double.join({other: right_double_conflict, on: ['a', 'b'], how: 'outer', lsuffix: '_L'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c']));
expect([...result.get('a')]).toEqual([0, 1, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 10, 20]);
expect([...result.get('c_L')]).toEqual([1, 2, 3, null]);
expect([...result.get('c')]).toEqual([10, 30, null, 20]);
});
test('can join on multi-index with conflict, lsuffix and rsuffix', () => {
const result = left_double.join(
{other: right_double_conflict, on: ['a', 'b'], how: 'outer', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c_L', 'c_R']));
expect([...result.get('a')]).toEqual([0, 1, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 10, 20]);
expect([...result.get('c_L')]).toEqual([1, 2, 3, null]);
expect([...result.get('c_R')]).toEqual([10, 30, null, 20]);
});
test('can find common type for single-index join', () => {
const left_double =
new DataFrame({a: Series.new([1, 2, 3, 4, 5]), b: Series.new([0, 0, 1, 1, 2])});
const result = left_double.join({other: right, on: ['b'], how: 'outer'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
expect([...result.get('b')]).toEqual([0, 0, 1, 1, 2, 3]);
expect([...result.get('a')]).toEqual([1, 2, 3, 4, 5, null]);
expect([...result.get('c')]).toEqual([0, 0, 10, 10, null, 30]);
});
test('can find common type on multi-index join', () => {
const left_double_float = new DataFrame({
a: Series.new([0, 1, 1]),
b: Series.new([10, 20, 10]),
c: Series.new({type: new Float32, data: [1., 2., 3.]})
});
const result = left_double_float.join({other: right_double, on: ['a', 'b'], how: 'outer'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 10, 20]);
expect([...result.get('c')]).toEqual([1, 2, 3, null]);
expect([...result.get('d')]).toEqual([10, 30, null, 20]);
});
});
describe('DataFrame.join({how="right"}) ', () => {
test('can join with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'right'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
expect([...sorted_result.get('a')]).toEqual([1, 2, 3, 4, null]);
expect([...sorted_result.get('c')]).toEqual([0, 0, 10, 10, 30]);
});
test('discards right conflicts without suffices', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'right'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('a')]).toEqual([0, 0, 10, 10, 30]);
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
});
test('applies lsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'right', lsuffix: '_L'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_L']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
expect([...sorted_result.get('a_L')]).toEqual([1, 2, 3, 4, null]);
expect([...sorted_result.get('a')]).toEqual([0, 0, 10, 10, 30]);
});
test('applies rsuffix', () => {
const result = left.join({other: right_conflict, on: ['b'], how: 'right', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'a_R']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
expect([...sorted_result.get('a')]).toEqual([1, 2, 3, 4, null]);
expect([...sorted_result.get('a_R')]).toEqual([0, 0, 10, 10, 30]);
});
test('applies lsuffix and rsuffix', () => {
const result =
left.join({other: right_conflict, on: ['b'], how: 'right', lsuffix: '_L', rsuffix: '_R'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a_L', 'b', 'a_R']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
expect([...sorted_result.get('a_L')]).toEqual([1, 2, 3, 4, null]);
expect([...sorted_result.get('a_R')]).toEqual([0, 0, 10, 10, 30]);
});
test('can join on multi-index', () => {
const result = left_double.join({other: right_double, on: ['a', 'b'], how: 'right'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 20]);
expect([...result.get('c')]).toEqual([1, 2, null]);
expect([...result.get('d')]).toEqual([10, 30, 20]);
});
test('can find common type for single-index join', () => {
const left_float =
new DataFrame({a: Series.new([1, 2, 3, 4, 5]), b: Series.new([0, 0, 1, 1, 2])});
const result = left_float.join({other: right, on: ['b'], how: 'right'});
expect(result.numColumns).toEqual(3);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c']));
// Sorting is just to get 1-1 agreement with order of pd/cudf results
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1, 3]);
expect([...sorted_result.get('a')]).toEqual([1, 2, 3, 4, null]);
expect([...sorted_result.get('c')]).toEqual([0, 0, 10, 10, 30]);
});
test('can find common type on multi-index join', () => {
const left_double_float = new DataFrame({
a: Series.new([0, 1, 1]),
b: Series.new([10, 20, 10]),
c: Series.new({type: new Float32, data: [1., 2., 3.]})
});
const result = left_double_float.join({other: right_double, on: ['a', 'b'], how: 'right'});
expect(result.numColumns).toEqual(4);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b', 'c', 'd']));
expect([...result.get('a')]).toEqual([0, 1, 0]);
expect([...result.get('b')]).toEqual([10, 20, 20]);
expect([...result.get('c')]).toEqual([1, 2, null]);
expect([...result.get('d')]).toEqual([10, 30, 20]);
});
});
describe('DataFrame.join({how="leftsemi"}) ', () => {
test('can semijoin with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'leftanti'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([2]);
expect([...sorted_result.get('a')]).toEqual([5]);
});
});
describe('DataFrame.join({how="leftanti"}) ', () => {
test('can antijoin with no column name conflicts', () => {
const result = left.join({other: right, on: ['b'], how: 'leftsemi'});
expect(result.numColumns).toEqual(2);
expect(result.names).toEqual(expect.arrayContaining(['a', 'b']));
const sorted_result = result.sortValues({b: {ascending: true, null_order: 'after'}});
expect([...sorted_result.get('b')]).toEqual([0, 0, 1, 1]);
expect([...sorted_result.get('a')]).toEqual([1, 2, 3, 4]);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/sum-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
DataFrame,
Float32,
Int32,
Series,
} from '@rapidsai/cudf';
describe('dataframe.sum', () => {
test('int sum', () => {
const a = Series.new({type: new Int32, data: [1, 2, 3]});
const b = Series.new({type: new Int32, data: [4, 5, 6]});
const df = new DataFrame({'a': a, 'b': b});
expect([...df.sum()]).toEqual([6n, 15n]);
});
test('float sum', () => {
const a = Series.new({type: new Float32, data: [1, 2.5]});
const b = Series.new({type: new Float32, data: [3, 4.5]});
const df = new DataFrame({'a': a, 'b': b});
expect([...df.sum()]).toEqual([3.5, 7.5]);
});
test('empty dataframe', () => {
const df = new DataFrame({
'a': Series.new({type: new Float32, data: []}),
'b': Series.new({type: new Float32, data: []})
});
expect([...df.sum()]).toEqual([null, null]);
});
test('skip na is false', () => {
const df = new DataFrame({'a': Series.new([NaN, 1.5, NaN]), 'b': Series.new([4.5, 5.5, 6.5])});
expect([...df.sum(undefined, false)]).toEqual([NaN, 16.5]);
});
test('skip true is true', () => {
const df = new DataFrame({'a': Series.new([NaN, 1.5, NaN]), 'b': Series.new([4.5, 5.5, 6.5])});
expect([...df.sum(undefined, true)]).toEqual([1.5, 16.5]);
});
test('subset', () => {
const df = new DataFrame({'a': Series.new([1, 2, 3]), 'b': Series.new([4.5, 5.5, 6.5])});
expect([...df.sum(['a'])]).toEqual([6]);
});
test('subset and skip na is false', () => {
const df = new DataFrame({'a': Series.new([NaN, 1.5, NaN]), 'b': Series.new([4.5, 5.5, 6.5])});
expect([...df.sum(['a'], false)]).toEqual([NaN]);
});
test('subset contains incompatiable types', () => {
const a = Series.new({type: new Float32, data: [1, 2.5]});
const b = Series.new({type: new Float32, data: [3, 4.5]});
const c = Series.new({type: new Int32, data: [1, 2]});
const df = new DataFrame({'a': a, 'b': b, 'c': c});
expect(() => {
const result = df.sum(['b', 'c']);
verifySumResultType(result);
}).toThrow();
});
test('throws if dataframe contains incompatiable types', () => {
const df = new DataFrame({'a': Series.new(['foo', 'bar']), 'b': Series.new([4.5, 5.5])});
expect(() => {
const result = df.sum();
verifySumResultType(result);
}).toThrow();
const df2 = new DataFrame({'a': Series.new([false, true])});
expect(() => {
const result = df2.sum();
verifySumResultType(result);
}).toThrow();
});
test('throws if dataframe contains float and int types', () => {
const a = Series.new({type: new Int32, data: [1, 2]});
const b = Series.new({type: new Float32, data: [1.5, 2.5]});
const df = new DataFrame({'a': a, 'b': b});
expect(() => {
const result = df.sum();
verifySumResultType(result);
}).toThrow();
});
// Typescript does not allow us to throw a compile-time error if
// the return type of `sum()` is `never`.
// Instead, let's just verify the result is `never`.
function verifySumResultType(_: never) { return _; }
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/interleave-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DataFrame, Float64, Int32, List, Series} from '@rapidsai/cudf';
import {DeviceBuffer} from '@rapidsai/rmm';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
describe('DataFrame.interleaveColumns', () => {
test(`interleaves Float64 columns`, () => {
const df = new DataFrame({
a: Series.new([1, 2, 3]),
b: Series.new([4, 5, 6]),
});
const expected = [1, 4, 2, 5, 3, 6];
const actual = df.interleaveColumns();
expect([...actual]).toEqual(expected);
expectFloat64(actual.type);
// Cause a compile error if `df.interleaveColumns()` type handling fails, e.g.
// ```ts
// expectFloat64(<Int32|Float64>new Float64());
// ```
function expectFloat64(type: Float64) { expect(type).toBeInstanceOf(Float64); }
});
test(`interleaves List columns`, () => {
const df = new DataFrame({
a: Series.new([[0, 1, 2], [3, 4, 5], [6, 7, 8]]),
b: Series.new([[10, 11, 12], [13, 14, 15], [16, 17, 18]]),
});
const expected = [
[0, 1, 2],
[10, 11, 12],
[3, 4, 5],
[13, 14, 15],
[6, 7, 8],
[16, 17, 18],
];
const actual = df.interleaveColumns();
expect([...actual].map((x) => x ? [...x] : null)).toEqual(expected);
expectListOfFloat64(actual.type);
// Cause a compile error if `df.interleaveColumns()` type handling fails, e.g.
// ```ts
// expectListOfFloat64(<Int32|Float64>new List(new Field('', new Int32)));
// ```
function expectListOfFloat64(type: List<Float64>) {
expect(type).toBeInstanceOf(List);
expect(type.children[0].type).toBeInstanceOf(Float64);
}
});
test(`casts mixed types to the input dtype`, () => {
const df = new DataFrame({
a: Series.new([1, 2, 3]).cast(new Int32),
b: Series.new([4, 5, 6]),
});
const expected = [1, 4, 2, 5, 3, 6];
const actual = df.interleaveColumns(df.types['a']);
expect([...actual]).toEqual(expected);
expectInt32(actual.type);
// Cause a compile error if `df.interleaveColumns()` type handling fails, e.g.
// ```ts
// expectInt32(<Int32|Float64>new Int32());
// ```
function expectInt32(type: Int32) { expect(type).toBeInstanceOf(Int32); }
});
test(`throws an error if mixed types and no input dtype`, () => {
const df = new DataFrame({
a: Series.new([1, 2, 3]).cast(new Int32),
b: Series.new([4, 5, 6]),
});
expect(() => df.interleaveColumns()).toThrow();
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/print-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DataFrame, Int32, Series} from '@rapidsai/cudf';
const a = Series.new([0, 1, 2, 3, 4, 5, 6]);
const b = Series.new([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.61234567]);
const c = Series.new([
'foo',
null,
null,
'bar',
'baz',
null,
'123456789012345678901234567890123456789012345678901234567890'
]);
const d = a.log();
describe('dataframe.toString', () => {
test('single column', () => {
expect(new DataFrame({'a': a}).toString())
.toEqual(
`\
a
0.0
1.0
2.0
3.0
4.0
5.0
6.0
`);
expect(new DataFrame({'b': b}).toString())
.toEqual(
`\
b
0.0
1.1
2.2
3.3
4.4
5.5
6.61234567
`);
});
test('exceeds maxColWidth', () => {
expect(new DataFrame({'c': c}).toString())
.toEqual(
`\
c
foo
null
null
bar
baz
null
...
`);
});
test('maxColWidth', () => {
expect(new DataFrame({'b': b, 'c': c}).toString({maxColWidth: 70}))
.toEqual(
`\
b c
0.0 foo
1.1 null
2.2 null
3.3 bar
4.4 baz
5.5 null
6.61234567 123456789012345678901234567890123456789012345678901234567890
`);
});
test('exceeds width', () => {
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxColWidth: 70, width: 80}))
.toEqual(
`\
a b d
0.0 0.0 ... -Inf
1.0 1.1 ... 0.0
2.0 2.2 ... 0.693147181
3.0 3.3 ... 1.098612289
4.0 4.4 ... 1.386294361
5.0 5.5 ... 1.609437912
6.0 6.61234567 ... 1.791759469
`);
});
test('maxRows', () => {
// 3
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 3}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
... ... ... ...
`);
// 4
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 4}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
... ... ... ...
6.0 6.61234567 ... 1.791759469
`);
// 5
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 5}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
... ... ... ...
6.0 6.61234567 ... 1.791759469
`);
// 6
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 6}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
... ... ... ...
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
// 7
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 7}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
2.0 2.2 null 0.693147181
... ... ... ...
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
// 8
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 8}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
2.0 2.2 null 0.693147181
3.0 3.3 bar 1.098612289
4.0 4.4 baz 1.386294361
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
// 9 (+1)
expect(new DataFrame({'a': a, 'b': b, 'c': c, 'd': d}).toString({maxRows: 9}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
2.0 2.2 null 0.693147181
3.0 3.3 bar 1.098612289
4.0 4.4 baz 1.386294361
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
});
test('maxColumns', () => {
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
// 1
expect(df.toString({maxColumns: 1}))
// editor trims significant trailing whitespace in a template string
.toEqual(' a \n0.0 ...\n1.0 ...\n2.0 ...\n3.0 ...\n4.0 ...\n5.0 ...\n6.0 ...\n');
// 2
expect(df.toString({maxColumns: 2}))
.toEqual(
`\
a d
0.0 ... -Inf
1.0 ... 0.0
2.0 ... 0.693147181
3.0 ... 1.098612289
4.0 ... 1.386294361
5.0 ... 1.609437912
6.0 ... 1.791759469
`);
// 3
expect(df.toString({maxColumns: 3}))
.toEqual(
`\
a b d
0.0 0.0 ... -Inf
1.0 1.1 ... 0.0
2.0 2.2 ... 0.693147181
3.0 3.3 ... 1.098612289
4.0 4.4 ... 1.386294361
5.0 5.5 ... 1.609437912
6.0 6.61234567 ... 1.791759469
`);
// 4
expect(df.toString({maxColumns: 4}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
2.0 2.2 null 0.693147181
3.0 3.3 bar 1.098612289
4.0 4.4 baz 1.386294361
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
// 5 (+1)
expect(df.toString({maxColumns: 5}))
.toEqual(
`\
a b c d
0.0 0.0 foo -Inf
1.0 1.1 null 0.0
2.0 2.2 null 0.693147181
3.0 3.3 bar 1.098612289
4.0 4.4 baz 1.386294361
5.0 5.5 null 1.609437912
6.0 6.61234567 ... 1.791759469
`);
});
test('exceeds maxRows and maxCols', () => {
const df = new DataFrame({'a': a, 'b': b, 'c': c, 'd': d});
expect(df.toString({maxColumns: 3, maxRows: 4}))
.toEqual(
`\
a b d
0.0 0.0 ... -Inf
... ... ... ...
6.0 6.61234567 ... 1.791759469
`);
});
test('maxRows=0', () => {
const a = Series.sequence({type: new Int32, size: 5000, step: 1, init: 0});
const df = new DataFrame({'a': a});
expect(df.toString({maxRows: 0}).split('\n').length)
.toEqual(5002); // header + trailing newline
});
test('maxColumns=0', () => {
const a = Series.new([0, 1]);
const cols: any = {};
for (let i = 0; i < 30; ++i) { cols[`a${i}`] = a; }
const df = new DataFrame(cols);
expect(df.toString({maxColumns: 30}))
.toEqual(
`\
a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26 a27 a28 a29
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
`);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/dataframe/arrow-tests.ts
|
// Copyright (c) 2020, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DataFrame, Float64, Int32, Struct} from '@rapidsai/cudf';
import * as arrow from 'apache-arrow';
import {ChildProcessByStdio, spawn} from 'child_process';
import {Readable, Writable} from 'stream';
jest.setTimeout(60 * 1000);
test(`fromArrow works from host memory`, () => {
const table = arrow.tableFromArrays({
ints: new Int32Array([1, 2, 0, -3, -4]),
floats: new Float64Array([1.1, 2.2, 0, -3.3, -4.4]),
points: [
{x: 0, y: 4},
{x: 1, y: 3},
{x: 2, y: 2},
{x: 3, y: 1},
{x: 4, y: 0},
],
});
const serialized_table = arrow.tableToIPC(table); // Uint8Array
const df = DataFrame.fromArrow<{
ints: Int32, //
floats: Float64, //
points: Struct<{
x: Float64,
y: Float64,
}>;
}>(serialized_table);
expect([...df.names]).toStrictEqual(['ints', 'floats', 'points']);
expect([...df.get('ints')]).toStrictEqual([1, 2, 0, -3, -4]);
expect([...df.get('floats')]).toStrictEqual([1.1, 2.2, 0, -3.3, -4.4]);
expect([...df.get('points')].map((x) => x?.toJSON())).toStrictEqual([
{x: 0, y: 4},
{x: 1, y: 3},
{x: 2, y: 2},
{x: 3, y: 1},
{x: 4, y: 0},
]);
});
test(`fromArrow works between subprocesses`, async () => {
let src: ChildProcessByStdio<Writable, Readable, null>|undefined;
let dst: ChildProcessByStdio<Writable, Readable, null>|undefined;
try {
src = spawnIPCSourceSubprocess();
const handle = await readChildProcessOutput(src);
if (handle) {
dst = spawnIPCTargetSubprocess(JSON.parse(handle));
const data = await readChildProcessOutput(dst);
if (data) {
expect(JSON.parse(data))
.toStrictEqual(
{names: ['floats', 'ints'], a: [1.1, 2.2, 0, -3.3, -4.4], b: [1, 2, 0, -3, -4]});
} else {
throw new Error(`Invalid data from target child process: ${JSON.stringify(data)}`);
}
} else {
throw new Error(`Invalid IPC handle from source child process: ${JSON.stringify(handle)}`);
}
} finally {
dst && !dst.killed && dst.kill();
src && !src.killed && src.kill();
}
});
async function readChildProcessOutput(proc: ChildProcessByStdio<Writable, Readable, null>) {
const {stdout} = proc;
return (async () => {
for await (const chunk of stdout) {
if (chunk) {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return '' + chunk;
}
}
return '';
})();
}
function spawnIPCSourceSubprocess() {
return spawn('node',
[
`-e`,
`
const arrow = require('apache-arrow');
const { Uint8Buffer } = require('@rapidsai/cuda');
const table = arrow.tableFromArrays({
floats: new Float64Array([1.1, 2.2, 0, -3.3, -4.4]),
ints: new Int32Array([1, 2, 0, -3, -4])
});
const serialized_table = arrow.tableToIPC(table); // Uint8Array
const device_buffer = new Uint8Buffer(serialized_table.length);
device_buffer.copyFrom(serialized_table);
const handle = device_buffer.getIpcHandle();
process.stdout.write(JSON.stringify(handle));
process.on("exit", () => handle.close());
setInterval(() => { }, 60 * 1000);
`
],
{stdio: ['pipe', 'pipe', 'inherit']});
}
function spawnIPCTargetSubprocess({handle}: {handle: Array<number>}) {
return spawn('node',
[
'-e',
`
const { IpcMemory } = require("@rapidsai/cuda");
const { DataFrame } = require(".");
const dmem = new IpcMemory([${handle.toString()}]);
const df = DataFrame.fromArrow(dmem);
process.stdout.write(JSON.stringify({ names: [...df.names], a: [...df.get('floats')], b: [...df.get('ints')] }));
`
],
{stdio: ['pipe', 'pipe', 'inherit']});
}
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/utils.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
BigIntArray,
TypedArray,
TypedArrayConstructor,
} from '@rapidsai/cuda';
import {
Bool8,
DataType,
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
Numeric,
Series,
Uint16,
Uint32,
Uint64,
Uint8
} from '@rapidsai/cudf';
import * as arrow from 'apache-arrow';
export function toBigInt(value: any) { return BigInt(value == null ? 0n : value); }
export function makeTestNumbers(values: (number|null)[] = [0, 1, 2]) {
return [
values.map((x: number|null) => x == null ? null : Number(x) + 0),
values.map((x: number|null) => x == null ? null : Number(x) + 1),
] as [(number | null)[], (number | null)[]];
}
export function makeTestBigInts(values: (number|bigint|null)[] = [0, 1, 2]) {
return [
values.map((x: number|bigint|null) => x == null ? null : BigInt(x) + 0n),
values.map((x: number|bigint|null) => x == null ? null : BigInt(x) + 1n),
] as [(bigint | null)[], (bigint | null)[]];
}
export function makeTestSeries<T extends arrow.DataType>(
type: T, [lhs, rhs]: [(number | bigint | null)[], (number | bigint | null)[]]) {
return {
lhs: Series.new(arrow.vectorFromArray(lhs, type)),
rhs: Series.new(arrow.vectorFromArray(rhs, type)),
};
}
export type MathematicalUnaryOp = 'sin'|'cos'|'tan'|'asin'|'acos'|'atan'|'sinh'|'cosh'|'tanh'|
'asinh'|'acosh'|'atanh'|'exp'|'log'|'sqrt'|'cbrt'|'ceil'|'floor'|'abs';
export const mathematicalUnaryOps: MathematicalUnaryOp[] = [
'sin',
'cos',
'tan',
'asin',
'acos',
'atan',
'sinh',
'cosh',
'tanh',
'asinh',
'acosh',
'atanh',
'exp',
'log',
'sqrt',
'cbrt',
'ceil',
'floor',
'abs'
];
export const clampIntValuesLikeUnaryCast =
(a: Int8Array|Int16Array|Int32Array|Uint8Array|Uint16Array|Uint32Array) =>
<T extends DataType>(type: T, input: number[]) => {
return input.map((x) => {
a[0] = x;
if (type instanceof Bool8) { return a[0] ? 1 : 0; }
if (type instanceof Int64) { return BigInt.asIntN(64, BigInt(a[0])); }
if (type instanceof Uint64) { return BigInt.asUintN(64, BigInt(a[0])); }
return a[0];
});
};
export function clampFloatValuesLikeUnaryCast<T extends DataType>(type: T, input: number[]) {
return input.map((x) => {
if (type instanceof Bool8) { return x ? 1 : 0; }
if ((type instanceof Int8) || (type instanceof Int16) || (type instanceof Int32)) {
return x | 0;
}
if (type instanceof Int64) { return BigInt.asIntN(64, BigInt(x | 0)); }
if ((type instanceof Uint8) || (type instanceof Uint16) || (type instanceof Uint32)) {
return x < 0 ? 0 : x | 0;
}
if (type instanceof Uint64) { return BigInt.asUintN(64, BigInt(x < 0 ? 0 : x | 0)); }
return x;
});
}
export const testForEachNumericType =
(name: string,
fn: (() => void)|(<T extends TypedArray|BigIntArray, R extends Numeric>(
TypedArrayCtor: TypedArrayConstructor<T>, type: R) => void)) =>
test.each([
[Int8Array, new Int8],
[Int16Array, new Int16],
[Int32Array, new Int32],
[BigInt64Array, new Int64],
[Uint8Array, new Uint8],
[Uint16Array, new Uint16],
[Uint32Array, new Uint32],
[BigUint64Array, new Uint64],
[Float32Array, new Float32],
[Float64Array, new Float64],
[Uint8ClampedArray, new Bool8],
])(name, (TypedArrayCtor: any, type: any) => fn(TypedArrayCtor, type));
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/struct-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import '../jest-extensions';
import {setDefaultAllocator} from '@rapidsai/cuda';
import {Int32, Series} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength) => new DeviceBuffer(byteLength, mr));
describe('StructSeries', () => {
const validateElements = (vec: arrow.Vector<arrow.Int32>, col: Series<Int32>) => {
const expectedElements = vec.data[0].values.subarray(0, vec.length);
const actualElements = col.data.toArray();
expect(expectedElements).toEqualTypedArray(actualElements);
};
test('Can create from Array of Objects', () => {
const col = Series.new([
{a: 1, b: 2},
{a: 3, b: 3},
]);
expect([...col].map((x) => x!.toJSON())).toEqual([
{a: 1, b: 2},
{a: 3, b: 3},
]);
});
test('Can create from Arrow', () => {
const vec = structsOfInt32s([
{x: 0, y: 3},
{x: 1, y: 4},
{x: 2, y: 5},
]);
const xs = vec.getChildAt<arrow.Int32>(0)!;
const ys = vec.getChildAt<arrow.Int32>(1)!;
const col = Series.new(vec);
validateElements(xs, col.getChild('x'));
validateElements(ys, col.getChild('y'));
});
test('Can create a Struct of Structs from Arrow', () => {
const vec = structsOfStructsOfInt32s([
{point: {x: 0, y: 3}},
{point: {x: 1, y: 4}},
{point: {x: 2, y: 5}},
]);
const points = vec.getChildAt<StructOfInt32>(0)!;
const xs = points.getChildAt<arrow.Int32>(0)!;
const ys = points.getChildAt<arrow.Int32>(1)!;
const col = Series.new(vec);
validateElements(xs, col.getChild('point').getChild('x'));
validateElements(ys, col.getChild('point').getChild('y'));
});
test('Can gather a Struct of Structs', () => {
const vec = structsOfStructsOfInt32s([
{point: {x: 0, y: 3}},
{point: {x: 1, y: 4}},
{point: {x: 2, y: 5}},
]);
const col = Series.new(vec);
const out = col.gather(Series.new({type: new Int32, data: new Int32Array([0, 1, 2])}));
expect(out.type.children[0].name).toEqual('point');
expect(out.type.children[0].type.children[0].name).toEqual('x');
expect(out.type.children[0].type.children[1].name).toEqual('y');
const points = vec.getChildAt<StructOfInt32>(0)!;
const xs = points.getChildAt<arrow.Int32>(0)!;
const ys = points.getChildAt<arrow.Int32>(1)!;
validateElements(xs, col.getChild('point').getChild('x'));
validateElements(ys, col.getChild('point').getChild('y'));
});
test('Can concat', () => {
const vec = structsOfStructsOfInt32s([
{point: {x: 0, y: 3}},
{point: {x: 1, y: 4}},
{point: {x: 2, y: 5}},
]);
const vecToConcat = structsOfStructsOfInt32s([
{point: {x: 0, y: 3}},
{point: {x: 1, y: 4}},
{point: {x: 2, y: 5}},
]);
const result = vec.concat(vecToConcat);
expect([...result]).toEqual([...vec, ...vecToConcat]);
});
test('Can copy', () => {
const vec = structsOfStructsOfInt32s([
{point: {x: 0, y: 3}},
{point: {x: 1, y: 4}},
{point: {x: 2, y: 5}},
]);
const result = vec.concat();
expect([...result]).toEqual([...vec]);
});
});
type StructOfInt32 = arrow.Struct<{x: arrow.Int32, y: arrow.Int32}>;
type StructOfStructs = arrow.Struct<{point: StructOfInt32}>;
function structsOfInt32s(values: {x: number, y: number}[]) {
return arrow.vectorFromArray(values, new arrow.Struct([
arrow.Field.new({name: 'x', type: new arrow.Int32}),
arrow.Field.new({name: 'y', type: new arrow.Int32})
])) as arrow.Vector<StructOfInt32>;
}
function structsOfStructsOfInt32s(values: {point: {x: number, y: number}}[]) {
return arrow.vectorFromArray(values, new arrow.Struct([arrow.Field.new({
name: 'point',
type: new arrow.Struct([
arrow.Field.new({name: 'x', type: new arrow.Int32}),
arrow.Field.new({name: 'y', type: new arrow.Int32})
]),
})])) as arrow.Vector<StructOfStructs>;
}
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/timestamp-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {
Series,
TimestampDay,
TimestampMicrosecond,
TimestampMillisecond,
TimestampNanosecond,
TimestampSecond,
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr));
const data: Date[] = [
new Date('2021-08-15T12:00:00.000Z'),
new Date('2018-08-15T12:30:00.000Z'),
new Date('2118-08-15T12:30:10.000Z'),
new Date('2118-08-15T12:30:10.050Z'),
];
describe('TimestampNanosecond', () => {
test('can create', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col]).toEqual([
1629028800000,
1534336200000,
4690009810000,
4690009810050,
]);
});
test('cast Second', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampSecond).data.toArray()]).toEqual([
1629028800n,
1534336200n,
4690009810n,
4690009810n,
]);
});
test('cast MilliSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMillisecond).data.toArray()]).toEqual([
1629028800000n,
1534336200000n,
4690009810000n,
4690009810049n,
]);
});
test('cast Microsecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMicrosecond).data.toArray()]).toEqual([
1629028800000000n,
1534336200000000n,
4690009810000000n,
4690009810049999n,
]);
});
test('cast NanoSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampNanosecond).data.toArray()]).toEqual([
1629028800000000000n,
1534336200000000000n,
4690009810000000000n,
4690009810049999872n,
]);
});
});
describe('TimestampMicrosecond', () => {
test('can create', () => {
const col = Series.new({type: new TimestampMicrosecond, data: data});
expect([...col]).toEqual([
1629028800000,
1534336200000,
4690009810000,
4690009810050,
]);
});
test('cast Second', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampSecond).data.toArray()]).toEqual([
1629028800n,
1534336200n,
4690009810n,
4690009810n,
]);
});
test('cast MilliSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMillisecond).data.toArray()]).toEqual([
1629028800000n,
1534336200000n,
4690009810000n,
4690009810049n,
]);
});
test('cast Microsecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMicrosecond).data.toArray()]).toEqual([
1629028800000000n,
1534336200000000n,
4690009810000000n,
4690009810049999n,
]);
});
test('cast NanoSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampNanosecond).data.toArray()]).toEqual([
1629028800000000000n,
1534336200000000000n,
4690009810000000000n,
4690009810049999872n,
]);
});
});
describe('TimestampMillisecond', () => {
test('can create', () => {
const col = Series.new({type: new TimestampMillisecond, data: data});
expect([...col]).toEqual([
1629028800000,
1534336200000,
4690009810000,
4690009810050,
]);
});
test('cast Second', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampSecond).data.toArray()]).toEqual([
1629028800n,
1534336200n,
4690009810n,
4690009810n,
]);
});
test('cast MilliSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMillisecond).data.toArray()]).toEqual([
1629028800000n,
1534336200000n,
4690009810000n,
4690009810049n,
]);
});
test('cast Microsecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMicrosecond).data.toArray()]).toEqual([
1629028800000000n,
1534336200000000n,
4690009810000000n,
4690009810049999n,
]);
});
test('cast NanoSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampNanosecond).data.toArray()]).toEqual([
1629028800000000000n,
1534336200000000000n,
4690009810000000000n,
4690009810049999872n,
]);
});
});
describe('TimestampSecond', () => {
test('can create', () => {
const col = Series.new({type: new TimestampSecond, data: data});
expect([...col]).toEqual([
1629028800000,
1534336200000,
4690009810000,
4690009810000, // millis truncated
]);
});
test('cast Second', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampSecond).data.toArray()]).toEqual([
1629028800n,
1534336200n,
4690009810n,
4690009810n,
]);
});
test('cast MilliSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMillisecond).data.toArray()]).toEqual([
1629028800000n,
1534336200000n,
4690009810000n,
4690009810049n,
]);
});
test('cast Microsecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMicrosecond).data.toArray()]).toEqual([
1629028800000000n,
1534336200000000n,
4690009810000000n,
4690009810049999n,
]);
});
test('cast NanoSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampNanosecond).data.toArray()]).toEqual([
1629028800000000000n,
1534336200000000000n,
4690009810000000000n,
4690009810049999872n,
]);
});
});
describe('TimestampDay', () => {
test('can create', () => {
const col = Series.new({type: new TimestampDay, data: data});
expect([...col]).toEqual([
new Date('2021-08-15T00:00:00.000Z'),
new Date('2018-08-15T00:00:00.000Z'),
new Date('2118-08-15T00:00:00.000Z'),
new Date('2118-08-15T00:00:00.000Z'),
]);
});
test('cast Second', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampSecond).data.toArray()]).toEqual([
1629028800n,
1534336200n,
4690009810n,
4690009810n,
]);
});
test('cast MilliSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMillisecond).data.toArray()]).toEqual([
1629028800000n,
1534336200000n,
4690009810000n,
4690009810049n,
]);
});
test('cast Microsecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampMicrosecond).data.toArray()]).toEqual([
1629028800000000n,
1534336200000000n,
4690009810000000n,
4690009810049999n,
]);
});
test('cast NanoSecond', () => {
const col = Series.new({type: new TimestampNanosecond, data: data});
expect([...col.cast(new TimestampNanosecond).data.toArray()]).toEqual([
1629028800000000000n,
1534336200000000000n,
4690009810000000000n,
4690009810049999872n,
]);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/string-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {
Float32,
Float64,
Int16,
Int32,
Int64,
Int8,
Series,
StringSeries,
Uint16,
Uint32,
Uint64,
Uint8
} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength, mr));
const data: string[] = [
'foo bar baz', // start of string
' foo bar baz', // start of string after whitespace
'baz bar foo', // end of string
'foo bar foo', // start and end
'bar foo baz', // middle
'baz quux', // missing
'FoO', // wrong case
'bar\n foo', // multi-line
'bar\nfoo' // multi-line
];
describe('StringSeries', () => {
test('Can concat', () => {
const col = StringSeries.new(['foo']);
const colToConcat = StringSeries.new(['bar']);
const result = col.concat(colToConcat);
expect([...result]).toEqual([...col, ...colToConcat]);
});
});
describe('StringSeries', () => {
test('Can copy', () => {
const col = StringSeries.new(['foo', 'bar']);
const result = col.copy();
expect([...result]).toEqual([...col]);
});
});
describe('StringSeries.concatenate', () => {
const s = StringSeries.new(['a', 'b', null]);
const t = StringSeries.new(['foo', null, 'bar']);
test('basic (no opts)', () => {
const result = StringSeries.concatenate([s, t]);
expect([...result]).toEqual(['afoo', null, null]);
});
test('basic (repeat)', () => {
const result = StringSeries.concatenate([s, t, s, t]);
expect([...result]).toEqual(['afooafoo', null, null]);
});
test('basic (empty opts)', () => {
const result = StringSeries.concatenate([s, t], {});
expect([...result]).toEqual(['afoo', null, null]);
});
test('separator', () => {
const result = StringSeries.concatenate([s, t], {separator: '::'});
expect([...result]).toEqual(['a::foo', null, null]);
});
test('separator (repeat)', () => {
const result = StringSeries.concatenate([s, t, s], {separator: '::'});
expect([...result]).toEqual(['a::foo::a', null, null]);
});
test('nullRepr (no separator)', () => {
const result = StringSeries.concatenate([s, t], {nullRepr: 'null'});
expect([...result]).toEqual(['afoo', 'bnull', 'nullbar']);
});
test('nullRepr (separator)', () => {
const result = StringSeries.concatenate([s, t], {separator: '::', nullRepr: 'null'});
expect([...result]).toEqual(['a::foo', 'b::null', 'null::bar']);
});
test('nullRepr (separatorOnNulls)', () => {
const result = StringSeries.concatenate(
[s, t], {separator: '::', nullRepr: 'null', separatorOnNulls: false});
expect([...result]).toEqual(['a::foo', 'bnull', 'nullbar']);
});
});
describe.each([['foo'], [/foo/], [/foo/ig]])('Series regex search (pattern=%p)', (pattern) => {
test('containsRe', () => {
const expected = [true, true, true, true, true, false, false, true, true];
const s = Series.new(data);
expect([...s.containsRe(pattern)]).toEqual(expected);
});
test('countRe', () => {
const expected = [1, 1, 1, 2, 1, 0, 0, 1, 1];
const s = StringSeries.new(data);
expect([...s.countRe(pattern)]).toEqual(expected);
});
test('matchesRe', () => {
const expected = [true, false, false, true, false, false, false, false, false];
const s = StringSeries.new(data);
expect([...s.matchesRe(pattern)]).toEqual(expected);
});
});
// getJSONObject tests
test('getJSONObject', () => {
const object_data =
[{goat: {id: 0, species: 'Capra Hircus'}}, {leopard: {id: 1, species: 'Panthera pardus'}}];
const a = Series.new(object_data.map((x) => JSON.stringify(x)));
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(JSON.parse(a.getJSONObject('$.goat').getValue(0)!)).toEqual(object_data[0].goat);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(JSON.parse(a.getJSONObject('$.leopard').getValue(1)!)).toEqual(object_data[1].leopard);
const b = Series.new(['']).getJSONObject('');
expect(b.length).toBe(1);
expect(b.nullCount).toBe(1);
expect([...b]).toStrictEqual([null]);
const c = Series.new(['']).getJSONObject('$');
expect(c.length).toBe(1);
expect(c.nullCount).toBe(1);
expect(c.getValue(0)).toBeNull();
expect([...c]).toStrictEqual([null]);
expect([...Series.new(['']).getJSONObject('$.foo')]).toStrictEqual([null]);
expect([...Series.new(['{"foo":0}']).getJSONObject('$.bar')]).toStrictEqual([null]);
});
function testIntegralCast<T extends Int8|Int16|Int32|Uint8|Uint16|Uint32>(type: T) {
const a = Series.new(['0', '1', '2', null]);
expect([...a.cast(type)]).toStrictEqual([0, 1, 2, null]);
}
function testBigIntegralCast<T extends Uint64|Int64>(type: T) {
const a = Series.new(['0', '1', '2', null]);
expect([...a.cast(type)]).toStrictEqual([0n, 1n, 2n, null]);
}
describe('Series.cast Integral', () => {
test('Int8', () => { testIntegralCast(new Int8); });
test('Int16', () => { testIntegralCast(new Int16); });
test('Int32', () => { testIntegralCast(new Int32); });
test('Int64', () => { testBigIntegralCast(new Int64); });
test('Uint8', () => { testIntegralCast(new Uint8); });
test('Uint16', () => { testIntegralCast(new Uint16); });
test('Uint32', () => { testIntegralCast(new Uint32); });
test('Uint64', () => { testBigIntegralCast(new Uint64); });
});
test('Series.cast Float32', () => {
const a = Series.new(['0', '2.5', '-2', '10.2', null, '2.48e+2']);
expect([...a.cast(new Float32)]).toStrictEqual([0, 2.5, -2, 10.199999809265137, null, 248.0]);
});
test('Series.cast Float64', () => {
const a = Series.new(['0', '2.5', '-2', '10.2', null, '2.48e+2']);
expect([...a.cast(new Float64)]).toStrictEqual([0, 2.5, -2, 10.2, null, 248.0]);
});
test('Series.len', () => {
const a = Series.new(['dog', '', '\n', null]);
expect([...a.len()]).toStrictEqual([3, 0, 1, null]);
});
test('Series.byteCount', () => {
const a = Series.new(['Hello', 'Bye', 'Thanks 😊', null]);
expect([...a.byteCount()]).toStrictEqual([5, 3, 11, null]);
});
test('Series.pad (defaults)', () => {
const a = Series.new(['aa', 'bbb', 'cccc', 'ddddd', null]);
expect([...a.pad(4)]).toStrictEqual(['aa ', 'bbb ', 'cccc', 'ddddd', null]);
});
test('Series.pad (left)', () => {
const a = Series.new(['aa', 'bbb', 'cccc', 'ddddd', null]);
expect([...a.pad(4, 'left')]).toStrictEqual([' aa', ' bbb', 'cccc', 'ddddd', null]);
});
test('Series.pad (right)', () => {
const a = Series.new(['aa', 'bbb', 'cccc', 'ddddd', null]);
expect([...a.pad(4)]).toStrictEqual(['aa ', 'bbb ', 'cccc', 'ddddd', null]);
});
test('Series.pad (both)', () => {
const a = Series.new(['aa', 'bbb', 'cccc', 'ddddd', null]);
expect([...a.pad(4, 'both')]).toStrictEqual([' aa ', 'bbb ', 'cccc', 'ddddd', null]);
});
test('Series.pad (right, fill)', () => {
const a = Series.new(['aa', 'bbb', 'cccc', 'ddddd', null]);
expect([...a.pad(4, 'right', '-')]).toStrictEqual(['aa--', 'bbb-', 'cccc', 'ddddd', null]);
});
test('Series.zfill', () => {
const a = Series.new(['1234', '-9876', '+0.34', '-342567', null]);
expect([...a.zfill(6)]).toStrictEqual(['001234', '-09876', '+00.34', '-342567', null]);
});
test('Series.isHex', () => {
const a = Series.new(['123', '-456', '', 'AGE', '+17EA', '0x9EF', '123ABC', null]);
expect([...a.isHex()]).toStrictEqual([true, false, false, false, false, true, true, null]);
});
function testSmallIntegralHex<T extends Uint8|Int8>(type: T) {
const a = Series.new(['00', '1B', null]);
expect([...a.hexToIntegers(type)]).toStrictEqual([0, 27, null]);
}
function testIntegralHex<T extends Int16|Int32|Uint16|Uint32>(type: T) {
const a = Series.new(['04D2', '00', '1B', null]);
expect([...a.hexToIntegers(type)]).toStrictEqual([1234, 0, 27, null]);
}
function testBigIntegralHex<T extends Uint64|Int64>(type: T) {
const a = Series.new(['04D2', '00', '1B', null]);
expect([...a.hexToIntegers(type)]).toStrictEqual([1234n, 0n, 27n, null]);
}
describe('Series.hexToIntegers', () => {
test('Int8', () => { testSmallIntegralHex(new Int8); });
test('Int16', () => { testIntegralHex(new Int16); });
test('Int32', () => { testIntegralHex(new Int32); });
test('Int64', () => { testBigIntegralHex(new Int64); });
test('Uint8', () => { testSmallIntegralHex(new Uint8); });
test('Uint16', () => { testIntegralHex(new Uint16); });
test('Uint32', () => { testIntegralHex(new Uint32); });
test('Uint64', () => { testBigIntegralHex(new Uint64); });
});
test('Series.isIpv4', () => {
const a = Series.new(['123.255.0.7', '127.0.0.1', '', '1.2.34', '123.456.789.10', null]);
expect([...a.isIpv4()]).toStrictEqual([true, true, false, false, false, null]);
});
test('Series.ipv4ToIntegers', () => {
const a = Series.new(['123.255.0.7', '127.0.0.1', null]);
expect([...a.ipv4ToIntegers()]).toStrictEqual([2080309255n, 2130706433n, null]);
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/list-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import '../jest-extensions';
import {setDefaultAllocator} from '@rapidsai/cuda';
import {Int32, Int32Series, List, Series} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength) => new DeviceBuffer(byteLength, mr));
describe('ListSeries', () => {
const validateOffsets = (vec: arrow.Vector<arrow.List>, col: Series<List>) => {
const expectedOffsets = vec.data[0].valueOffsets.subarray(0, vec.length + 1);
const actualOffsets = col.offsets.data.toArray();
expect(expectedOffsets).toEqualTypedArray(actualOffsets);
};
const validateElements = (vec: arrow.Vector<arrow.Int32>, col: Series<Int32>) => {
const expectedElements = vec.data[0].values.subarray(0, vec.length);
const actualElements = col.data.toArray();
expect(expectedElements).toEqualTypedArray(actualElements);
};
test('Can create from JS Arrays', () => {
const listOfLists = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, null]];
const col = Series.new(listOfLists);
expect([...col].map((elt) => [...elt!])).toEqual(listOfLists);
});
test('Can create from Arrow', () => {
const vec = listsOfInt32s([[0, 1, 2], [3, 4, 5]]);
const ints = vec.getChildAt<arrow.Int32>(0)!;
const col = Series.new(vec);
validateOffsets(vec, col);
validateElements(ints, col.elements);
});
test('Can get individual values', () => {
const vec = listsOfInt32s([[0, 1, 2], [3, 4, 5]]);
const col = Series.new(vec);
for (let i = -1; ++i < col.length;) {
const elt = col.getValue(i);
expect(elt).not.toBeNull();
expect(elt).toBeInstanceOf(Int32Series);
expect([...elt]).toEqual([...vec.get(i)!]);
}
});
// Uncomment this once libcudf supports scatter w/ list_scalar
// test('Can set individual values', () => {
// const listOfLists = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, null]];
// const col = Series.new(listOfLists);
// col.setValue(0, [1, 1, 1]);
// expect([...col].map((elt) => [...elt!])).toEqual([[1, 1, 1], [3, 4, 5], [6, 7, 8], [9,
// null]]);
// });
test('Can create a List of Lists from Arrow', () => {
const vec = listsOfListsOfInt32s([[[0, 1, 2]], [[3, 4, 5], [7, 8, 9]]]);
const list = vec.getChildAt<ListOfInt32>(0)!;
const ints = list.getChildAt<arrow.Int32>(0)!;
const col = Series.new(vec);
validateOffsets(vec, col);
validateOffsets(list, col.elements);
validateElements(ints, col.elements.elements);
});
test('Can gather a List of Lists', () => {
const vec = listsOfListsOfInt32s([[[0, 1, 2]], [[3, 4, 5], [7, 8, 9]]]);
const list = vec.getChildAt<ListOfInt32>(0)!;
const ints = list.getChildAt<arrow.Int32>(0)!;
const col = Series.new(vec);
const out = col.gather(Series.new({type: new Int32, data: new Int32Array([0, 1, 2])}));
expect(out.type.children[0].name).toEqual('lists');
expect(out.type.children[0].type.children[0].name).toEqual('ints');
validateOffsets(vec, col);
validateOffsets(list, col.elements);
validateElements(ints, col.elements.elements);
});
test('Can concat Lists', () => {
const vec = listsOfInt32s([[1, 2, 3], [4, 5, 6]]);
const col = Series.new(vec);
const vecToConcat = listsOfInt32s([[7, 8, 9], [10, 11, 12]]);
const colToConcat = Series.new(vecToConcat);
const result = col.concat(colToConcat);
expect([...result]).toEqual([...col, ...colToConcat]);
});
test('Can concat List of Lists', () => {
const vec = listsOfListsOfInt32s([[[0, 1, 2]], [[3, 4, 5], [7, 8, 9]]]);
const col = Series.new(vec);
const vecToConcat = listsOfListsOfInt32s([[[10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]);
const colToConcat = Series.new(vecToConcat);
const result = col.concat(colToConcat);
expect([...result]).toEqual([...col, ...colToConcat]);
});
test('Can copy Lists', () => {
const vec = listsOfInt32s([[1, 2, 3], [4, 5, 6]]);
const col = Series.new(vec);
const result = col.copy();
expect([...result]).toEqual([...col]);
});
test('Can copy List of Lists', () => {
const vec = listsOfListsOfInt32s([[[0, 1, 2]], [[3, 4, 5], [7, 8, 9]]]);
const col = Series.new(vec);
const result = col.copy();
expect([...result]).toEqual([...col]);
});
test('Can flatten Lists', () => {
const vec = listsOfInt32s([[1, 2, 3], [4, 5, 6]]);
const col = Series.new(vec);
const result = col.flatten();
expect([...result]).toEqual([1, 2, 3, 4, 5, 6]);
const indices = col.flattenIndices();
expect([...indices]).toEqual([0, 1, 2, 0, 1, 2]);
});
test('Can flatten List of Lists', () => {
const vec = listsOfListsOfInt32s([[[0, 1, 2]], [[3, 4, 5], [7, 8, 9]]]);
const col = Series.new(vec);
const result = col.flatten();
expect([...result].map((xs) => xs ? [...xs] : null)) //
.toEqual([[0, 1, 2], [3, 4, 5], [7, 8, 9]]);
const indices = col.flattenIndices();
expect([...indices]).toEqual([0, 0, 1]);
});
test('Can flatten Lists of Structs', () => {
const vec = Series.new([
[{a: 0, b: '0'}, {a: 1, b: '1'}],
[{a: 2, b: '2'}],
[{a: 3, b: '3'}, {a: 4, b: '4'}, {a: 5, b: '5'}],
]);
const expected = Series.new([
{a: 0, b: '0'},
{a: 1, b: '1'},
{a: 2, b: '2'},
{a: 3, b: '3'},
{a: 4, b: '4'},
{a: 5, b: '5'},
]);
const actual = vec.flatten();
expect([...actual].map((x) => x!.toJSON())) //
.toEqual([...expected].map((x) => x!.toJSON()));
compareTypes(actual.type, expected.type);
});
});
type ListOfInt32 = arrow.List<arrow.Int32>;
type ListOfLists = arrow.List<ListOfInt32>;
function listsOfInt32s(values: number[][]) {
return arrow.vectorFromArray(
values, new arrow.List(arrow.Field.new({name: 'ints', type: new arrow.Int32}))) as
arrow.Vector<ListOfInt32>;
}
function listsOfListsOfInt32s(values: number[][][]) {
return arrow.vectorFromArray(values, new arrow.List(arrow.Field.new({
name: 'lists',
type: new arrow.List(arrow.Field.new({name: 'ints', type: new arrow.Int32}))
}))) as arrow.Vector<ListOfLists>;
}
| 0 |
rapidsai_public_repos/node/modules/cudf/test
|
rapidsai_public_repos/node/modules/cudf/test/series/categorical-tests.ts
|
// Copyright (c) 2021-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import '../jest-extensions';
import {setDefaultAllocator} from '@rapidsai/cuda';
import {Categorical, Series, Utf8String} from '@rapidsai/cudf';
import {CudaMemoryResource, DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
const mr = new CudaMemoryResource();
setDefaultAllocator((byteLength) => new DeviceBuffer(byteLength, mr));
describe('CategoricalSeries', () => {
test('Constructs CategoricalSeries from Arrow Dictionary Vector', () => {
const codes = arrow.vectorFromArray(new Int32Array([0, 1, 2, 2, 1, 0]));
const categories = arrow.vectorFromArray(['foo', 'bar', 'baz'], new arrow.Utf8);
const dictionary = arrow.makeVector(arrow.makeData({
type: new arrow.Dictionary(categories.type, codes.type),
length: codes.length,
data: codes.data[0].values,
dictionary: categories
}));
const categorical = Series.new(dictionary);
expect([...categorical]).toEqual([...dictionary]);
expect([...categorical.codes]).toEqual([...codes]);
expect([...categorical.categories]).toEqual([...categories]);
});
test('Can cast a String Series to Categorical', () => {
const categories = Series.new(['foo', 'foo', 'bar', 'bar']);
const categorical = categories.cast(new Categorical(categories.type));
expect([...categorical]).toEqual(['foo', 'foo', 'bar', 'bar']);
expect([...categorical.codes]).toEqual([0, 0, 1, 1]);
expect([...categorical.categories]).toEqual(['foo', 'bar']);
});
test('Can cast an Integral Series to Categorical', () => {
const vals = Series.new(new Int32Array([0, 1, 2, 1, 1, 3]));
const categorical = vals.cast(new Categorical(new Utf8String));
expect([...categorical]).toEqual(['0', '1', '2', '1', '1', '3']);
expect([...categorical.codes]).toEqual([0, 1, 2, 1, 1, 3]);
expect([...categorical.categories]).toEqual(['0', '1', '2', '3']);
});
test('Can set new categories', () => {
const categories = Series.new(['foo', 'foo', 'bar', 'bar']);
const lhs = categories.cast(new Categorical(categories.type));
const rhs = lhs.setCategories(Series.new(['bar', 'foo']));
expect([...rhs]).toEqual(['foo', 'foo', 'bar', 'bar']);
expect([...rhs.codes]).toEqual([1, 1, 0, 0]);
expect([...rhs.categories]).toEqual(['bar', 'foo']);
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test/series
|
rapidsai_public_repos/node/modules/cudf/test/series/binaryop/float32-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {makeTestNumbers, makeTestSeries} from '../utils';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
const makeTestData = (values?: (number|null)[]) =>
makeTestSeries(new arrow.Float32, makeTestNumbers(values));
describe('Series binaryops (Float32)', () => {
describe('Series.add', () => {
test('adds a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs + lhs == [0 + 0, 1 + 1, 2 + 2]
expect([...lhs.add(lhs)].map(Number)).toEqual([0, 2, 4]);
// lhs + rhs == [0 + 1, 1 + 2, 2 + 3]
expect([...lhs.add(rhs)].map(Number)).toEqual([1, 3, 5]);
});
test('adds a number', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.add(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.add(1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.add(2)].map(Number)).toEqual([2, 3, 4]);
});
test('adds a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1n)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.add(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.add(1n)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.add(2n)].map(Number)).toEqual([2, 3, 4]);
});
});
describe('Series.sub', () => {
test('subtracts a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs - lhs == [0 - 0, 1 - 1, 2 - 2]
expect([...lhs.sub(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs - rhs == [0 - 1, 1 - 2, 2 - 3]
expect([...lhs.sub(rhs)].map(Number)).toEqual([-1, -1, -1]);
// rhs - lhs == [1 - 0, 2 - 1, 3 - 2]
expect([...rhs.sub(lhs)].map(Number)).toEqual([1, 1, 1]);
});
test('subtracts a number', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.sub(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.sub(1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.sub(2)].map(Number)).toEqual([-2, -1, 0]);
});
test('subtracts a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1n)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.sub(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.sub(1n)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.sub(2n)].map(Number)).toEqual([-2, -1, 0]);
});
});
describe('Series.mul', () => {
test('multiplies against a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs * lhs == [0 * 0, 1 * 1, 2 * 2]
expect([...lhs.mul(lhs)].map(Number)).toEqual([0, 1, 4]);
// lhs * rhs == [0 * 1, 1 * 2, 2 * 3]
expect([...lhs.mul(rhs)].map(Number)).toEqual([0, 2, 6]);
});
test('multiplies against a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.mul(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mul(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.mul(2)].map(Number)).toEqual([0, 2, 4]);
});
test('multiplies against a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1n)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.mul(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mul(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.mul(2n)].map(Number)).toEqual([0, 2, 4]);
});
});
describe('Series.div', () => {
test('divides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.div(lhs)].map(Number)).toEqual([NaN, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.div(rhs)].map(Number)).toEqual([0, 0.5, 0.6666666865348816]);
});
test('divides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.div(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.div(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.div(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('divides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1n)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.div(0n)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.div(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.div(2n)].map(Number)).toEqual([0, 0.5, 1]);
});
});
describe('Series.trueDiv', () => {
test('trueDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.trueDiv(lhs)].map(Number)).toEqual([NaN, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.trueDiv(rhs)].map(Number)).toEqual([0, 0.5, 0.6666666865348816]);
});
test('trueDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.trueDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.trueDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.trueDiv(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('trueDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1n)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.trueDiv(0n)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.trueDiv(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.trueDiv(2n)].map(Number)).toEqual([0, 0.5, 1]);
});
});
describe('Series.floorDiv', () => {
test('floorDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == floor([0/0, 1/1, 2/2])
expect([...lhs.floorDiv(lhs)].map(Number)).toEqual([NaN, 1, 1]);
// lhs / rhs == floor([0/1, 1/2, 2/3])
expect([...lhs.floorDiv(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('floorDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.floorDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.floorDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.floorDiv(2)].map(Number)).toEqual([0, 0, 1]);
});
test('floorDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1n)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.floorDiv(0n)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.floorDiv(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.floorDiv(2n)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.mod', () => {
test('modulo by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs % lhs == [0 % 0, 1 % 1, 2 % 2])
expect([...lhs.mod(lhs)].map(Number)).toEqual([NaN, 0, 0]);
// lhs % rhs == [0 % 1, 1 % 2, 2 % 3])
expect([...lhs.mod(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('modulo by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(0)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.mod(1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2)].map(Number)).toEqual([0, 1, 0]);
});
test('modulo by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(0n)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.mod(1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2n)].map(Number)).toEqual([0, 1, 0]);
});
});
describe('Series.pow', () => {
test('computes to the power of a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ** lhs == [0 ** 0, 1 ** 1, 2 ** 2])
expect([...lhs.pow(lhs)].map(Number)).toEqual([1, 1, 4]);
// lhs ** rhs == [0 ** 1, 1 ** 2, 2 ** 3])
expect([...lhs.pow(rhs)].map(Number)).toEqual([0, 1, 8]);
});
test('computes to the power of a number', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1)].map(Number)).toEqual([Infinity, 1, 0.5]);
expect([...lhs.pow(0)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2)].map(Number)).toEqual([0, 1, 4]);
});
test('computes to the power of a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1n)].map(Number)).toEqual([Infinity, 1, 0.5]);
expect([...lhs.pow(0n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2n)].map(Number)).toEqual([0, 1, 4]);
});
});
describe('Series.eq', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs == lhs == true
expect([...lhs.eq(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs == rhs == false
expect([...lhs.eq(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.eq(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.eq(2)].map(Number)).toEqual([0, 0, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0n)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.eq(1n)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.eq(2n)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.ne', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs != rhs == true
expect([...lhs.ne(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs != lhs == false
expect([...lhs.ne(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ne(1)].map(Number)).toEqual([1, 0, 1]);
expect([...lhs.ne(2)].map(Number)).toEqual([1, 1, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ne(1n)].map(Number)).toEqual([1, 0, 1]);
expect([...lhs.ne(2n)].map(Number)).toEqual([1, 1, 0]);
});
});
describe('Series.lt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs < rhs == true
expect([...lhs.lt(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs < lhs == false
expect([...lhs.lt(lhs)].map(Number)).toEqual([0, 0, 0]);
// rhs < lhs == false
expect([...rhs.lt(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.lt(2)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.lt(1)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.lt(0)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.lt(2n)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.lt(1n)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.lt(0n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.le', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs <= lhs == true
expect([...lhs.le(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs <= rhs == true
expect([...lhs.le(rhs)].map(Number)).toEqual([1, 1, 1]);
// rhs <= lhs == false
expect([...rhs.le(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.le(1)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.le(0)].map(Number)).toEqual([1, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.le(1n)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.le(0n)].map(Number)).toEqual([1, 0, 0]);
});
});
describe('Series.gt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// rhs > lhs == true
expect([...rhs.gt(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs > rhs == false
expect([...lhs.gt(rhs)].map(Number)).toEqual([0, 0, 0]);
// lhs > lhs == false
expect([...lhs.gt(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.gt(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.gt(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.gt(-1)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.gt(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.gt(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.gt(-1n)].map(Number)).toEqual([1, 1, 1]);
});
});
describe('Series.ge', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs >= lhs == true
expect([...lhs.ge(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs >= rhs == false
expect([...lhs.ge(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.ge(2)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.ge(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ge(0)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.ge(2n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.ge(1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ge(0n)].map(Number)).toEqual([1, 1, 1]);
});
});
describe('Series.logicalAnd', () => {
test('logicalAnd with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs && lhs == [0 && 0, 1 && 1, 2 && 2])
expect([...lhs.logicalAnd(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs && rhs == [0 && 1, 1 && 2, 2 && 3])
expect([...lhs.logicalAnd(rhs)].map(Number)).toEqual([0, 1, 1]);
});
test('logicalAnd with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalAnd(-1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logicalAnd(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(2)].map(Number)).toEqual([0, 1, 1]);
});
});
describe('Series.logicalOr', () => {
test('logicalOr with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logicalOr(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logicalOr(rhs)].map(Number)).toEqual([1, 1, 1]);
});
test('logicalOr with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalOr(-1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalOr(1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(2)].map(Number)).toEqual([1, 1, 1]);
});
});
describe('Series.logBase', () => {
test('logBase with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logBase(lhs)].map(Number)).toEqual([NaN, NaN, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logBase(rhs)].map(Number)).toEqual([-Infinity, 0, 0.6309297680854797]);
});
test('logBase with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logBase(-1)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.logBase(0)].map(Number)).toEqual([NaN, -0, -0]);
expect([...lhs.logBase(1)].map(Number)).toEqual([-Infinity, NaN, Infinity]);
expect([...lhs.logBase(2)].map(Number)).toEqual([-Infinity, 0, 1]);
});
});
describe('Series.atan2', () => {
test('atan2 with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.atan2(lhs)].map(Number)).toEqual([0, 0.7853981852531433, 0.7853981852531433]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.atan2(rhs)].map(Number)).toEqual([0, 0.46364760398864746, 0.588002622127533]);
});
test('atan2 with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.atan2(-1)].map(Number))
.toEqual([3.141592653589793, 2.356194490192345, 2.0344439357957027]);
expect([...lhs.atan2(0)].map(Number)).toEqual([0, 1.5707963267948966, 1.5707963267948966]);
expect([...lhs.atan2(1)].map(Number)).toEqual([0, 0.7853981633974483, 1.1071487177940904]);
expect([...lhs.atan2(2)].map(Number)).toEqual([0, 0.46364760900080615, 0.7853981633974483]);
});
});
describe('Series.nullEquals', () => {
test('nullEquals with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullEquals(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullEquals(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('nullEquals with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullEquals(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullEquals(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.nullEquals(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.nullEquals(2)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.nullMax', () => {
test('nullMax with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMax(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMax(rhs)].map(Number)).toEqual([1, 2, 3]);
});
test('nullMax with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMax(-1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(1)].map(Number)).toEqual([1, 1, 2]);
expect([...lhs.nullMax(2)].map(Number)).toEqual([2, 2, 2]);
});
});
describe('Series.nullMin', () => {
test('nullMin with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMin(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMin(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('nullMin with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMin(-1)].map(Number)).toEqual([-1, -1, -1]);
expect([...lhs.nullMin(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullMin(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.nullMin(2)].map(Number)).toEqual([0, 1, 2]);
});
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test/series
|
rapidsai_public_repos/node/modules/cudf/test/series/binaryop/uint32-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {makeTestNumbers, makeTestSeries, toBigInt} from '../utils';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
const makeTestData = (values?: (number|null)[]) =>
makeTestSeries(new arrow.Uint32, makeTestNumbers(values));
describe('Series binaryops (Uint32)', () => {
describe('Series.add', () => {
test('adds a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs + lhs == [0 + 0, 1 + 1, 2 + 2]
expect([...lhs.add(lhs)].map(Number)).toEqual([0, 2, 4]);
// lhs + rhs == [0 + 1, 1 + 2, 2 + 3]
expect([...lhs.add(rhs)].map(Number)).toEqual([1, 3, 5]);
});
test('adds a number', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.add(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.add(1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.add(2)].map(Number)).toEqual([2, 3, 4]);
});
test('adds a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1n)].map(toBigInt)).toEqual([-1n, 0n, 1n]);
expect([...lhs.add(0n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.add(1n)].map(toBigInt)).toEqual([1n, 2n, 3n]);
expect([...lhs.add(2n)].map(toBigInt)).toEqual([2n, 3n, 4n]);
});
});
describe('Series.sub', () => {
test('subtracts a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs - lhs == [0 - 0, 1 - 1, 2 - 2]
expect([...lhs.sub(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs - rhs == [0 - 1, 1 - 2, 2 - 3]
expect([...lhs.sub(rhs)].map(Number)).toEqual([4294967295, 4294967295, 4294967295]);
// rhs - lhs == [1 - 0, 2 - 1, 3 - 2]
expect([...rhs.sub(lhs)].map(Number)).toEqual([1, 1, 1]);
});
test('subtracts a number', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.sub(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.sub(1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.sub(2)].map(Number)).toEqual([-2, -1, 0]);
});
test('subtracts a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1n)].map(toBigInt)).toEqual([1n, 2n, 3n]);
expect([...lhs.sub(0n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.sub(1n)].map(toBigInt)).toEqual([-1n, 0n, 1n]);
expect([...lhs.sub(2n)].map(toBigInt)).toEqual([-2n, -1n, 0n]);
});
});
describe('Series.mul', () => {
test('multiplies against a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs * lhs == [0 * 0, 1 * 1, 2 * 2]
expect([...lhs.mul(lhs)].map(Number)).toEqual([0, 1, 4]);
// lhs * rhs == [0 * 1, 1 * 2, 2 * 3]
expect([...lhs.mul(rhs)].map(Number)).toEqual([0, 2, 6]);
});
test('multiplies against a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.mul(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mul(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.mul(2)].map(Number)).toEqual([0, 2, 4]);
});
test('multiplies against a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1n)].map(toBigInt)).toEqual([0n, -1n, -2n]);
expect([...lhs.mul(0n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
expect([...lhs.mul(1n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.mul(2n)].map(toBigInt)).toEqual([0n, 2n, 4n]);
});
});
describe('Series.div', () => {
test('divides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.div(lhs)].map(Number)).toEqual([4294967295, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.div(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('divides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.div(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.div(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.div(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('divides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1n)].map(toBigInt)).toEqual([0n, -1n, -2n]);
expect([...lhs.div(0n)].map(toBigInt)).toEqual([4294967295n, 4294967295n, 4294967295n]);
expect([...lhs.div(1n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.div(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
});
});
describe('Series.trueDiv', () => {
test('trueDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.trueDiv(lhs)].map(Number)).toEqual([2147483648, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.trueDiv(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('trueDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.trueDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.trueDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.trueDiv(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('trueDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1n)].map(toBigInt)).toEqual([0n, -1n, -2n]);
expect([...lhs.trueDiv(0n)].map(toBigInt))
.toEqual([-9223372036854775808n, 9223372036854775807n, 9223372036854775807n]);
expect([...lhs.trueDiv(1n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.trueDiv(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
});
});
describe('Series.floorDiv', () => {
test('floorDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == floor([0/0, 1/1, 2/2])
expect([...lhs.floorDiv(lhs)].map(Number)).toEqual([2147483648, 1, 1]);
// lhs / rhs == floor([0/1, 1/2, 2/3])
expect([...lhs.floorDiv(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('floorDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.floorDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.floorDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.floorDiv(2)].map(Number)).toEqual([0, 0, 1]);
});
test('floorDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1n)].map(toBigInt)).toEqual([0n, -1n, -2n]);
expect([...lhs.floorDiv(0n)].map(toBigInt))
.toEqual([-9223372036854775808n, 9223372036854775807n, 9223372036854775807n]);
expect([...lhs.floorDiv(1n)].map(toBigInt)).toEqual([0n, 1n, 2n]);
expect([...lhs.floorDiv(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
});
});
describe('Series.mod', () => {
test('modulo by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs % lhs == [0 % 0, 1 % 1, 2 % 2])
expect([...lhs.mod(lhs)].map(Number)).toEqual([4294967295, 0, 0]);
// lhs % rhs == [0 % 1, 1 % 2, 2 % 3])
expect([...lhs.mod(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('modulo by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(0)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.mod(1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2)].map(Number)).toEqual([0, 1, 0]);
});
test('modulo by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(0n)].map(Number)).toEqual([4294967295, 4294967295, 4294967295]);
expect([...lhs.mod(1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2n)].map(Number)).toEqual([0, 1, 0]);
});
});
describe('Series.pow', () => {
test('computes to the power of a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ** lhs == [0 ** 0, 1 ** 1, 2 ** 2])
expect([...lhs.pow(lhs)].map(Number)).toEqual([1, 1, 4]);
// lhs ** rhs == [0 ** 1, 1 ** 2, 2 ** 3])
expect([...lhs.pow(rhs)].map(Number)).toEqual([0, 1, 8]);
});
test('computes to the power of a number', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1)].map(Number)).toEqual([Infinity, 1, 0.5]);
expect([...lhs.pow(0)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2)].map(Number)).toEqual([0, 1, 4]);
});
test('computes to the power of a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1n)].map(Number)).toEqual([9223372036854776000, 1, 0]);
expect([...lhs.pow(0n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2n)].map(Number)).toEqual([0, 1, 4]);
});
});
describe('Series.eq', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs == lhs == true
expect([...lhs.eq(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs == rhs == false
expect([...lhs.eq(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.eq(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.eq(2)].map(Number)).toEqual([0, 0, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
expect([...lhs.eq(1n)].map(toBigInt)).toEqual([0n, 1n, 0n]);
expect([...lhs.eq(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
});
});
describe('Series.ne', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs != rhs == true
expect([...lhs.ne(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs != lhs == false
expect([...lhs.ne(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ne(1)].map(Number)).toEqual([1, 0, 1]);
expect([...lhs.ne(2)].map(Number)).toEqual([1, 1, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.ne(1n)].map(toBigInt)).toEqual([1n, 0n, 1n]);
expect([...lhs.ne(2n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
});
});
describe('Series.lt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs < rhs == true
expect([...lhs.lt(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs < lhs == false
expect([...lhs.lt(lhs)].map(Number)).toEqual([0, 0, 0]);
// rhs < lhs == false
expect([...rhs.lt(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.lt(2)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.lt(1)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.lt(0)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
expect([...lhs.lt(2n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
expect([...lhs.lt(1n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
expect([...lhs.lt(0n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
});
});
describe('Series.le', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs <= lhs == true
expect([...lhs.le(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs <= rhs == true
expect([...lhs.le(rhs)].map(Number)).toEqual([1, 1, 1]);
// rhs <= lhs == false
expect([...rhs.le(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.le(1)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.le(0)].map(Number)).toEqual([1, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
expect([...lhs.le(1n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
expect([...lhs.le(0n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
});
});
describe('Series.gt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// rhs > lhs == true
expect([...rhs.gt(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs > rhs == false
expect([...lhs.gt(rhs)].map(Number)).toEqual([0, 0, 0]);
// lhs > lhs == false
expect([...lhs.gt(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.gt(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.gt(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.gt(-1)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
expect([...lhs.gt(1n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
expect([...lhs.gt(0n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.gt(-1n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
});
});
describe('Series.ge', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs >= lhs == true
expect([...lhs.ge(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs >= rhs == false
expect([...lhs.ge(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.ge(2)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.ge(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ge(0)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
expect([...lhs.ge(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
expect([...lhs.ge(1n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.ge(0n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
});
});
describe('Series.bitwiseAnd', () => {
test('bitwiseAnd with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ** lhs == [0 & 0, 1 & 1, 2 & 2])
expect([...lhs.bitwiseAnd(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs ** rhs == [0 & 1, 1 & 2, 2 & 3])
expect([...lhs.bitwiseAnd(rhs)].map(Number)).toEqual([0, 0, 2]);
});
test('bitwiseAnd with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseAnd(-1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseAnd(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.bitwiseAnd(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.bitwiseAnd(2)].map(Number)).toEqual([0, 0, 2]);
});
test('bitwiseAnd with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseAnd(-1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseAnd(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.bitwiseAnd(1n)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.bitwiseAnd(2n)].map(Number)).toEqual([0, 0, 2]);
});
});
describe('Series.bitwiseOr', () => {
test('bitwiseOr with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs | lhs == [0 | 0, 1 | 1, 2 | 2])
expect([...lhs.bitwiseOr(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs | rhs == [0 | 1, 1 | 2, 2 | 3])
expect([...lhs.bitwiseOr(rhs)].map(Number)).toEqual([1, 3, 3]);
});
test('bitwiseOr with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseOr(-1)].map(Number)).toEqual([4294967295, 4294967295, 4294967295]);
expect([...lhs.bitwiseOr(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseOr(1)].map(Number)).toEqual([1, 1, 3]);
expect([...lhs.bitwiseOr(2)].map(Number)).toEqual([2, 3, 2]);
});
test('bitwiseOr with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseOr(-1n)].map(Number)).toEqual([4294967295, 4294967295, 4294967295]);
expect([...lhs.bitwiseOr(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseOr(1n)].map(Number)).toEqual([1, 1, 3]);
expect([...lhs.bitwiseOr(2n)].map(Number)).toEqual([2, 3, 2]);
});
});
describe('Series.bitwiseXor', () => {
test('bitwiseXor with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ^ lhs == [0 ^ 0, 1 ^ 1, 2 ^ 2])
expect([...lhs.bitwiseXor(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs ^ rhs == [0 ^ 1, 1 ^ 2, 2 ^ 3])
expect([...lhs.bitwiseXor(rhs)].map(Number)).toEqual([1, 3, 1]);
});
test('bitwiseXor with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseXor(-1)].map(Number)).toEqual([4294967295, 4294967294, 4294967293]);
expect([...lhs.bitwiseXor(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseXor(1)].map(Number)).toEqual([1, 0, 3]);
expect([...lhs.bitwiseXor(2)].map(Number)).toEqual([2, 3, 0]);
});
test('bitwiseXor with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseXor(-1n)].map(Number)).toEqual([4294967295, 4294967294, 4294967293]);
expect([...lhs.bitwiseXor(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseXor(1n)].map(Number)).toEqual([1, 0, 3]);
expect([...lhs.bitwiseXor(2n)].map(Number)).toEqual([2, 3, 0]);
});
});
describe('Series.logicalAnd', () => {
test('logicalAnd with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs && lhs == [0 && 0, 1 && 1, 2 && 2])
expect([...lhs.logicalAnd(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs && rhs == [0 && 1, 1 && 2, 2 && 3])
expect([...lhs.logicalAnd(rhs)].map(Number)).toEqual([0, 1, 1]);
});
test('logicalAnd with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalAnd(-1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logicalAnd(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(2)].map(Number)).toEqual([0, 1, 1]);
});
test('logicalAnd with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalAnd(-1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logicalAnd(1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(2n)].map(Number)).toEqual([0, 1, 1]);
});
});
describe('Series.logicalOr', () => {
test('logicalOr with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logicalOr(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logicalOr(rhs)].map(Number)).toEqual([1, 1, 1]);
});
test('logicalOr with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalOr(-1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalOr(1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(2)].map(Number)).toEqual([1, 1, 1]);
});
test('logicalOr with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalOr(-1n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalOr(1n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(2n)].map(Number)).toEqual([1, 1, 1]);
});
});
describe('Series.shiftLeft', () => {
test('shiftLeft with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftLeft(lhs)].map(Number)).toEqual([0, 2, 8]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftLeft(rhs)].map(Number)).toEqual([0, 4, 16]);
});
test('shiftLeft with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftLeft(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftLeft(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftLeft(1)].map(Number)).toEqual([0, 2, 4]);
expect([...lhs.shiftLeft(2)].map(Number)).toEqual([0, 4, 8]);
});
test('shiftLeft with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftLeft(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftLeft(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftLeft(1n)].map(Number)).toEqual([0, 2, 4]);
expect([...lhs.shiftLeft(2n)].map(Number)).toEqual([0, 4, 8]);
});
});
describe('Series.shiftRight', () => {
test('shiftRight with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftRight(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftRight(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRight with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRight(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRight(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRight(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRight(2)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRight with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRight(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRight(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRight(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRight(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.shiftRightUnsigned', () => {
test('shiftRightUnsigned with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftRightUnsigned(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftRightUnsigned(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRightUnsigned with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRightUnsigned(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRightUnsigned(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRightUnsigned(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRightUnsigned(2)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRightUnsigned with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRightUnsigned(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRightUnsigned(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRightUnsigned(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRightUnsigned(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.logBase', () => {
test('logBase with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logBase(lhs)].map(Number)).toEqual([2147483648, 2147483648, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logBase(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('logBase with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logBase(-1)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.logBase(0)].map(Number)).toEqual([NaN, -0, -0]);
expect([...lhs.logBase(1)].map(Number)).toEqual([-Infinity, NaN, Infinity]);
expect([...lhs.logBase(2)].map(Number)).toEqual([-Infinity, 0, 1]);
});
test('logBase with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logBase(-1n)].map(Number))
.toEqual([-9223372036854776000, -9223372036854776000, -9223372036854776000]);
expect([...lhs.logBase(0n)].map(Number)).toEqual([-9223372036854776000, 0, 0]);
expect([...lhs.logBase(1n)].map(Number))
.toEqual([-9223372036854776000, -9223372036854776000, 9223372036854776000]);
expect([...lhs.logBase(2n)].map(Number)).toEqual([-9223372036854776000, 0, 1]);
});
});
describe('Series.atan2', () => {
test('atan2 with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.atan2(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.atan2(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('atan2 with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.atan2(-1)].map(Number))
.toEqual([3.141592653589793, 2.356194490192345, 2.0344439357957027]);
expect([...lhs.atan2(0)].map(Number)).toEqual([0, 1.5707963267948966, 1.5707963267948966]);
expect([...lhs.atan2(1)].map(Number)).toEqual([0, 0.7853981633974483, 1.1071487177940904]);
expect([...lhs.atan2(2)].map(Number)).toEqual([0, 0.46364760900080615, 0.7853981633974483]);
});
test('atan2 with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.atan2(-1n)].map(Number)).toEqual([3, 2, 2]);
expect([...lhs.atan2(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.atan2(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.atan2(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.nullEquals', () => {
test('nullEquals with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullEquals(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullEquals(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('nullEquals with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullEquals(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullEquals(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.nullEquals(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.nullEquals(2)].map(Number)).toEqual([0, 0, 1]);
});
test('nullEquals with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullEquals(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullEquals(0n)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.nullEquals(1n)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.nullEquals(2n)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.nullMax', () => {
test('nullMax with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMax(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMax(rhs)].map(Number)).toEqual([1, 2, 3]);
});
test('nullMax with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMax(-1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(1)].map(Number)).toEqual([1, 1, 2]);
expect([...lhs.nullMax(2)].map(Number)).toEqual([2, 2, 2]);
});
test('nullMax with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMax(-1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(1n)].map(Number)).toEqual([1, 1, 2]);
expect([...lhs.nullMax(2n)].map(Number)).toEqual([2, 2, 2]);
});
});
describe('Series.nullMin', () => {
test('nullMin with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMin(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMin(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('nullMin with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMin(-1)].map(Number)).toEqual([-1, -1, -1]);
expect([...lhs.nullMin(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullMin(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.nullMin(2)].map(Number)).toEqual([0, 1, 2]);
});
test('nullMin with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMin(-1n)].map(Number)).toEqual([-1, -1, -1]);
expect([...lhs.nullMin(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullMin(1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.nullMin(2n)].map(Number)).toEqual([0, 1, 2]);
});
});
});
| 0 |
rapidsai_public_repos/node/modules/cudf/test/series
|
rapidsai_public_repos/node/modules/cudf/test/series/binaryop/uint64-tests.ts
|
// Copyright (c) 2021, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {setDefaultAllocator} from '@rapidsai/cuda';
import {DeviceBuffer} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {makeTestBigInts, makeTestSeries, toBigInt} from '../utils';
setDefaultAllocator((byteLength: number) => new DeviceBuffer(byteLength));
const makeTestData = (values?: (number|null)[]) =>
makeTestSeries(new arrow.Uint64, makeTestBigInts(values));
describe('Series binaryops (Uint64)', () => {
describe('Series.add', () => {
test('adds a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs + lhs == [0 + 0, 1 + 1, 2 + 2]
expect([...lhs.add(lhs)].map(Number)).toEqual([0, 2, 4]);
// lhs + rhs == [0 + 1, 1 + 2, 2 + 3]
expect([...lhs.add(rhs)].map(Number)).toEqual([1, 3, 5]);
});
test('adds a number', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.add(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.add(1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.add(2)].map(Number)).toEqual([2, 3, 4]);
});
test('adds a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.add(-1n)]).toEqual([18446744073709551615n, 0n, 1n]);
expect([...lhs.add(0n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.add(1n)]).toEqual([1n, 2n, 3n]);
expect([...lhs.add(2n)]).toEqual([2n, 3n, 4n]);
});
});
describe('Series.sub', () => {
test('subtracts a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs - lhs == [0 - 0, 1 - 1, 2 - 2]
expect([...lhs.sub(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs - rhs == [0 - 1, 1 - 2, 2 - 3]
expect([...lhs.sub(rhs)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
// rhs - lhs == [1 - 0, 2 - 1, 3 - 2]
expect([...rhs.sub(lhs)].map(Number)).toEqual([1, 1, 1]);
});
test('subtracts a number', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1)].map(Number)).toEqual([1, 2, 3]);
expect([...lhs.sub(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.sub(1)].map(Number)).toEqual([-1, 0, 1]);
expect([...lhs.sub(2)].map(Number)).toEqual([-2, -1, 0]);
});
test('subtracts a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.sub(-1n)]).toEqual([1n, 2n, 3n]);
expect([...lhs.sub(0n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.sub(1n)]).toEqual([18446744073709551615n, 0n, 1n]);
expect([...lhs.sub(2n)]).toEqual([18446744073709551614n, 18446744073709551615n, 0n]);
});
});
describe('Series.mul', () => {
test('multiplies against a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs * lhs == [0 * 0, 1 * 1, 2 * 2]
expect([...lhs.mul(lhs)].map(Number)).toEqual([0, 1, 4]);
// lhs * rhs == [0 * 1, 1 * 2, 2 * 3]
expect([...lhs.mul(rhs)].map(Number)).toEqual([0, 2, 6]);
});
test('multiplies against a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.mul(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mul(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.mul(2)].map(Number)).toEqual([0, 2, 4]);
});
test('multiplies against a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mul(-1n)]).toEqual([0n, 18446744073709551615n, 18446744073709551614n]);
expect([...lhs.mul(0n)]).toEqual([0n, 0n, 0n]);
expect([...lhs.mul(1n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.mul(2n)]).toEqual([0n, 2n, 4n]);
});
});
describe('Series.div', () => {
test('divides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.div(lhs)].map(Number)).toEqual([4294967295, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.div(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('divides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.div(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.div(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.div(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('divides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.div(-1n)]).toEqual([0n, 0n, 0n]);
expect([...lhs.div(0n)]).toEqual([4294967295n, 4294967295n, 4294967295n]);
expect([...lhs.div(1n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.div(2n)]).toEqual([0n, 0n, 1n]);
});
});
describe('Series.trueDiv', () => {
test('trueDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == [0/0, 1/1, 2/2]
expect([...lhs.trueDiv(lhs)].map(Number)).toEqual([9223372036854776000, 1, 1]);
// lhs / rhs == [0/1, 1/2, 2/3]
expect([...lhs.trueDiv(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('trueDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.trueDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.trueDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.trueDiv(2)].map(Number)).toEqual([0, 0.5, 1]);
});
test('trueDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.trueDiv(-1n)]).toEqual([0n, 0n, 0n]);
expect([
...lhs.trueDiv(0n)
]).toEqual([9223372036854775808n, 18446744073709551615n, 18446744073709551615n]);
expect([...lhs.trueDiv(1n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.trueDiv(2n)]).toEqual([0n, 0n, 1n]);
});
});
describe('Series.floorDiv', () => {
test('floorDivides by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs / lhs == floor([0/0, 1/1, 2/2])
expect([...lhs.floorDiv(lhs)].map(Number)).toEqual([9223372036854776000, 1, 1]);
// lhs / rhs == floor([0/1, 1/2, 2/3])
expect([...lhs.floorDiv(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('floorDivides by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1)].map(Number)).toEqual([-0, -1, -2]);
expect([...lhs.floorDiv(0)].map(Number)).toEqual([NaN, Infinity, Infinity]);
expect([...lhs.floorDiv(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.floorDiv(2)].map(Number)).toEqual([0, 0, 1]);
});
test('floorDivides by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.floorDiv(-1n)]).toEqual([0n, 0n, 0n]);
expect([
...lhs.floorDiv(0n)
]).toEqual([9223372036854775808n, 18446744073709551615n, 18446744073709551615n]);
expect([...lhs.floorDiv(1n)]).toEqual([0n, 1n, 2n]);
expect([...lhs.floorDiv(2n)]).toEqual([0n, 0n, 1n]);
});
});
describe('Series.mod', () => {
test('modulo by a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs % lhs == [0 % 0, 1 % 1, 2 % 2])
expect([...lhs.mod(lhs)].map(Number)).toEqual([4294967295, 0, 0]);
// lhs % rhs == [0 % 1, 1 % 2, 2 % 3])
expect([...lhs.mod(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('modulo by a number', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(0)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.mod(1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2)].map(Number)).toEqual([0, 1, 0]);
});
test('modulo by a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.mod(-1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.mod(0n)].map(Number)).toEqual([4294967295, 4294967295, 4294967295]);
expect([...lhs.mod(1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.mod(2n)].map(Number)).toEqual([0, 1, 0]);
});
});
describe('Series.pow', () => {
test('computes to the power of a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ** lhs == [0 ** 0, 1 ** 1, 2 ** 2])
expect([...lhs.pow(lhs)].map(Number)).toEqual([1, 1, 4]);
// lhs ** rhs == [0 ** 1, 1 ** 2, 2 ** 3])
expect([...lhs.pow(rhs)].map(Number)).toEqual([0, 1, 8]);
});
test('computes to the power of a number', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1)].map(Number)).toEqual([Infinity, 1, 0.5]);
expect([...lhs.pow(0)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2)].map(Number)).toEqual([0, 1, 4]);
});
test('computes to the power of a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.pow(-1n)].map(Number)).toEqual([0, 1, 18446744073709552000]);
expect([...lhs.pow(0n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.pow(1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.pow(2n)].map(Number)).toEqual([0, 1, 4]);
});
});
describe('Series.eq', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs == lhs == true
expect([...lhs.eq(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs == rhs == false
expect([...lhs.eq(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.eq(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.eq(2)].map(Number)).toEqual([0, 0, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.eq(0n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
expect([...lhs.eq(1n)].map(toBigInt)).toEqual([0n, 1n, 0n]);
expect([...lhs.eq(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
});
});
describe('Series.ne', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs != rhs == true
expect([...lhs.ne(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs != lhs == false
expect([...lhs.ne(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ne(1)].map(Number)).toEqual([1, 0, 1]);
expect([...lhs.ne(2)].map(Number)).toEqual([1, 1, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ne(0n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.ne(1n)].map(toBigInt)).toEqual([1n, 0n, 1n]);
expect([...lhs.ne(2n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
});
});
describe('Series.lt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs < rhs == true
expect([...lhs.lt(rhs)].map(Number)).toEqual([1, 1, 1]);
// lhs < lhs == false
expect([...lhs.lt(lhs)].map(Number)).toEqual([0, 0, 0]);
// rhs < lhs == false
expect([...rhs.lt(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.lt(2)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.lt(1)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.lt(0)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.lt(3n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
expect([...lhs.lt(2n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
expect([...lhs.lt(1n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
expect([...lhs.lt(0n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
});
});
describe('Series.le', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs <= lhs == true
expect([...lhs.le(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs <= rhs == true
expect([...lhs.le(rhs)].map(Number)).toEqual([1, 1, 1]);
// rhs <= lhs == false
expect([...rhs.le(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.le(1)].map(Number)).toEqual([1, 1, 0]);
expect([...lhs.le(0)].map(Number)).toEqual([1, 0, 0]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.le(2n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
expect([...lhs.le(1n)].map(toBigInt)).toEqual([1n, 1n, 0n]);
expect([...lhs.le(0n)].map(toBigInt)).toEqual([1n, 0n, 0n]);
});
});
describe('Series.gt', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// rhs > lhs == true
expect([...rhs.gt(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs > rhs == false
expect([...lhs.gt(rhs)].map(Number)).toEqual([0, 0, 0]);
// lhs > lhs == false
expect([...lhs.gt(lhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.gt(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.gt(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.gt(-1)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.gt(2n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
expect([...lhs.gt(1n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
expect([...lhs.gt(0n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.gt(-1n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
});
});
describe('Series.ge', () => {
test('compares against Series', () => {
const {lhs, rhs} = makeTestData();
// lhs >= lhs == true
expect([...lhs.ge(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs >= rhs == false
expect([...lhs.ge(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('compares against numbers', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.ge(2)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.ge(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.ge(0)].map(Number)).toEqual([1, 1, 1]);
});
test('compares against bigints', () => {
const {lhs} = makeTestData();
expect([...lhs.ge(3n)].map(toBigInt)).toEqual([0n, 0n, 0n]);
expect([...lhs.ge(2n)].map(toBigInt)).toEqual([0n, 0n, 1n]);
expect([...lhs.ge(1n)].map(toBigInt)).toEqual([0n, 1n, 1n]);
expect([...lhs.ge(0n)].map(toBigInt)).toEqual([1n, 1n, 1n]);
});
});
describe('Series.bitwiseAnd', () => {
test('bitwiseAnd with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ** lhs == [0 & 0, 1 & 1, 2 & 2])
expect([...lhs.bitwiseAnd(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs ** rhs == [0 & 1, 1 & 2, 2 & 3])
expect([...lhs.bitwiseAnd(rhs)].map(Number)).toEqual([0, 0, 2]);
});
test('bitwiseAnd with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseAnd(-1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseAnd(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.bitwiseAnd(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.bitwiseAnd(2)].map(Number)).toEqual([0, 0, 2]);
});
test('bitwiseAnd with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseAnd(-1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseAnd(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.bitwiseAnd(1n)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.bitwiseAnd(2n)].map(Number)).toEqual([0, 0, 2]);
});
});
describe('Series.bitwiseOr', () => {
test('bitwiseOr with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs | lhs == [0 | 0, 1 | 1, 2 | 2])
expect([...lhs.bitwiseOr(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs | rhs == [0 | 1, 1 | 2, 2 | 3])
expect([...lhs.bitwiseOr(rhs)].map(Number)).toEqual([1, 3, 3]);
});
test('bitwiseOr with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseOr(-1)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
expect([...lhs.bitwiseOr(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseOr(1)].map(Number)).toEqual([1, 1, 3]);
expect([...lhs.bitwiseOr(2)].map(Number)).toEqual([2, 3, 2]);
});
test('bitwiseOr with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseOr(-1n)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
expect([...lhs.bitwiseOr(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseOr(1n)].map(Number)).toEqual([1, 1, 3]);
expect([...lhs.bitwiseOr(2n)].map(Number)).toEqual([2, 3, 2]);
});
});
describe('Series.bitwiseXor', () => {
test('bitwiseXor with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs ^ lhs == [0 ^ 0, 1 ^ 1, 2 ^ 2])
expect([...lhs.bitwiseXor(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs ^ rhs == [0 ^ 1, 1 ^ 2, 2 ^ 3])
expect([...lhs.bitwiseXor(rhs)].map(Number)).toEqual([1, 3, 1]);
});
test('bitwiseXor with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseXor(-1)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
expect([...lhs.bitwiseXor(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseXor(1)].map(Number)).toEqual([1, 0, 3]);
expect([...lhs.bitwiseXor(2)].map(Number)).toEqual([2, 3, 0]);
});
test('bitwiseXor with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.bitwiseXor(-1n)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
expect([...lhs.bitwiseXor(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.bitwiseXor(1n)].map(Number)).toEqual([1, 0, 3]);
expect([...lhs.bitwiseXor(2n)].map(Number)).toEqual([2, 3, 0]);
});
});
describe('Series.logicalAnd', () => {
test('logicalAnd with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs && lhs == [0 && 0, 1 && 1, 2 && 2])
expect([...lhs.logicalAnd(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs && rhs == [0 && 1, 1 && 2, 2 && 3])
expect([...lhs.logicalAnd(rhs)].map(Number)).toEqual([0, 1, 1]);
});
test('logicalAnd with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalAnd(-1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logicalAnd(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(2)].map(Number)).toEqual([0, 1, 1]);
});
test('logicalAnd with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalAnd(-1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logicalAnd(1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalAnd(2n)].map(Number)).toEqual([0, 1, 1]);
});
});
describe('Series.logicalOr', () => {
test('logicalOr with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logicalOr(lhs)].map(Number)).toEqual([0, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logicalOr(rhs)].map(Number)).toEqual([1, 1, 1]);
});
test('logicalOr with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalOr(-1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(0)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalOr(1)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(2)].map(Number)).toEqual([1, 1, 1]);
});
test('logicalOr with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logicalOr(-1n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.logicalOr(1n)].map(Number)).toEqual([1, 1, 1]);
expect([...lhs.logicalOr(2n)].map(Number)).toEqual([1, 1, 1]);
});
});
describe('Series.shiftLeft', () => {
test('shiftLeft with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftLeft(lhs)].map(Number)).toEqual([0, 2, 8]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftLeft(rhs)].map(Number)).toEqual([0, 4, 16]);
});
test('shiftLeft with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftLeft(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftLeft(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftLeft(1)].map(Number)).toEqual([0, 2, 4]);
expect([...lhs.shiftLeft(2)].map(Number)).toEqual([0, 4, 8]);
});
test('shiftLeft with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftLeft(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftLeft(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftLeft(1n)].map(Number)).toEqual([0, 2, 4]);
expect([...lhs.shiftLeft(2n)].map(Number)).toEqual([0, 4, 8]);
});
});
describe('Series.shiftRight', () => {
test('shiftRight with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftRight(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftRight(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRight with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRight(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRight(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRight(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRight(2)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRight with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRight(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRight(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRight(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRight(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.shiftRightUnsigned', () => {
test('shiftRightUnsigned with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.shiftRightUnsigned(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.shiftRightUnsigned(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRightUnsigned with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRightUnsigned(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRightUnsigned(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRightUnsigned(1)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRightUnsigned(2)].map(Number)).toEqual([0, 0, 0]);
});
test('shiftRightUnsigned with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.shiftRightUnsigned(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.shiftRightUnsigned(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.shiftRightUnsigned(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.shiftRightUnsigned(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.logBase', () => {
test('logBase with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.logBase(lhs)].map(Number))
.toEqual([9223372036854776000, 9223372036854776000, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.logBase(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('logBase with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.logBase(-1)].map(Number)).toEqual([NaN, NaN, NaN]);
expect([...lhs.logBase(0)].map(Number)).toEqual([NaN, -0, -0]);
expect([...lhs.logBase(1)].map(Number)).toEqual([-Infinity, NaN, Infinity]);
expect([...lhs.logBase(2)].map(Number)).toEqual([-Infinity, 0, 1]);
});
test('logBase with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.logBase(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.logBase(0n)].map(Number)).toEqual([9223372036854776000, 0, 0]);
expect([...lhs.logBase(1n)].map(Number))
.toEqual([0, 9223372036854776000, 18446744073709552000]);
expect([...lhs.logBase(2n)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.atan2', () => {
test('atan2 with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.atan2(lhs)].map(Number)).toEqual([0, 0, 0]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.atan2(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('atan2 with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.atan2(-1)].map(Number))
.toEqual([3.141592653589793, 2.356194490192345, 2.0344439357957027]);
expect([...lhs.atan2(0)].map(Number)).toEqual([0, 1.5707963267948966, 1.5707963267948966]);
expect([...lhs.atan2(1)].map(Number)).toEqual([0, 0.7853981633974483, 1.1071487177940904]);
expect([...lhs.atan2(2)].map(Number)).toEqual([0, 0.46364760900080615, 0.7853981633974483]);
});
test('atan2 with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.atan2(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.atan2(0n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.atan2(1n)].map(Number)).toEqual([0, 0, 1]);
expect([...lhs.atan2(2n)].map(Number)).toEqual([0, 0, 0]);
});
});
describe('Series.nullEquals', () => {
test('nullEquals with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullEquals(lhs)].map(Number)).toEqual([1, 1, 1]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullEquals(rhs)].map(Number)).toEqual([0, 0, 0]);
});
test('nullEquals with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullEquals(-1)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullEquals(0)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.nullEquals(1)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.nullEquals(2)].map(Number)).toEqual([0, 0, 1]);
});
test('nullEquals with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullEquals(-1n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullEquals(0n)].map(Number)).toEqual([1, 0, 0]);
expect([...lhs.nullEquals(1n)].map(Number)).toEqual([0, 1, 0]);
expect([...lhs.nullEquals(2n)].map(Number)).toEqual([0, 0, 1]);
});
});
describe('Series.nullMax', () => {
test('nullMax with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMax(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMax(rhs)].map(Number)).toEqual([1, 2, 3]);
});
test('nullMax with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMax(-1)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(0)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(1)].map(Number)).toEqual([1, 1, 2]);
expect([...lhs.nullMax(2)].map(Number)).toEqual([2, 2, 2]);
});
test('nullMax with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMax(-1n)].map(Number))
.toEqual([18446744073709552000, 18446744073709552000, 18446744073709552000]);
expect([...lhs.nullMax(0n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMax(1n)].map(Number)).toEqual([1, 1, 2]);
expect([...lhs.nullMax(2n)].map(Number)).toEqual([2, 2, 2]);
});
});
describe('Series.nullMin', () => {
test('nullMin with a Series', () => {
const {lhs, rhs} = makeTestData();
// lhs || lhs == [0 || 0, 1 || 1, 2 || 2])
expect([...lhs.nullMin(lhs)].map(Number)).toEqual([0, 1, 2]);
// lhs || rhs == [0 || 1, 1 || 2, 2 || 3])
expect([...lhs.nullMin(rhs)].map(Number)).toEqual([0, 1, 2]);
});
test('nullMin with a scalar', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMin(-1)].map(Number)).toEqual([-1, -1, -1]);
expect([...lhs.nullMin(0)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullMin(1)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.nullMin(2)].map(Number)).toEqual([0, 1, 2]);
});
test('nullMin with a bigint', () => {
const {lhs} = makeTestData();
expect([...lhs.nullMin(-1n)].map(Number)).toEqual([0, 1, 2]);
expect([...lhs.nullMin(0n)].map(Number)).toEqual([0, 0, 0]);
expect([...lhs.nullMin(1n)].map(Number)).toEqual([0, 1, 1]);
expect([...lhs.nullMin(2n)].map(Number)).toEqual([0, 1, 2]);
});
});
});
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.