Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return balancing weights as numpy arrays #114

Merged
merged 3 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 64 additions & 4 deletions src/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
#include "hictkpy/nanobind.hpp"
#include "hictkpy/pixel_selector.hpp"
#include "hictkpy/reference.hpp"
#include "hictkpy/to_pyarrow.hpp"

namespace nb = nanobind;

Expand Down Expand Up @@ -189,11 +190,62 @@ static std::vector<std::string> avail_normalizations(const hictk::File &f) {
return norms;
}

static std::vector<double> weights(const hictk::File &f, std::string_view normalization,
bool divisive) {
static auto weights(const hictk::File &f, std::string_view normalization, bool divisive) {
using WeightVector = nb::ndarray<nb::numpy, nb::shape<-1>, nb::c_contig, double>;

if (normalization == "NONE") {
return WeightVector{};
}

const auto type = divisive ? hictk::balancing::Weights::Type::DIVISIVE
: hictk::balancing::Weights::Type::MULTIPLICATIVE;

// NOLINTNEXTLINE
auto *weights_ptr = new std::vector<double>(f.normalization(normalization).to_vector(type));

auto capsule = nb::capsule(weights_ptr, [](void *vect_ptr) noexcept {
delete reinterpret_cast<std::vector<double> *>(vect_ptr); // NOLINT
});

return WeightVector{weights_ptr->data(), {weights_ptr->size()}, capsule};
}

static nb::object weights_df(const hictk::File &f, const std::vector<std::string> &normalizations,
bool divisive) {
phmap::flat_hash_set<std::string_view> names(normalizations.size());
arrow::FieldVector fields(normalizations.size());
std::vector<std::shared_ptr<arrow::Array>> columns(normalizations.size());

fields.clear();
columns.clear();

const auto type = divisive ? hictk::balancing::Weights::Type::DIVISIVE
: hictk::balancing::Weights::Type::MULTIPLICATIVE;
return f.normalization(normalization).to_vector(type);

for (const auto &normalization : normalizations) {
if (normalization == "NONE") {
fields.resize(fields.size() - 1);
columns.resize(columns.size() - 1);
continue;
}

if (names.contains(normalization)) {
throw std::runtime_error(fmt::format(
FMT_STRING("found duplicated value \"{}\" in the provided normalization name list"),
normalization));
}

names.emplace(normalization);
fields.emplace_back(arrow::field(normalization, arrow::float64(), false));
columns.emplace_back(std::make_shared<arrow::DoubleArray>(
f.nbins(), arrow::Buffer::FromVector(f.normalization(normalization).to_vector(type)),
nullptr, 0, 0));
}

auto schema = std::make_shared<arrow::Schema>(std::move(fields));

return export_pyarrow_table(arrow::Table::Make(std::move(schema), columns))
.attr("to_pandas")(nb::arg("self_destruct") = true);
}

static std::filesystem::path get_path(const hictk::File &f) { return f.path(); }
Expand Down Expand Up @@ -237,7 +289,15 @@ void declare_file_class(nb::module_ &m) {
file.def("has_normalization", &hictk::File::has_normalization, nb::arg("normalization"),
"Check whether a given normalization is available.");
file.def("weights", &file::weights, nb::arg("name"), nb::arg("divisive") = true,
"Fetch the balancing weights for the given normalization method.");
"Fetch the balancing weights for the given normalization method.",
nb::rv_policy::take_ownership);
file.def(
"weights", &file::weights_df, nb::arg("names"), nb::arg("divisive") = true,
"Fetch the balancing weights for the given normalization methods."
"Weights are returned as a pandas.DataFrame.",
nb::sig("def weights(self, names: collections.abc.Sequence[str], divisive: bool = True) -> "
"pandas.DataFrame"),
nb::rv_policy::take_ownership);
}

} // namespace hictkpy::file
15 changes: 13 additions & 2 deletions test/test_file_accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,24 @@ def test_attributes(self, file, resolution):
def test_normalizations(self, file, resolution):
f = hictkpy.File(file, resolution)

cooler_weights = ["KR", "SCALE", "VC", "VC_SQRT", "weight"]
hic_weights = ["ICE"]

if f.is_cooler():
assert f.avail_normalizations() == ["KR", "SCALE", "VC", "VC_SQRT", "weight"]
assert f.avail_normalizations() == cooler_weights
else:
assert f.avail_normalizations() == ["ICE"]
assert f.avail_normalizations() == hic_weights

assert not f.has_normalization("foo")

name = "weight" if f.is_cooler() else "ICE"
weights = f.weights(name)
assert len(weights) == f.nbins()

if f.is_cooler():
df = f.weights(cooler_weights)
assert len(df.columns) == len(cooler_weights)
else:
df = f.weights(hic_weights)
assert len(df.columns) == len(hic_weights)
assert len(df) == f.nbins()
Loading