1111#define MASHPL_HPP
1212
1313#include < stdint.h>
14+ #include < cmath>
15+ #include < functional>
1416#include < iostream>
1517#include < vector>
1618#include < cstdio>
2123
2224namespace MashPlacement
2325{
24- /* * CLI and pipeline parameters; threads for TBB. */
26+ inline bool g_printBinaryNewick = false ;
27+
2528 struct Param
2629 {
2730 uint64_t kmerSize;
@@ -327,6 +330,63 @@ namespace MashPlacement
327330 };
328331 static KPlacementDeviceArraysDC kplacementDeviceArraysDC;
329332
333+ inline void printNewickFromHostAdjacency (std::ostream& out, const std::vector<std::string>& name, int * h_head,
334+ int * h_e, int * h_nxt, double * h_len, int rootNode, bool binaryNewick) {
335+ const double kLenEps = 1e-12 ;
336+ auto hasKids = [h_head, h_e, h_nxt](int node, int from) -> bool {
337+ for (int i = h_head[node]; i != -1 ; i = h_nxt[i]) {
338+ if (h_e[i] != from) {
339+ return true ;
340+ }
341+ }
342+ return false ;
343+ };
344+ std::function<void (int , int )> dfs;
345+ dfs = [&](int node, int from) {
346+ if (!hasKids (node, from)) {
347+ out << name[node];
348+ return ;
349+ }
350+ if (binaryNewick) {
351+ out << " (" ;
352+ std::vector<int > pos;
353+ for (int i = h_head[node]; i != -1 ; i = h_nxt[i]) {
354+ if (h_e[i] != from) {
355+ pos.push_back (i);
356+ }
357+ }
358+ for (size_t i = 0 ; i < pos.size (); ++i) {
359+ dfs (h_e[pos[i]], node);
360+ out << " :" << h_len[pos[i]] << (i + 1 == pos.size () ? " )" : " ," );
361+ }
362+ return ;
363+ }
364+ std::vector<std::pair<int , double >> kids;
365+ std::function<void (int , int )> addCollapsed;
366+ addCollapsed = [&](int n, int fr) {
367+ for (int i = h_head[n]; i != -1 ; i = h_nxt[i]) {
368+ int ch = h_e[i];
369+ if (ch == fr) {
370+ continue ;
371+ }
372+ double L = h_len[i];
373+ if (std::fabs (L) <= kLenEps && hasKids (ch, n)) {
374+ addCollapsed (ch, n);
375+ } else {
376+ kids.push_back ({ch, L});
377+ }
378+ }
379+ };
380+ addCollapsed (node, from);
381+ out << " (" ;
382+ for (size_t i = 0 ; i < kids.size (); ++i) {
383+ dfs (kids[i].first , node);
384+ out << " :" << kids[i].second << (i + 1 == kids.size () ? " )" : " ," );
385+ }
386+ };
387+ dfs (rootNode, -1 );
388+ }
389+
330390};
331391
332392#endif
0 commit comments