[med-svn] [Git][med-team/libpinchesandcacti][master] 2 commits: Restore the vg-compatible cactus snarl decomposition API
Andreas Tille (@tille)
gitlab at salsa.debian.org
Wed Nov 4 06:53:30 GMT 2026
Andreas Tille pushed to branch master at Debian Med / libpinchesandcacti
Commits:
9a024134 by Andreas Tille at 2026-11-04T07:24:48+01:00
Restore the vg-compatible cactus snarl decomposition API
Upstream 1d38818 rewrote impl/stCactusGraphs.c with opaque internal data
structures and dropped the snarl decomposition layer (stSnarl,
stSnarlDecomposition, stCactusGraph_getSnarlDecomposition,
stCactusGraph_getTopLevelSnarlChain, stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash)
that vg (med-team/vg) needs. Restore the API and implementation of the
previous upstream (0.0~git20240507.67138b5) with its unit test. The three
edge connected component routine is the in-tree MIT licensed C port from
the previous package, so the result stays DFSG-clean. The new
stPinchGraphs, stPinchPhylogeny and stThreeEdgeConnected code is
unaffected; it only shares sonLib with the cactus module.
- - - - -
e69105ed by Andreas Tille at 2026-11-04T07:52:46+01:00
Upload to unstable
- - - - -
3 changed files:
- debian/changelog
- + debian/patches/0002-Restore-vg-compatible-cactus-snarl-API.patch
- debian/patches/series
Changes:
=====================================
debian/changelog
=====================================
@@ -1,3 +1,12 @@
+libpinchesandcacti (0.0~git20261029.1d38818-2) unstable; urgency=medium
+
+ * Restore the vg-compatible cactus snarl decomposition API
+ (stSnarl, stSnarlDecomposition, stCactusGraph_getSnarlDecomposition,
+ stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash) that upstream
+ 1d38818 removed and that vg needs in order to build.
+
+ -- Andreas Tille <tille at debian.org> Wed, 04 Nov 2026 07:38:28 +0100
+
libpinchesandcacti (0.0~git20261029.1d38818-1) unstable; urgency=medium
* Change packaging to fork which immediately replaced non-free parts
=====================================
debian/patches/0002-Restore-vg-compatible-cactus-snarl-API.patch
=====================================
@@ -0,0 +1,2759 @@
+Description: Restore the vg-compatible cactus snarl decomposition API
+ The 2026 upstream rewrite (1d38818) removed the snarl decomposition layer
+ from the cactus graph code (stSnarl, stSnarlDecomposition,
+ stCactusGraph_getSnarlDecomposition, stCactusGraph_getTopLevelSnarlChain,
+ stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash) and reimplemented
+ stCactusGraphs.c with opaque internal data structures. vg
+ (https://salsa.debian.org/med-team/vg) computes its snarl decomposition
+ entirely through that public API, so it can no longer be built against the
+ current upstream.
+ .
+ This restores the public API and implementation of the previous upstream
+ (0.0~git20240507.67138b5) as packaged by Debian, whose three-edge-connected
+ component routine is the in-tree translation of the MIT licensed vg
+ implementation (Erik Garrison) rather than the non-free
+ externalTools/threeEdgeConnected code, so it stays DFSG-clean. The matching
+ upstream unit test is restored with it.
+ .
+ The new stPinchGraphs, stPinchPhylogeny and stThreeEdgeConnected
+ implementation keep the current upstream code: they only share sonLib with
+ the cactus graph module, which vg does not use for snarls.
+Author: Andreas Tille <tille at debian.org>
+Forwarded: not-needed
+Last-Update: 2026-11-04
+Assisted-By: deepseek-v4.1-flash-free
+
+--- a/impl/stCactusGraphs.c
++++ b/impl/stCactusGraphs.c
+@@ -7,91 +7,16 @@
+
+ #include "sonLib.h"
+ #include "stCactusGraphs.h"
+-#include "stThreeEdgeConnected.h"
+ #include <stdio.h>
+ #include <stdlib.h>
+-#include <inttypes.h>
+-
+-/*
+- * The nodes of a graph are kept on an intrusive doubly linked list, in the order the old
+- * object-to-node hash iterated them: creation order, with a merged node moving to the tail (the hash
+- * removed and re-inserted it). That order decides how the graph is traversed and so what the caller
+- * gets out, so it is preserved exactly. Nodes and edge ends come from chunk arenas owned by the graph:
+- * a merged-away node is simply unlinked, and destruction frees the chunks.
+- */
+-struct _stCactusNode {
+- stCactusEdgeEnd *head;
+- stCactusEdgeEnd *tail;
+- void *nodeObject;
+- stCactusNode *prevNode, *nextNode;
+- stCactusEdgeEnd *onChainEdgeEnd; //scratch for stCactusGraph_markCycles
+- int64_t index; //scratch: dense id for the 3-edge-connected computation
+- uint64_t mark; //scratch: the epoch the node was last visited in by a component search
+-};
+-
+-struct _stCactusEdgeEnd {
+- stCactusEdgeEnd *otherEdgeEnd;
+- stCactusNode *node;
+- stCactusEdgeEnd *nEdgeEnd;
+- void *endObject;
+- stCactusEdgeEnd *link;
+- bool linkOrientation;
+- bool isChainEnd;
+-};
+-
+-#define ST_CACTUS_CHUNK_SIZE 4096
+-
+-struct _stCactusGraph {
+- stCactusNode *firstNode, *lastNode;
+- int64_t nodeNumber;
+- uint64_t markEpoch;
+- stList *nodeChunks; //arrays of ST_CACTUS_CHUNK_SIZE nodes
+- int64_t nodeChunkUsed;
+- stList *edgeEndChunks; //arrays of ST_CACTUS_CHUNK_SIZE edge ends
+- int64_t edgeEndChunkUsed;
+- void (*destructNodeObjectFn)(void *);
+- void (*destructEdgeEndObjectFn)(void *);
+-};
+
+ //Node functions
+
+-static void stCactusGraph_appendNode(stCactusGraph *graph, stCactusNode *node) {
+- node->prevNode = graph->lastNode;
+- node->nextNode = NULL;
+- if (graph->lastNode == NULL) {
+- graph->firstNode = node;
+- } else {
+- graph->lastNode->nextNode = node;
+- }
+- graph->lastNode = node;
+- graph->nodeNumber++;
+-}
+-
+-static void stCactusGraph_unlinkNode(stCactusGraph *graph, stCactusNode *node) {
+- if (node->prevNode == NULL) {
+- assert(graph->firstNode == node);
+- graph->firstNode = node->nextNode;
+- } else {
+- node->prevNode->nextNode = node->nextNode;
+- }
+- if (node->nextNode == NULL) {
+- assert(graph->lastNode == node);
+- graph->lastNode = node->prevNode;
+- } else {
+- node->nextNode->prevNode = node->prevNode;
+- }
+- node->prevNode = node->nextNode = NULL;
+- graph->nodeNumber--;
+-}
+-
+ stCactusNode *stCactusNode_construct(stCactusGraph *graph, void *nodeObject) {
+- if (graph->nodeChunkUsed == ST_CACTUS_CHUNK_SIZE || stList_length(graph->nodeChunks) == 0) {
+- stList_append(graph->nodeChunks, st_calloc(ST_CACTUS_CHUNK_SIZE, sizeof(stCactusNode)));
+- graph->nodeChunkUsed = 0;
+- }
+- stCactusNode *node = &((stCactusNode *) stList_peek(graph->nodeChunks))[graph->nodeChunkUsed++];
++ stCactusNode *node = st_calloc(1, sizeof(stCactusNode));
+ node->nodeObject = nodeObject;
+- stCactusGraph_appendNode(graph, node);
++ assert(stHash_search(graph->objectToNodeHash, nodeObject) == NULL);
++ stHash_insert(graph->objectToNodeHash, nodeObject, node);
+ return node;
+ }
+
+@@ -118,7 +43,7 @@ stCactusEdgeEnd *stCactusNode_getFirstEd
+ }
+
+ int64_t stCactusGraph_getNodeNumber(stCactusGraph *graph) {
+- return graph->nodeNumber;
++ return stHash_size(graph->objectToNodeHash);
+ }
+
+ //Private node functions
+@@ -134,7 +59,7 @@ static void stCactusNode_destruct(stCact
+ if (destructNodeObjectFn != NULL) {
+ destructNodeObjectFn(node->nodeObject);
+ }
+- //the node's memory belongs to the graph's arena
++ free(node);
+ }
+
+ static void stCactusNode_mergeNodes(stCactusGraph *graph, stCactusNode *node1, stCactusNode *node2,
+@@ -142,11 +67,12 @@ static void stCactusNode_mergeNodes(stCa
+ if (node1 == node2) {
+ return;
+ }
+- //The surviving node moves to the end of the node order, as the hash re-insert used to put it
+- stCactusGraph_unlinkNode(graph, node2);
+- stCactusGraph_unlinkNode(graph, node1);
++ assert(stHash_search(graph->objectToNodeHash, stCactusNode_getObject(node1)) == node1);
++ assert(stHash_search(graph->objectToNodeHash, stCactusNode_getObject(node2)) == node2);
++ stHash_remove(graph->objectToNodeHash, stCactusNode_getObject(node1));
++ stHash_remove(graph->objectToNodeHash, stCactusNode_getObject(node2));
+ node1->nodeObject = mergeNodeObjects(node1->nodeObject, node2->nodeObject);
+- stCactusGraph_appendNode(graph, node1);
++ stHash_insert(graph->objectToNodeHash, stCactusNode_getObject(node1), node1);
+ if (node2->head != NULL) {
+ if (node1->head == NULL) {
+ node1->head = node2->head;
+@@ -161,7 +87,7 @@ static void stCactusNode_mergeNodes(stCa
+ }
+ node1->tail = node2->tail;
+ }
+- //node2's memory belongs to the graph's arena
++ free(node2);
+ }
+
+ //Edge functions
+@@ -178,18 +104,10 @@ static void connectUpEdgeEnd(stCactusEdg
+ node->tail = edgeEnd;
+ }
+
+-static stCactusEdgeEnd *stCactusGraph_allocateEdgeEnd(stCactusGraph *graph) {
+- if (graph->edgeEndChunkUsed == ST_CACTUS_CHUNK_SIZE || stList_length(graph->edgeEndChunks) == 0) {
+- stList_append(graph->edgeEndChunks, st_calloc(ST_CACTUS_CHUNK_SIZE, sizeof(stCactusEdgeEnd)));
+- graph->edgeEndChunkUsed = 0;
+- }
+- return &((stCactusEdgeEnd *) stList_peek(graph->edgeEndChunks))[graph->edgeEndChunkUsed++];
+-}
+-
+ stCactusEdgeEnd *stCactusEdgeEnd_construct(stCactusGraph *graph, stCactusNode *node1, stCactusNode *node2, void *edgeEndObject1,
+ void *edgeEndObject2) {
+- stCactusEdgeEnd *edgeEnd1 = stCactusGraph_allocateEdgeEnd(graph);
+- stCactusEdgeEnd *edgeEnd2 = stCactusGraph_allocateEdgeEnd(graph);
++ stCactusEdgeEnd *edgeEnd1 = st_calloc(1, sizeof(stCactusEdgeEnd));
++ stCactusEdgeEnd *edgeEnd2 = st_calloc(1, sizeof(stCactusEdgeEnd));
+
+ connectUpEdgeEnd(edgeEnd1, node1, edgeEnd2, edgeEndObject1);
+ connectUpEdgeEnd(edgeEnd2, node2, edgeEnd1, edgeEndObject2);
+@@ -234,7 +152,7 @@ static void stCactusEdgeEnd_destruct(stC
+ if (destructEdgeEndObjectFn != NULL) {
+ destructEdgeEndObjectFn(edgeEnd->endObject);
+ }
+- //the edge end's memory belongs to the graph's arena
++ free(edgeEnd);
+ }
+
+ static void stCactusEdgeEnd_setLink(stCactusEdgeEnd *edgeEnd, stCactusEdgeEnd *otherEdgeEnd) {
+@@ -252,9 +170,8 @@ static void stCactusEdgeEnd_setIsChainEn
+ //Graph functions
+
+ stCactusGraph *stCactusGraph_construct2(void(*destructNodeObjectFn)(void *), void(*destructEdgeEndObjectFn)(void *)) {
+- stCactusGraph *cactusGraph = st_calloc(1, sizeof(stCactusGraph));
+- cactusGraph->nodeChunks = stList_construct3(0, free);
+- cactusGraph->edgeEndChunks = stList_construct3(0, free);
++ stCactusGraph *cactusGraph = st_malloc(sizeof(stCactusGraph));
++ cactusGraph->objectToNodeHash = stHash_construct();
+ cactusGraph->destructNodeObjectFn = destructNodeObjectFn;
+ cactusGraph->destructEdgeEndObjectFn = destructEdgeEndObjectFn;
+ return cactusGraph;
+@@ -271,104 +188,246 @@ void stCactusGraph_destruct(stCactusGrap
+ stCactusNode_destruct(node, graph->destructNodeObjectFn, graph->destructEdgeEndObjectFn);
+ }
+ stCactusGraphNodeIterator_destruct(nodeIt);
+- stList_destruct(graph->nodeChunks);
+- stList_destruct(graph->edgeEndChunks);
++ stHash_destruct(graph->objectToNodeHash);
+ free(graph);
+ }
+
+-stCactusNode *stCactusGraph_getNode(stCactusGraph *graph, void *nodeObject) {
+- //A linear scan: only the tests look nodes up by object
+- for (stCactusNode *node = graph->firstNode; node != NULL; node = node->nextNode) {
+- if (node->nodeObject == nodeObject) {
+- return node;
+- }
+- }
+- return NULL;
+-}
+-
+-/*
+- * A stack of pointers on a plain array. The depth first searches below push and pop at every edge
+- * end, and the bounds checks and calls a list costs per operation were a measurable share of every
+- * cactus graph build. Pushes and pops are in the same order as with the list they replace.
+- */
+-typedef struct _ptrStack {
+- void **items;
+- int64_t length, capacity;
+-} PtrStack;
+-
+-static void ptrStack_init(PtrStack *stack) {
+- stack->capacity = 1024;
+- stack->length = 0;
+- stack->items = st_malloc(stack->capacity * sizeof(void *));
++stCactusNode *stCactusGraph_getNode(stCactusGraph *node, void *nodeObject) {
++ return stHash_search(node->objectToNodeHash, nodeObject);
+ }
+
+-static inline void ptrStack_push(PtrStack *stack, void *item) {
+- if (stack->length == stack->capacity) {
+- stack->capacity *= 2;
+- stack->items = st_realloc(stack->items, stack->capacity * sizeof(void *));
++static int64_t getComponentRoot(int64_t vertex, int64_t *component) {
++ while (component[vertex] != vertex) {
++ component[vertex] = component[component[vertex]];
++ vertex = component[vertex];
++ }
++ return vertex;
++}
++
++//Port, in C, of the near linear absorb-eject algorithm of Norouzi and Tsin (2014),
++//translated from the independent MIT implementation in vg
++//(src/algorithms/three_edge_connected_components.cpp); see the provenance note in
++//debian/patches. Repeated max flow computes the same components but is cubic in the
++//vertex number. Vertex path tails are -1 where the path ends.
++typedef struct {
++ int64_t current;
++ int64_t neighborIndex; //cursor into the vertex's adjacency list
++ bool sawParentTreeEdge;
++ bool recursing;
++} TsinStackFrame;
++
++typedef struct {
++ stList *adjacencyList;
++ int64_t *dfsCounter;
++ int64_t *dfsExit;
++ int64_t *lowPoint;
++ int64_t *effectiveDegree; //degree in the graph with all absorb-eject merges applied
++ int64_t *pathTail;
++ int64_t *component;
++ bool *isOnPath;
++ bool *visited;
++} TsinState;
++
++//Merges every vertex on the path from pathStart, up to but excluding pathPastEnd, into
++//into; when into is -1 the first vertex found on the path becomes the merge target.
++//Vertices that were absorbed out of their own path are passed over, and pathPastEnd
++//lets a prefix of a path be merged.
++static void absorbAllAlongPath(TsinState *state, int64_t into, int64_t pathStart, int64_t pathPastEnd) {
++ bool pathNull = true; //set once an edge is crossed, proving the path was not empty
++ int64_t here = pathStart;
++ while (here != pathPastEnd) {
++ if (here == -1) {
++ //Only a path with no edges may stop short of the waypoint.
++ assert(pathNull);
++ break;
++ }
++ if (state->isOnPath[here]) {
++ if (into == -1) {
++ into = here;
++ } else {
++ pathNull = false;
++ state->effectiveDegree[into] = state->effectiveDegree[into]
++ + state->effectiveDegree[here] - 2;
++ state->component[getComponentRoot(into, state->component)] =
++ getComponentRoot(here, state->component);
++ }
++ }
++ here = state->pathTail[here];
+ }
+- stack->items[stack->length++] = item;
+-}
+-
+-static inline void *ptrStack_pop(PtrStack *stack) {
+- assert(stack->length > 0);
+- return stack->items[--stack->length];
+ }
+
+-static inline void *ptrStack_peek(PtrStack *stack) {
+- assert(stack->length > 0);
+- return stack->items[stack->length - 1];
++//Computes the three edge connected components of the multigraph described by adjacencyList,
++//returning one stList of vertex ids per component. Self loops are censored and bridge
++//edges are hidden from the degree bookkeeping, so that degree two vertices cannot be
++//merged and each of them ends up in its own component.
++static stList *getThreeEdgeConnectedComponents(stList *adjacencyList) {
++ int64_t vertexNumber = stList_length(adjacencyList);
++ TsinState state;
++ state.adjacencyList = adjacencyList;
++ state.dfsCounter = st_calloc(vertexNumber, sizeof(int64_t));
++ state.dfsExit = st_calloc(vertexNumber, sizeof(int64_t));
++ state.lowPoint = st_calloc(vertexNumber, sizeof(int64_t));
++ state.effectiveDegree = st_calloc(vertexNumber, sizeof(int64_t));
++ state.pathTail = st_malloc(vertexNumber * sizeof(int64_t));
++ state.component = st_malloc(vertexNumber * sizeof(int64_t));
++ state.isOnPath = st_calloc(vertexNumber, sizeof(bool));
++ state.visited = st_calloc(vertexNumber, sizeof(bool));
++ for (int64_t vertex = 0; vertex < vertexNumber; vertex++) {
++ state.pathTail[vertex] = -1;
++ state.component[vertex] = vertex;
++ }
++ TsinStackFrame *stack = st_malloc(vertexNumber * sizeof(TsinStackFrame));
++ int64_t stackDepth = 0;
++ int64_t nextUnvisited = 0;
++ int64_t dfsCount = 1; //the algorithm numbers vertices from one
++ while (nextUnvisited != vertexNumber) {
++ stack[0] = (TsinStackFrame) {nextUnvisited, 0, 0, 0};
++ stackDepth = 1;
++ while (stackDepth > 0) {
++ TsinStackFrame *frame = &stack[stackDepth - 1];
++ int64_t nodeNumber = frame->current;
++ if (!state.visited[nodeNumber]) {
++ state.visited[nodeNumber] = 1;
++ while (nextUnvisited != vertexNumber && state.visited[nextUnvisited]) {
++ nextUnvisited++;
++ }
++ state.dfsCounter[nodeNumber] = dfsCount++;
++ state.lowPoint[nodeNumber] = state.dfsCounter[nodeNumber];
++ state.pathTail[nodeNumber] = -1;
++ state.isOnPath[nodeNumber] = 1;
++ continue;
++ }
++ stList *neighbors = stList_get(adjacencyList, nodeNumber);
++ if (frame->neighborIndex == stList_length(neighbors)) {
++ state.dfsExit[nodeNumber] = dfsCount;
++ stackDepth--;
++ continue;
++ }
++ int64_t neighborNumber = stIntTuple_get(stList_get(neighbors, frame->neighborIndex), 0);
++ if (!frame->recursing) {
++ state.effectiveDegree[nodeNumber]++;
++ if (!state.visited[neighborNumber]) {
++ frame->recursing = 1;
++ stack[stackDepth++] = (TsinStackFrame) {neighborNumber, 0, 0, 0};
++ continue;
++ }
++ if (stackDepth > 1 && neighborNumber == stack[stackDepth - 2].current
++ && !frame->sawParentTreeEdge) {
++ frame->sawParentTreeEdge = 1; //the edge we descended by, not a back edge
++ } else if (state.dfsCounter[neighborNumber] < state.dfsCounter[nodeNumber]) {
++ //Outgoing back edge: absorb our path and adopt the lower low point.
++ if (state.dfsCounter[neighborNumber] < state.lowPoint[nodeNumber]) {
++ absorbAllAlongPath(&state, -1, nodeNumber, -1);
++ state.lowPoint[nodeNumber] = state.dfsCounter[neighborNumber];
++ state.isOnPath[nodeNumber] = 1;
++ state.pathTail[nodeNumber] = -1;
++ }
++ } else if (state.dfsCounter[nodeNumber] < state.dfsCounter[neighborNumber]) {
++ //Incoming back edge: the neighbour may have been absorbed, so absorb up to
++ //the last ancestor on our path whose subtree still contains it.
++ state.effectiveDegree[nodeNumber] -= 2;
++ int64_t replacement = nodeNumber;
++ int64_t candidate = state.pathTail[replacement];
++ while (candidate != -1
++ && state.dfsCounter[candidate] <= state.dfsCounter[neighborNumber]
++ && state.dfsExit[candidate] >= state.dfsExit[neighborNumber]) {
++ replacement = candidate;
++ candidate = state.pathTail[replacement];
++ }
++ absorbAllAlongPath(&state, -1, nodeNumber, state.pathTail[replacement]);
++ state.pathTail[nodeNumber] = state.pathTail[replacement];
++ } else {
++ state.effectiveDegree[nodeNumber]--; //self loop
++ }
++ frame->neighborIndex++;
++ } else {
++ if (state.lowPoint[neighborNumber] == state.dfsCounter[neighborNumber]) {
++ //Neighbour reaches back no further than itself, so the edge is a bridge.
++ state.effectiveDegree[neighborNumber]--;
++ state.effectiveDegree[nodeNumber]--;
++ } else {
++ if (state.effectiveDegree[neighborNumber] == 2) {
++ state.isOnPath[neighborNumber] = 0; //absorbed by the edge we came along
++ }
++ assert(state.effectiveDegree[neighborNumber] != 1);
++ if (state.lowPoint[nodeNumber] <= state.lowPoint[neighborNumber]) {
++ absorbAllAlongPath(&state, nodeNumber, neighborNumber, -1);
++ } else {
++ state.lowPoint[nodeNumber] = state.lowPoint[neighborNumber];
++ absorbAllAlongPath(&state, -1, nodeNumber, -1);
++ state.isOnPath[nodeNumber] = 1;
++ state.pathTail[nodeNumber] = neighborNumber;
++ }
++ }
++ frame->recursing = 0;
++ frame->neighborIndex++;
++ }
++ }
++ }
++ stList *components = stList_construct3(0, (void(*)(void *)) stList_destruct);
++ stList **componentLists = st_calloc(vertexNumber, sizeof(stList *));
++ for (int64_t vertex = 0; vertex < vertexNumber; vertex++) {
++ int64_t root = getComponentRoot(vertex, state.component);
++ if (componentLists[root] == NULL) {
++ componentLists[root] = stList_construct3(0, (void(*)(void *)) stIntTuple_destruct);
++ stList_append(components, componentLists[root]);
++ }
++ stList_append(componentLists[root], stIntTuple_construct1(vertex));
++ }
++ free(componentLists);
++ free(stack);
++ free(state.visited);
++ free(state.isOnPath);
++ free(state.component);
++ free(state.pathTail);
++ free(state.effectiveDegree);
++ free(state.lowPoint);
++ free(state.dfsExit);
++ free(state.dfsCounter);
++ return components;
+ }
+
+-static void ptrStack_destruct(PtrStack *stack) {
+- free(stack->items);
+-}
+
+ void stCactusGraph_collapseToCactus(stCactusGraph *graph, void *(*mergeNodeObjects)(void *, void *), stCactusNode *startNode) {
+- //stThreeEdgeConnected_getComponents indexes vertices with int, so bail out here rather
+- //than truncate the node count into an int and work on a graph that is not the input
+- int64_t nodeNumber = stCactusGraph_getNodeNumber(graph);
+- if (nodeNumber >= INT32_MAX) {
+- st_errAbort("Cactus graph has %" PRIi64 " nodes, exceeding the %" PRIi64 " node limit of the "
+- "3-edge-connected component algorithm", nodeNumber, (int64_t)INT32_MAX - 1);
+- }
++ //Basic data structures
++ stHash *nodesToPositions = stHash_construct();
++ stHash *positionsToNodes = stHash_construct3((uint64_t(*)(const void *)) stIntTuple_hashKey,
++ (int(*)(const void *, const void *)) stIntTuple_equalsFn, (void(*)(void *)) stIntTuple_destruct, NULL);
++ stList *adjacencyList = stList_construct3(0, (void(*)(void *)) stList_destruct);
+
+- //Number the nodes in iteration order and lay the graph out in compressed sparse row form,
+- //edge ends in their list order, for the three edge connected code
+- stCactusNode **nodes = st_malloc((nodeNumber > 0 ? nodeNumber : 1) * sizeof(stCactusNode *));
+- int *offsets = st_malloc((nodeNumber + 1) * sizeof(int));
+- int64_t edgeEndNumber = 0;
++ //Set up and run the three edge connected code.
++ stCactusGraphNodeIt *nodeIt = stCactusGraphNodeIterator_construct(graph);
++ stCactusNode *node;
+ int64_t nodeIdCounter = 0;
+- for (stCactusNode *node = graph->firstNode; node != NULL; node = node->nextNode) {
+- node->index = nodeIdCounter;
+- nodes[nodeIdCounter] = node;
+- offsets[nodeIdCounter++] = edgeEndNumber;
+- stCactusNodeEdgeEndIt edgeEndIt = stCactusNode_getEdgeEndIt(node);
+- while (stCactusNodeEdgeEndIt_getNext(&edgeEndIt) != NULL) {
+- edgeEndNumber++;
+- }
+- }
+- offsets[nodeNumber] = edgeEndNumber;
+- if (edgeEndNumber >= INT32_MAX) {
+- st_errAbort("Cactus graph has %" PRIi64 " edge ends, exceeding the limit of the 3-edge-connected component algorithm", edgeEndNumber);
++ while ((node = stCactusGraphNodeIterator_getNext(nodeIt)) != NULL) {
++ stIntTuple *nodeId = stIntTuple_construct1( nodeIdCounter++);
++ stHash_insert(nodesToPositions, node, nodeId);
++ stHash_insert(positionsToNodes, nodeId, node);
+ }
+- int *adj = st_malloc((edgeEndNumber > 0 ? edgeEndNumber : 1) * sizeof(int));
+- int64_t k = 0;
+- for (stCactusNode *node = graph->firstNode; node != NULL; node = node->nextNode) {
++ stCactusGraphNodeIterator_destruct(nodeIt);
++ nodeIt = stCactusGraphNodeIterator_construct(graph);
++ while ((node = stCactusGraphNodeIterator_getNext(nodeIt)) != NULL) {
++ stList *edges = stList_construct();
++ stList_append(adjacencyList, edges);
+ stCactusNodeEdgeEndIt edgeEndIt = stCactusNode_getEdgeEndIt(node);
+ stCactusEdgeEnd *edgeEnd;
+ while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeEndIt)) != NULL) {
+- adj[k++] = stCactusEdgeEnd_getOtherNode(edgeEnd)->index;
++ stCactusNode *otherNode = stCactusEdgeEnd_getOtherNode(edgeEnd);
++ stIntTuple *otherNodeId = stHash_search(nodesToPositions, otherNode);
++ assert(otherNodeId != NULL);
++ stList_append(edges, otherNodeId);
+ }
+ }
+- assert(k == edgeEndNumber);
+- int *members, *starts, componentNumber;
+- stThreeEdgeConnected_getComponents(nodeNumber, offsets, adj, &members, &starts, &componentNumber);
++ stCactusGraphNodeIterator_destruct(nodeIt);
+ //Now do the merging
+- for (int64_t i = 0; i < componentNumber; i++) {
+- stCactusNode *node = nodes[members[starts[i]]];
+- for (int64_t j = starts[i] + 1; j < starts[i + 1]; j++) {
+- stCactusNode *otherNode = nodes[members[j]];
++ stList *_3EdgeConnectedComponents = getThreeEdgeConnectedComponents(adjacencyList);
++ for (int64_t i = 0; i < stList_length(_3EdgeConnectedComponents); i++) {
++ stList *_3EdgeConnectedComponent = stList_get(_3EdgeConnectedComponents, i);
++ stCactusNode *node = stHash_search(positionsToNodes, stList_get(_3EdgeConnectedComponent, 0));
++ assert(node != NULL);
++ for (int64_t j = 1; j < stList_length(_3EdgeConnectedComponent); j++) {
++ stCactusNode *otherNode = stHash_search(positionsToNodes, stList_get(_3EdgeConnectedComponent, j));
++ assert(otherNode != NULL);
+ assert(node != otherNode);
+ if (otherNode == startNode) { //This prevents the start node from being destructed.
+ otherNode = node;
+@@ -378,61 +437,45 @@ void stCactusGraph_collapseToCactus(stCa
+ }
+ }
+ //Cleanup
+- free(members);
+- free(starts);
+- free(nodes);
+- free(offsets);
+- free(adj);
+-
+- //Mark the cycles, one connected component at a time, starting each from its first node in
+- //iteration order (or from startNode, for the component that holds it)
+- PtrStack stack;
+- ptrStack_init(&stack);
+- uint64_t firstEpoch = graph->markEpoch + 1;
+- for (stCactusNode *root = graph->firstNode; root != NULL; root = root->nextNode) {
+- if (root->mark >= firstEpoch) {
+- continue; //already in a component found in this pass
+- }
+- uint64_t epoch = ++graph->markEpoch;
+- root->mark = epoch;
+- ptrStack_push(&stack, root);
+- while (stack.length > 0) {
+- stCactusNode *node = ptrStack_pop(&stack);
+- stCactusNodeEdgeEndIt edgeEndIt = stCactusNode_getEdgeEndIt(node);
+- stCactusEdgeEnd *edgeEnd;
+- while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeEndIt)) != NULL) {
+- stCactusNode *otherNode = stCactusEdgeEnd_getOtherNode(edgeEnd);
+- if (otherNode->mark != epoch) {
+- otherNode->mark = epoch;
+- ptrStack_push(&stack, otherNode);
+- }
+- }
+- }
+- if (startNode != NULL && startNode->mark == epoch) {
++ stList_destruct(adjacencyList);
++ stList_destruct(_3EdgeConnectedComponents);
++ stHash_destruct(nodesToPositions);
++ stHash_destruct(positionsToNodes);
++
++ //Mark the cycles
++ stList *components = stCactusGraph_getComponents(graph, 0);
++ for(int64_t i=0; i<stList_length(components); i++) {
++ stSet *component = stList_get(components, i);
++ if(startNode != NULL && stSet_search(component, startNode) == startNode) {
+ stCactusGraph_markCycles(graph, startNode);
+- } else {
+- stCactusGraph_markCycles(graph, root);
++ }
++ else {
++ // Pick an arbitrary node as the start node for the component
++ assert(stSet_size(component) > 0);
++ stCactusGraph_markCycles(graph, stSet_peek(component));
+ }
+ }
+- ptrStack_destruct(&stack);
++ stList_destruct(components);
++
+ }
+
+ stCactusGraphNodeIt *stCactusGraphNodeIterator_construct(stCactusGraph *graph) {
+ stCactusGraphNodeIt *nodeIt = st_malloc(sizeof(stCactusGraphNodeIt));
+- nodeIt->next = graph->firstNode;
++ nodeIt->it = stHash_getIterator(graph->objectToNodeHash);
+ nodeIt->graph = graph;
+ return nodeIt;
+ }
+
+ stCactusNode *stCactusGraphNodeIterator_getNext(stCactusGraphNodeIt *nodeIt) {
+- stCactusNode *node = nodeIt->next;
+- if (node != NULL) {
+- nodeIt->next = node->nextNode; //read now, so the caller may destroy the returned node
++ void *key = stHash_getNext(nodeIt->it);
++ if (key != NULL) {
++ return stHash_search(nodeIt->graph->objectToNodeHash, key);
+ }
+- return node;
++ return NULL;
+ }
+
+ void stCactusGraphNodeIterator_destruct(stCactusGraphNodeIt *nodeIt) {
++ stHash_destructIterator(nodeIt->it);
+ free(nodeIt);
+ }
+
+@@ -451,17 +494,16 @@ void stCactusGraph_unmarkCycles(stCactus
+ stCactusGraphNodeIterator_destruct(nodeIt);
+ }
+
+-static void makeChain(stCactusEdgeEnd *edgeEnd, stCactusEdgeEnd *edgeEnd2, PtrStack *chainPath) {
++static void makeChain(stCactusEdgeEnd *edgeEnd, stCactusEdgeEnd *edgeEnd2, stList *chainPath) {
+ assert(edgeEnd != edgeEnd2);
+ stCactusEdgeEnd_setLink(edgeEnd, edgeEnd2);
+ stCactusEdgeEnd_setLink(edgeEnd2, edgeEnd);
+ stCactusEdgeEnd_setIsChainEnd(edgeEnd, 1);
+ stCactusEdgeEnd_setIsChainEnd(edgeEnd2, 1);
+ stCactusEdgeEnd_setLinkOrientation(edgeEnd2, 1);
+- for (int64_t j = chainPath->length - 1; j >= 0; j -= 2) {
+- assert(j >= 1);
+- stCactusEdgeEnd *edgeEnd3 = chainPath->items[j];
+- stCactusEdgeEnd *edgeEnd4 = chainPath->items[j - 1];
++ for (int64_t j = stList_length(chainPath) - 1; j >= 0; j -= 2) {
++ stCactusEdgeEnd *edgeEnd3 = stList_get(chainPath, j);
++ stCactusEdgeEnd *edgeEnd4 = stList_get(chainPath, j - 1);
+ assert(edgeEnd3 != edgeEnd2);
+ assert(edgeEnd4 != edgeEnd2);
+ assert(edgeEnd4 != edgeEnd);
+@@ -474,16 +516,12 @@ static void makeChain(stCactusEdgeEnd *e
+ }
+ }
+
+-/*
+- * The nodes on the current path each remember the edge end the path left them by, in onChainEdgeEnd;
+- * it is NULL for every node off the path, and every node is off the path again on return.
+- */
+-static void stCactusGraph_markCyclesP(stCactusEdgeEnd *edgeEnd, PtrStack *chainPath) {
+- ptrStack_push(chainPath, edgeEnd);
+- ptrStack_push(chainPath, NULL);
+- while (chainPath->length > 0) {
+- stCactusEdgeEnd *edgeEnd2 = ptrStack_pop(chainPath);
+- edgeEnd = ptrStack_peek(chainPath);
++static void stCactusGraph_markCyclesP(stCactusEdgeEnd *edgeEnd, stHash *nodesOnChainToEdgeEnds, stList *chainPath) {
++ stList_append(chainPath, edgeEnd);
++ stList_append(chainPath, NULL);
++ while (stList_length(chainPath) > 0) {
++ stCactusEdgeEnd *edgeEnd2 = stList_pop(chainPath);
++ edgeEnd = stList_peek(chainPath);
+ stCactusNode *node = stCactusEdgeEnd_getNode(edgeEnd);
+ if (edgeEnd2 == NULL) {
+ edgeEnd2 = stCactusNode_getFirstEdgeEnd(node);
+@@ -491,19 +529,19 @@ static void stCactusGraph_markCyclesP(st
+ edgeEnd2 = stCactusEdgeEnd_getNextEdgeEnd(edgeEnd2);
+ }
+ if (edgeEnd2 == NULL) {
+- ptrStack_pop(chainPath);
+- node->onChainEdgeEnd = NULL;
++ stList_pop(chainPath);
++ stHash_remove(nodesOnChainToEdgeEnds, node);
+ } else {
+- ptrStack_push(chainPath, edgeEnd2);
++ stList_append(chainPath, edgeEnd2);
+ if (edgeEnd2 != edgeEnd && stCactusEdgeEnd_getLink(edgeEnd2) == NULL) {
+- node->onChainEdgeEnd = edgeEnd2;
++ stHash_insert(nodesOnChainToEdgeEnds, node, edgeEnd2);
+ stCactusEdgeEnd *edgeEnd3 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2);
+ stCactusEdgeEnd *edgeEnd4;
+- if ((edgeEnd4 = stCactusEdgeEnd_getNode(edgeEnd3)->onChainEdgeEnd) != NULL) { //We've traversed a cycle
++ if ((edgeEnd4 = stHash_search(nodesOnChainToEdgeEnds, stCactusEdgeEnd_getNode(edgeEnd3))) != NULL) { //We've traversed a cycle
+ makeChain(edgeEnd4, edgeEnd3, chainPath);
+ } else {
+- ptrStack_push(chainPath, edgeEnd3);
+- ptrStack_push(chainPath, NULL);
++ stList_append(chainPath, edgeEnd3);
++ stList_append(chainPath, NULL);
+ }
+ }
+ }
+@@ -511,38 +549,34 @@ static void stCactusGraph_markCyclesP(st
+ }
+
+ void stCactusGraph_markCycles(stCactusGraph *graph, stCactusNode *startNode) {
+- PtrStack chainPath;
+- ptrStack_init(&chainPath);
++ stHash *nodesOnChainToEdgeEnds = stHash_construct();
++ stList *chainPath = stList_construct();
+ stCactusNodeEdgeEndIt edgeIterator = stCactusNode_getEdgeEndIt(startNode);
+ stCactusEdgeEnd *edgeEnd;
+ while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeIterator))) {
+ if (!stCactusEdgeEnd_isChainEnd(edgeEnd)) {
+ stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd);
+ if (stCactusEdgeEnd_getNode(edgeEnd2) == startNode) {
+- makeChain(edgeEnd, edgeEnd2, &chainPath);
++ makeChain(edgeEnd, edgeEnd2, chainPath);
+ } else {
+- startNode->onChainEdgeEnd = edgeEnd;
+- stCactusGraph_markCyclesP(edgeEnd2, &chainPath);
+- startNode->onChainEdgeEnd = NULL;
++ stHash_insert(nodesOnChainToEdgeEnds, startNode, edgeEnd);
++ stCactusGraph_markCyclesP(edgeEnd2, nodesOnChainToEdgeEnds, chainPath);
++ stHash_remove(nodesOnChainToEdgeEnds, startNode);
+ }
+ }
+ }
+- ptrStack_destruct(&chainPath);
+-#ifndef NDEBUG
+- for (stCactusNode *node = graph->firstNode; node != NULL; node = node->nextNode) {
+- assert(node->onChainEdgeEnd == NULL);
+- }
+-#endif
++ stList_destruct(chainPath);
++ assert(stHash_size(nodesOnChainToEdgeEnds) == 0);
++ stHash_destruct(nodesOnChainToEdgeEnds);
+ }
+
+ static void stCactusGraph_collapseBridgesP(stCactusNode *parentNode, stCactusEdgeEnd *edgeEnd, stList *nodesToMerge) {
+- PtrStack stack;
+- ptrStack_init(&stack);
+- ptrStack_push(&stack, parentNode);
+- ptrStack_push(&stack, edgeEnd);
+- while (stack.length > 0) {
+- edgeEnd = ptrStack_pop(&stack);
+- parentNode = ptrStack_pop(&stack);
++ stList *stack = stList_construct();
++ stList_append(stack, parentNode);
++ stList_append(stack, edgeEnd);
++ while (stList_length(stack) > 0) {
++ edgeEnd = stList_pop(stack);
++ parentNode = stList_pop(stack);
+ stCactusNode *node = stCactusEdgeEnd_getNode(edgeEnd);
+ if (stCactusEdgeEnd_getLink(edgeEnd) == NULL) { //Is a bridge
+ //Establish if this is a leaf
+@@ -555,8 +589,8 @@ static void stCactusGraph_collapseBridge
+ bridges++;
+ }
+ if (!stCactusEdgeEnd_getLinkOrientation(edgeEnd2)) {
+- ptrStack_push(&stack, parentNode);
+- ptrStack_push(&stack, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
++ stList_append(stack, parentNode);
++ stList_append(stack, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
+ }
+ }
+ }
+@@ -569,13 +603,13 @@ static void stCactusGraph_collapseBridge
+ stCactusEdgeEnd *edgeEnd2;
+ while ((edgeEnd2 = stCactusNodeEdgeEndIt_getNext(&edgeIterator))) {
+ if (edgeEnd2 != edgeEnd && !stCactusEdgeEnd_getLinkOrientation(edgeEnd2)) {
+- ptrStack_push(&stack, node);
+- ptrStack_push(&stack, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
++ stList_append(stack, node);
++ stList_append(stack, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
+ }
+ }
+ }
+ }
+- ptrStack_destruct(&stack);
++ stList_destruct(stack);
+ }
+
+ void mergeNodes(stCactusGraph *graph, stCactusNode *startNode, stList *nodesToMerge, void *(*mergeNodeObjects)(void *, void *)) {
+@@ -855,13 +889,12 @@ stCactusNode *stCactusGraph_breakChainsB
+ }
+
+ static void buildComponent(stSet *component, stCactusNode *cactusNode, bool ignoreBridgeEdges) {
+- PtrStack stack; // Nodes to be visited
+- ptrStack_init(&stack);
+- ptrStack_push(&stack, cactusNode);
++ stList *stack = stList_construct(); // List of nodes to be visited
++ stList_append(stack, cactusNode);
+
+ // While there exists nodes to visit
+- while(stack.length > 0) {
+- stCactusNode *cactusNode2 = ptrStack_pop(&stack);
++ while(stList_length(stack) > 0) {
++ stCactusNode *cactusNode2 = stList_pop(stack);
+
+ // If not already in the component
+ if(stSet_search(component, cactusNode2) == NULL) {
+@@ -878,13 +911,13 @@ static void buildComponent(stSet *compon
+ // If not ignoreBridgeEdges or is not a bridge edge
+ if(!ignoreBridgeEdges || stCactusEdgeEnd_getLink(edgeEnd) != NULL) {
+ // Add to nodes to visit
+- ptrStack_push(&stack, stCactusEdgeEnd_getNode(stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd)));
++ stList_append(stack, stCactusEdgeEnd_getNode(stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd)));
+ }
+ }
+ }
+ }
+
+- ptrStack_destruct(&stack);
++ stList_destruct(stack);
+ }
+
+ stList *stCactusGraph_getComponents(stCactusGraph *cactusGraph,
+@@ -962,7 +995,12 @@ void stBridgeNode_destruct(stBridgeNode
+ free(bridgeNode);
+ }
+
+-static void buildBridgeComponent(stBridgeNode *bridgeNode, stCactusEdgeEnd *edgeEnd) {
++static void constructConnectedNodes(stBridgeNode *bridgeNode, stCactusEdgeEnd *edgeEnd) {
++ /*
++ * Adds the subset of nodes in the 2-EC component containing bridgeNode that are on a path in the
++ * cactus tree between bridge edges to the set of connected nodes, bridgeNode->connectedCactusNodes
++ */
++
+ // Stack object containing pairs of cactus edge ends
+ stList *stack = stList_construct();
+
+@@ -1042,7 +1080,7 @@ static void buildBridgeComponent(stBridg
+ stSet_insert(bridgeNode->connectedCactusNodes, cactusNode);
+
+ // Search for the predecessor and update its connected path variable to
+- // indicate it is also one a connected path
++ // indicate it is also on a connected path
+ onConnectedPath = stHash_search(edgeEndsToConnectedStatus, pEdgeEnd);
+ assert(onConnectedPath != NULL);
+ onConnectedPath[0] = 1;
+@@ -1103,6 +1141,10 @@ void stBridgeNode_print(stBridgeNode *br
+ }
+
+ stBridgeGraph *stBridgeGraph_getBridgeGraph(stCactusNode *cactusNode) {
++ /*
++ * Build the bridge graph for the connnected component containing cactusNode.
++ */
++
+ // Create the bridge graph container
+ stBridgeGraph *bridgeGraph = st_malloc(sizeof(stBridgeGraph));
+ bridgeGraph->bridgeNodes = stList_construct3(0, (void (*)(void *))stBridgeNode_destruct);
+@@ -1115,6 +1157,8 @@ stBridgeGraph *stBridgeGraph_getBridgeGr
+
+ stHash *bridgeEndsToBridgeNodes = stHash_construct();
+
++ // Make bridge nodes in component
++
+ // For each cactus node
+ stSetIterator *componentIt = stSet_getIterator(component);
+ stCactusNode *cactusNode2;
+@@ -1144,7 +1188,12 @@ stBridgeGraph *stBridgeGraph_getBridgeGr
+ stSetIterator *bridgeEndIt = stSet_getIterator(bridgeNode->bridgeEnds);
+ stCactusEdgeEnd *bridgeEnd;
+ while((bridgeEnd = stSet_getNext(bridgeEndIt)) != NULL) {
+- buildBridgeComponent(bridgeNode, bridgeEnd);
++
++ // Call adds the set of connected nodes to bridgeNode->connectedNodes reachable
++ // from connected nodes
++ constructConnectedNodes(bridgeNode, bridgeEnd);
++
++ // Map bridgeEnd to the bridgeNode
+ stHash_insert(bridgeEndsToBridgeNodes, bridgeEnd, bridgeNode);
+ }
+ stSet_destructIterator(bridgeEndIt);
+@@ -1188,364 +1237,674 @@ void stBridgeGraph_destruct(stBridgeGrap
+ free(bridgeGraph);
+ }
+
+-/*
+- * Core functions for computing ultrabubbles for a cactus graph.
+- */
++stHash *stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash(stBridgeGraph *bridgeGraph) {
++ /*
++ * Returns a hash of the bridge edge ends in the bridge graph to their incident nodes in the graph.
++ */
++ stHash *bridgeEndsToBridgeNodes = stHash_construct();
++
++ for(int64_t i=0; i<stList_length(bridgeGraph->bridgeNodes); i++) {
++ stBridgeNode *bridgeNode = stList_get(bridgeGraph->bridgeNodes, i);
++
++ stCactusEdgeEnd *edgeEnd;
++ stSetIterator *endIt = stSet_getIterator(bridgeNode->bridgeEnds);
++ while((edgeEnd = stSet_getNext(endIt)) != NULL) {
++ assert(stHash_search(bridgeEndsToBridgeNodes, edgeEnd) == NULL);
++ stHash_insert(bridgeEndsToBridgeNodes, edgeEnd, bridgeNode);
++ }
++ stSet_destructIterator(endIt);
++ }
+
+-stUltraBubble *stUltraBubble_construct(stList *parentChain,
+- stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2) {
+- stUltraBubble *ultraBubble = st_malloc(sizeof(stUltraBubble));
+- if(parentChain != NULL) {
+- stList_append(parentChain, ultraBubble);
+- }
+- ultraBubble->chains = stList_construct3(0,
+- (void (*)(void *))stList_destruct);
+- ultraBubble->edgeEnd1 = edgeEnd1;
+- ultraBubble->edgeEnd2 = edgeEnd2;
+- return ultraBubble;
+-}
+-
+-void stUltraBubble_destruct(stUltraBubble *ultraBubble) {
+- stList_destruct(ultraBubble->chains);
+- free(ultraBubble);
++ return bridgeEndsToBridgeNodes;
+ }
+
+ /*
+- * Functions for printing ultra bubble decomposition.
++ * Functions to build the snarl decomposition
+ */
+
+-void stUltraBubble_print2(stUltraBubble *ultraBubble, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix);
+-
+-void stUltraBubble_printChains2(stList *ultraBubbleChains, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix) {
+- for(int64_t i=0; i<stList_length(ultraBubbleChains); i++) {
+- stList *chain = stList_get(ultraBubbleChains, i);
+- char *chainPrefix = stString_print("%s-%" PRIi64 "", parentChainPrefix, i);
+- fprintf(fileHandle, "%s\tChain: %s\tLength: %" PRIi64 "\n", parentPrefix, chainPrefix, stList_length(chain));
+- for(int64_t j=0; j<stList_length(chain); j++) {
+- char *prefix = stString_print("%s%s", parentPrefix, "\t\t");
+- stUltraBubble_print2(stList_get(chain, j), fileHandle, prefix, chainPrefix);
+- free(prefix);
+- }
+- free(chainPrefix);
+- }
+-}
+-
+-void stUltraBubble_print2(stUltraBubble *ultraBubble, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix) {
+- fprintf(fileHandle, "%sBubble,\tchild-chain-number: %" PRIi64 "\tSide1:(%" PRIi64 ",%" PRIi64 ")\tSide2:(%" PRIi64 ",%" PRIi64 ")\n", parentPrefix,
+- stList_length(ultraBubble->chains), (int64_t)stCactusEdgeEnd_getOtherEdgeEnd(ultraBubble->edgeEnd1), (int64_t)ultraBubble->edgeEnd1,
+- (int64_t)ultraBubble->edgeEnd2, (int64_t)stCactusEdgeEnd_getOtherEdgeEnd(ultraBubble->edgeEnd2));
+- stUltraBubble_printChains2(ultraBubble->chains, fileHandle, parentPrefix, parentChainPrefix);
+-}
+-
+-void stUltraBubble_print(stUltraBubble *ultraBubble, FILE *fileHandle) {
+- stUltraBubble_print2(ultraBubble, fileHandle, "", "C");
+-}
++stSnarl *stSnarl_constructEmptySnarl(stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2) {
++ stSnarl *snarl = st_calloc(1, sizeof(stSnarl));
+
+-void stUltraBubble_printChains(stList *ultraBubbleChains, FILE *fileHandle) {
+- fprintf(fileHandle, "Top level chains, total: %" PRIi64 "\n", stList_length(ultraBubbleChains));
+- stUltraBubble_printChains2(ultraBubbleChains, fileHandle, "", "C");
++ snarl->edgeEnd1 = edgeEnd1;
++ snarl->edgeEnd2 = edgeEnd2;
++ snarl->chains = stList_construct3(0, (void (*)(void *))stList_destruct);
++ snarl->unarySnarls = stList_construct3(0, (void (*)(void *))stSnarl_destruct);
++ snarl->parentCount = 1; // start off assuming there is one parent referencing the snarl
++
++ return snarl;
++}
++
++void stSnarl_destruct(stSnarl *snarl) {
++ // Cleanup only happens once all references to the snarl are released
++ assert(snarl->parentCount > 0);
++ if(--snarl->parentCount <= 0) {
++ stList_destruct(snarl->chains);
++ stList_destruct(snarl->unarySnarls);
++ free(snarl);
++ }
++}
++
++uint64_t stSnarl_hashKey(const void *snarl) {
++ /*
++ * Hash key for snarls that hashes on boundary edge end references.
++ */
++ stSnarl *s = (stSnarl *)snarl;
++ return stHash_pointer(s->edgeEnd1) ^ stHash_pointer(s->edgeEnd2);
++}
++
++int stSnarl_equals(const void *snarl1, const void *snarl2) {
++ /*
++ * Returns zero iff the two snarls have the same boundaries in the same order.
++ */
++ stSnarl *s1 = (stSnarl *)snarl1;
++ stSnarl *s2 = (stSnarl *)snarl2;
++ return s1->edgeEnd1 == s2->edgeEnd1 && s1->edgeEnd2 == s2->edgeEnd2;
++}
++
++static stSet *getEmptySnarlCache() {
++ return stSet_construct3(stSnarl_hashKey, stSnarl_equals, NULL);
++}
++
++static stSnarl *getSnarlFromCache(stSet *snarlCache,
++ stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2) {
++ /*
++ * Gets a snarl from the cache, NULL if not present;
++ */
++ stSnarl snarl;
++ snarl.edgeEnd1 = edgeEnd1;
++ snarl.edgeEnd2 = edgeEnd2;
++ return stSet_search(snarlCache, &snarl);
++}
++
++stSnarl *stSnarl_makeRecursiveSnarl(stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2,
++ stSet *snarlCache) {
++ /*
++ * Makes a snarl, recursively constructing all its child snarls. If a unary snarl
++ * edgeEnd1 == edgeEnd2.
++ */
++
++ // A stack object to avoid recursion
++ stList *snarlStack = stList_construct();
++ stList_append(snarlStack, NULL);
++ stList_append(snarlStack, edgeEnd1);
++ stList_append(snarlStack, edgeEnd2);
++ stSnarl *snarlToReturn = NULL;
++
++ while(stList_length(snarlStack) > 0) {
++ edgeEnd2 = stList_pop(snarlStack);
++ edgeEnd1 = stList_pop(snarlStack);
++ stList *parent = stList_pop(snarlStack);
++
++ // Must either be a bridge or be opposite ends of a link within a chain
++ if(edgeEnd1 != edgeEnd2) { // If both equal is a unary snarl
++ assert(edgeEnd1->node == edgeEnd2->node);
++ assert(edgeEnd1->link == edgeEnd2);
++ assert(edgeEnd2->link == edgeEnd1);
++ }
++
++ // Check the cache
++ stSnarl *snarl = getSnarlFromCache(snarlCache, edgeEnd1, edgeEnd2);
++
++ if(snarl == NULL) { // If not in the cache
++ snarl = stSnarl_constructEmptySnarl(edgeEnd1, edgeEnd2); // This sets the initial parent count to 1
++ stSet_insert(snarlCache, snarl); // Add to the cache
++
++ // For each edge end incident with the cactus node
++ stCactusEdgeEnd *edgeEnd = edgeEnd1->node->head;
++ while(edgeEnd != NULL) {
++ assert(edgeEnd->node == edgeEnd1->node);
++
++ // If not edgeEnd1 or edgeEnd2
++ if(edgeEnd != edgeEnd1 && edgeEnd != edgeEnd2) {
++
++ if(edgeEnd->link == NULL) { // is a bridge
++ assert(edgeEnd->otherEdgeEnd->node != edgeEnd->node); // not a trivial chain
++ // Queue up making a new nested unary snarl
++ stList_append(snarlStack, snarl->unarySnarls);
++ stList_append(snarlStack, edgeEnd->otherEdgeEnd);
++ stList_append(snarlStack, edgeEnd->otherEdgeEnd);
++ }
++ // else is a chain
++ else if(edgeEnd->linkOrientation /* is the positive end of link in chain */ &&
++ edgeEnd->link != edgeEnd->otherEdgeEnd /* is not a trivial chain (i.e. a self loop) */) {
++
++ // Make a new nested chain
++ stList *chain = stList_construct3(0, (void (*)(void *))stSnarl_destruct);
++ stList_append(snarl->chains, chain);
++
++ // Add links to the chain
++ stCactusEdgeEnd *chainEnd = edgeEnd->otherEdgeEnd;
++ assert(chainEnd != edgeEnd);
++ do {
++ assert(chainEnd->node != edgeEnd->node);
++ assert(!chainEnd->linkOrientation);
++ assert(chainEnd->link != edgeEnd);
++ assert(chainEnd->node == chainEnd->link->node);
++
++ stList_append(snarlStack, chain);
++ stList_append(snarlStack, chainEnd->link); // Note beng added in reverse order
++ stList_append(snarlStack, chainEnd);
++
++ chainEnd = chainEnd->link->otherEdgeEnd;
++ } while(chainEnd->link != edgeEnd);
++ }
++ }
++
++ // Get next incident edge end
++ edgeEnd = edgeEnd->nEdgeEnd;
++ }
++ }
++ else { // As we got it from the cache, increase the parent count
++ snarl->parentCount++;
++ }
++
++ if(parent != NULL) {
++ // As parent is not null, must be a nested snarl
++ stList_append(parent, snarl);
++ }
++ else {
++ snarlToReturn = snarl;
++ }
++
++ }
++
++ assert(snarlToReturn != NULL);
++ stList_destruct(snarlStack);
++
++ return snarlToReturn;
++}
++
++stList *getBridgePathConnectingEnds(stBridgeGraph *bridgeGraph, stCactusEdgeEnd *startEdgeEnd, stCactusEdgeEnd *endEdgeEnd) {
++ /*
++ * Gets a path of bridge edges in the bridge graph connecting the projection of two cactus edge ends, and including these ends.
++ * Returned path is represented as a sequence of pairs of bridge edge ends, each of which is a snarl.
++ */
++
++ // Build hash of bridge ends to bridge nodes
++ stHash *bridgeEndsToBridgeNodes = stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash(bridgeGraph);
++
++ // Get bridge node incident with startEdgeEnd
++ stBridgeNode *startBridgeNode = stHash_search(bridgeEndsToBridgeNodes, startEdgeEnd);
++ assert(startBridgeNode != NULL);
++
++ // Do DFS from startBridgeNode until we find a path to endBridgeNode
++ // We use a stack to prevent stack overflows as recursion can get pretty deep
++ stList *stack = stList_construct();
++
++ stList_append(stack, startEdgeEnd);
++ stList_append(stack, stSet_getIterator(startBridgeNode->bridgeEnds)); // Iterator over incident bridge ends
++ while(1) {
++ assert(stList_length(stack) > 0);
++ stSetIterator *endIt = stList_get(stack, stList_length(stack)-1);
++ stCactusEdgeEnd *edgeEnd = stList_get(stack, stList_length(stack)-2);
++
++ // Get next incident edge end
++ stCactusEdgeEnd *edgeEnd2 = stSet_getNext(endIt);
++
++ if(edgeEnd == edgeEnd2) { // Go around again in this case
++ continue;
++ }
++
++ // Pop the stack if finished
++ if(edgeEnd2 == NULL) {
++ stList_pop(stack);
++ stList_pop(stack);
++ stSet_destructIterator(endIt);
++ continue;
++ }
++
++ // If we're done, convert stack to final path
++ if(edgeEnd2 == endEdgeEnd) {
++ stList *bridgePath = stList_construct();
++ assert(stList_length(stack) % 2 == 0); // Check stack has even length
++ for(int64_t i=0; i<stList_length(stack); i+=2) {
++ stList_append(bridgePath, stList_get(stack, i));
++ stSet_destructIterator(stList_get(stack, i+1));
++ stList_append(bridgePath, i+2 < stList_length(stack) ?
++ ((stCactusEdgeEnd *)stList_get(stack, i+2))->otherEdgeEnd : endEdgeEnd);
++ }
++
++ // Cleanup
++ stList_destruct(stack);
++ stHash_destruct(bridgeEndsToBridgeNodes);
++
++ return bridgePath;
++ }
++
++ // Else add to the stack and continue traverse
++ stList_append(stack, edgeEnd2->otherEdgeEnd);
++ stList_append(stack, stSet_getIterator(((stBridgeNode *)stHash_search(bridgeEndsToBridgeNodes,
++ edgeEnd2->otherEdgeEnd))->bridgeEnds));
++ }
++ return NULL; // This is unreachable
+ }
+
+ /*
+- * Functions for building ultrabubble decomposition
++ * We need a frame on a stack for each edge end we consider including.
+ */
++typedef struct {
++ // What's the edge end we are at
++ stCactusEdgeEnd *currentEdgeEnd;
++ // Did we recurse on its link?
++ bool followedLink;
++ // What's the last edge end we were working on incedent on the same thing as currentEdgeEnd?
++ stCactusEdgeEnd *edgeEnd;
++} stPathDfsFrame;
+
+-static stList *addNewNestedChain(stList *chains) {
+- // Adds an ultrabubble chain to a list of ultrabubble chains.
+- stList *chain = stList_construct3(0, (void (*)(void *))stUltraBubble_destruct);
+- stList_append(chains, chain);
+- return chain;
+-}
+-
+-static void recursiveEnumerateChainBubbles(stList *parentUltraBubbleChain, stCactusNode *parentNode, stCactusEdgeEnd *parentChain) {
+- // Stack to keep track of recursion
+- stList *stack = stList_construct();
+- stList_append(stack, parentUltraBubbleChain);
+- stList_append(stack, parentNode);
+- stList_append(stack, parentChain);
+-
+- while(stList_length(stack) > 0) {
+- // Pop the stack
+- parentChain = stList_pop(stack);
+- parentNode = stList_pop(stack);
+- parentUltraBubbleChain = stList_pop(stack);
+-
+- // Checks
+- assert(stCactusEdgeEnd_getNode(parentChain) == parentNode);
+- assert(stCactusEdgeEnd_getNode(stCactusEdgeEnd_getLink(parentChain)) == parentNode);
+- assert(stCactusEdgeEnd_getLinkOrientation(parentChain));
+- assert(!stCactusEdgeEnd_getLinkOrientation(stCactusEdgeEnd_getLink(parentChain)));
+-
+- // Create a bubble and append it to the parent's ultrabubble chain
+- stUltraBubble *ultraBubble = stUltraBubble_construct(parentUltraBubbleChain,
+- parentChain, stCactusEdgeEnd_getLink(parentChain));
+-
+- // For each child chain incident with parentNode and not equal to parentChain
+- stCactusNodeEdgeEndIt edgeIterator = stCactusNode_getEdgeEndIt(parentNode);
+- stCactusEdgeEnd *edgeEnd;
+- while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeIterator))) {
+- assert(parentNode == stCactusEdgeEnd_getNode(edgeEnd));
+- assert(stCactusEdgeEnd_getLink(edgeEnd) != NULL); // Can not be a bridge, by definition
+- if (stCactusEdgeEnd_getLinkOrientation(edgeEnd) && edgeEnd != parentChain) {
+-
+- stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_getLink(stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd));
+-
+- if(edgeEnd != edgeEnd2) {
+- // Make a new ultrabubble chain
+- stList *childUltraBubbleChain = addNewNestedChain(ultraBubble->chains);
+-
+- // For each node in the chain not equal to parentNode
+- do {
+-
+- // Add to the stack
+- stList_append(stack, childUltraBubbleChain);
+- stList_append(stack, stCactusEdgeEnd_getNode(edgeEnd2));
+- stList_append(stack, edgeEnd2);
+-
+- edgeEnd2 = stCactusEdgeEnd_getLink(stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
+- } while (edgeEnd != edgeEnd2);
+- }
+- }
+- }
+- }
+-
+- // Cleanup
+- stList_destruct(stack);
+-}
+-
+-void bridgeGraphToUltraBubbles(stBridgeNode *pBridgeNode, stBridgeNode *bridgeNode, stSet *seen,
+- stList *topLevelChains, stSet *cactusGraphComponent, stCactusNode *startNode) {
+- // Stack for recursion
+- stList *stack = stList_construct();
+- stList_append(stack, pBridgeNode);
+- stList_append(stack, bridgeNode);
++stList *getNodesOnPathInCactusTreeBetweenBridgeSnarlBoundaries(stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2) {
++ /*
++ * Gets net nodes in the cactus tree on the path connecting two cactus bridge edge ends,
++ * edgeEnd1 and edgeEnd2, that are both in the same bridge component.
++ * Path includes the nodes in the cactus graph
++ * incident with these ends. Path goes from edgeEnd1 to edgeEnd2.
++ */
++
++ // Check they are both bridges
++ assert(edgeEnd1->link == NULL);
++ assert(edgeEnd2->link == NULL);
++ assert(edgeEnd1->node != edgeEnd1->otherEdgeEnd->node);
++ assert(edgeEnd2->node != edgeEnd2->otherEdgeEnd->node);
++
++ // A set to represent the vertices visited by the dfs,
++ // used to avoid walking backwards in the cactus tour
++ stSet *seen = stSet_construct();
++
++ // A list representing the nodes on the path
++ stList *nodePath = stList_construct();
++
++ // A list functioning as a stack for our DFS.
++ // We can't just use the real stack; we may need more space than is available there.
++ stList *stack = stList_construct3(0, &free);
++
++ // Make a first frame
++ stPathDfsFrame *baseFrame = malloc(sizeof(stPathDfsFrame));
++ baseFrame->currentEdgeEnd = edgeEnd1;
++ baseFrame->followedLink = false;
++ // Always initialize this like this so we can use this to detect iteration start and NULL as an iteration-over value.
++ baseFrame->edgeEnd = baseFrame->currentEdgeEnd->node->head;
++ stList_append(stack, baseFrame);
++
++ // Allocate a return value to bring up the stack. True if we found a path, false otherwise.
++ bool retVal = 0;
+
+- // Loop while there are bridge nodes to consider
+ while(stList_length(stack) > 0) {
+- bridgeNode = stList_pop(stack);
+- pBridgeNode = stList_pop(stack);
+-
+- // This check ensures we do not loop in the case that the bridge graph contains a cycle
+- if(stSet_search(seen, bridgeNode) != NULL) {
+- continue;
+- }
+- stSet_insert(seen, bridgeNode);
+-
+- // If the bridge node has incident edges
+- if(stSet_size(bridgeNode->bridgeEnds) > 0) {
+- stList *workingLevelChains = topLevelChains;
+-
+- // If incident edges equals 2
+- if(stSet_size(bridgeNode->bridgeEnds) == 2) {
+-
+- // Continue the existing top level chain if previous node was link in the chain, else start a new one
+- stList *topLevelChain = (pBridgeNode != NULL && stSet_size(pBridgeNode->bridgeEnds) == 2) ?
+- stList_peek(topLevelChains) : addNewNestedChain(topLevelChains);
+-
+- // Create a bubble and add it to the top level chain
+- stList *bridgeEnds = stSet_getList(bridgeNode->bridgeEnds);
+-
+- if(stList_length(topLevelChain) > 0) { // If continuing chain orient
+- // the ends correctly in the chain
+- stUltraBubble *pUltraBubble = stList_peek(topLevelChain);
+- stCactusEdgeEnd *oppEnd = stCactusEdgeEnd_getOtherEdgeEnd(pUltraBubble->edgeEnd2);
+-
+- // This statement is true if the start of the chain was oriented backwards
+- // with respect to this link
+- if(!stList_contains(bridgeEnds, oppEnd)) {
+- assert(stList_length(topLevelChain) == 1);
+- oppEnd = stCactusEdgeEnd_getOtherEdgeEnd(pUltraBubble->edgeEnd1);
+- assert(stList_contains(bridgeEnds, oppEnd));
+- stCactusEdgeEnd *edgeEnd = pUltraBubble->edgeEnd1;
+- pUltraBubble->edgeEnd1 = pUltraBubble->edgeEnd2;
+- pUltraBubble->edgeEnd2 = edgeEnd;
+- }
+-
+- // Reverse the orientation if backwards with respect to the previous
+- // link
+- if(oppEnd == stList_get(bridgeEnds, 1)) {
+- stList_reverse(bridgeEnds);
+- }
+- }
+-
+- stUltraBubble *ultraBubble = stUltraBubble_construct(topLevelChain,
+- stList_get(bridgeEnds, 0), stList_get(bridgeEnds, 1));
+-
+- stList_destruct(bridgeEnds);
+-
+- // Set working chains to be those nested in the ultraBubble
+- workingLevelChains = ultraBubble->chains;
+- }
+-
+- // A set to track which nodes we've constructed ultrabubbles for
+- stSet *visitedCactusNodes = stSet_construct();
+-
+- // For each node in cactusNodes
+- stSetIterator *cactusNodesIt = stSet_getIterator(bridgeNode->connectedCactusNodes);
+- stCactusNode *cactusNode;
+- while((cactusNode = stSet_getNext(cactusNodesIt)) != NULL) {
+-
+- // For each chain incident with the cactusNode
+- stCactusNodeEdgeEndIt edgeIterator = stCactusNode_getEdgeEndIt(cactusNode);
+- stCactusEdgeEnd *edgeEnd;
+- while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeIterator))) {
+- assert(cactusNode == stCactusEdgeEnd_getNode(edgeEnd));
+- if (stCactusEdgeEnd_getLink(edgeEnd) != NULL && stCactusEdgeEnd_getLinkOrientation(edgeEnd)) {
+-
+- // Make new chain
+- stList *ultraBubbleChain = addNewNestedChain(workingLevelChains);
+-
+- // For each node in the chain not in cactusNodes and not yet visited
+- stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_getOtherEdgeEnd(stCactusEdgeEnd_getLink(edgeEnd));;
+- while (edgeEnd != edgeEnd2) {
+- stCactusNode *cactusNode2 = stCactusEdgeEnd_getNode(edgeEnd2);
+- assert(cactusNode2 != cactusNode);
+- if(stSet_search(bridgeNode->connectedCactusNodes, cactusNode2) == NULL) {
+- if(stSet_search(visitedCactusNodes, cactusNode2) == NULL) {
+-
+- // Call recursivelyEnumerateChainBubbles
+- recursiveEnumerateChainBubbles(ultraBubbleChain, cactusNode2, edgeEnd2);
+-
+- // Add to visited
+- stSet_insert(visitedCactusNodes, cactusNode2);
+- }
+- }
+- else {
+- // As we encountered a node in connected nodes we break the chain if it is already started
+- if(stList_length(ultraBubbleChain) > 0) {
+- ultraBubbleChain = addNewNestedChain(workingLevelChains);
+- }
+- }
+- edgeEnd2 = stCactusEdgeEnd_getOtherEdgeEnd(stCactusEdgeEnd_getLink(edgeEnd2));
+- }
+-
+- // If new chain has zero length delete
+- if(stList_length(ultraBubbleChain) == 0) {
+- assert(stList_peek(workingLevelChains) == ultraBubbleChain);
+- stList_pop(workingLevelChains);
+- stList_destruct(ultraBubbleChain);
+- }
++ // If we recursed and found a path, we need to clean up our stack frame and return 1 also, because we also found a path.
++ if(retVal) {
++ stList_pop(stack);
++ } else {
++ // Find our stack frame
++ stPathDfsFrame *frame = stList_peek(stack);
++
++ // If we haven't done the link step already, do it.
++ if(!frame->followedLink) {
++ frame->followedLink = 1;
++ // As part of that, we first check to see if we saw this edge end already.
++ if(stSet_search(seen, frame->currentEdgeEnd->node) == NULL) {
++ // This frame is a new edge end and has work to do.
++ stSet_insert(seen, frame->currentEdgeEnd->node);
++
++ // If currentEdgeEnd is in a chain,
++ // extend this chain without adding the node incident with currentEdgeEnd
++ // to the path, because as we are extending the chain the node incident with currentEdgeEnd
++ // is not on the path in the corresponding cactus tree
++ if(frame->currentEdgeEnd->link != NULL) {
++ // Try looking off of where we go next (recurse).
++ stPathDfsFrame *childFrame = malloc(sizeof(stPathDfsFrame));
++ childFrame->currentEdgeEnd = frame->currentEdgeEnd->link->otherEdgeEnd;
++ childFrame->followedLink = false;
++ childFrame->edgeEnd = childFrame->currentEdgeEnd->node->head;
++ stList_append(stack, childFrame);
++ continue;
+ }
++ } else {
++ // Has been seen already. Return 0 to parent frame and don't recurse on anything.
++ retVal = 0;
++ stList_pop(stack);
++ continue;
+ }
+ }
+- stSet_destructIterator(cactusNodesIt);
+- stSet_destruct(visitedCactusNodes);
+-
+- // Recursively walk the remainder of the bridge graph to construct chains for the other nodes
+- for(int64_t i=0; i<stList_length(bridgeNode->connectedNodes); i++) {
+- stBridgeNode *nBridgeNode = stList_get(bridgeNode->connectedNodes, i);
+- if(nBridgeNode != pBridgeNode) {
+- assert(nBridgeNode != bridgeNode);
+- stList_append(stack, bridgeNode);
+- stList_append(stack, nBridgeNode);
+- }
+- }
+- }
+-
+- // Else the bridgeNode is in a circular component
+- else {
+- // Pick the start node, otherwise the highest degree node in the cactus component
+- // Mostly this is just to make things deterministic.
+- stSetIterator *componentIt = stSet_getIterator(cactusGraphComponent);
+- stCactusNode *cactusNode = stSet_getNext(componentIt);
+- int64_t chainNumber = stCactusNode_getChainNumber(cactusNode);
+- stCactusNode *cactusNode2;
+- while((cactusNode2 = stSet_getNext(componentIt)) != NULL) {
+- if(cactusNode2 == startNode || (stCactusNode_getChainNumber(cactusNode2) > chainNumber && cactusNode != startNode)) {
+- cactusNode = cactusNode2;
+- chainNumber = stCactusNode_getChainNumber(cactusNode2);
+- }
+- }
+- stSet_destructIterator(componentIt);
++
++ // When we get here, either we returned from following the link
++ // (which didn't find anything), or there wasn't a good link to
++ // follow.
++
++ if(frame->edgeEnd == frame->currentEdgeEnd->node->head) {
++ // We are just starting the loop over each other chain / bridge incident with the node
++
++ // Now add the node incident with currentEdgeEnd to the current path, as any path
++ // between the start and end edges in the cactus
++ // graph reached in this traversal must include the node incident with currentEdgeEnd
++ stList_append(nodePath, frame->currentEdgeEnd->node);
++ }
++
++ // If we've reached the end of the path we're done
++ if(frame->edgeEnd == edgeEnd2) {
++ retVal = 1;
++ stList_pop(stack);
++ continue;
++ }
++
++ if(frame->edgeEnd == NULL) {
++ // Done iterating in this frame, and we didn't find anything.
++
++ // Remove the current node from the path as we haven't found a path to edgeEnd2
++ // including the node
++ assert(stList_peek(nodePath) == frame->currentEdgeEnd->node);
++ stList_pop(nodePath);
++
++ // Return 0.
++ retVal = 0;
++ stList_pop(stack);
++ continue;
++ }
++
++ // Otherwise, if edgeEnd is in a chain and not in the chain
++ // containing currentEdgeEnd
++ if(frame->edgeEnd->link != NULL && frame->edgeEnd->linkOrientation /* traverse in one direction only */ &&
++ frame->edgeEnd != frame->currentEdgeEnd && frame->edgeEnd != frame->currentEdgeEnd->link) {
++
++ // Set up recursive call
++ stPathDfsFrame *childFrame = malloc(sizeof(stPathDfsFrame));
++ childFrame->currentEdgeEnd = frame->edgeEnd->otherEdgeEnd;
++ childFrame->followedLink = false;
++ childFrame->edgeEnd = childFrame->currentEdgeEnd->node->head;
++
++ // Increment edgeEnd
++ frame->edgeEnd = frame->edgeEnd->nEdgeEnd;
++
++ // Call the child frame
++ stList_append(stack, childFrame);
++ continue;
+
+- // For each chain incident with the cactusNode
+- stCactusNodeEdgeEndIt edgeIterator = stCactusNode_getEdgeEndIt(cactusNode);
+- stCactusEdgeEnd *edgeEnd;
+- while ((edgeEnd = stCactusNodeEdgeEndIt_getNext(&edgeIterator))) {
+- assert(cactusNode == stCactusEdgeEnd_getNode(edgeEnd));
+- assert(stCactusEdgeEnd_getLink(edgeEnd) != NULL); // Can not be a bridge, by definition
+- if (stCactusEdgeEnd_getLinkOrientation(edgeEnd)) {
+-
+- // For each node in the chain not equal to cactusNode
+- stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_getOtherEdgeEnd(stCactusEdgeEnd_getLink(edgeEnd));
+-
+- if(edgeEnd != edgeEnd2) { // If not a self loop
+- // Make new chain
+- stList *ultraBubbleChain = addNewNestedChain(topLevelChains);
+-
+- do {
+- assert(stCactusEdgeEnd_getNode(edgeEnd2) != cactusNode);
+-
+- // Call recursivelyEnumerateChainBubbles
+- recursiveEnumerateChainBubbles(ultraBubbleChain, stCactusEdgeEnd_getNode(edgeEnd2), edgeEnd2);
+-
+- edgeEnd2 = stCactusEdgeEnd_getOtherEdgeEnd(stCactusEdgeEnd_getLink(edgeEnd2));
+- } while (edgeEnd != edgeEnd2);
+-
+- assert(stList_length(ultraBubbleChain) > 0);
+- }
+- }
++ } else {
++ // We're skipping recursing on this item.
++ // Still increment edgeEnd
++ frame->edgeEnd = frame->edgeEnd->nEdgeEnd;
+ }
++
++
++ // If we get here, we didn't make a recursive call, but we did do the increment.
++ // Loop around on the same frame to check for completion.
+ }
+ }
+
+- // Clean up
++ assert(retVal); // If this is not true then we did not find a path in the cactus tree between the edge ends
++
++ // Cleanup
+ stList_destruct(stack);
+-}
++ stSet_destruct(seen);
+
+-stBridgeNode *getStartingNode(stBridgeGraph *bridgeGraph) {
+- /*
+- * Picks a non-chain node (if it exists). A chain node is a node with two incident edges.
+- * This ensures that all chains are complete, or if cyclic are broken arbitrarily.
+- */
+- for(int64_t i=0; i<stList_length(bridgeGraph->bridgeNodes); i++) {
+- stBridgeNode *bridgeNode = stList_get(bridgeGraph->bridgeNodes, i);
+- if(stList_length(bridgeNode->connectedNodes) != 2) {
+- return bridgeNode;
+- }
+- }
+- return stList_peek(bridgeGraph->bridgeNodes);
++ return nodePath;
+ }
+
+-stList *stCactusGraph_getUltraBubbles(stCactusGraph *graph, stCactusNode *startNode) {
+- /*
+- * Constructs the set of nested ultrabubbles for a cactus graph, returning the
+- * set of top level chains as a list. A bubble is top level if it is not
+- * contained in any other. A chain is a sequence of bubbles, such that each successive
+- * bubble in the chain starts with the opposite side of a side in the previous bubble.
++stList *stCactusGraph_getTopLevelSnarlChain(stCactusGraph *cactusGraph,
++ stCactusEdgeEnd *startEdgeEnd, stCactusEdgeEnd *endEdgeEnd, stSet *snarlCache) {
++ /*
++ * Constructs the set of nested snarls and unary snarls between two edge ends in a cactus graph,
++ * returning the top level chain as a list.
+ *
+- * The startNode is used as a tip for the ultra-bubble construction, it may be NULL.
+- */
+-
+- // Create the list to contain the top level chains
+- stList *topLevelChains = stList_construct3(0, (void (*)(void *))stList_destruct);
+-
+- // Get cactus graph components
+- stList *cactusGraphComponents = stCactusGraph_getComponents(graph, 0);
+-
+- // For each component in the cactus graph
+- for(int64_t i=0; i<stList_length(cactusGraphComponents); i++) {
+- stSet *cactusGraphComponent = stList_get(cactusGraphComponents, i);
++ * The startEdgeEnd and endEdgeEnd are used as the boundaries of the top level chain.
++ * They must both be in the same chain and distinct or both be part of bridges in the same component
++ */
++
++ // Get cactus graph component containing startEdgeEnd and endEdgeEnd
++ stSet *component = stSet_construct();
++ buildComponent(component, startEdgeEnd->node, 0);
++
++ // Check two edge ends are in the same component
++ assert(stSet_search(component, startEdgeEnd->node) == startEdgeEnd->node);
++ assert(stSet_search(component, endEdgeEnd->node) == endEdgeEnd->node);
++
++ // Make top level chain, which we'll then fill out
++ stList *topLevelChain = stList_construct3(0, (void (*)(void *))stSnarl_destruct);
++
++ // If the two edge ends are in a chain
++ // then walk over the links in the chain between the two boundaries creating
++ // the top level chain
++
++ if(startEdgeEnd->link != NULL) { // Is a chain end
++
++ assert(endEdgeEnd->link != NULL); // Check the other edge end is also in a chain
++ assert(startEdgeEnd != endEdgeEnd); // Check not the same
++
++ stCactusEdgeEnd *end = startEdgeEnd;
++ while(1) {
++ stList_append(topLevelChain, stSnarl_makeRecursiveSnarl(end, end->link, snarlCache));
++
++ if(end->link == endEdgeEnd) {
++ break; // we're done
++ }
++
++ end = end->link->otherEdgeEnd;
++ assert(end != startEdgeEnd); // Check we haven't looped
++ assert(end != endEdgeEnd); // Check end edge end doesn't have the wrong orientation
++ // with respect start edge end
++ }
++ }
++
++ // Else they are bridges
++ else {
++ assert(endEdgeEnd->link == NULL); // Check other end is also a bridge
++ assert(startEdgeEnd != endEdgeEnd);
++
++ // Get bridge graph
++ stBridgeGraph *bridgeGraph = stBridgeGraph_getBridgeGraph(stSet_peek(component));
++ assert(stList_length(bridgeGraph->bridgeNodes) > 0);
++
++ // Get edges on the path in the bridge graph connecting the projection of startEdgeEnd and endEdgeEnd, starting
++ // with startEdgeEnd and ending with endEdgeEnd
++ stList *bridgePath = getBridgePathConnectingEnds(bridgeGraph, startEdgeEnd, endEdgeEnd);
++ assert(stList_length(bridgePath) > 0);
++ assert(stList_length(bridgePath) % 2 == 0);
++
++ // For each induced snarl on the path of bridge nodes
++
++ for(int64_t i=0; i+1<stList_length(bridgePath); i+=2) {
++ // Get the link in the chain
++ stCactusEdgeEnd *leftSnarlEnd = stList_get(bridgePath, i);
++ stCactusEdgeEnd *rightSnarlEnd = stList_get(bridgePath, i+1);
++
++ // If we can't find it in the cache build it
++ stSnarl *snarl;
++ if((snarl = getSnarlFromCache(snarlCache, leftSnarlEnd, rightSnarlEnd)) == NULL) {
++
++ // Build top level snarl and add to top level chain
++ snarl = stSnarl_constructEmptySnarl(leftSnarlEnd, rightSnarlEnd);
++ stSet_insert(snarlCache, snarl); // Add to the cache
++
++ // Get nodes on the path in the cactus tree that connect the induced snarl
++ stList *nodesOnPathBetweenSnarlBoundariesList = getNodesOnPathInCactusTreeBetweenBridgeSnarlBoundaries(leftSnarlEnd, rightSnarlEnd);
++ stSet *nodesOnPathBetweenSnarlBoundaries = stList_getSet(nodesOnPathBetweenSnarlBoundariesList);
++
++ // Traverse chains incident with these nodes, breaking chains where ever they intersect these nodes
++
++ // For each node on the path in the cactus tree between the induced snarl ends
++ for(int64_t j=0; j<stList_length(nodesOnPathBetweenSnarlBoundariesList); j++) {
++ stCactusNode *cactusNode = stList_get(nodesOnPathBetweenSnarlBoundariesList, j);
++
++ // For each chain or bridge incident with the node
++ stCactusEdgeEnd *edgeEnd = cactusNode->head;
++ while(edgeEnd != NULL) {
++ assert(edgeEnd->node == cactusNode);
++
++ if(edgeEnd != leftSnarlEnd && edgeEnd != rightSnarlEnd) { // Do not exit the snarl in this traversal
++
++ if(edgeEnd->link != NULL) { // Is in a chain
++ if(edgeEnd->linkOrientation) { // Is positively oriented (avoid going around it twice)
++
++ // There exists a part of the chain that contains snarls not collapsed by the induced snarl
++ if(stSet_search(nodesOnPathBetweenSnarlBoundaries, edgeEnd->link->otherEdgeEnd->node) == NULL) {
++
++ // Create a new nested chain
++ stList *nestedChain = stList_construct3(0, (void (*)(void *))stSnarl_destruct);
++ stList_append(snarl->chains, nestedChain);
++
++ // Add links to the chain while they involve a node not in the
++ // nodesOnPathBetweenSnarlBoundaries
++
++ stCactusEdgeEnd *chainEnd = edgeEnd->link->otherEdgeEnd; // Walk around chain in positive orientation
++ do {
++ assert(chainEnd->linkOrientation);
++ assert(stSet_search(nodesOnPathBetweenSnarlBoundaries, chainEnd->node) == NULL);
++
++ // Add a nested snarl to the chain
++ stList_append(nestedChain, stSnarl_makeRecursiveSnarl(chainEnd, chainEnd->link, snarlCache));
++
++ chainEnd = chainEnd->link->otherEdgeEnd;
++ } while(stSet_search(nodesOnPathBetweenSnarlBoundaries, chainEnd->node) == NULL);
++ }
++ }
++ }
++ else { // Is a bridge
++ assert(edgeEnd->otherEdgeEnd->node != edgeEnd->node); // Is a bridge, not a trivial chain
++ stList_append(snarl->unarySnarls, stSnarl_makeRecursiveSnarl(edgeEnd->otherEdgeEnd, edgeEnd->otherEdgeEnd, snarlCache));
++ }
++ }
++
++ // Get next edge end incident with the node
++ edgeEnd = edgeEnd->nEdgeEnd;
++ }
++ }
++
++ // Cleanup
++ stSet_destruct(nodesOnPathBetweenSnarlBoundaries);
++ stList_destruct(nodesOnPathBetweenSnarlBoundariesList);
++ }
++ else {
++ // As we got the snarl from the cache, increase its parent count
++ snarl->parentCount++;
++ }
++
++ // Add to the chain
++ stList_append(topLevelChain, snarl);
++ }
++
++ // Cleanup
++ stBridgeGraph_destruct(bridgeGraph);
++ stList_destruct(bridgePath);
++ }
++
++ // Cleanup
++ stSet_destruct(component);
++
++
++ return topLevelChain;
++}
++
++stSnarlDecomposition *stCactusGraph_getSnarlDecomposition(stCactusGraph *cactusGraph, stList *snarlChainEnds) {
++ /*
++ * Gets the snarl decomposition for a set paths, each specified by a pair of
++ * stCactusEdgeEnds. Each such pair appears consecutively in
++ * snarlChainEnds. One pair must exist per connected component in the graph.
++ *
++ * The edge end pairs must meet one of two criteria:
++ *
++ * 1. The pair are ends of two bridge edges which, by their deletion, would
++ * disconnect a part of the graph from the rest of its component. The ends
++ * should face towards the part to be disconnected. The ends may actually by
++ * equal if the top level telomere pair represents a unary snarl.
++ *
++ * 2. The pair are inward-facing ends in the same chain of snarls, which
++ * would themselves form a snarl when ignoring the minimality constraint. In
++ * this case, the decomposition only operates on the part of the connected
++ * component along that chain between the specified edge ends.
++ *
++ * An easy way to generate such pairs is to select inward-facing ends of
++ * "tips" (which are always bridge edges). Ideally, one tip should be
++ * reachable from the other. One can also select opposite ends of a node in
++ * a cycle.
++ */
++
++ // Make snarl decomposition object
++ stSnarlDecomposition *snarlDecomposition = st_calloc(1, sizeof(stSnarlDecomposition));
++ snarlDecomposition->topLevelChains = stList_construct3(0, (void (*)(void *))stList_destruct);
++ snarlDecomposition->topLevelUnarySnarls = stList_construct3(0, (void (*)(void *))stSnarl_destruct);
++
++ // Make empty snarl cache, used to avoid constructing the same snarl twice
++ stSet *snarlCache = getEmptySnarlCache();
++
++ // Build snarl chain for each pair of ends
++ for(int64_t i=0; i+1<stList_length(snarlChainEnds); i+=2) {
++ stCactusEdgeEnd *edgeEnd1 = stList_get(snarlChainEnds, i);
++ stCactusEdgeEnd *edgeEnd2 = stList_get(snarlChainEnds, i+1);
++ if(edgeEnd1 != edgeEnd2) { // If forms a chain
++ stList_append(snarlDecomposition->topLevelChains,
++ stCactusGraph_getTopLevelSnarlChain(cactusGraph, edgeEnd1, edgeEnd2, snarlCache));
++ }
++ else { // If is a unary snarl
++ stList_append(snarlDecomposition->topLevelUnarySnarls,
++ stSnarl_makeRecursiveSnarl(edgeEnd1, edgeEnd2, snarlCache));
++ }
++ }
++
++ // Cleanup
++ stSet_destruct(snarlCache);
++
++ return snarlDecomposition;
++}
++
++void stSnarlDecomposition_destruct(stSnarlDecomposition *snarls) {
++ stList_destruct(snarls->topLevelChains);
++ stList_destruct(snarls->topLevelUnarySnarls);
++ free(snarls);
++}
+
+- // Determine the bridge graph for the component
+- stBridgeGraph *bridgeGraph = stBridgeGraph_getBridgeGraph(stSet_peek(cactusGraphComponent));
+- assert(stList_length(bridgeGraph->bridgeNodes) > 0);
++/*
++ * Functions for printing snarl decomposition.
++ */
+
+- // Get a starting node for recursion
+- stBridgeNode *bridgeNode = getStartingNode(bridgeGraph);
++void stSnarl_print2(stSnarl *snarl, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix);
+
+- // Recursively build the ultra bubble chains for the bridge graph
+- stSet *seen = stSet_construct();
+- bridgeGraphToUltraBubbles(NULL, bridgeNode, seen, topLevelChains, cactusGraphComponent, startNode);
+- assert(stSet_size(seen) == stList_length(bridgeGraph->bridgeNodes));
+- stSet_destruct(seen);
++void stSnarl_printUnary(stSnarl *snarl, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix);
+
+- // Cleanup the bridge graph
+- stBridgeGraph_destruct(bridgeGraph);
++void stSnarl_printChains2(stList *chains, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix) {
++ for(int64_t i=0; i<stList_length(chains); i++) {
++ stList *chain = stList_get(chains, i);
++ char *chainPrefix = stString_print("%s-%" PRIi64 "", parentChainPrefix, i);
++ fprintf(fileHandle, "%sChain: %s\tLength: %" PRIi64 "\n", parentPrefix, chainPrefix, stList_length(chain));
++ for(int64_t j=0; j<stList_length(chain); j++) {
++ char *prefix = stString_print("\t%s", parentPrefix);
++ stSnarl_print2(stList_get(chain, j), fileHandle, prefix, chainPrefix);
++ free(prefix);
++ }
++ free(chainPrefix);
+ }
++}
+
+- // Cleanup the cactus graph components
+- stList_destruct(cactusGraphComponents);
+-
+- return topLevelChains;
++void stSnarl_print2(stSnarl *snarl, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix) {
++ fprintf(fileHandle, "%sSnarl,\tchild-chain-number: %" PRIi64 ", \tunary-snarl-child-number: %" PRIi64 ", \tparent-number: %" PRIi64
++ "\tis_bridge_snarl: %s\tSide1:(%" PRIi64 ",%" PRIi64 ")\tSide2:(%" PRIi64 ",%" PRIi64 ")\n", parentPrefix,
++ stList_length(snarl->chains), stList_length(snarl->unarySnarls), snarl->parentCount,
++ stCactusEdgeEnd_getLink(snarl->edgeEnd1) == NULL ? "true" : "false",
++ (int64_t)stCactusEdgeEnd_getOtherEdgeEnd(snarl->edgeEnd1), (int64_t)snarl->edgeEnd1,
++ (int64_t)snarl->edgeEnd2, (int64_t)stCactusEdgeEnd_getOtherEdgeEnd(snarl->edgeEnd2));
++ char *childPrefix = stString_print("\t%s", parentPrefix);
++ stSnarl_printChains2(snarl->chains, fileHandle, childPrefix, parentChainPrefix);
++ for(int64_t i=0; i<stList_length(snarl->unarySnarls); i++) {
++ stSnarl_printUnary(stList_get(snarl->unarySnarls, i), fileHandle, childPrefix, parentChainPrefix);
++ }
++ free(childPrefix);
++}
++
++void stSnarl_printUnary(stSnarl *snarl, FILE *fileHandle, const char *parentPrefix, const char *parentChainPrefix) {
++ fprintf(fileHandle, "%sUnary Snarl,\tchild-chain-number: %" PRIi64 ", \tunary-snarl-child-number: %" PRIi64 ", \tparent-number: %" PRIi64
++ "\tSide:(%" PRIi64 ",%" PRIi64 ")\n", parentPrefix,
++ stList_length(snarl->chains), stList_length(snarl->unarySnarls), snarl->parentCount,
++ (int64_t)stCactusEdgeEnd_getOtherEdgeEnd(snarl->edgeEnd1), (int64_t)snarl->edgeEnd1);
++ stSnarl_printChains2(snarl->chains, fileHandle, parentPrefix, parentChainPrefix);
++ for(int64_t i=0; i<stList_length(snarl->unarySnarls); i++) {
++ stSnarl_printUnary(stList_get(snarl->unarySnarls, i), fileHandle, parentPrefix, parentChainPrefix);
++ }
++}
++
++void stSnarl_print(stSnarl *snarl, FILE *fileHandle) {
++ stSnarl_print2(snarl, fileHandle, "", "C");
++}
++
++void stSnarlDecomposition_print(stSnarlDecomposition *snarls, FILE *fileHandle) {
++ fprintf(fileHandle, "Top level chains, total: %" PRIi64 "\n", stList_length(snarls->topLevelChains));
++ stSnarl_printChains2(snarls->topLevelChains, fileHandle, "\t", "C");
++ for(int64_t i=0; i<stList_length(snarls->topLevelUnarySnarls); i++) {
++ stSnarl_printUnary(stList_get(snarls->topLevelUnarySnarls, i), fileHandle, "", "C");
++ }
+ }
+--- a/inc/stCactusGraphs.h
++++ b/inc/stCactusGraphs.h
+@@ -14,32 +14,115 @@
+ extern "C"{
+ #endif
+
+-typedef struct _stCactusNode stCactusNode;
++/*
++ * The basic data structures representing a cactus graph
++ */
+
+ typedef struct _stCactusEdgeEnd stCactusEdgeEnd;
+
++typedef struct _stCactusNode {
++ /*
++ * A vertex in the cactus graph
++ */
++
++ // A linked list of the edge ends (sides) in the cactus graph incident with this node
++ stCactusEdgeEnd *head;
++ stCactusEdgeEnd *tail;
++
++ // The underlying object, e.g. adjacency component of pinchNodes, that "project to" this cactus node
++ void *nodeObject;
++} stCactusNode;
++
++struct _stCactusEdgeEnd {
++ /*
++ * The end of an edge in the cactus graph.
++ * Symmetrically, each edge is composed of two such ends.
++ */
++
++ // The other end (side) of the edge
++ stCactusEdgeEnd *otherEdgeEnd;
++
++ // The incident vertex in the cactus graph
++ stCactusNode *node;
++
++ // A link in linked-list of edge ends that are incident with the incident node. See
++ // stCactusNode->head and stCactusNode->tail
++ stCactusEdgeEnd *nEdgeEnd;
++
++ // The underlying object, e.g. a pinchEdgeEnd
++ void *endObject;
++
++ // If the edge end is in a snarl, the other edge end in the snarl - which must also
++ // be incident with the given cactus node
++ stCactusEdgeEnd *link;
++
++ // Variables used to orient the cactus graph
++ bool linkOrientation;
++ bool isChainEnd;
++};
++
++typedef struct _stCactusGraph {
++ // A hash from underlying node objects to their given nodes
++ stHash *objectToNodeHash;
++
++ // Cleanup functions for the underlying node and edge end objects
++ void (*destructNodeObjectFn)(void *);
++ void (*destructEdgeEndObjectFn)(void *);
++} stCactusGraph;
++
+ typedef struct _stCactusNodeEdgeEndIt {
++ /*
++ * Iterator over the edge ends incident with a given node in the cactus graph.
++ */
+ stCactusEdgeEnd *edgeEnd;
+ } stCactusNodeEdgeEndIt;
+
+-typedef struct _stCactusGraph stCactusGraph;
+-
+ typedef struct _stCactusGraphNodeIterator {
+- stCactusNode *next;
++ /*
++ * Iterator over the nodes in a cactus graph
++ */
++ stHashIterator *it;
+ stCactusGraph *graph;
+ } stCactusGraphNodeIt;
+
+-// Ultra bubbles
+-typedef struct _stUltraBubble stUltraBubble;
+-struct _stUltraBubble {
+- stList *chains; // Each chain is an stList list of ultrabubbles in a sequence
+- // such that for i > 0, edgeEnd1 of ultrabubble i in the chain is the opposite end to edgeEnd2 of ultrabubble i-1.
++/*
++ * Snarls
++ */
++
++typedef struct _stSnarl {
++ // The boundaries of the snarl
+ stCactusEdgeEnd *edgeEnd1, *edgeEnd2;
+-};
++
++ // The chains contained in the snarl
++ stList *chains; // Each chain is an stList list of stSnarls in a sequence
++ // such that for i > 0, edgeEnd1 of snarl i in the chain is the opposite end to edgeEnd2 of snarl i-1.
++
++ // The unary snarls contained in the snarl, for which edgeEnd1 == edgeEnd2
++ // Connected components of unary snarls in a cactus graph form a tree
++ // To
++ stList *unarySnarls;
++
++ // The number of snarls / top-level chains this snarl is contained, vital for memory management
++ uint64_t parentCount;
++
++} stSnarl;
++
++typedef struct _stSnarlDecomposition {
++ // List of top level chains. These chains may overlap.
++ stList *topLevelChains;
++
++ // Top level unary snarls, these are created by handing in a pair of equal bridge ends as telomeres
++ stList *topLevelUnarySnarls;
++
++} stSnarlDecomposition;
++
++/*
++ * Bridge graph
++ */
+
+ typedef struct _stBridgeNode stBridgeNode;
+ struct _stBridgeNode {
+- stList *connectedNodes; // (stBridgNode) Connected bridge nodes
++ stList *connectedNodes; // (stBridgeNode) Connected bridge nodes
+ stSet *bridgeEnds; // (stCactusEdgeEnd) The ends of the bridges in the cactus graph
+ // that project to the node
+ stSet *cactusNodes; // (stCactusNode) The cactus nodes which project to the node
+@@ -134,11 +217,13 @@ stList *stCactusGraph_getComponents(stCa
+
+ stHash *stCactusGraphComponents_getNodesToComponentsMap(stList *components);
+
+-// Used to compute ultrabubbles, startNode may be NULL.
+-stList *stCactusGraph_getUltraBubbles(stCactusGraph *graph, stCactusNode *startNode);
+-
+ int64_t stCactusGraph_getNodeNumber(stCactusGraph *graph);
+
++stSnarlDecomposition *stCactusGraph_getSnarlDecomposition(stCactusGraph *cactusGraph, stList *snarlChainEnds);
++
++stList *stCactusGraph_getTopLevelSnarlChain(stCactusGraph *cactusGraph,
++ stCactusEdgeEnd *startEdgeEnd, stCactusEdgeEnd *endEdgeEnd, stSet *snarlCache);
++
+ // Bridge graphs
+
+ void stBridgeNode_destruct(stBridgeNode *bridgeNode);
+@@ -149,17 +234,26 @@ void stBridgeGraph_destruct(stBridgeGrap
+
+ void stBridgeNode_print(stBridgeNode *bridgeNode, FILE *fileHandle);
+
+-// Ultrabubbles
++stHash *stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash(stBridgeGraph *bridgeGraph);
++
++// Snarls
++
++stSnarl *stSnarl_constructEmptySnarl(stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2);
++
++void stSnarl_destruct(stSnarl *snarl);
++
++stSnarl *stSnarl_makeRecursiveSnarl(stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2,
++ stSet *snarlCache);
+
+-stUltraBubble *stUltraBubble_construct(stList *parentChain,
+- stCactusEdgeEnd *edgeEnd1, stCactusEdgeEnd *edgeEnd2);
++uint64_t stSnarl_hashKey(const void *snarl);
+
+-void stUltraBubble_destruct(stUltraBubble *ultraBubble);
++int stSnarl_equals(const void *snarl1, const void *snarl2);
+
+-void stUltraBubble_print(stUltraBubble *ultraBubble, FILE *fileHandle);
++void stSnarl_print(stSnarl *snarl, FILE *fileHandle);
+
+-void stUltraBubble_printChains(stList *ultraBubbleChains, FILE *fileHandle);
++void stSnarlDecomposition_destruct(stSnarlDecomposition *snarls);
+
++void stSnarlDecomposition_print(stSnarlDecomposition *snarls, FILE *fileHandle);
+
+ #ifdef __cplusplus
+ }
+--- a/tests/stCactusGraphsTest.c
++++ b/tests/stCactusGraphsTest.c
+@@ -72,7 +72,7 @@ static void setup() {
+ stCactusGraph_collapseToCactus(g, mergeNodeObjects, n1);
+ }
+
+-static void invariantNodeTests(CuTest *testCase) {
++void invariantNodeTests(CuTest *testCase) {
+ //Test the get object
+ CuAssertPtrEquals(testCase, &nO1, stCactusNode_getObject(n1));
+ CuAssertPtrEquals(testCase, &nO2, stCactusNode_getObject(n2));
+@@ -115,7 +115,7 @@ static void invariantNodeTests(CuTest *t
+ CuAssertPtrEquals(testCase, NULL, stCactusNodeEdgeEndIt_getNext(&it));
+ }
+
+-static void testStCactusNode(CuTest *testCase) {
++void testStCactusNode(CuTest *testCase) {
+ setup();
+ invariantNodeTests(testCase);
+
+@@ -148,7 +148,7 @@ static void testStCactusNode(CuTest *tes
+ teardown();
+ }
+
+-static void testStCactusGraph(CuTest *testCase) {
++void testStCactusGraph(CuTest *testCase) {
+ setup();
+
+ //stCactusGraph_getNode
+@@ -366,14 +366,14 @@ static void chainStructureTests(CuTest *
+ }
+ }
+
+-static void testStCactusEdgeEnd(CuTest *testCase) {
++void testStCactusEdgeEnd(CuTest *testCase) {
+ setup();
+ edgeEndTests(testCase);
+ chainStructureTests(testCase);
+ teardown();
+ }
+
+-static void testStCactusGraph_unmarkAndMarkCycles(CuTest *testCase) {
++void testStCactusGraph_unmarkAndMarkCycles(CuTest *testCase) {
+ setup();
+ stCactusGraph_unmarkCycles(g);
+ edgeEndTests(testCase);
+@@ -398,7 +398,7 @@ static void testStCactusGraph_unmarkAndM
+ teardown();
+ }
+
+-static void testStCactusGraph_collapseBridges(CuTest *testCase) {
++void testStCactusGraph_collapseBridges(CuTest *testCase) {
+ setup();
+ stCactusGraph_collapseBridges(g, n1, mergeNodeObjects);
+ n2 = stCactusGraph_getNode(g, &nO2);
+@@ -480,7 +480,7 @@ bool endIsNotInChain(stCactusEdgeEnd *ed
+ return stSet_search(endsNotInChainSet, edgeEnd) != NULL;
+ }
+
+-static void testStCactusGraph_breakChainsByEndsNotInChains(CuTest *testCase) {
++void testStCactusGraph_breakChainsByEndsNotInChains(CuTest *testCase) {
+ setup();
+ stCactusGraph_collapseBridges(g, n1, mergeNodeObjects);
+ stSet *endsNotInChainSet = stSet_construct();
+@@ -587,7 +587,7 @@ static void destroyRandomCactusGraph(str
+ free(rGraph);
+ }
+
+-static void testStCactusGraph_randomTest(CuTest *testCase) {
++void testStCactusGraph_randomTest(CuTest *testCase) {
+ // Creates problem instances, then checks graph is okay by checking every edge
+ // is properly connected, with right number of nodes and that everyone is in a chain
+ for (int64_t test = 0; test < 1000; test++) {
+@@ -755,7 +755,7 @@ static void makeComponent(stCactusNode *
+ }
+ }
+
+-static void testStCactusGraph_getComponents(CuTest *testCase) {
++void testStCactusGraph_getComponents(CuTest *testCase) {
+ // Creates problem instances, then checks resulting component set.
+ for (int64_t test = 0; test < 1000; test++) {
+ // Make a random graph
+@@ -916,7 +916,7 @@ static stSet *getNodesOnPathsBetweenBrid
+ return connectedCactusNodes;
+ }
+
+-static void testStCactusGraph_getBridgeGraphs(CuTest *testCase) {
++void testStCactusGraph_getBridgeGraphs(CuTest *testCase) {
+ // Creates problem instances, then checks resulting component set.
+ for (int64_t test = 0; test < 1000; test++) {
+ // Make a random graph
+@@ -1012,61 +1012,555 @@ static void testStCactusGraph_getBridgeG
+ }
+ }
+
+-static void checkUltraBubbleChains(CuTest *testCase, stList *ultraBubbleChains, bool isNested);
++static void checkSnarlChain(CuTest *testCase, stList *chain, bool hasParent);
++
++static void checkSnarl(CuTest *testCase, stSnarl *snarl, bool hasParent);
++
++static void checkUnarySnarl(CuTest *testCase, stSnarl *snarl);
++
++static void checkNestedSnarls(CuTest *testCase, stSnarl *snarl) {
++ // Check nested unary snarls
++ for(int64_t i=0; i<stList_length(snarl->unarySnarls); i++) {
++ checkUnarySnarl(testCase, stList_get(snarl->unarySnarls, i));
++ }
++
++ // Check nested chains
++ for(int64_t i=0; i<stList_length(snarl->chains); i++) {
++ checkSnarlChain(testCase, stList_get(snarl->chains, i), snarl);
++ }
++}
++
++static void checkUnarySnarl(CuTest *testCase, stSnarl *snarl) {
++ // Check has just one boundary
++ CuAssertTrue(testCase, snarl->edgeEnd1 == snarl->edgeEnd2);
++
++ // Check is bridge
++ CuAssertTrue(testCase, stCactusEdgeEnd_getLink(snarl->edgeEnd1) == NULL);
++
++ checkNestedSnarls(testCase, snarl); // Recursively check children
++}
++
++static void checkSnarl(CuTest *testCase, stSnarl *snarl, bool hasParent) {
++ // Check not a unary snarl
++ CuAssertTrue(testCase, snarl->edgeEnd1 != snarl->edgeEnd2);
+
+-static void checkUltraBubble(CuTest *testCase, stUltraBubble *ultraBubble, bool isNested) {
+ // Check that the removal of both edges disconnects the cactus
+
+- if(stCactusEdgeEnd_getLink(ultraBubble->edgeEnd1) == NULL) { // Is a bridge
++ if(stCactusEdgeEnd_getLink(snarl->edgeEnd1) == NULL) { // Is a bridge
+ // The other end must also be a bridge for the graph to be disconnected by their removal
+- CuAssertTrue(testCase, stCactusEdgeEnd_getLink(ultraBubble->edgeEnd2) == NULL);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getLink(snarl->edgeEnd2) == NULL);
+
+ // Can not be nested
+- CuAssertTrue(testCase, !isNested);
++ CuAssertTrue(testCase, !hasParent);
+ }
+- else {
++ else { // Is in a chain
+ // Other end can not be a bridge
+- CuAssertTrue(testCase, stCactusEdgeEnd_getLink(ultraBubble->edgeEnd2) != NULL);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getLink(snarl->edgeEnd2) != NULL);
+
+ // As both are in a chain, must be connected
+- CuAssertTrue(testCase, stCactusEdgeEnd_getLink(ultraBubble->edgeEnd1) == ultraBubble->edgeEnd2);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getLink(snarl->edgeEnd1) == snarl->edgeEnd2);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getLink(snarl->edgeEnd2) == snarl->edgeEnd1);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getNode(snarl->edgeEnd1) == stCactusEdgeEnd_getNode(snarl->edgeEnd2));
+ }
+
+- checkUltraBubbleChains(testCase, ultraBubble->chains, 1);
++ checkNestedSnarls(testCase, snarl); // Recursively check children
+ }
+
+-static void checkUltraBubbleChains(CuTest *testCase, stList *ultraBubbleChains, bool isNested) {
+- // For each chain
+- for(int64_t i=0; i<stList_length(ultraBubbleChains); i++) {
+- stList *chain = stList_get(ultraBubbleChains, i);
++static void checkSnarlChain(CuTest *testCase, stList *chain, bool hasParent) {
++ // Check chain is not empty
++ CuAssertTrue(testCase, stList_length(chain) > 0);
+
+- // Check chain is not empty
+- CuAssertTrue(testCase, stList_length(chain) > 0);
++ // For each snarl in chain
++ for(int64_t j=0; j<stList_length(chain); j++) {
++ stSnarl *snarl = stList_get(chain, j);
+
+- // For each ultra bubble
+- for(int64_t j=0; j<stList_length(chain); j++) {
+- stUltraBubble *ultraBubble = stList_get(chain, j);
++ // If there is a preceding element in the chain, check that the ends match up
++ if(j > 0) {
++ stSnarl *pSnarl = stList_get(chain, j-1);
++ CuAssertTrue(testCase, stCactusEdgeEnd_getOtherEdgeEnd(pSnarl->edgeEnd2) == snarl->edgeEnd1);
++ }
+
+- // If there is a preceding element in the chain, check that the ends match up
+- if(j > 0) {
+- stUltraBubble *pUltraBubble = stList_get(chain, j-1);
+- CuAssertTrue(testCase, stCactusEdgeEnd_getOtherEdgeEnd(pUltraBubble->edgeEnd2) == ultraBubble->edgeEnd1);
+- }
++ // Recursively check the nested snarl
++ checkSnarl(testCase, snarl, hasParent);
++ }
++}
+
+- // Recursively check the nested ultrabubble
+- checkUltraBubble(testCase, ultraBubble, isNested);
+- }
++static void checkSnarlDecomposition(CuTest *testCase, stSnarlDecomposition *snarls, stList *telomeres) {
++
++ // Check we got the expected number of top level chains
++ CuAssertIntEquals(testCase, stList_length(telomeres)/2,
++ stList_length(snarls->topLevelChains) + stList_length(snarls->topLevelUnarySnarls));
++
++ // For each top level chain / unary snarl
++ int64_t i=0, j=0;
++ for(int64_t k=0; k<stList_length(telomeres); k+=2) {
++ stCactusEdgeEnd *edgeEnd1 = stList_get(telomeres, k);
++ stCactusEdgeEnd *edgeEnd2 = stList_get(telomeres, k+1);
++
++ if(edgeEnd1 != edgeEnd2) { // Is a chain
++ stList *chain = stList_get(snarls->topLevelChains, i++);
++
++ // Check chain, recursively
++ checkSnarlChain(testCase, chain, 0);
++
++ // Check boundaries are what we expect
++ CuAssertTrue(testCase, edgeEnd1 == ((stSnarl *)stList_get(chain, 0))->edgeEnd1);
++ CuAssertTrue(testCase, edgeEnd2 == ((stSnarl *)stList_peek(chain))->edgeEnd2);
++ }
++ else { // is a unary snarl
++ stSnarl *uSnarl = stList_get(snarls->topLevelUnarySnarls, j++);
++
++ // Check unary snarl, recursively
++ checkUnarySnarl(testCase, uSnarl);
++
++ // Check boundaries are what we expect
++ CuAssertTrue(testCase, edgeEnd1 == uSnarl->edgeEnd1);
++ CuAssertTrue(testCase, edgeEnd1 == uSnarl->edgeEnd2);
++ }
++ }
++}
++
++static void getReachableBridges2(stCactusEdgeEnd *edgeEnd1,
++ stHash *bridgeEndsToBridgeNodes, stList *bridgeEnds) {
++ assert(edgeEnd1->link == NULL); // is a bridge
++
++ // The node in the bridge graph incident with edgeEnd1
++ stBridgeNode *bNode = stHash_search(bridgeEndsToBridgeNodes, edgeEnd1);
++
++ // Walk from bNode to all the reachable nodes
++ stSetIterator *endIt = stSet_getIterator(bNode->bridgeEnds);
++ stCactusEdgeEnd *edgeEnd2;
++ while((edgeEnd2 = stSet_getNext(endIt)) != NULL) {
++ if(edgeEnd2 != edgeEnd1) {
++ stList_append(bridgeEnds, edgeEnd2);
++ getReachableBridges2(edgeEnd2->otherEdgeEnd, bridgeEndsToBridgeNodes, bridgeEnds);
++ }
++ }
++ stSet_destructIterator(endIt);
++}
++
++static void getReachableBridges(stCactusEdgeEnd *edgeEnd1, stList *bridgeEnds) {
++ /*
++ * Get the bridge ends that form boundary pairs with edgeEnd1.
++ */
++
++ // Get bridge graph and map of bridge ends to bridge nodes in the bridge graph
++ stBridgeGraph *bGraph = stBridgeGraph_getBridgeGraph(edgeEnd1->node);
++ stHash *bridgeEndsToBridgeNodes = stBridgeGraph_getBridgeEdgeEndsToBridgeNodesHash(bGraph);
++
++ // Do DFS to get reachable bridges
++ getReachableBridges2(edgeEnd1, bridgeEndsToBridgeNodes, bridgeEnds);
++
++ // Cleanup
++ stHash_destruct(bridgeEndsToBridgeNodes);
++ stBridgeGraph_destruct(bGraph);
++}
++
++static void addRandomTelomerePair(struct RandomCactusGraph *rGraph, stList *telomeres) {
++ /*
++ * Finds a random pair of telomeres, which are are either a pair or bridge edge ends or a pair chain edge ends, oriented such that they
++ * form a pair of boundaries.
++ */
++
++ // If empty graph, print warning and exit
++ if(stSortedSet_size(rGraph->edgeEnds) == 0) {
++ st_logCritical("Empty graph, no telomeres to select\n");
++ return;
++ }
++
++ // Pick a random edge end
++ stList *edgeEndsList = stSortedSet_getList(rGraph->edgeEnds);
++ stCactusEdgeEnd *edgeEnd1 = st_randomChoice(edgeEndsList);
++ stList_destruct(edgeEndsList);
++
++ // Now find a compatible end
++ stCactusEdgeEnd *edgeEnd2;
++
++ // If a chain end
++ if(edgeEnd1->link != NULL) {
++ // Get the other elligible edge ends in the chain that form a pair of boundaries
++ stList *boundaries = stList_construct();
++ edgeEnd2 = edgeEnd1->link;
++ do {
++ stList_append(boundaries, edgeEnd2);
++ edgeEnd2 = edgeEnd2->otherEdgeEnd->link;
++ } while(!stList_contains(boundaries, edgeEnd2));
++ edgeEnd2 = st_randomChoice(boundaries);
++ stList_destruct(boundaries);
++ }
++ // Else, is a bridge end
++ else {
++ // Else, get the other bridges in the subtree
++ stList *bridgeEnds = stList_construct();
++ getReachableBridges(edgeEnd1, bridgeEnds);
++ stList_append(bridgeEnds, edgeEnd1); // Case it is a unary top-level snarl
++
++ // Pick a random one as the partner
++ edgeEnd2 = st_randomChoice(bridgeEnds);
++
++ // Cleanup
++ stList_destruct(bridgeEnds);
++ }
++
++ // Add to telomeres
++ stList_append(telomeres, edgeEnd1);
++ stList_append(telomeres, edgeEnd2);
++}
++
++static void testStCactusGraph_tinySnarlTest(CuTest *testCase) {
++ // Define a graph of two sequences connected back-to-back
++
++ // The graph
++ stCactusGraph* cactusGraph = stCactusGraph_construct();
++
++ // External containers for tracking nodes and edges
++ stList* nodeObjects = stList_construct3(0, free);
++ stSortedSet* edgeEnds = stSortedSet_construct();
++
++ // Create the nodes (3 of them)
++ for (int64_t i = 0; i < 3; i++) {
++ int64_t *j = st_malloc(sizeof(int64_t));
++ j[0] = i;
++ stCactusNode_construct(cactusGraph, j);
++ stList_append(nodeObjects, j);
++ }
++
++ // Connect node 0 to node 1
++ void *nodeObject1 = stList_get(nodeObjects, 0);
++ void *nodeObject2 = stList_get(nodeObjects, 1);
++ stCactusNode *node1 = stCactusGraph_getNode(cactusGraph, nodeObject1);
++ assert(node1 != NULL);
++ stCactusNode *node2 = stCactusGraph_getNode(cactusGraph, nodeObject2);
++ assert(node2 != NULL);
++ stCactusEdgeEnd *edgeEnd = stCactusEdgeEnd_construct(cactusGraph, node1, node2, nodeObject1, nodeObject2);
++ stSortedSet_insert(edgeEnds, edgeEnd);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd));
++
++ // The right side of this edge is one telomere
++ stCactusEdgeEnd* telomere1 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd);
++
++ // Connect node 2 to node 1
++ nodeObject1 = stList_get(nodeObjects, 2);
++ nodeObject2 = stList_get(nodeObjects, 1);
++ node1 = stCactusGraph_getNode(cactusGraph, nodeObject1);
++ assert(node1 != NULL);
++ node2 = stCactusGraph_getNode(cactusGraph, nodeObject2);
++ assert(node2 != NULL);
++ edgeEnd = stCactusEdgeEnd_construct(cactusGraph, node1, node2, nodeObject1, nodeObject2);
++ stSortedSet_insert(edgeEnds, edgeEnd);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd));
++
++ // The right side of this edge is the other telomere
++ stCactusEdgeEnd* telomere2 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd);
++
++ // Collapse to cactus
++ stCactusGraph_collapseToCactus(cactusGraph, mergeNodeObjects, stList_get(nodeObjects, 0));
++
++ // Add the two inside edge ends as telomeres
++ stList *telomeres = stList_construct();
++ stList_append(telomeres, (void*) telomere1);
++ stList_append(telomeres, (void*) telomere2);
++
++ // Make snarls
++ stSnarlDecomposition *snarls = stCactusGraph_getSnarlDecomposition(cactusGraph, telomeres);
++
++ // Make sure we got the right number
++ CuAssertIntEquals(testCase, stList_length(telomeres)/2,
++ stList_length(snarls->topLevelChains) + stList_length(snarls->topLevelUnarySnarls));
++
++ // Clean up the snarls
++ stSnarlDecomposition_destruct(snarls);
++
++ // And up the telomeres
++ stList_destruct(telomeres);
++
++ // And the cactus graph
++ stCactusGraph_destruct(cactusGraph);
++
++ // And the node objects in their list
++ stList_destruct(nodeObjects);
++
++ // And the edge ends
++ stSortedSet_destruct(edgeEnds);
++
++}
++
++static void testStCactusGraph_unreachableSnarlTest(CuTest *testCase) {
++ /*
++ * Define a graph with two tips that can't reach each other.
++ *
++ * 1\
++ * 2---3
++ * v\4 v
++ *
++ * The head is 1, the tail is 4, 2 and 3 have self loops, and the graph is
++ * connected. But the head cannot reach the tail.
++ */
++
++
++ // The graph
++ stCactusGraph* cactusGraph = stCactusGraph_construct();
++
++ // External containers for tracking nodes and edges
++ stList* nodeObjects = stList_construct3(0, free);
++ stSortedSet* edgeEnds = stSortedSet_construct();
++
++ // Create the adjacency component nodes (5 of them)
++ for (int64_t i = 0; i < 5; i++) {
++ int64_t *j = st_malloc(sizeof(int64_t));
++ j[0] = i;
++ stCactusNode_construct(cactusGraph, j);
++ stList_append(nodeObjects, j);
++ }
++
++ // Node 1 connects component 0 to component 1
++ stCactusEdgeEnd *edgeEnd1 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 0)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stList_get(nodeObjects, 0),
++ stList_get(nodeObjects, 1));
++ stSortedSet_insert(edgeEnds, edgeEnd1);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd1));
++
++ // Node 2 connects component 2 to component 1
++ stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 2)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stList_get(nodeObjects, 2),
++ stList_get(nodeObjects, 1));
++ stSortedSet_insert(edgeEnds, edgeEnd2);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
++
++ // Node 3 connects component 1 to component 3
++ stCactusEdgeEnd *edgeEnd3 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 3)),
++ stList_get(nodeObjects, 1),
++ stList_get(nodeObjects, 3));
++ stSortedSet_insert(edgeEnds, edgeEnd3);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd3));
++
++ // Node 4 connects component 1 to component 4
++ stCactusEdgeEnd *edgeEnd4 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 4)),
++ stList_get(nodeObjects, 1),
++ stList_get(nodeObjects, 4));
++ stSortedSet_insert(edgeEnds, edgeEnd4);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd4));
++
++ // The right side of node 1's edge is one telomere
++ stCactusEdgeEnd* telomere1 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd1);
++
++ // The left side of node 4's edge is the other telomere
++ stCactusEdgeEnd* telomere2 = edgeEnd4;
++
++ // Collapse to cactus
++ stCactusGraph_collapseToCactus(cactusGraph, mergeNodeObjects, stList_get(nodeObjects, 0));
++
++ // Add the two inside edge ends as telomeres
++ stList *telomeres = stList_construct();
++ stList_append(telomeres, (void*) telomere1);
++ stList_append(telomeres, (void*) telomere2);
++
++ // Make snarls
++ stSnarlDecomposition *snarls = stCactusGraph_getSnarlDecomposition(cactusGraph, telomeres);
++
++ // Make sure we got the right number of items (one chain per telomere pair)
++ CuAssertIntEquals(testCase, stList_length(telomeres)/2,
++ stList_length(snarls->topLevelChains) + stList_length(snarls->topLevelUnarySnarls));
++
++ // Make sure it really is a chain and not a unary snarl.
++ CuAssertIntEquals(testCase, 1, stList_length(snarls->topLevelChains));
++
++ // Make sure it has one top-level snarl
++ stList* chain1 = stList_get(snarls->topLevelChains, 0);
++ CuAssertIntEquals(testCase, 1, stList_length(chain1));
++ stSnarl* snarl = stList_get(chain1, 0);
++
++ // Make sure that snarl has 2 unary children (one per graph sequence node)
++ CuAssertIntEquals(testCase, 0, stList_length(snarl->chains));
++ CuAssertIntEquals(testCase, 2, stList_length(snarl->unarySnarls));
++
++ // Clean up the snarls
++ stSnarlDecomposition_destruct(snarls);
++
++ // And up the telomeres
++ stList_destruct(telomeres);
++
++ // And the cactus graph
++ stCactusGraph_destruct(cactusGraph);
++
++ // And the node objects in their list
++ stList_destruct(nodeObjects);
++
++ // And the edge ends
++ stSortedSet_destruct(edgeEnds);
++
++}
++
++static void testStCactusGraph_adjacentSnarlTest(CuTest *testCase) {
++ /*
++ * Define a graph with two adjacent bubbles
++ *
++ * 2 5
++ * 1 4 7
++ * 3 6
++ *
++ * We need to make sure the bubbles don't contain unary child snarls that want to contain the other bubbles.
++ */
++
++
++ // The graph
++ stCactusGraph* cactusGraph = stCactusGraph_construct();
++
++ // External containers for tracking nodes and edges
++ stList* nodeObjects = stList_construct3(0, free);
++ stSortedSet* edgeEnds = stSortedSet_construct();
++
++ // Create the adjacency component nodes (6 of them)
++ for (int64_t i = 0; i < 6; i++) {
++ int64_t *j = st_malloc(sizeof(int64_t));
++ j[0] = i;
++ stCactusNode_construct(cactusGraph, j);
++ stList_append(nodeObjects, j);
+ }
++
++ // Node 1 connects component 0 to component 1
++ stCactusEdgeEnd *edgeEnd1 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 0)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stList_get(nodeObjects, 0),
++ stList_get(nodeObjects, 1));
++ stSortedSet_insert(edgeEnds, edgeEnd1);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd1));
++
++ // Node 2 connects component 1 to component 2
++ stCactusEdgeEnd *edgeEnd2 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 2)),
++ stList_get(nodeObjects, 1),
++ stList_get(nodeObjects, 2));
++ stSortedSet_insert(edgeEnds, edgeEnd2);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd2));
++
++ // Node 3 connects component 1 to component 2
++ stCactusEdgeEnd *edgeEnd3 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 1)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 2)),
++ stList_get(nodeObjects, 1),
++ stList_get(nodeObjects, 2));
++ stSortedSet_insert(edgeEnds, edgeEnd3);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd3));
++
++ // Node 4 connects component 2 to component 3
++ stCactusEdgeEnd *edgeEnd4 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 2)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 3)),
++ stList_get(nodeObjects, 2),
++ stList_get(nodeObjects, 3));
++ stSortedSet_insert(edgeEnds, edgeEnd4);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd4));
++
++ // Node 5 connects component 3 to component 4
++ stCactusEdgeEnd *edgeEnd5 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 3)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 4)),
++ stList_get(nodeObjects, 3),
++ stList_get(nodeObjects, 4));
++ stSortedSet_insert(edgeEnds, edgeEnd5);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd5));
++
++ // Node 6 connects component 3 to component 4
++ stCactusEdgeEnd *edgeEnd6 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 3)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 4)),
++ stList_get(nodeObjects, 3),
++ stList_get(nodeObjects, 4));
++ stSortedSet_insert(edgeEnds, edgeEnd6);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd6));
++
++ // Node 7 connects component 4 to component 5
++ stCactusEdgeEnd *edgeEnd7 = stCactusEdgeEnd_construct(cactusGraph,
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 4)),
++ stCactusGraph_getNode(cactusGraph, stList_get(nodeObjects, 5)),
++ stList_get(nodeObjects, 4),
++ stList_get(nodeObjects, 5));
++ stSortedSet_insert(edgeEnds, edgeEnd7);
++ stSortedSet_insert(edgeEnds, stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd7));
++
++ // The right side of node 1's edge is one telomere
++ stCactusEdgeEnd* telomere1 = stCactusEdgeEnd_getOtherEdgeEnd(edgeEnd1);
++
++ // The left side of node 7's edge is the other telomere
++ stCactusEdgeEnd* telomere2 = edgeEnd7;
++
++ // Collapse to cactus
++ stCactusGraph_collapseToCactus(cactusGraph, mergeNodeObjects, stList_get(nodeObjects, 0));
++
++ // Add the two inside edge ends as telomeres
++ stList *telomeres = stList_construct();
++ stList_append(telomeres, (void*) telomere1);
++ stList_append(telomeres, (void*) telomere2);
++ CuAssertTrue(testCase, telomere1->link == NULL);
++ CuAssertTrue(testCase, telomere2->link == NULL);
++
++ // Make snarls
++ stSnarlDecomposition *snarls = stCactusGraph_getSnarlDecomposition(cactusGraph, telomeres);
++
++ // Make sure we got the right number of items (one chain per telomere pair)
++ CuAssertIntEquals(testCase, stList_length(telomeres)/2,
++ stList_length(snarls->topLevelChains) + stList_length(snarls->topLevelUnarySnarls));
++
++ // Make sure it really is a chain and not a unary snarl.
++ CuAssertIntEquals(testCase, 1, stList_length(snarls->topLevelChains));
++
++ // Make sure it has two top-level snarls
++ stList* chain1 = stList_get(snarls->topLevelChains, 0);
++ CuAssertIntEquals(testCase, 2, stList_length(chain1));
++ stSnarl* snarl1 = stList_get(chain1, 0);
++ stSnarl* snarl2 = stList_get(chain1, 1);
++
++ // Make sure that snarl1 has 0 chains and 0 unary children
++ CuAssertIntEquals(testCase, 0, stList_length(snarl1->chains));
++ CuAssertIntEquals(testCase, 0, stList_length(snarl1->unarySnarls));
++
++ // Make sure that snarl2 has 0 chains and 0 unary children
++ CuAssertIntEquals(testCase, 0, stList_length(snarl2->chains));
++ CuAssertIntEquals(testCase, 0, stList_length(snarl2->unarySnarls));
++
++ // Clean up the snarls
++ stSnarlDecomposition_destruct(snarls);
++
++ // And up the telomeres
++ stList_destruct(telomeres);
++
++ // And the cactus graph
++ stCactusGraph_destruct(cactusGraph);
++
++ // And the node objects in their list
++ stList_destruct(nodeObjects);
++
++ // And the edge ends
++ stSortedSet_destruct(edgeEnds);
++
+ }
+
+-static void testStCactusGraph_randomUltraBubbleTest(CuTest *testCase) {
+- // Creates problem instances, then checks resulting ultrabubble set.
++
++static void testStCactusGraph_randomSnarlTest(CuTest *testCase) {
++ // Creates problem instances, then checks resulting snarl set.
+ for (int64_t test = 0; test < 1000; test++) {
+ // Make a random graph
+ struct RandomCactusGraph *rGraph = getRandomCactusGraph(0);
+
+- // Make ultrabubbles
+- stList *topLevelUltraBubbleChains = stCactusGraph_getUltraBubbles(rGraph->cactusGraph, rGraph->startNode);
++ // Get a random set of one or more telomere pairs
++ stList *telomeres = stList_construct();
++ do {
++ addRandomTelomerePair(rGraph, telomeres);
++ } while(st_random() > 0.5);
++
++ // Make snarls
++ stSnarlDecomposition *snarls = stCactusGraph_getSnarlDecomposition(rGraph->cactusGraph, telomeres);
+
+ // Print the bridge graphs
+ /*stList *components = stCactusGraph_getComponents(rGraph->cactusGraph, 0);
+@@ -1076,20 +1570,21 @@ static void testStCactusGraph_randomUltr
+ for(int64_t j=0; j<stList_length(bridgeGraph->bridgeNodes); j++) {
+ stBridgeNode_print(stList_get(bridgeGraph->bridgeNodes, j), stdout);
+ }
++ stBridgeGraph_destruct(bridgeGraph);
+ }
+ stList_destruct(components);*/
+
+- // Print the ultrabubble decomposition
+- //stUltraBubble_printChains(topLevelUltraBubbleChains, stdout);
++ // Print the snarl decomposition
++ //stSnarlDecomposition_print(snarls, stdout);
+
+- // Test the ultrabubbles
+- checkUltraBubbleChains(testCase, topLevelUltraBubbleChains, 0);
++ // Test the snarls
++ checkSnarlDecomposition(testCase, snarls, telomeres);
+
+ // Cleanup
+ destroyRandomCactusGraph(rGraph);
+- stList_destruct(topLevelUltraBubbleChains);
++ stSnarlDecomposition_destruct(snarls);
++ stList_destruct(telomeres);
+ }
+-
+ }
+
+ CuSuite* stCactusGraphsTestSuite(void) {
+@@ -1103,6 +1598,9 @@ CuSuite* stCactusGraphsTestSuite(void) {
+ SUITE_ADD_TEST(suite, testStCactusGraph_randomTest);
+ SUITE_ADD_TEST(suite, testStCactusGraph_getComponents);
+ SUITE_ADD_TEST(suite, testStCactusGraph_getBridgeGraphs);
+- SUITE_ADD_TEST(suite, testStCactusGraph_randomUltraBubbleTest);
++ SUITE_ADD_TEST(suite, testStCactusGraph_tinySnarlTest);
++ SUITE_ADD_TEST(suite, testStCactusGraph_unreachableSnarlTest);
++ SUITE_ADD_TEST(suite, testStCactusGraph_adjacentSnarlTest);
++ SUITE_ADD_TEST(suite, testStCactusGraph_randomSnarlTest);
+ return suite;
+ }
=====================================
debian/patches/series
=====================================
@@ -1 +1,2 @@
0001-Use-available-sonLib-list-constructor.patch
+0002-Restore-vg-compatible-cactus-snarl-API.patch
View it on GitLab: https://salsa.debian.org/med-team/libpinchesandcacti/-/compare/0e64d385972db223d999693e2cbb3ef5a2efa40e...e69105edf0566acb66883519ff5aded18f584926
--
View it on GitLab: https://salsa.debian.org/med-team/libpinchesandcacti/-/compare/0e64d385972db223d999693e2cbb3ef5a2efa40e...e69105edf0566acb66883519ff5aded18f584926
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/debian-med-commit/attachments/20261104/a3bd4f47/attachment-0001.htm>
More information about the debian-med-commit
mailing list