Skip to content
Draft
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
20 changes: 18 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ include(GNUInstallDirs)

# Project's name
project(libhandlegraph)
include(cmake/HandlegraphOpenMP.cmake)
# We build using c++14
set(CMAKE_CXX_STANDARD 14)

Expand Down Expand Up @@ -109,6 +110,13 @@ add_library(handlegraph_objs OBJECT

# Use the include directory when building the objects.
# It can't be picked up via dependency by the other libraries even if it's public.
if(OpenMP_CXX_FOUND)
separate_arguments(HANDLEGRAPH_OPENMP_FLAGS NATIVE_COMMAND "${OpenMP_CXX_FLAGS}")
target_compile_options(handlegraph_objs PRIVATE ${HANDLEGRAPH_OPENMP_FLAGS})
if(OpenMP_CXX_INCLUDE_DIRS)
target_include_directories(handlegraph_objs SYSTEM PRIVATE ${OpenMP_CXX_INCLUDE_DIRS})
endif()
endif()
target_include_directories(handlegraph_objs PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/include")

# Build objects position-independent to allow a shared library
Expand All @@ -122,6 +130,10 @@ add_library(handlegraph_shared SHARED $<TARGET_OBJECTS:handlegraph_objs>)
set_target_properties(handlegraph_shared PROPERTIES OUTPUT_NAME handlegraph)
target_include_directories(handlegraph_shared INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/include> $<INSTALL_INTERFACE:include>)
add_library(handlegraph_static STATIC $<TARGET_OBJECTS:handlegraph_objs>)
if(OpenMP_CXX_FOUND)
target_link_libraries(handlegraph_shared PRIVATE OpenMP::OpenMP_CXX)
target_link_libraries(handlegraph_static INTERFACE OpenMP::OpenMP_CXX)
endif()
set_target_properties(handlegraph_static PROPERTIES OUTPUT_NAME handlegraph)
target_include_directories(handlegraph_static INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src/include> $<INSTALL_INTERFACE:include>)

Expand Down Expand Up @@ -160,7 +172,10 @@ export(EXPORT libhandlegraphTargets
# We don't use configure_package_config_file because we *only* provide targets, not any variables.
configure_file(cmake/libhandlegraphConfig.cmake
"${CMAKE_CURRENT_BINARY_DIR}/libhandlegraph/libhandlegraphConfig.cmake"
COPYONLY
@ONLY
)
configure_file(cmake/HandlegraphOpenMP.cmake
"${CMAKE_CURRENT_BINARY_DIR}/libhandlegraph/HandlegraphOpenMP.cmake" COPYONLY
)

set(ConfigPackageLocation lib/cmake/libhandlegraph)
Expand All @@ -175,7 +190,8 @@ install(EXPORT libhandlegraphTargets
)
install(
FILES
cmake/libhandlegraphConfig.cmake
"${CMAKE_CURRENT_BINARY_DIR}/libhandlegraph/libhandlegraphConfig.cmake"
cmake/HandlegraphOpenMP.cmake
"${CMAKE_CURRENT_BINARY_DIR}/libhandlegraph/libhandlegraphConfigVersion.cmake"
DESTINATION
${ConfigPackageLocation}
Expand Down
16 changes: 16 additions & 0 deletions cmake/HandlegraphOpenMP.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
find_package(OpenMP QUIET COMPONENTS CXX)
if(NOT OpenMP_CXX_FOUND AND CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang"
AND NOT CMAKE_DISABLE_FIND_PACKAGE_OpenMP)
# AppleClang needs the separately installed libomp from Homebrew or MacPorts.
find_path(HANDLEGRAPH_OMP_INCLUDE omp.h
HINTS "$ENV{HOMEBREW_PREFIX}/opt/libomp/include" /opt/homebrew/opt/libomp/include /usr/local/opt/libomp/include /opt/local/include/libomp)
find_library(HANDLEGRAPH_OMP_LIBRARY omp
HINTS "$ENV{HOMEBREW_PREFIX}/opt/libomp/lib" /opt/homebrew/opt/libomp/lib /usr/local/opt/libomp/lib /opt/local/lib/libomp)
if(HANDLEGRAPH_OMP_INCLUDE AND HANDLEGRAPH_OMP_LIBRARY)
set(OpenMP_CXX_FLAGS "-Xpreprocessor -fopenmp")
set(OpenMP_CXX_INCLUDE_DIR "${HANDLEGRAPH_OMP_INCLUDE}")
set(OpenMP_CXX_LIB_NAMES omp)
set(OpenMP_omp_LIBRARY "${HANDLEGRAPH_OMP_LIBRARY}")
find_package(OpenMP QUIET COMPONENTS CXX)
endif()
endif()
9 changes: 8 additions & 1 deletion cmake/libhandlegraphConfig.cmake
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
if("@OpenMP_CXX_FOUND@")
include("${CMAKE_CURRENT_LIST_DIR}/HandlegraphOpenMP.cmake")
if(NOT OpenMP_CXX_FOUND)
set(libhandlegraph_FOUND FALSE)
set(libhandlegraph_NOT_FOUND_MESSAGE "This libhandlegraph build requires C++ OpenMP")
return()
endif()
endif()
include("${CMAKE_CURRENT_LIST_DIR}/libhandlegraphTargets.cmake")

95 changes: 89 additions & 6 deletions src/chop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
#include <cassert>
#include <algorithm>
#include <stdexcept>
#include <exception>
#ifdef _OPENMP
#include <omp.h>
#endif

namespace handlegraph {
namespace algorithms {
Expand Down Expand Up @@ -340,7 +344,13 @@ bool nodes_are_perfect_path_neighbors(const PathHandleGraph& graph, handle_t lef

}

vector<deque<handle_t>> simple_components(const PathHandleGraph& graph, int min_size = 1) {
// The edge walk checks that the left handle's only outgoing edge is also
// the right handle's only incoming edge. The optional neighbor_check(left,
// right) tests only whether each visit to either handle has a matching
// adjacent visit to the other in the expected orientation, including
// repeated visits. Without the callback, check the path steps directly.
vector<deque<handle_t>> simple_components(const PathHandleGraph& graph, int min_size = 1,
const std::function<bool(handle_t, handle_t)>* neighbor_check = nullptr) {
Comment on lines +352 to +353

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There probably should be documentation for what question exactly neighbor_check() is expected to answer.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented the callback contract in 9b02f6c. The edge walk has already checked that the pair is unbranched. neighbor_check(left, right) then answers whether every path visit to either handle has a matching adjacent visit to the other in the expected orientation, including repeated visits. Without a callback, the same check runs directly on the path steps.


// go around and establish groupings
unordered_set<nid_t> seen;
Expand Down Expand Up @@ -391,7 +401,7 @@ vector<deque<handle_t>> simple_components(const PathHandleGraph& graph, int min_
// Move over left to that node
l = prev.front();
// avoid merging if it breaks stored paths
if (!nodes_are_perfect_path_neighbors(graph, l, last)) {
if (!(neighbor_check ? (*neighbor_check)(l, last) : nodes_are_perfect_path_neighbors(graph, l, last))) {
#ifdef debug
cerr << "\tNot perfect neighbors!" << endl;
#endif
Expand Down Expand Up @@ -454,7 +464,7 @@ vector<deque<handle_t>> simple_components(const PathHandleGraph& graph, int min_
// Move over right to that node
r = next.front();
// avoid merging if it breaks stored paths
if (!nodes_are_perfect_path_neighbors(graph, last, r)) {
if (!(neighbor_check ? (*neighbor_check)(last, r) : nodes_are_perfect_path_neighbors(graph, last, r))) {
#ifdef debug
cerr << "\tNot perfect neighbors!" << endl;
#endif
Expand Down Expand Up @@ -681,13 +691,79 @@ void unchop(MutablePathDeletableHandleGraph& graph) {
#ifdef debug
std::cerr << "Running unchop" << std::endl;
#endif

std::unordered_map<nid_t, uint64_t> node_rank;
uint64_t rank = 0;
graph.for_each_handle([&](const handle_t& h) {
node_rank[graph.get_id(h)] = rank++;
});
Comment thread
adamnovak marked this conversation as resolved.
Resolved


// The OpenMP pass caches path compatibility for unbranched oriented
// pairs so simple_components() can use those answers without rescanning paths.
// The component walk still follows edges and checks degrees. If OpenMP
// is unavailable or the pass is skipped, neighbor_check is left unset
// and the same path compatibility check runs on demand.
std::vector<uint64_t> perfect_neighbors;
std::function<bool(handle_t, handle_t)> neighbor_check;
#ifdef _OPENMP
Comment on lines +706 to +708

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a little trouble seeing how the control flow comes back together between OpenMP and non-OpenMP mode and still gets the right result, since there isn't a comment explaining the idea here and there's a bit OpenMP-only block with no else branch. So it might want explaining.

Suggested change
std::vector<uint64_t> perfect_neighbors;
std::function<bool(handle_t, handle_t)> neighbor_check;
#ifdef _OPENMP
// This is a bit vector of whether a handle and the one to its right are
// perfect path neighbors (i.e. participate in exactly the same paths)
// and can be merged. If we fill it in in parallel now, we don't have
// to look at the paths in a single thread later.
std::vector<uint64_t> perfect_neighbors;
// We can fill this in with a function to quickly answer the question
// of whether nodes are perfect path neighbors. If left unset, the
// graph will be checked.
std::function<bool(handle_t, handle_t)> neighbor_check;
#ifdef _OPENMP
// Do a parallel pass now to fill in the neighbor information cache.

Looking more closely, it looks like we check both degree and path constraints here to fill the cache, and then in simple_components() we do all the degree checks/edge-following again and then consult the cache just for the path check. Ideally we'd do something clever with linked lists or a big table of next-perfect-neighbor ranks that we could fill in parallel, and then turn into a vector<deque<handle_t>> without any more need to touch the edges. But that might be overkill.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. In 9b02f6c I documented how both paths reach the same check. The OpenMP pass caches path compatibility for the unbranched pairs. When that pass is skipped, simple_components() checks the path steps on demand. The component walk still checks edges and degrees. I’d revisit the successor table if profiling shows that the repeated edge walk is costly.

std::vector<handle_t> original_handles;
const auto* ranked = dynamic_cast<const RankedHandleGraph*>(&graph);
const auto& ranks = node_rank;
auto cache_index = [&](handle_t h) {
return ranked ? ranked->handle_to_rank(h) - 1
: 2 * ranks.at(graph.get_id(h)) + graph.get_is_reverse(h);
};
if (omp_get_max_threads() > 1 && !omp_in_parallel() && graph.get_node_count() != 0) {
if (!ranked) {
original_handles.resize(graph.get_node_count());
graph.for_each_handle([&](const handle_t& h) {
original_handles[ranks.at(graph.get_id(h))] = h;
});
}

// Store only the canonical direction of each edge. A worker writes one
// complete word, even if the other orientation ranks in another block.
const size_t orientations = 2 * graph.get_node_count();
constexpr size_t word_bits = 64;
perfect_neighbors.resize((orientations - 1) / word_bits + 1);
std::exception_ptr failure;
#pragma omp parallel for schedule(dynamic, 8)
for (size_t word = 0; word < perfect_neighbors.size(); ++word) {
try {
uint64_t bits = 0;
size_t start = word * word_bits;
size_t end = std::min(start + word_bits, orientations);
for (size_t i = start; i < end; ++i) {
handle_t left = ranked ? ranked->rank_to_handle(i + 1)
: (i % 2 ? graph.flip(original_handles[i / 2]) : original_handles[i / 2]);
if (graph.get_degree(left, false) != 1) continue;
handle_t right;
graph.follow_edges(left, false, [&](const handle_t& h) {
right = h;
return false;
});
if (graph.get_degree(right, true) != 1) continue;
if (as_integer(left) > as_integer(graph.flip(right))) continue;
if (nodes_are_perfect_path_neighbors(graph, left, right)) {
bits |= uint64_t{1} << (i - start);
}
}
perfect_neighbors[word] = bits;
} catch (...) {
#pragma omp critical(handlegraph_unchop_failure)
{
if (!failure) failure = std::current_exception();
}
}
}
if (failure) std::rethrow_exception(failure);
neighbor_check = [&](handle_t left, handle_t right) {
handle_t opposite = graph.flip(right);
size_t i = cache_index(as_integer(left) <= as_integer(opposite) ? left : opposite);
return ((perfect_neighbors[i / word_bits] >> (i % word_bits)) & 1) != 0;
};
}
#endif
// if possible, don't hold these in memory
// meanwhile, we exploit the it for parallelizing the paths' validation
std::vector<std::string> path_names;
Expand All @@ -708,7 +784,14 @@ void unchop(MutablePathDeletableHandleGraph& graph) {
++rank;
});

auto components = simple_components(graph, 2);
auto components = simple_components(graph, 2, neighbor_check ? &neighbor_check : nullptr);
// No parallel reader may survive into graph mutation.
perfect_neighbors.clear();
perfect_neighbors.shrink_to_fit();
#ifdef _OPENMP
original_handles.clear();
original_handles.shrink_to_fit();
#endif
std::unordered_set<nid_t> to_merge;
for (auto& comp : components) {
for (auto& handle : comp) {
Expand Down
4 changes: 4 additions & 0 deletions src/include/handlegraph/algorithms/chop.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ void chop(MutablePathDeletableHandleGraph& graph, const std::vector<std::pair<ni
* nodes.
*
* Invalidates handles into the graph.
*
* OpenMP can parallelize read-only edge and path traversal. Graph edits
* are serial. When using multiple threads the backend must permit
* concurrent const traversal.
*/
void unchop(MutablePathDeletableHandleGraph& graph);

Expand Down