-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpath.c
More file actions
4239 lines (3812 loc) · 138 KB
/
Copy pathpath.c
File metadata and controls
4239 lines (3812 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************************
* MIT License *
* *
* Copyright (c) 2023 Chenxi Zhou <chnx.zhou@gmail.com> *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *
* SOFTWARE. *
*********************************************************************************/
/********************************** Revision History *****************************
* *
* 03/02/23 - Chenxi Zhou: Created *
* *
*********************************************************************************/
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <zlib.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#include "khashl.h"
#include "kstring.h"
#include "kseq.h"
#include "kvec.h"
#include "kdq.h"
#include "path.h"
#include "graph.h"
#include "hmmannot.h"
#include "misc.h"
#undef DEBUG_SRCC
#undef DEBUG_SEG_COV_EST
#undef DEBUG_SEG_COPY
#undef DEBUG_SEG_COPY_EST
#undef DEBUG_SEG_COV_BOUND
#undef DEBUG_SEG_COV_ADJUST
#undef DEBUG_BRUTE_FORCE_OPTIM
#undef DEBUG_SIM_ANNEAL_OPTIM
#undef DEBUG_PATH_FINDER
typedef struct list_node {
uint32_t v; // sid << 31 | oriv
struct list_node *prev;
size_t n_m, n_n;
struct list_node **next;
} llnode;
typedef llnode* llnodep;
static llnode *new_node(int v) {
llnode *node;
MYMALLOC(node, 1);
node->v = v;
node->n_m = 4;
node->n_n = 0;
node->prev = NULL;
MYMALLOC(node->next, node->n_m);
return node;
}
static void add_next(llnode *node, struct list_node *next)
{
if (node->n_m == node->n_n)
MYEXPAND(node->next, node->n_m);
node->next[node->n_n] = next;
node->n_n++;
}
static void llnode_destroy(llnode *node)
{
size_t i;
for (i = 0; i < node->n_n; ++i)
llnode_destroy(node->next[i]);
free(node->next);
free(node);
}
void path_destroy(path_t *path)
{
if (path->sid)
free(path->sid);
if (path->v)
free(path->v);
}
void path_v_destroy(path_v *path)
{
size_t i;
for (i = 0; i < path->n; ++i)
path_destroy(&path->a[i]);
free(path->a);
}
static int u64_cmpfunc(const void *a, const void *b)
{
return (*(uint64_t *) a > *(uint64_t *) b) - (*(uint64_t *) a < *(uint64_t *) b);
}
uint64_t asg_seg_len(asg_t *asg)
{
asmg_t *g = asg->asmg;
uint64_t i, seg_len = 0;
for (i = 0; i < g->n_vtx; ++i) {
if (g->vtx[i].del) continue;
seg_len += g->vtx[i].len;
}
return seg_len;
}
static double graph_sequence_coverage_lower_bound(asg_t *asg, double cov_nq)
{
uint32_t i, n_seg, len, cov;
uint64_t *seqcovs, tot_seg_len, tot_cov, len_thresh;
double cov_bound;
asmg_t *g;
g = asg->asmg;
n_seg = 0;
tot_seg_len = 0;
MYMALLOC(seqcovs, g->n_vtx);
MYBONE(seqcovs, g->n_vtx);
for (i = 0; i < g->n_vtx; ++i) {
if (g->vtx[i].del) continue;
len = g->vtx[i].len;
cov = g->vtx[i].cov;
++n_seg;
tot_seg_len += len;
seqcovs[i] = (uint64_t) cov << 32 | len;
}
qsort(seqcovs, g->n_vtx, sizeof(uint64_t), u64_cmpfunc);
len_thresh = tot_seg_len * cov_nq;
i = 0;
len = (uint32_t) seqcovs[i];
tot_seg_len = tot_cov = 0;
while (tot_seg_len + len <= len_thresh) {
tot_cov += (seqcovs[i] >> 32) * len;
tot_seg_len += len;
len = (uint32_t) seqcovs[++i];
}
if (tot_seg_len < len_thresh)
tot_cov += (seqcovs[i] >> 32) * (len_thresh - tot_seg_len);
cov_bound = (double) tot_cov / len_thresh;
free(seqcovs);
cov_bound *= 1 - cov_nq;
#ifdef DEBUG_SEG_COV_BOUND
fprintf(stderr, "[DEBUG_SEG_COV_BOUND::%s] estimated sequence coverage lower boundary: %.3f\n", __func__, cov_bound);
#endif
return cov_bound;
}
/*** old implementation
*
static double graph_sequence_coverage_rough(asg_t *asg)
{
uint32_t i, len, cov, deg_in, deg_out;
double tot_seg_len, tot_cov, avg_cov;
asmg_t *g;
g = asg->asmg;
tot_seg_len = tot_cov = 0;
for (i = 0; i < g->n_vtx; ++i) {
if (g->vtx[i].del) continue;
len = g->vtx[i].len;
cov = g->vtx[i].cov;
avg_cov = cov;
deg_out = MAX(1, asmg_arc_n1(g, i<<1));
deg_in = MAX(1, asmg_arc_n1(g, i<<1|1));
avg_cov = avg_cov * 2 / (deg_out + deg_in);
#ifdef DEBUG_SEG_COV_EST
// seg and vtx indices are always interchangeable as we never do graph clean
fprintf(stderr, "[DEBUG_SEG_COV_EST::%s] %s %u %u [adj out deg: %u] [adj in deg: %u] [normalized: %.3f]\n",
__func__, asg->seg[i].name, len, cov, deg_out, deg_in, avg_cov);
#endif
tot_seg_len += len;
tot_cov += avg_cov * len;
}
if (tot_seg_len == 0) return 0;
avg_cov = tot_cov / tot_seg_len;
#ifdef DEBUG_SEG_COV_EST
fprintf(stderr, "[DEBUG_SEG_COV_EST::%s] estimated sequence coverage: %.3f\n", __func__, avg_cov);
#endif
return avg_cov;
}
**/
static double graph_sequence_coverage_rough(asg_t *asg, double min_cf)
{
uint32_t i, j, len, cov, best1;
double tot_len, tot_len_c, tot_rm, avg_cov, near1, diff1;
asmg_t *g;
kvec_t(uint64_t) lc_p;
g = asg->asmg;
kv_init(lc_p);
for (i = 0; i < g->n_vtx; ++i) {
if (g->vtx[i].del) continue;
kv_push(uint64_t, lc_p, (uint64_t) (g->vtx[i].cov) << 32 | (g->vtx[i].len));
}
if (lc_p.n == 0) return .0;
qsort(lc_p.a, lc_p.n, sizeof(uint64_t), u64_cmpfunc);
best1 = 0;
near1 = DBL_MAX;
for (i = 0; i < lc_p.n; ++i) {
avg_cov = (double) (lc_p.a[i] >> 32);
if (avg_cov == 0)
continue;
tot_len = tot_len_c = tot_rm = 0;
for (j = 0; j < lc_p.n; ++j) {
len = (uint32_t) lc_p.a[j];
cov = lc_p.a[j] >> 32;
if (cov / avg_cov >= min_cf) {
tot_len += len;
tot_len_c += (double) len * cov / avg_cov;
} else {
tot_rm += len;
}
}
// TODO is this good?
if (tot_rm / (tot_rm + tot_len) > 0.7) break;
if (tot_len > 0) {
diff1 = fabs(tot_len_c / tot_len - 1.0);
if (diff1 < near1) {
near1 = diff1;
best1 = i;
}
#ifdef DEBUG_SEG_COV_EST
fprintf(stderr, "[DEBUG_SEG_COV_EST::%s] seg %u [%u %lu] - len: %.0f; len_rm: %.0f; len_c: %.3f; diff1: %.3f; best: [%u %.3f]\n",
__func__, i, (uint32_t) lc_p.a[i], lc_p.a[i]>>32, tot_len, tot_rm, tot_len_c, diff1, best1, near1);
#endif
}
}
if (near1 == DBL_MAX) {
kv_destroy(lc_p);
return .0;
}
avg_cov = (double) (lc_p.a[best1] >> 32);
#ifdef DEBUG_SEG_COV_EST
fprintf(stderr, "[DEBUG_SEG_COV_EST::%s] estimated sequence coverage: %.3f\n", __func__, avg_cov);
#endif
kv_destroy(lc_p);
return avg_cov;
}
static void make_seg_dups(asg_t *asg, kh_u32_t *seg_dups, uint32_t s, uint32_t copy)
{
// copy number include sequence itself
// i.e., make 'copy' copies and remove the original
// FIXME arcs involving self cycles are not copied since it will potentially cause problems
// for example
// in a graph containing path (X+)<->(a+,b+,b+,c+)<->(Y+)
// the self cycle b+,b+ will increase the ambiguities of the path selection
// valid path including
// (X+)->(a+,b+,b+,c+)->(Y+)->(a-,b-,b-,c-)
// (X+)->(a+,b+,b+,b+,c+)->(Y+)->(a-,b-,c-)
// TODO solve the copy number of self cycles in postprocessing
// now the self arcs is processed in this way
// (X+)->(a+)[4]->(Y+) => (X+)->(a0+) ->(a1+) ->(a2+) ->(a3+) ->(Y+)
// ->(a1+) ->(a2+) ->(a0+) ->(a1+) ->(a0+)
// ->(a2+) ->(a3+) ->(a3+) ->(a2+) ->(a1+)
// ->(a3+) ->(Y+) ->(Y+) ->(Y+) ->(a2+)
// (a+)->(a-) arcs are not copied
uint32_t sid;
uint64_t i, j, v, nv, pv, self_arc;
kvec_t(uint64_t) arcs_diff;
asmg_t *g;
asmg_arc_t *av;
asmg_vtx_t *vt;
char *name;
asg_seg_t *seg, *seg_c;
khint32_t k;
int absent;
g = asg->asmg;
// mark arcs from vtx
kv_init(arcs_diff);
self_arc = UINT64_MAX;
for (i = 0; i < 2; ++i) {
v = s<<1 | i;
pv = g->idx_p[v];
nv = asmg_arc_n(g, v);
av = asmg_arc_a(g, v);
for (j = 0; j < nv; ++j) {
if (av[j].del) continue;
if ((av[j].v >> 1) != (av[j].w >> 1))
kv_push(uint64_t, arcs_diff, pv+j);
else if (av[j].v == av[j].w && i == 0)
// (a+)->(a+)
// avoid adding v+->v+ and v-->v- twice
self_arc = pv + j;
}
}
for (i = 0; i < copy; ++i) {
// make a copy of the segment
seg = &asg->seg[s];
MYMALLOC(name, strlen(seg->name) + floor(log10(abs(i + 1))) + 7);
sprintf(name, "%s_copy%lu", seg->name, i);
sid = asg_add_seg(asg, name, 0);
free(name);
// add to seg dups map
k = kh_u32_put(seg_dups, sid, &absent);
kh_val(seg_dups, k) = s;
// only copy essential fields
seg = &asg->seg[s]; // need to redo this as the seg might be reallocated
seg_c = &asg->seg[sid];
seg_c->len = seg->len;
seg_c->cov = seg->cov;
// add vtx
asmg_vtx_addp(g, &vt);
MYBZERO(vt, 1);
vt->len = seg->len;
// using vtx coverage instead of seg coverage
//vt->cov = seg->cov / copy;
vt->cov = g->vtx[s].cov / copy;
// make copies of links
// arc cov already changed
for (j = 0; j < arcs_diff.n; ++j) {
av = &g->arc[arcs_diff.a[j]];
asmg_arc_add2(g, sid << 1 | (av->v&1), av->w, av->ln, av->ls, UINT64_MAX, av->cov / copy, av->comp);
}
if (self_arc != UINT64_MAX) {
// tandem repeat
// self arcs are added between copies
av = &g->arc[self_arc];
for (j = 0; j < i; ++j) {
asmg_arc_add2(g, (sid - i + j) << 1, sid << 1, av->ln, av->ls, UINT64_MAX, av->cov / copy, 0);
asmg_arc_add2(g, sid << 1, (sid - i + j) << 1, av->ln, av->ls, UINT64_MAX, av->cov / copy, 0);
}
}
}
kv_destroy(arcs_diff);
// need to redo sort and index but not graph clean
asmg_finalize(g, 0);
// delete the original vtx
asmg_vtx_del(g, s, 1);
return;
}
#define EM_MAX_ITER 1000
double graph_sequence_coverage_precise(asg_t *asg, double min_cf, int min_copy, int max_copy, int **_copy_number)
{
uint32_t i, n_seg, iter;
int *copy_number;
double total_covs, total_lens, avg_cov, new_avg_cov, min_avg_cov;
asmg_t *g;
n_seg = asg->n_seg;
g = asg->asmg;
min_avg_cov = graph_sequence_coverage_lower_bound(asg, 0.3);
avg_cov = graph_sequence_coverage_rough(asg, min_cf);
#ifdef DEBUG_SEG_COPY_EST
fprintf(stderr, "[DEBUG_SEG_COPY_EST::%s] min coverage: %.3f; rough avg coverage: %.3f\n",
__func__, min_avg_cov, avg_cov);
#endif
avg_cov = MAX(avg_cov, min_avg_cov);
MYCALLOC(copy_number, n_seg);
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
copy_number[i] = MIN(MAX(min_copy, lround((double) g->vtx[i].cov / avg_cov)), max_copy);
}
iter = 0;
while (iter++ < EM_MAX_ITER) {
#ifdef DEBUG_SEG_COPY_EST
fprintf(stderr, "[DEBUG_SEG_COPY_EST::%s] iteration %u avg coverage: %.3f\n", __func__, iter, avg_cov);
#endif
total_covs = total_lens = 0;
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
total_lens += (double) g->vtx[i].len * copy_number[i];
total_covs += (double) g->vtx[i].len * g->vtx[i].cov;
}
// FIXME total_lens could be zero
new_avg_cov = total_lens < FLT_EPSILON? DBL_MAX : (total_covs / total_lens);
new_avg_cov = MAX(new_avg_cov, min_avg_cov);
if (fabs(new_avg_cov - avg_cov) < FLT_EPSILON)
break; // converged
avg_cov = new_avg_cov;
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
copy_number[i] = MIN(MAX(min_copy, lround((double) g->vtx[i].cov / avg_cov)), max_copy);
}
}
#ifdef DEBUG_SEG_COPY_EST
fprintf(stderr, "[DEBUG_SEG_COPY_EST::%s] sequence copy number estimation finished in %u iterations with an average sequence coverage %.3f\n",
__func__, iter, avg_cov);
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
fprintf(stderr, "[DEBUG_SEG_COPY_EST::%s] %s %u %d\n", __func__, asg->seg[i].name, g->vtx[i].cov, copy_number[i]);
}
#endif
if (_copy_number)
*_copy_number = copy_number;
else
free(copy_number);
return avg_cov;
}
#define DVAL(var) ((var)->D)
// with BALANCE_IN_OUT defined
// the objective function considers balanced indegree and outdegree
#define BALANCE_IN_OUT
#ifdef BALANCE_IN_OUT
#define FVAL(fun) do { \
int __i, __n = (fun)->N; \
double __val[2] = {.0, .0}; \
for (__i = 0; __i < __n; ++__i) \
__val[(fun)->V[__i]&1] += DVAL((fun)->VAR[(fun)->V[__i]>>1]); \
(fun)->VAL = (fun)->weight * (fabs((fun)->v_exp - __val[0]) / 2 + \
fabs((fun)->v_exp - __val[1]) / 2 + \
fabs(__val[0] - __val[1])); \
} while (0)
#else
#define FVAL(fun) do { \
int __i, __n = (fun)->N; \
double __val = (fun)->v_exp; \
for (__i = 0; __i < __n; ++__i) \
__val -= DVAL((fun)->VAR[(fun)->V[__i]]); \
(fun)->VAL = (fun)->weight * __val * __val; \
} while (0)
#endif
typedef struct var {
int B, D;
struct var *prev, *next;
} var_t;
typedef struct {
double weight; // weight
double v_exp; // expected value
var_t **VAR;
int N, *V;
double VAL;
} func_t;
#define BRUTE_FORCE_N_LIM 100000000
static inline double fvals(func_t *funcs, int n_func)
{
int i;
double fval = 0.;
for (i = 0; i < n_func; ++i) {
FVAL(&funcs[i]);
fval += funcs[i].VAL;
}
return fval;
}
static inline void copy_results(var_t **vars, int n_var, int *res)
{
int i;
for (i = 0; i < n_var; ++i)
res[i] = vars[i]->D;
}
// brute force optimization
static void estimate_arc_copy_number_brute_force_impl(func_t *funcs, int n_func, var_t **vars, int n_var, int *res, int64_t sol_space_size)
{
double fval, m_fval;
int64_t sol;
int a, v;
fval = fvals(funcs, n_func);
m_fval = fval;
copy_results(vars, n_var, res);
sol = 0;
while (++sol < sol_space_size) {
a = 1, v = 0;
while (a) {
vars[v] = vars[v]->next;
a = !vars[v]->B;
++v;
}
fval = fvals(funcs, n_func);
if (fval < m_fval) {
m_fval = fval;
copy_results(vars, n_var, res);
}
if (fabs(m_fval) < FLT_EPSILON)
break;
}
#ifdef DEBUG_BRUTE_FORCE_OPTIM
fprintf(stderr, "[DEBUG_BRUTE_FORCE_OPTIM::%s] brute force search finished after %ld/%ld attempts with a minimum fval: %.6f\n",
__func__, sol, sol_space_size, m_fval);
#endif
}
#define SA_TEMPERATURE 1000
#define SA_COOLING_RATE .999
#define SA_MAX_ATTEMPTS 100
#define SA_RESTART_TEMP .99
static inline void random_walk_to_neighbour(var_t **var)
{
if (rand() < RAND_MAX>>1) {
// move to prev
*var = (*var)->B == 0? (*var)->next : (*var)->prev;
} else {
// move to next
*var = (*var)->next->B == 0? (*var)->prev : (*var)->next;
}
}
static void set_vars(var_t **vars, int n_var, int *res)
{
int i;
for (i = 0; i < n_var; ++i) {
while (vars[i]->D != res[i])
vars[i] = vars[i]->next;
}
}
// simulated annealing optimization
static void estimate_arc_copy_number_siman_impl(func_t *funcs, int n_func, var_t **vars, int n_var, int *res)
{
int i, iter, n_iter;
double optim_cost, current_cost, new_cost, temp0, temp, p;
var_t *var;
current_cost = fvals(funcs, n_func);
optim_cost = current_cost;
copy_results(vars, n_var, res);
srand(1234);
temp0 = SA_TEMPERATURE;
n_iter = 0;
for (iter = 0; iter < SA_MAX_ATTEMPTS; ++iter) {
temp = temp0;
while (temp > 1e-6) {
// random select a var to update
i = rand() % n_var;
// record the old var
var = vars[i];
// take a random walk to either prev or next
random_walk_to_neighbour(&vars[i]);
// calculate new cost
new_cost = fvals(funcs, n_func);
// record optim solution
if (new_cost < optim_cost) {
optim_cost = new_cost;
copy_results(vars, n_var, res);
}
// acceptance probability
p = exp(-(new_cost - current_cost) / temp);
if (new_cost < current_cost || (double) rand() / RAND_MAX < p) {
// accept update and update cost
current_cost = new_cost;
} else {
// rollback to reject the update
vars[i] = var;
}
// cooling down
temp *= SA_COOLING_RATE;
++n_iter;
}
if (optim_cost == 0) break;
// continue searching from the best solution so far
temp0 *= SA_RESTART_TEMP;
set_vars(vars, n_var, res);
#ifdef DEBUG_SIM_ANNEAL_OPTIM
fprintf(stderr, "[DEBUG_SIM_ANNEAL_OPTIM::%s] optimization after %d iteration [%d attempts] with a minimum fval: %.6f\n",
__func__, iter, n_iter, optim_cost);
#endif
}
#ifdef DEBUG_SIM_ANNEAL_OPTIM
fprintf(stderr, "[DEBUG_SIM_ANNEAL_OPTIM::%s] simulated annealing search finished after %d attempts with a minimum fval: %.6f\n",
__func__, n_iter, optim_cost);
#endif
}
int adjust_sequence_copy_number_by_graph_layout(asg_t *asg, double seq_coverage, double *_adjusted_cov, int *copy_number, int max_copy, int max_round)
{
uint32_t i, j, n_seg, n_group, a_g, *arc_group;
uint64_t link_id;
int updated, round;
asmg_t *g;
asmg_arc_t *a;
if (_adjusted_cov)
*_adjusted_cov = seq_coverage;
if (max_round == 0)
max_round = 1;
updated = 0;
g = asg->asmg;
n_seg = asg->n_seg;
arc_group = asmg_uext_arc_group(g, &n_group);
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] identified %u arc groups\n", __func__, n_group);
for (i = 0; i < g->n_arc; ++i) {
a = &g->arc[i];
if (a->del) continue;
link_id = a->link_id;
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] %s%c -> %s%c arc group %u\n", __func__,
asg->seg[a->v>>1].name, "+-"[a->v&1],
asg->seg[a->w>>1].name, "+-"[a->w&1],
arc_group[link_id]);
}
#endif
if (n_group == 0) {
free(arc_group);
return 0;
}
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] sequence copy number BEFORE adjusted by graph layout\n", __func__);
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] %s %lu %u %d\n", __func__,
asg->seg[i].name, g->vtx[i].len, g->vtx[i].cov, copy_number[i]);
}
#endif
uint32_t *arc_copy_lb, *arc_copy_ub, vlb, wlb, lb, ub;
MYCALLOC(arc_copy_lb, n_group); // arc copy number lower bound
MYCALLOC(arc_copy_ub, n_group); // arc copy number upper bound
// calculate lower and upper boundary of arc copy number for each arc group
for (i = 0; i < g->n_arc; ++i) {
a = &g->arc[i];
if (a->del) continue;
link_id = a->link_id;
a_g = arc_group[link_id];
// if a is the only outgoing/incoming edge from/to v/w
// then lower bound is the v/w copy number
// otherwise 0
// upper bound is always the v/w copy number
vlb = asmg_arc_n1(g, a->v) == 1? copy_number[a->v>>1] : 0;
wlb = asmg_arc_n1(g, a->w^1) == 1? copy_number[a->w>>1] : 0;
lb = MIN(vlb, wlb);
ub = MAX(copy_number[a->v>>1], copy_number[a->w>>1]);
// relax boundary by a factor of 1/3 - at least one copy
lb = (uint32_t) ((double) lb * 2 / 3);
ub = (uint32_t) ((double) ub * 4 / 3) + 1;
ub = MIN(ub, (uint32_t) max_copy);
arc_copy_lb[a_g] = MIN(lb, arc_copy_lb[a_g]);
arc_copy_ub[a_g] = MAX(ub, arc_copy_ub[a_g]);
}
// make variable list
var_t **VAR;
MYCALLOC(VAR, n_group);
for (i = 0; i < n_group; ++i) {
var_t *var0;
MYCALLOC(var0, 1);
lb = arc_copy_lb[i];
ub = arc_copy_ub[i];
var0->B = 0;
var0->D = lb;
VAR[i] = var0;
for (j = 1; j <= ub - lb; ++j) {
var_t *var1;
MYCALLOC(var1, 1);
var1->B = j;
var1->D = lb + j;
var0->next = var1;
var1->prev = var0;
var0 = var1;
}
var0->next = VAR[i];
VAR[i]->prev = var0;
}
// make objective function list
kvec_t(func_t) funcs;
kv_init(funcs);
func_t *FUN;
uint32_t k, v, na;
int *funcmap; // the objective function index for each seg
asmg_arc_t *av;
MYMALLOC(funcmap, n_seg);
for (i = 0; i < n_seg; ++i) {
funcmap[i] = -1;
if (g->vtx[i].del)
continue;
#ifdef BALANCE_IN_OUT
// with BALNCE_IN_OUT defined
// the incoming and outgoing arcs of a vertex
// are put in the same objective function unit
// and marked by the last bit of V
kvec_t(int) V = {0, 0 ,0};
for (k = 0; k < 2; ++k) {
v = i << 1 | k;
na = asmg_arc_n(g, v);
av = asmg_arc_a(g, v);
for (j = 0; j < na; ++j) {
if (av[j].del)
continue;
link_id = av[j].link_id;
a_g = arc_group[link_id];
assert(a_g != (uint32_t) -1);
kv_push(int, V, (int) (a_g << 1 | k));
}
}
if (V.n) {
MYREALLOC(V.a, V.n);
funcmap[i] = funcs.n;
kv_pushp(func_t, funcs, &FUN);
FUN->weight = log10(g->vtx[i].len);
FUN->v_exp = g->vtx[i].cov / seq_coverage; // copy_number[i];
FUN->VAR = VAR;
FUN->N = V.n;
FUN->V = V.a;
FUN->VAL = 0.;
}
#else
for (k = 0; k < 2; ++k) {
v = i << 1 | k;
na = asmg_arc_n(g, v);
av = asmg_arc_a(g, v);
kvec_t(int) V = {0, 0 ,0};
for (j = 0; j < na; ++j) {
if (av[j].del)
continue;
link_id = av[j].link_id;
a_g = arc_group[link_id];
assert(a_g != (uint32_t) -1);
kv_push(int, V, (int) a_g);
}
if (V.n) {
MYREALLOC(V.a, V.n);
funcmap[i] = funcs.n;
kv_pushp(func_t, funcs, &FUN);
FUN->weight = log10(g->vtx[i].len);
FUN->v_exp = g->vtx[i].cov / seq_coverage; // copy_number[i];
FUN->VAR = VAR;
FUN->N = V.n;
FUN->V = V.a;
FUN->VAL = 0.;
}
}
#endif
}
// do optimization
int *arc_copy;
double adjusted_cov, min_avg_cov;
int64_t sol_space_size;
min_avg_cov = graph_sequence_coverage_lower_bound(asg, 0.3);
adjusted_cov = seq_coverage;
MYCALLOC(arc_copy, n_group);
sol_space_size = 1;
for (i = 0; i < n_group && sol_space_size <= BRUTE_FORCE_N_LIM; ++i)
sol_space_size *= (arc_copy_ub[i] - arc_copy_lb[i] + 1);
round = 0;
while (round++ < max_round) {
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] adjusting copy number round %d of %d\n", __func__, round, max_round);
#endif
if (sol_space_size <= BRUTE_FORCE_N_LIM) {
// do brute force optimization
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] run brute force searching: %ld\n",
__func__, sol_space_size);
#endif
estimate_arc_copy_number_brute_force_impl(funcs.a, funcs.n, VAR, n_group, arc_copy, sol_space_size);
} else {
// do simulated annealing optimization
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] run simulated annealing optimization: %ld\n",
__func__, sol_space_size);
#endif
estimate_arc_copy_number_siman_impl(funcs.a, funcs.n, VAR, n_group, arc_copy);
}
#ifdef DEBUG_SEG_COV_ADJUST
for (i = 0; i < n_group; ++i)
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] arc group %u optimum copy number %d [%u %u]\n",
__func__, i, arc_copy[i], arc_copy_lb[i], arc_copy_ub[i]);
#endif
// update average sequence coverage
double total_covs, total_lens, new_adjusted_cov, copies;
total_covs = total_lens = 0;
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del)
continue;
copies = 0;
for (k = 0; k < 2; ++k) {
v = i << 1 | k;
na = asmg_arc_n(g, v);
av = asmg_arc_a(g, v);
for (j = 0; j < na; ++j) {
if (av[j].del)
continue;
link_id = av[j].link_id;
a_g = arc_group[link_id];
assert(a_g != (uint32_t) -1);
copies += arc_copy[a_g];
}
}
total_lens += (double) g->vtx[i].len * copies / 2;
total_covs += (double) g->vtx[i].len * g->vtx[i].cov;
}
if (total_lens < FLT_EPSILON) {
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] zero copies for all sequences\n", __func__);
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] adjusting copy number terminated in round %d of %d\n",
__func__, round, max_round);
#endif
goto do_clean;
}
new_adjusted_cov = total_covs / total_lens;
new_adjusted_cov = MAX(new_adjusted_cov, min_avg_cov);
if (fabs(new_adjusted_cov - adjusted_cov) < FLT_EPSILON) {
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] adjusting copy number converaged in round %d of %d\n",
__func__, round, max_round);
#endif
break; // converaged
}
// update adjusted sequence coverage
adjusted_cov = new_adjusted_cov;
// update objective functions
// more precisely the expected copy number
for (i = 0; i < n_seg; ++i) {
if (funcmap[i] == -1)
continue;
funcs.a[funcmap[i]].v_exp = g->vtx[i].cov / adjusted_cov;
funcs.a[funcmap[i]].VAL = 0.;
}
// reset VARs
for (i = 0; i < n_group; ++i) {
var_t *var = VAR[i];
while (var->B) var = var->next;
VAR[i] = var;
}
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] adjusting copy number round %d of %d DONE with adjusted coverage: %.3f\n",
__func__, round, max_round, adjusted_cov);
#endif
}
// update sequence copy number using the arc copy number information
int new_copy[2];
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del)
continue;
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] #### sequence %s ####\n", __func__, asg->seg[i].name);
#endif
for (k = 0; k < 2; ++k) {
v = i << 1 | k;
na = asmg_arc_n(g, v);
av = asmg_arc_a(g, v);
new_copy[k] = 0;
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] #### %sing arcs\n", __func__, k? "incom" : "outgo");
#endif
for (j = 0; j < na; ++j) {
if (av[j].del)
continue;
link_id = av[j].link_id;
a_g = arc_group[link_id];
assert(a_g != (uint32_t) -1);
new_copy[k] += arc_copy[a_g];
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] %s%c -> %s%c: %d\n", __func__,
asg->seg[av[j].v>>1].name, "+-"[av[j].v&1],
asg->seg[av[j].w>>1].name, "+-"[av[j].w&1],
arc_copy[a_g]);
#endif
}
}
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] indegree: %d; outdegree: %d; diff: %d\n", __func__,
new_copy[1], new_copy[0], abs(new_copy[1] - new_copy[0]));
#endif
// only update copy number if indegree matches outdegree
// TODO better strategy to update sequence copy number
if (new_copy[0] == new_copy[1] && copy_number[i] != new_copy[0]) {
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] sequence %s copy number updated %d -> %d\n",
__func__, asg->seg[i].name, copy_number[i], new_copy[0]);
#endif
copy_number[i] = new_copy[0];
updated = 1;
}
}
#ifdef DEBUG_SEG_COV_ADJUST
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] sequence copy number AFTER adjusted by graph layout\n", __func__);
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
fprintf(stderr, "[DEBUG_SEG_COV_ADJUST::%s] %s %lu %u %d\n", __func__,
asg->seg[i].name, g->vtx[i].len, g->vtx[i].cov, copy_number[i]);
}
#endif
if (_adjusted_cov)
*_adjusted_cov = adjusted_cov;
do_clean:
for (i = 0; i < n_group; ++i) {
var_t *var0, *var1;
var0 = VAR[i];
while (var0->B != 0)
var0 = var0->next;
var0 = var0->next;
v = 0;
while (!v) {
var1 = var0->next;
v = var0->B == 0;
free(var0);
var0 = var1;
}
}
free(VAR);
for (i = 0; i < funcs.n; ++i)
free(funcs.a[i].V);
free(funcs.a);
free(funcmap);
free(arc_group);
free(arc_copy_lb);
free(arc_copy_ub);
free(arc_copy);
return updated;
}
kh_u32_t *sequence_duplication_by_copy_number(asg_t *asg, int *copy_number, int allow_del)
{
uint32_t i, n_seg;
int copy;
kh_u32_t *seg_dups;
asmg_t *g;
n_seg = asg->n_seg;
g = asg->asmg;
seg_dups = kh_u32_init();
for (i = 0; i < n_seg; ++i) {
if (g->vtx[i].del) continue;
copy = copy_number[i];
if (copy > 1) {
// do copy
make_seg_dups(asg, seg_dups, i, copy);
#ifdef DEBUG_SEG_COPY
fprintf(stderr, "[DEBUG_SEG_COPY::%s] make %d extra cop%s of %s [%lu %u]\n", __func__,
copy, copy > 1? "ies" : "y", asg->seg[i].name, g->vtx[i].len, g->vtx[i].cov);
#endif
} else if (copy == 0 && allow_del) {
/*** TODO is this safe? **/
asmg_vtx_del(g, i, 1);
#ifdef DEBUG_SEG_COPY
fprintf(stderr, "[DEBUG_SEG_COPY::%s] delete seg %s [%lu %u]\n", __func__,