-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoButton.cpp
More file actions
6984 lines (5657 loc) · 318 KB
/
GoButton.cpp
File metadata and controls
6984 lines (5657 loc) · 318 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
#include <iostream>
#include <utility>
#include <sstream>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <openssl/md5.h>
#include <stdint.h>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h" // for stringify JSON
#include <curl/curl.h>
#include <string>
#include <EXTERN.h>
#include <perl.h>
#include <my_global.h>
#include <mysql.h>
#include <tinyxml2.h>
#include <myhtml/tree.h>
#include <signal.h>
#include <execinfo.h>
// #ifdef _OPENMP // when was this used?
#include <omp.h>
// #endif
#undef min
#undef max
#include "interop/model/metric_base/metric_set.h"
#include "interop/model/metrics/corrected_intensity_metric.h"
#include "interop/io/metric_file_stream.h"
#include "interop/util/statistics.h"
#include "interop/logic/summary/run_summary.h"
#include "interop/model/metric_base/metric_set.h"
#include "interop/model/metrics/tile_metric.h"
#include "interop/model/run_metrics.h"
// #ifndef RELEASE_H
// #define RELEASE_H
// use vector of pairs of macro set funcname/func-pointer and shuffle
// put in those absurdly hacking merge recover things?!?
// just add ethnicity here!
// add merge rescue object too?!?
// add reset to bcl BUT with lock issue telling them to run it ONLY if they're sure!?!? : update Flowcell set fc_status = 'registered' where FCillumID = 'HMJCJDSXX' and fc_status = 'sequenced' and fail = 0 ; select row_count() locked
#define BASE_DIR "/nfs/seqscratch_ssd/informatics/"
#define SCRIPT_DIR BASE_DIR "logs/merge/"
#define LOG_DIR "/nfs/central/home/dh2880/.logs/"
#define ALIGNSTATS "/nfs/goldstein/software/alignstats/alignstats"
#define POSTMERGE "/nfs/seqscratch_ssd/informatics/logs/postmerge/"
// int merge_and_release(int, char **);
// inline bool isregfile(const char* fn) { struct stat test; if (stat(fn, &test) != 0) { return false; } return S_ISREG(test.st_mode); }
using namespace std;
namespace opts {
float wgs_min = 29.3, // 30.0, /// this is put into capture but whatever?!?
wes_min = 60.0;
bool commit = false, force = false;
char const * serv = "seqprod";
static bool email = true;
float required_space = 4.5;
using std::cout;
using std::cerr;
/// this MUST be removed but need to change users ASAP
class MysqlUser {
public:
char const * user() const { return _user; }
char const * pass() const { return _pass; }
char const * host() const { return _host; }
char const * connstr() const { return _connstr; }
char const * connstr_quick_hack() const { return _connstr_quick_hack; }
MysqlUser() {
char const * tmp = getenv("LIMS_USER");
// char const * tmp = getenv("USER");
if(!tmp) cerr << "Need LIMS_USER env\n",exit(1);
strcpy(_user,tmp);
tmp = getenv("LIMS_PASS");
if(!tmp) cerr << "Need LIMS_PASS env\n",exit(1);
strcpy(_pass,tmp);
tmp = getenv("LIMS_HOST");
if(!tmp) cerr << "Need LIMS_HOST env\n",exit(1);
strcpy(_host,tmp);
sprintf(_connstr,"mysql -u%s -p%s -h%s sequenceDB",_user,_pass,_host);
sprintf(_connstr_quick_hack,"%s -BN -e ",_connstr);
// if(strcmp(_user,"dh2880")==0 || strcmp(_user,"dsth")==0 )
// cout << "we have " << _user << "\n" << /* "we have " << _pass << "\n" << */ "we have " << _host << "\n";
//// should do a test connection here to check it all works??!!?!?
// return a string for value semanatics or just have a data member?!?
//char const * LAZY_CONN_STR_SEQDB = "mysql -udh2880 -p -hseqprod.igm.cumc.columbia.edu sequenceDB",
// whatever, return initialised member?!? clearly, dbname should be treated consistently...
}
private:
char _user[32], _pass[32], _host[32], _connstr[1024], _connstr_quick_hack[1024];
};
static MysqlUser myuser;
char const * usage =
" run This is the main pipeline manager. Run a single instance of this.\n"
" bcl Run BCL conversion of a flowcell.\n"
" pipe Perform a number of auxiliary functions associated with FASTQ and Pipeline integrity. Run several instances of this.\n"
" load_atav Self-explanatory. Only ever run a single instance of this.\n";
}
bool myfunction (float i,float j) { return (i<j); }
void finish_with_error(MYSQL *con) { // http://zetcode.com/db/mysqlc/
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
struct FUNKY { std::string experiment_id, prepid, sample_name, sample_type, capture_kit, priority, is_external, end_point; };
#define FDP_OFFSET 11
// #define FDP_OFFSET 15
char const * Q1 = "select "
"SUM(LNYIELD) l_lane_sum, "
"sum(rg_metrics_capturemean) l_capmean_sum, "
"avg(rg_metrics_contamination) l_contamination_mean, "
"avg(rg_metrics_dups) l_dups_mean, "
"replace(concat('gaf_bin=',e.gafbin,'&irb_protocol__irb_protocol=',e.protocol,'&fund_code__fund_code=',e.fundcode,'&sub_project_name=',e.subproject),' ','+') CORE_QUERY, "
"e.sample_type e_sample_type, "
" e.id e_experiment_id, s.sample_internal_name, e.sample_id, p.sample_type, p.exomekit, "
"w.prep_id w_experiment_id, w.sample_finished w_sample_finished, w.sample_failure w_sample_failure, "
"merge_metrics_capturemean,merge_metrics_capturemedian,merge_metrics_contamination,merge_metrics_dups,eligible_readgroups, "
" pool_count, name pool_name, "
" (select group_concat(concat(step_name,':',pipeline_step_id,':',step_status)) from dragen_pipeline_step dsp join dragen_pipeline_step_desc junk on junk.id=dsp.pipeline_step_id where dsp.pseudo_prepid=e.id) dsp_step_ids, "
" (select count(pipeline_step_id) from dragen_pipeline_step where pseudo_prepid=e.id) dsp_step_id_count, "
" (select count(distinct(pp.prepid)) from prepT pp where pp.experiment_id=e.id) sum_prepids, "
" (select count(distinct(pp.status)) from prepT pp where pp.experiment_id=e.id) sum_statuses_count, "
" (select group_concat(distinct(pp.status)) from prepT pp where pp.experiment_id=e.id) sum_statuses, "
" (select count(distinct(pp.poolid)) from prepT pp where pp.experiment_id=e.id) sum_pools, "
" (select count(distinct(ll.fcid)) from Lane ll where ll.prepid in (select ppp.prepid from prepT ppp where ppp.experiment_id=e.id)) sum_flowcells, "
" (select count(distinct(concat(rg_status,':',rg_metrics_status))) from Lane ll where ll.prepid in (select ppp.prepid from prepT ppp where ppp.experiment_id=e.id)) sum_rg_statuses_count, "
" ( select group_concat(distinct(concat(rg_status,':',rg_metrics_status))) "
" from Lane ll join Flowcell ff on ll.fcid=ff.fcid "
" where ff.fail=0 and ff.complete=1 and ff.pipelinecomplete=1 and ll.failr1 is null and ll.failr2 is null "
" and ll.prepid in (select ppp.prepid from prepT ppp where ppp.experiment_id=e.id) "
" ) sum_rg_statuses, "
"count(l.id) sum_eligible_readgroups, "
"e.is_released e_is_released, "
" group_concat(concat(p.prepid,':',name,':',fcillumid,'.',lanenum),'---') summary, "
" group_concat(rg_status) rg_statuses, "
" group_concat(rg_metrics_status) rg_metrics_statuses, group_concat(l.id order by l.id) NEW_RGS_STAMP, e.rgs CURRENT_RGS_STAMP, "
" dqm.experiment_id dqm_experiment_id, "
" d.experiment_id dsm_experiment_id, d.is_merged d_ism, "
" concat( 'id=', e.subproject_id ) CORE_QUERY_NEW "
" from Lane l "
" join Flowcell f on l.fcid =f.fcid "
" join prepT p on l.prepid =p.prepid "
" join Experiment e on p.experiment_id =e.id"
" join SampleT s on s.sample_id =e.sample_id "
" left join dragen_sample_metadata d on d.pseudo_prepid =p.experiment_id "
" left join dsth.sample w on w.prep_id =p.experiment_id "
" left join dragen_qc_metrics dqm on dqm.pseudo_prepid =p.experiment_id "
" left join pool on p.poolid=pool.id "
// evil
" where (failedprep = 0 or failedprep >= 100) "
// don't care about 'complete' button : " and f.complete = 1 "
" and pipelinecomplete = 1 "
" and failr1 is null and failr2 is null "
" and externaldata is null "
" and e.sample_type in ('Genome', 'Exome') "
" and e.is_released in ('not_released', 'release_rejected') "
// 'could' impose flowcell and pool grouping here?!?
" and pool.is_releasable = 1 "
" group by e.id order by e.sample_type, p.poolid; ";
char const * REPLACE_INTO_DPS =
"replace into dragen_pipeline_step "
"(pseudo_prepid, pipeline_step_id, version, submit_time, finish_time, times_ran, step_status) values "
"(%s, 1, '0.0.1', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP(), 1, '%s');";
inline bool isregfile(const char* fn) { struct stat test; if (stat(fn, &test) != 0) { return false; } return S_ISREG(test.st_mode); }
inline bool isdir(const char* fn) { struct stat test; if (stat(fn, &test) != 0) { return false; } return S_ISDIR(test.st_mode); }
inline void touchfile(const std::string& file) { FILE* fp = fopen(file.data(), "ab+"); fclose(fp); }
namespace rarp {
typedef std::vector<std::string> LIST;
typedef std::map<std::string,std::string> NLIST;
typedef std::vector<NLIST> NLISTS;
typedef std::vector<LIST> LISTS;
}
namespace options { bool debug = false; }
// MUST STOP HAVING DPS/DQM ERRORS IF IT'S IN WALDB ALREADY. WIPE IT ALL AND SEND EMAIL - SHOULD DEPRECATE!?!?!?
enum status {
WGS = -5, INCONSISTENT = -6, MERGE_ERROR = -7, PROB = -8, DQM = -9, JUNK = -10,
// must split COMPONENT_ERROR into COMPONENT_RG_ERROR, COMPONENT_EOF_ERROR...
MISSING_FCINFO = -11, RG_COUNT_ERROR = -12, DSP = -13, COMPONENT_ERROR = -14,
MOVE = -15, NO_DIR = -16, NULL_COMPONENTS = -17,
MERGE_RESCUE = -18, MERGE_RESCUE_ERROR = -19,
SCRIPT_EXISTS = -20, CHECKPOINT_EXISTS = -21, RG_PU_VERSUS_READNAME_ERROR = -22, RG_LIMS_READNAME_MISMATCH_ERROR = -23,
DT_TAGS = -24,
MERGE_METRICS_RESCUE = -28, MERGE_METRICS_RESCUE_ERROR = -29,
COMPONENT_RG_ERROR = -30, COMPONENT_EOF_ERROR = -31, FEW_MT = -32,
GAFE_NO_DATA = -52, GAFE_ALREADY_HAS_DATA = -51,
FINAL_BAM_MISSING = -60, BAM_CHECKING_PROB = -61, BAM_IS_A_MESS = -62, BAM_LIMS_SAMPLE_NAME_MISMATCH = -63,
BAM_COUNT_MISMATCH = -64, NOT_A_BAM = -65, EXTERNAL_STATUS_SCREWED = -66, DB_SCREWED = -67, MERGE_METRICS_ERROR = -70
};
void tokenise(std::vector<std::string>& t, std::string const l, char s) {
// void tokenise(std::vector<std::string>& t, std::string const& l, char s) {
using namespace std;
size_t pos = 0;
size_t lst = 0;
while (pos != std::string::npos) {
pos = l.find(s, pos + 1);
size_t g = lst == 0 ? 0 : 1;
string a = l.substr(lst + g, pos - lst - g);
// cout << a << "\n";
for (unsigned c=0 ;c<a.length(); ++c) {
// cout << "["<<c<<"]" <<a[c] << "\n";
}
t.push_back(a);
lst = pos;
}
}
class Popen {
public:
Popen(char const * cmd, int const z,char const * m) : _m(m), _ml(z), _bf(new char [_ml]) {
if(!(_in = popen(cmd,_m))) std::cout << "problem with command\n", exit(1);
}
Popen();
~Popen() { fflush(_in); pclose(_in); delete [] _bf; }
void write(std::string const & a) {
// void write(char const * a) {
assert(_m[0]=='w');
// bored of warning
// fwrite(a.data(),sizeof(char),a.length(),_in);
assert(fwrite(a.data(),sizeof(char),a.length(),_in));
fflush(_in);
}
char* getline() const {
assert(_m[0]=='r');
char *hmm = _bf; int x = 0;
for( x=0, hmm=_bf; (*hmm=fgetc(_in))!=EOF && *hmm++!='\n'; x++){ assert(x<_ml); }
assert(!(_bf[0]=='\t'&&_bf[1]=='\t'));
_bf[x]='\0';
return _bf;
}
private:
char const *_m;
int const _ml;
char *_bf;
FILE *_in;
};
int filesize(char const * p) {
struct stat a;
stat(p,&a);
return a.st_size;
}
// implicit ctor in string or better yet use operator()?!?
template<typename A> struct Yum { // struct Yum {
Yum(char const * cmd) : output(cmd) {} // Yum(char const * cmd, A a) {
std::string operator()(A a){ // std::string operator()(char const * a){
char tmp[1024]; sprintf(tmp,output.data(),a);
Popen ox(tmp,16*1024,"r");
output=ox.getline();
return output;
}
void operator()(std::vector<std::string> & X,A a){
char tmp[1024]; sprintf(tmp,output.data(),a);
Popen ox(tmp,16*1024,"r");
char * z3;
while( *( z3=ox.getline() ) != '\0') X.push_back(z3);
}
std::string output;
};
inline void Lazy(char const * a, char const * b) {
char tmp[1024]; sprintf(tmp,a,b);
// std::cout << "LAZY : using\n'"<<tmp<<"'\n";
if(system(tmp)) std::cout << "what '" << tmp << "'",exit(1);
}
// https://stackoverflow.com/questions/9317305/sending-an-email-from-a-c-c-program-in-linux
// should just open a socket to local port and send direct...?!?
int sendmail(const char *to, const char *from, const char *subject, const char *message, bool html = false) {
int retval = -1;
FILE *mailpipe = popen("/usr/sbin/sendmail -t", "w");
if (mailpipe != NULL) {
fprintf(mailpipe, "To: %s\n", to);
fprintf(mailpipe, "From: %s\n", from);
time_t t = time(0);
struct tm * tm_s = localtime(&t);
char bits[1024], n[256], blah[1024];
strftime(blah,1024,"%c",tm_s);
if(html) fprintf(mailpipe, "Content-Type: text/html\n");
fprintf(mailpipe, "Subject: %s (%s)\n\n",subject,blah); // sick of merging subjects...?!?
gethostname(n,256);
sprintf(bits,"%s:%d : %s",n,getpid(),subject);
// bored of warning
// fwrite(message, 1, strlen(message), mailpipe);
// fwrite(".\n", 1, 2, mailpipe);
assert(fwrite(message, 1, strlen(message), mailpipe));
assert(fwrite(".\n", 1, 2, mailpipe));
pclose(mailpipe);
retval = 0;
}else{
perror("Failed to invoke sendmail");
}
return retval;
}
namespace lazy {
using namespace std;
inline std::string GetFirstLinePopen(char const * const a) {
Popen ns1(a,16*1024,"r");
// cout << "GetFirstLinePopen=\""<<a<<"\"\n\n";
// this was an error - duh! returning address
// return ns1.getline();
return std::string(ns1.getline());
}
template<typename T1> inline std::string GetFirstLinePopen(char const * const a, T1 t1) {
char tmp[1024]; sprintf(tmp,a,t1); return GetFirstLinePopen(tmp);
}
// this 'could' use next one down - i.e. just recurse instead of collapsing
template<typename T1, typename T2> inline std::string GetFirstLinePopen(char const * const a, T1 t1, T2 t2) {
char tmp[1024]; sprintf(tmp,a,t1,t2); return GetFirstLinePopen(tmp);
}
template<typename T1, typename T2, typename T3> inline std::string GetFirstLinePopen(char const * const a, T1 t1, T2 t2, T3 t3) {
char tmp[1024]; sprintf(tmp,a,t1,t2,t3); return GetFirstLinePopen(tmp);
}
template<typename T1, typename T2, typename T3, typename T4> inline std::string GetFirstLinePopen(char const * a, T1 t1, T2 t2, T3 t3, T4 t4) {
char tmp[1024]; sprintf(tmp,a,t1,t2,t3,t4); return GetFirstLinePopen(tmp);
}
}
inline std::string get_single_line_output_as_string(char const * const a, char const * const b) {
char tmp[1024];
sprintf(tmp,a,b);
Popen ns1(tmp,16*1024,"r");
return ns1.getline();
}
inline bool run_line(char const * const a, char const * const b) {
char tmp[1024];
sprintf(tmp,a,b);
if(system(tmp)!=0) { std::cout << "what : " << tmp << "\n\n\n"; exit(1); }
return true;
}
void get_named_table(rarp::NLISTS & nrows, char const * const q) {
rarp::LIST hrow;
Popen ns1(q,16*1024,"r"); char * z3=ns1.getline(); tokenise(hrow,z3,'\t');
assert(hrow.size()>=1);
while( *( z3=ns1.getline() ) != '\0') {
rarp::NLIST nrow; rarp::LIST row; tokenise(row,z3,'\t');
for(unsigned i=0; i<hrow.size(); ++i) nrow[hrow[i]]=row[i];
nrows.push_back(nrow);
}
}
void get_table(rarp::LISTS & rows, char const * const q) {
Popen ns1(q,16*1024,"r");
char * z3;
while( *( z3=ns1.getline() ) != '\0') {
rarp::LIST row;
tokenise(row,z3,'\t');
rows.push_back(row);
}
}
template<typename A> inline void get_table(rarp::LISTS & rows, char const * const q, A a) {
char preptq[16*1024];
sprintf(preptq,q,a);
// std::cout << "get_table<1>= " << preptq << "\n";
get_table(rows,preptq);
}
template<typename A, typename B> inline void get_table(rarp::LISTS & rows, char const * const q, A a, B b) {
char preptq[16*1024];
sprintf(preptq,q,a,b);
// std::cout << "get_table<2>= " << preptq << "\n";
get_table(rows,preptq);
}
template<typename A> inline void get_named_table(rarp::NLISTS & nrows, char const * const q, A a) {
char preptq[16*1024];
sprintf(preptq,q,a);
get_named_table(nrows,preptq);
}
namespace checks {
inline void check_rsync_checksum(std::string const & f, int m, long long s) {
using namespace std;
if(!isregfile(f.data())) cout << "file " << f << " is missing\n",exit(1);
struct stat st;
stat(f.data(),&st);
if(st.st_mtime==m) { // cout << f << " modification matches ("<<m<<")\n";
} else cout << f << " modification doesn't match ("<<m<<")\n",exit(1);
if(st.st_size==s) { // cout << f << " size matches ("<<s<<")\n";
} else cout << f << " size doesn't match ("<<s<<")\n",exit(1);
}
}
// was done in a major hurry. clearly change innerds to use mysql C API?!?
namespace db {
char const // * LAZY_CONN_STR_SEQDB = "mysql -udh2880 -p -hseqprod.igm.cumc.columbia.edu sequenceDB",
* LAZY_CONN_STR_DRGDB = "", // mysql -udh2880 -p -hannodb06 WalDB",
* LAZY_CONN_STR_PGM = "";// mysql -upipeline -p -h10.73.50.31 annodb_pgm" ;
rarp::NLIST get_named_row(char const * w, char const * const q) {
char const * d = strcmp(w,"seqdb")==0 ? opts::myuser.connstr() : strcmp(w,"drgdb")==0 ? LAZY_CONN_STR_DRGDB : strcmp(w,"pgmdb")==0 ? LAZY_CONN_STR_PGM : 0 ; assert(d);
char tmp[2048]; sprintf(tmp,"%s -B -e \"%s\"",d,q);
Popen ns1(tmp,16*1024,"r");
rarp::LIST hrow,row;
char * z3=ns1.getline(); tokenise(hrow,z3,'\t');
assert(hrow.size()>=1);
z3=ns1.getline(); tokenise(row,z3,'\t');
rarp::NLIST nrow;
for(unsigned i=0; i<hrow.size(); ++i) {
if(i==0 && hrow[i]=="" /* silly : */ && row[i]=="") continue;
nrow[hrow[i]]=row[i];
}
return nrow;
}
template<typename A> inline rarp::NLIST get_named_row(char const * w, char const * const q, A a) {
char preptq[16*1024];
sprintf(preptq,q,a);
return get_named_row(w,preptq);
}
template<typename A, typename B> inline rarp::NLIST get_named_row(char const * w, char const * const q, A a, B b) {
char preptq[16*1024];
sprintf(preptq,q,a,b);
return get_named_row(w,preptq);
}
template<typename A, typename B, typename C> inline rarp::NLIST get_named_row(char const * w, char const * const q, A a, B b, C c) {
char preptq[16*1024];
sprintf(preptq,q,a,b,c);
return get_named_row(w,preptq);
}
template<typename A, typename B, typename C, typename D> inline rarp::NLIST get_named_row(char const * w, char const * const q, A a, B b, C c, D d) {
char preptq[16*1024];
sprintf(preptq,q,a,b,c,d);
return get_named_row(w,preptq);
}
template<typename A, typename B, typename C, typename D, typename E> inline rarp::NLIST get_named_row(char const * w, char const * const q, A a, B b, C c, D d, E e) {
char preptq[16*1024]; std::cout << "using5 " << w << ", "<< q <<", "<<a<<", "<<b <<", "<<c<< ", "<<d<<", "<<e<<"\n";
sprintf(preptq,q,a,b,c,d,e);
return get_named_row(w,preptq);
}
void get_named_rows(char const * w, rarp::NLISTS & nrows, char const * const q) {
char const * d = strcmp(w,"seqdb")==0 ? opts::myuser.connstr() : strcmp(w,"drgdb")==0 ? LAZY_CONN_STR_DRGDB : strcmp(w,"pgmdb")==0 ? LAZY_CONN_STR_PGM : 0 ; assert(d);
/// why the heck are we overflowing all of a sudden?!?
char tmp[8*1024]; sprintf(tmp,"%s -B -e \"%s\"",d,q);
rarp::LIST hrow;
Popen ns1(tmp,16*1024,"r"); char * z3=ns1.getline(); tokenise(hrow,z3,'\t');
assert(hrow.size()>=1);
while( *( z3=ns1.getline() ) != '\0') {
rarp::NLIST nrow; rarp::LIST row; tokenise(row,z3,'\t');
for(unsigned i=0; i<hrow.size(); ++i) nrow[hrow[i]]=row[i];
nrows.push_back(nrow);
}
}
// use a variadic template?!?
template<typename A> inline void get_named_rows(char const * w, rarp::NLISTS & nrows, char const * const q, A a) {
char preptq[16*1024];
sprintf(preptq,q,a);
get_named_rows(w,nrows,preptq);
}
template<typename A, typename B> inline void get_named_rows(char const * w, rarp::NLISTS & nrows, char const * const q, A a, B b) {
char preptq[16*1024];
sprintf(preptq,q,a,b);
get_named_rows(w,nrows,preptq);
}
template<typename A, typename B, typename C> inline void get_named_rows(char const * w, rarp::NLISTS & nrows, char const * const q, A a, B b, C c) {
char preptq[16*1024];
sprintf(preptq,q,a,b,c);
get_named_rows(w,nrows,preptq);
}
std::string get_core_query(std::string whater) {
return db::get_named_row("seqdb","select replace( concat( 'gaf_bin=', e.gafbin, '&irb_protocol__irb_protocol=', e.protocol, '&fund_code__fund_code=', e.fundcode, '&sub_project_name=', e.subproject ), ' ', '+' ) CORE_QUERY from SampleT s join Experiment e on s.sample_id=e.sample_id where id = %s",whater.data())["CORE_QUERY"];
}
std::string get_core_query_NEW(std::string whater) {
return db::get_named_row("seqdb","select concat( 'id=', e.subproject_id ) CORE_QUERY_NEW from SampleT s join Experiment e on s.sample_id=e.sample_id where id = %s",whater.data())["CORE_QUERY_NEW"];
}
}
namespace fastq {
static std::map<std::string,std::string> FCT;
/* inline */ std::string fc(char const * const fn) {
using namespace std;
string ret;
if(strlen(fn)<9) return ret;
{
for(unsigned int o=7;o<strlen(fn);++o){
if(fn[o]=='X'
// && fn[o+1]=='X'
&& ( ( (int)fn[o+1]>=(int)'A' && (int)fn[o+1]<=(int)'Z') || ( (int)fn[o+1]>=(int)'0' && (int)fn[o+1]<=(int)'9') )
) {
bool fc=true;
string lazy;
for (unsigned int p=o-7;p<o+2;++p) {
// if( ( (int)fn[p]>=65&&(int)fn[p]<=90) || ( (int)fn[p]>=48&&(int)fn[p]<=57) ) {
if( ( (int)fn[p]>=(int)'A' && (int)fn[p]<=(int)'Z') || ( (int)fn[p]>=(int)'0' && (int)fn[p]<=(int)'9') ) {
lazy+=fn[p];
}else fc=false;
}
if((int)lazy[0]>=(int)'A' && (int)lazy[0]<=(int)'I') {
}else fc=false;
if(lazy.substr(0,2)=="EU")fc=false;
if(lazy.substr(0,6)=="ALSNEU")fc=false;
// assert((int)lazy[0]>=(int)'A' && (int)lazy[0]<=(int)'I');
if(fc) {
return lazy;
}
cout << "\n";
}
}
return ret;
}
}
bool rncheck(char const * const rn,std::string &fcs, std::string &bc, std::string &mtype_from_fc, std::string &mtype_from_pfx) {
using namespace std;
if(FCT.size()==0){
FCT.insert(make_pair("ACXX","HiSeq High-Output (8-lane) v3 flowcell (HiSeq 1000-2500)"));
FCT.insert(make_pair("ANXX","HiSeq High-Output (8-lane) v4 flowcell (HiSeq 1500-2500)"));
FCT.insert(make_pair("BGXX","High-Output NextSeq"));
FCT.insert(make_pair("BGXY","High-Output NextSeq"));
FCT.insert(make_pair("BGX2","High-Output NextSeq"));
FCT.insert(make_pair("BGX3","SUDC Sample : Guessing it's High-Output NextSeq"));
FCT.insert(make_pair("AFXX","Mid-Output NextSeq"));
FCT.insert(make_pair("ADXY","Old_Perhaps"));
FCT.insert(make_pair("BCX2","Old_Perhaps"));
FCT.insert(make_pair("BBXX","HiSeq 4000 (8-lane) v1 flowcell"));
FCT.insert(make_pair("BBXY","HiSeq 4000 (8-lane) v1 flowcell"));
FCT.insert(make_pair("ABXX","HiSeq 2000"));
FCT.insert(make_pair("DRXX","NovaSeq S1 flowcell"));
FCT.insert(make_pair("DMXX","NovaSeq S2 flowcell"));
FCT.insert(make_pair("BCX3","NovaSeq S2 flowcell (hack)"));
FCT.insert(make_pair("DSXX","NovaSeq S4 flowcell"));
FCT.insert(make_pair("DSX5","NovaSeq S4 flowcell"));
FCT.insert(make_pair("BGX5","NovaSeq S4 flowcell (hack EGI)"));
FCT.insert(make_pair("DSXY","NovaSeq S4 flowcell (hack)"));
FCT.insert(make_pair("DSX3","NovaSeq S4 flowcell (hack)"));
FCT.insert(make_pair("BGX7","NovaSeq S4 flowcell (hack EGI)"));
FCT.insert(make_pair("DSX2","NovaSeq S4 flowcell (hack EGI)"));
FCT.insert(make_pair("DMXY","NovaSeq S2 flowcell (hack EGI)"));
FCT.insert(make_pair("ALXX","HiSeqX (8-lane) flowcell"));
FCT.insert(make_pair("CCXX","HiSeqX (8-lane) flowcell"));
FCT.insert(make_pair("CCXY","HiSeqX (8-lane) flowcell"));
FCT.insert(make_pair("AAXX","Genome Analyzer"));
FCT.insert(make_pair("ADXX","HiSeq Rapid Run (2-lane) v1 (HiSeq 1500/2500)"));
FCT.insert(make_pair("AGXX","High-Output NextSeq"));
FCT.insert(make_pair("AMXX","HiSeq RR v2"));
FCT.insert(make_pair("BCXX","HiSeq Rapid Run (2-lane) v1.5/v2 (HiSeq 1500/2500)"));
FCT.insert(make_pair("BCXY","HiSeq Rapid Run (2-lane) v2 (HiSeq 1500/2500)"));
FCT.insert(make_pair("DRXY","NovaSeq S4 flowcell"));
}
std::vector<std::vector<std::string> > info;
std::vector<std::string> y;
tokenise(y,rn,' ');
for (unsigned int i=0;i<y.size();++i) {
std::vector<std::string> x;
tokenise(x,y[i],':');
info.push_back(x);
}
assert(info[0][0][0]=='@');
info[0][0]=info[0][0].substr(1);//,info[0][0].length()-1);
bool bcl2=false;
if(info.size()==2) {
assert(info[0].size()==7);
assert(info[1].size()==4);
++bcl2;
// ss << "THIS APPEARS TO BE ORIGINAL bcl2fastq...\n";
bc=info[1][3];
}
int fcbcc=0;
string bored;
bool one8plus=false;
for (unsigned int i=0;i<info.size();++i) {
for (unsigned int j=0;j<info[i].size();++j) {
string fcst;
if(i==0 && !(fcst=fc(info[i][j].data())).empty() ) {
++fcbcc;
fcs=fcst;
if(j==2) one8plus=true;
break;
}
}
}
assert(fcbcc<=1);
std::stringstream ss;
if(info[0][0].substr(0,5)=="HWUSI") { ss << "GA IIx\n";
}else if(info[0][0].substr(0,5)=="HWI-M") { ss << "MiSeq\n";
}else if(info[0][0].substr(0,5)=="HWI-C") { ss << "HiSeq (1500)\n";
}else if(info[0][0].substr(0,5)=="HWI-S") { ss << "HiSeq (2000)\n";
}else if(info[0][0].substr(0,5)=="HWI-D") { ss << "HiSeq (2500)\n";
//////
}else if(info[0][0].substr(0,5)=="HWI-E") { ss << "Old GAII/HiSeq?!?\n";
//// should check all following are digits!?!
}else if( ( info[0][0].substr(0,2)=="NB" || info[0][0].substr(0,2)=="NS" ) && ::isdigit(info[0][0][2]) ) { ss << "NextSeq\n";
}else if( info[0][0].substr(0,2)=="MN" && ::isdigit(info[0][0][2]) ) { ss << "MiniSeq\n";
}else if( info[0][0][0]=='D' && ::isdigit(info[0][0][1]) ) { ss << "HiSeq 2500\n";
}else if( info[0][0][0]=='E' && ::isdigit(info[0][0][1]) ) { ss << "HiSeqX\n";
}else if( info[0][0][0]=='J' && ::isdigit(info[0][0][1]) ) { ss << "HiSeq 3000\n";
}else if( info[0][0][0]=='K' && ::isdigit(info[0][0][1]) ) { ss << "HiSeq 3000/4000\n";
}else if( info[0][0][0]=='C' && ::isdigit(info[0][0][1]) ) { ss << "HiSeq 1500\n";
}// else{ ss << "no_idea\n"; }
mtype_from_pfx=ss.str();
if(!fcs.empty()) {
if(FCT.count(fcs.substr(5,4))==0) cout << "unknown chemistry : " << fcs << "\n", exit(1);
else mtype_from_fc=FCT[fcs.substr(5,4)];
}
bool one4=true;
if(fcs.empty()) {
if(info[0].size()!=5) one4=false;
if(info[0].size()==3) return false;
if(one4) for(int o=1;o<4;++o){
string &c=info[0][o];
for(unsigned int g=1;g<c.length();++g){
if(!::isdigit(c[g])) {
one4=false;
break;
}
}
}
if(info[0].size()<3) one4 =false;
else if(strchr(info[0][4].data(),'#')==0) one4=false;
}else one4=false;
if(!one8plus){
if(one4) cout << "classic 1.4\n";
else if(info[0].size()==7 && info[0][2]=="FC") {
cout << "WHAT:1: some form of nasty 1.4->1.8 hack?!? - eeeeew\n";
} else if(info[0].size()==7 && ( info[0][2][0]=='h' || info[0][2][0]=='c' ) && info[0][2][7]=='x' ) {
for(unsigned int y=0;y<info[0][2].length();++y) info[0][2][y]=::toupper(info[0][2][y]);
cout <<"WHAT: looks like some whatwit has been at this?!? ="<<info[0][2] << "\n";
fcs=info[0][2];
} else if(info[0].size()==7) {
cout << "WHAT:2: some other form of 1.4->1.8 hack?!? - yuck\n";
// exit(1);
}else if(!fcs.empty() && !one8plus){
cout << "WHAT1:3: this is a strange format in which someone has either merged FC/Machine or happens to have a legit' FCID in machine name?!?\n";
// exit(1);
} else {
cout << "WHAT:4: what in this?!?\n";
// assert(0);
}
}
return (!fcs.empty() && one8plus);
}
}
namespace lims {
inline std::string get_uname(rarp::NLIST & entry) { return entry["dsm_sample_name"]+"."+entry["dsm_pseudo_prepid"]; }
inline std::string get_archive(rarp::NLIST & entry) { return entry["qc_AlignSeqFileLoc"]+"/"+get_uname(entry)+"/"; }
inline std::string get_scratch(rarp::NLIST & entry) {
std::string type = entry["dsm_sample_type"];
for(unsigned i=0; i<type.length(); ++i) type[i]=::toupper(type[i]);
return "/nfs/"+entry["dsm_seqscratch_drive"]+"/ALIGNMENT/BUILD37/DRAGEN/"+type+"/"+get_uname(entry);
}
}
namespace query {
using namespace std;
template <typename A> inline bool silly_update(char const * b, A a) {
char q[2048];
strcpy(q,b);
strcat(q,"; select row_count() as affected");
// std::cout << "using " << q << " and " << a << "\n";
rarp::NLIST arsv2 = db::get_named_row("seqdb",q,a);
// std::cout << "we modified " << arsv2["affected"] << " affected rows\n";
return arsv2["affected"]=="1";
}
}
struct Timey {
Timey(struct tm * tm) : _tm(*tm) {
_tm.tm_isdst=0;
// Timey(struct tm * tm) : _tm(memset(&_tm,tm,sizeof(struct tm))) {
// printf("using struct tm\n");
blah();
}
Timey(time_t t) : _tm(*localtime(&t)) /* use localtime or gmtime for this?!? */ {
_tm.tm_isdst=0;
blah();
}
Timey(char const * a, char const * b,bool clean=false) {
_tm.tm_isdst=0;
if(clean) {
char silly[1024];
strcpy(silly,a);
for (unsigned p = 0, dop=0; p<strlen(silly); ++p ){
if(silly[p]=='.') ++dop;
assert(dop<2);
if(dop && silly[p]==' ') --dop;
if(dop) silly[p]=' ';
}
a=silly;
}
strptime(a, b,&_tm);
blah();
}
void blah() {
_tm.tm_isdst=0; // not explicitly setting this, or zero-initialising gives non-determinstics behavirou w/-or-w/o 1h offset?!?
assert(mktime(&_tm)>=1449263413); // ~end of 2015?!?
assert(mktime(&_tm)<=1607116213); // ~end of 2020?!?
std::cout.flush();
}
void check() {
// this seesm to force initialisation?!?
assert(mktime(&_tm)==1512508213);
}
// why?!?
mutable char _buf[1024];
struct tm _tm;
// get re-write of value when invoking multiple times in cout... - i.e. undefined order?!?
char const * epoch_time_as_string(char * const ext) const {
memset(_buf,sizeof(_buf),0);
strftime(_buf, sizeof(_buf), "%s", &_tm);
strcpy(ext,_buf);
return ext; // return _buf;
}
time_t epoch_time_as_time_t() { return mktime(&_tm); }
char const * iso_time(char * const ext) const {
memset(_buf,sizeof(_buf),0);
strftime(_buf, sizeof(_buf), "%Y-%m-%dT%H:%M:%S", &_tm);
strcpy(ext,_buf);
return ext; // return _buf;
}
};
namespace md5 {
uint32_t grab_something(char const * const x) { // uint64_t grab_something(char const * const x) {
unsigned char digest[MD5_DIGEST_LENGTH];
MD5( (unsigned char*) x, strlen(x), (unsigned char*) &digest );
uint32_t tmp; // uint64_t tmp;
memcpy(&tmp,&digest,sizeof(tmp));
return tmp;
}
//https://stackoverflow.com/questions/7627723/how-to-create-a-md5-hash-of-a-string-in-c
char *str2md5(const char *str, int length) {
int n;
MD5_CTX c;
unsigned char digest[16];
char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n) {
snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
}
return out;
}
/// clearly this should be called by str2md5
/* error to return pointer to locally allocated mem!?! unsigned char * */ void str2md5bin(const char *str, int length,unsigned char * digest) {// , unsigned char &* digest) {
// int n;
MD5_CTX c;
// unsigned char digest[16];
// char *out = (char*)malloc(33);
MD5_Init(&c);
while (length > 0) {
if (length > 512) {
MD5_Update(&c, str, 512);
} else {
MD5_Update(&c, str, length);
}
length -= 512;
str += 512;
}
MD5_Final(digest, &c);
// return digest;
}
}
namespace seq {
static char const * ARCHIVE_DIR = "/nfs/fastq_temp2/PIPE/FASTQ/"; /* ,
static char const * ARCHIVE_DIR = "/nfs/archive/p2018/FASTQ/"; ,
* NETAPP_OUT_DIR = "/nfs/seqscratch_ssd/",
* SEQ_RUN_DIR = "/nfs/hts/novaseq/sequence/Runs/"; */
#define CLEAN_NAME(X) \
{ int j=0; \
for (unsigned int i = 0; i < strlen((X))-1; ++i) { \
while((X)[j]=='/'&&(X)[j+1]=='/') ++j; \
(X)[i]=(X)[j++]; \
} \
if((X)[j-1]=='/') (X)[j-1]='\0'; \
(X)[j]='\0'; }
std::string se_archive_dir(rarp::NLIST & SE) {
assert(SE.count("seq_type_upper"));
assert(SE.count("sample_internal_name"));
assert(SE.count("fcillumid"));
std::string tmp = std::string(seq::ARCHIVE_DIR) + "/" + SE["seq_type_upper"] + "/" + SE["sample_internal_name"] + "/" + SE["fcillumid"] + "/";
char Y[2048];
strcpy(Y,tmp.data());
CLEAN_NAME(Y);
tmp=Y;
return tmp;
}
#undef CLEAN_NAME
}
namespace lists {
/*
#define SAMPLE_SCRATCH_DIR "{{SAMPLE_SCRATCH_DIR}}"
#define SAMPLE_ARCHIVE_DIR "{{SAMPLE_ARCHIVE_DIR}}"
#define SAMPLE_UNIQUE_NAME "{{SAMPLE_UNIQUE_NAME}}"
#define SAMPLE_NAME "{{SAMPLE_NAME}}"
*/
#define FILL_IN_DIR(X,Y,Z,A) char X[(A)]; (Y).fill_in_name((Z),X,sizeof(X)); \
{ int j=0; \
for (unsigned int i = 0; i < strlen((X))-1; ++i) { \
while((X)[j]=='/'&&(X)[j+1]=='/') ++j; \
(X)[i]=(X)[j++]; \
} \
if((X)[j-1]=='/') (X)[j-1]='\0'; \
(X)[j]='\0'; }
#define FILL_IN_DIR_2(R,Y,Z,A) { char X[(A)]; (Y).fill_in_name((Z),X,sizeof(X)); \
int j=0; \
for (unsigned int i = 0; i < strlen((X))-1; ++i) { \
while((X)[j]=='/'&&(X)[j+1]=='/') ++j; \
(X)[i]=(X)[j++]; \
} \
if((X)[j-1]=='/') (X)[j-1]='\0'; \
(X)[j]='\0'; \
(Y).add_name((R),X); }
struct NAMES {
// NAMES(char * a, char * b, char * c, char * d) : ssd(a), sad(
void add_name(char const * a, char const * b) {
names.insert(std::make_pair(a,b));
}
void show_names() {
for(std::map<std::string,std::string>::iterator i = names.begin(); i!=names.end(); i++)
std::cout << i->first << " = " << i->second << "\n";
}
void fill_in_name(char const * in, char * out, size_t l) {
memset(out,0,l);
int len = strlen(in);
bool sub = false;
char name[1024], * p = name, * outp=out;
for (int i = 0; i < len; ++i) {
if(in[i]=='{' && in[i+1]=='{') {
++in;
sub = true;
memset(name,0,sizeof name);
p = name;
} else if(in[i]=='}' && in[i+1]=='}') {
++in;
if(names.count(name)==0) std::cout << "what the heck is " << name << "\n", exit(1);
for (unsigned i =0; i<names.find(name)->second.size(); ++i) {
*outp++=names.find(name)->second[i];
}
sub = false;
} else if(sub) {
*p++=in[i];
} else {// if( (in[i]!='{' && in[i]!='}') {
*outp++=in[i];
}