-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_VKGL_data.php
More file actions
executable file
·2370 lines (2055 loc) · 118 KB
/
Copy pathprocess_VKGL_data.php
File metadata and controls
executable file
·2370 lines (2055 loc) · 118 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
#!/usr/bin/php
<?php
/*******************************************************************************
*
* LEIDEN OPEN VARIATION DATABASE (LOVD)
*
* Created : 2019-06-27
* Modified : 2026-01-20
* Version : 1.5
*
* Purpose : Processes the VKGL consensus data, and creates or updates the
* VKGL data in the LOVD instance.
*
* Changelog : 1.5 2026-01-20
* Handle empty annotation coming from the new UMCG JSON files.
* 1.4 2025-07-03
* Create a data file while processing the data. This allows us to
* see what is actually the result of the normalization. What are
* we loading into the database?
* 1.3 2025-05-02
* Handle WT variants that we're now receiving, and add more error
* messages to the NC cache.
* 1.2 2024-09-17
* Improved the script by re-using more LOVD code, removing custom
* built code. Also solved errors showing up when processing the
* data on LOVD+ and when processing very long variants. From now
* on, we're marking conflicting data as such, to explain to users
* who can see the entries, why they are non-public. Variants that
* are simply republished are now hidden from the debug output.
* 1.1 2023-07-14
* Added a dry run flag (the old $bDebug variable), so that we can
* control debugging when invoking the script, enabling automation
* of the whole workflow. Also, fixed string offsets; curly braces
* are no longer supported. Updated the script to allow running it
* from any directory other than the project's directory.
* 1.0 2023-04-17
* Updated all PDO queries to the new q() method, now that our
* LOVD3 code has been updated. Otherwise, the script refuses to
* function.
* Updated Mutalyzer URL to their v2 backup URL.
* Improved HGVS check.
* Updated 2023-04-18
* Handle some notices that sometimes show up in LOVD+.
* 0.9 2022-05-09
* The JSON will no longer reports differences to transcript
* mappings when in reality, only the effectid changed. Also the
* debugging info will now ignore effectid changes in VOT data.
* 0.8 2021-02-10
* Conflicts are now reported in a structured manner, so we can
* easily filter them out of the run logs, and convert them
* automatically into a tab-delimited format to be reported to all
* the centers.
* 0.7 2020-09-15
* The VOT/Classification column moved to VOG and was renamed to
* VOG/ClinicalClassification. Also, when debugging, silently skip
* reports of this column being filled in. The previous run (June
* 2020) was run without this column filled in.
* 0.6 2020-08-06
* Conflicts are now reported while determining consensus
* classifications, so we can report them. When debugging, changes
* caused by the new VV predictions (c.= transcript variants and
* changes to the protein field) are not easily reported anymore.
* 0.5 2020-04-02
* Improved variant validation error messages so they can be
* easily extracted from the output and reported to the centers.
* 0.4 2020-03-23
* Whether single-lab submissions are linked to a public owner or
* instead to a general VKGL account, is now a setting. Also, we
* check for the presence of some non-critical columns, so we
* won't die if LOVD doesn't have them activated (i.e. LOVD+).
* Finally, some other LOVD+ optimizations are added and genes
* have their timestamps updated.
* 0.3 2019-12-04
* Handle conflicts per gene per center, not just per center. Some
* centers are classifying a variant twice on purpose, on multiple
* genes. (L)P on one, (L)B on the other. From now on, we'll call
* conflicts only when the same gene is used within one center. If
* multiple genes are used, we'll pick the most severe
* classification.
* Also, prevent false positive updates while debugging.
* 0.2 2019-11-07
* Better debugging, store the new VKGL IDs, improved diff
* formatting, better annotation of double submissions so we can
* remove them in the future, and now ignoring the HGVS column.
* 0.1 2019-07-18
* Initial release.
*
* Copyright : 2004-2026 Leiden University Medical Center; http://www.LUMC.nl/
* Programmer : Ivo F.A.C. Fokkema <I.F.A.C.Fokkema@LUMC.nl>
*
*
* This file is part of LOVD.
*
* LOVD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LOVD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LOVD. If not, see <http://www.gnu.org/licenses/>.
*
*************/
// FIXME: When the position converter returns mappings that Mutalyzer cannot generate a protein change for because the
// transcript or later versions of it is not found in the NC, we skip the transcript, and we don't store it, either.
// This can be improved on, by taking in mappings that map into locations that we can generate the protein change for.
// Notes: Position converter descriptions are *not* normalized. For variants on the reverse strand, this is a problem.
// If you fix this, remove "numberConversion" as a method from the cache, so all variants will be repeated.
// Perhaps VV can help here, it may provide more mappings and surely is a lot faster.
// FIXME: Fix conflicts if on different genes, they can be regarded as non-conflicts.
// Command line only.
if (isset($_SERVER['HTTP_HOST'])) {
die('Please run this script through the command line.' . "\n");
}
// We're already using ROOT_PATH to point to LOVD, so define CWD to point to the directory where this script resides.
define('CWD', dirname(__FILE__) . '/');
// Default settings. Everything in 'user' will be verified with the user, and stored in settings.json.
$_CONFIG = array(
'name' => 'VKGL data importer',
'version' => '1.5',
'settings_file' => CWD . 'settings.json',
'flags' => array(
'n' => false, // Dry run.
'y' => false, // Yes; accept current settings and don't ask anything.
),
'columns_mandatory' => array(
// These are the columns that need to be present in order for the file to get processed.
'id',
'chromosome',
'start',
'ref',
'alt',
'gene',
'c_dna',
'transcript',
'protein',
),
'columns_ignore' => array(
// These are the columns that we'll ignore. If we find any others, we'll complain.
'stop',
'hgvs',
'consensus_classification',
'matches',
'disease',
'comments',
'history',
),
'columns_center_suffix' => '_link', // This is how we recognize a center, because it also has a *_link column.
'effect_mapping_LOVD' => array(
'B' => 1,
'LB' => 3,
'VUS' => 5,
'LP' => 7,
'P' => 9,
),
'effect_mapping_classification' => array(
'B' => 'benign',
'LB' => 'likely benign',
'VUS' => 'VUS',
'LP' => 'likely pathogenic',
'P' => 'pathogenic',
),
'mutalyzer_URL' => 'https://v2.mutalyzer.nl/',
'user' => array(
// Variables we will be asking the user.
'refseq_build' => 'hg19',
'lovd_path' => '/www/databases.lovd.nl/shared/',
'mutalyzer_cache_NC' => CWD . 'NC_cache.txt', // Stores NC g. descriptions and their corrected output.
'mutalyzer_cache_mapping' => CWD . 'mapping_cache.txt', // Stores NC to NM mappings and the protein predictions.
'vkgl_generic_id' => 0, // The LOVD ID of the generic VKGL account, needed for single lab submissions.
'public_singlelab_owners' => 'y', // Should single-lab submissions get a public owner?
'delete_redundant_variants' => 'n', // Should we remove variants in LOVD no longer in the dataset?
),
);
// Exit codes.
// See http://tldp.org/LDP/abs/html/exitcodes.html for recommendations, in particular:
// "[I propose] restricting user-defined exit codes to the range 64 - 113 (...), to conform with the C/C++ standard."
define('EXIT_OK', 0);
define('EXIT_WARNINGS_OCCURRED', 64);
define('EXIT_ERROR_ARGS_INSUFFICIENT', 65);
define('EXIT_ERROR_ARGS_NOT_UNDERSTOOD', 66);
define('EXIT_ERROR_INPUT_NOT_A_FILE', 67);
define('EXIT_ERROR_INPUT_UNREADABLE', 68);
define('EXIT_ERROR_INPUT_CANT_OPEN', 69);
define('EXIT_ERROR_HEADER_FIELDS_NOT_FOUND', 70);
define('EXIT_ERROR_HEADER_FIELDS_INCORRECT', 71);
define('EXIT_ERROR_SETTINGS_CANT_CREATE', 72);
define('EXIT_ERROR_SETTINGS_UNREADABLE', 73);
define('EXIT_ERROR_SETTINGS_CANT_UPDATE', 74);
define('EXIT_ERROR_SETTINGS_INCORRECT', 75);
define('EXIT_ERROR_CONNECTION_PROBLEM', 76);
define('EXIT_ERROR_CACHE_CANT_CREATE', 77);
define('EXIT_ERROR_CACHE_UNREADABLE', 78);
define('EXIT_ERROR_CACHE_CANT_UPDATE', 79);
define('EXIT_ERROR_DATA_FIELD_COUNT_INCORRECT', 80);
define('EXIT_ERROR_DATA_CONTENT_ERROR', 81);
define('VERBOSITY_NONE', 0); // No output whatsoever.
define('VERBOSITY_LOW', 3); // Low output, only the really important messages.
define('VERBOSITY_MEDIUM', 5); // Medium output. No output if there is nothing to do. Useful for when using cron.
define('VERBOSITY_HIGH', 7); // High output. The default.
define('VERBOSITY_FULL', 9); // Full output, including debug statements.
function lovd_printIfVerbose ($nVerbosity, $sMessage)
{
// This function only prints the given message when the current verbosity is set to a level high enough.
// If no verbosity is currently defined, just print everything.
if (!defined('VERBOSITY')) {
define('VERBOSITY', 9);
}
if (VERBOSITY >= $nVerbosity) {
print($sMessage);
}
return true;
}
function lovd_saveSettings ($bHaltOnError = true)
{
// Saves the settings we currently have to the JSON file.
global $_CONFIG;
if (!file_put_contents($_CONFIG['settings_file'], json_encode($_CONFIG['user'], JSON_PRETTY_PRINT))) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Could not save settings.' . "\n\n");
if ($bHaltOnError) {
die(EXIT_ERROR_SETTINGS_CANT_UPDATE);
} else {
return false;
}
}
return true;
}
function lovd_verifySettings ($sKeyName, $sMessage, $sVerifyType, $options)
{
// Based on a function provided by Ileos.nl in the interest of Open Source.
// Check if settings match certain input.
global $_CONFIG;
switch($sVerifyType) {
case 'array':
$aOptions = $options;
if (!is_array($aOptions)) {
return false;
}
break;
case 'int':
// Integer, options define a range in the format '1,3' (1 to 3) or '1,' (1 or higher).
$aRange = explode(',', $options);
if (!is_array($aRange) ||
($aRange[0] === '' && $aRange[1] === '') ||
($aRange[0] !== '' && !ctype_digit($aRange[0])) ||
($aRange[1] !== '' && !ctype_digit($aRange[1]))) {
return false;
}
break;
}
while (true) {
print(' ' . $sMessage .
($sVerifyType != 'int' || ($aRange === array('', ''))? '' : ' (' . (int) $aRange[0] . '-' . $aRange[1] . ')') .
(empty($_CONFIG['user'][$sKeyName])? '' : ' [' . $_CONFIG['user'][$sKeyName] . ']') . ' : ');
$sInput = trim(fgets(STDIN));
if (!strlen($sInput) && !empty($_CONFIG['user'][$sKeyName])) {
$sInput = $_CONFIG['user'][$sKeyName];
}
switch ($sVerifyType) {
case 'array':
$sInput = strtolower($sInput);
if (in_array($sInput, $aOptions)) {
$_CONFIG['user'][$sKeyName] = $sInput;
return true;
}
break;
case 'int':
$sInput = (int) $sInput;
// Check if input is lower than minimum required value (if configured).
if ($aRange[0] !== '' && $sInput < $aRange[0]) {
break;
}
// Check if input is higher than maximum required value (if configured).
if ($aRange[1] !== '' && $sInput > $aRange[1]) {
break;
}
$_CONFIG['user'][$sKeyName] = $sInput;
return true;
case 'string':
$_CONFIG['user'][$sKeyName] = $sInput;
return true;
case 'file':
case 'lovd_path':
case 'path':
// Always accept the default (if non-empty) or the given options.
if (($sInput && ($sInput == $_CONFIG['user'][$sKeyName] ||
$sInput === $options)) ||
(is_array($options) && in_array($sInput, $options))) {
$_CONFIG['user'][$sKeyName] = $sInput; // In case an option was chosen that was not the default.
return true;
}
if (in_array($sVerifyType, array('lovd_path', 'path')) && !is_dir($sInput)) {
print(' Given path is not a directory.' . "\n");
break;
} elseif (!is_readable($sInput)) {
print(' Cannot read given path.' . "\n");
break;
}
if ($sVerifyType == 'lovd_path') {
if (!file_exists($sInput . '/config.ini.php')) {
if (file_exists($sInput . '/src/config.ini.php')) {
$sInput .= '/src';
} else {
print(' Cannot locate config.ini.php in given path.' . "\n" .
' Please check that the given path is a correct path to an LOVD installation.' . "\n");
break;
}
}
if (!is_readable($sInput . '/config.ini.php')) {
print(' Cannot read configuration file in given LOVD directory.' . "\n");
break;
}
// We'll set everything up later, because we don't want to
// keep the $_DB open for as long as the user is answering questions.
}
$_CONFIG['user'][$sKeyName] = $sInput;
return true;
default:
return false;
}
}
return false; // We'd actually never get here.
}
// Parse command line options.
$aArgs = $_SERVER['argv'];
$nArgs = $_SERVER['argc'];
// We need at least one argument, the file to convert.
$nArgsRequired = 1;
$sScriptName = array_shift($aArgs);
$nArgs --;
$nWarningsOccurred = 0;
if ($nArgs < $nArgsRequired) {
lovd_printIfVerbose(VERBOSITY_LOW,
$_CONFIG['name'] . ' v' . $_CONFIG['version'] . '.' . "\n" .
'Usage: ' . $sScriptName . ' file_to_import.tsv [-y]' . "\n\n");
die(EXIT_ERROR_ARGS_INSUFFICIENT);
}
// First argument should be the file to convert.
$sFile = array_shift($aArgs);
$nArgs --;
while ($nArgs) {
// Check for flags.
$sArg = array_shift($aArgs);
$nArgs --;
if (preg_match('/^-[A-Z]+$/i', $sArg)) {
$sArg = substr($sArg, 1);
foreach (str_split($sArg) as $sFlag) {
if (isset($_CONFIG['flags'][$sFlag])) {
$_CONFIG['flags'][$sFlag] = true;
} else {
// Flag not recognized.
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Flag -' . $sFlag . ' not understood.' . "\n\n");
die(EXIT_ERROR_ARGS_NOT_UNDERSTOOD);
}
}
}
}
$bCron = (empty($_SERVER['REMOTE_ADDR']) && empty($_SERVER['TERM']));
define('VERBOSITY', ($bCron? 5 : 7));
// Record the start of the script, but correct for the timezone. This way, (time() - $tStart) doesn't seem to make sense
// to us human readers, but when used in combination with date('H:i:s', ...) to format hours, minutes, and seconds
// spent, it all makes sense. Note that date("H:i:s", 0) only returns 00:00:00 when your timezone is GMT.
$tStart = time() + date('Z', 0);
// Configure dry run.
$bDebug = !empty($_CONFIG['flags']['n']);
lovd_printIfVerbose(VERBOSITY_MEDIUM,
$_CONFIG['name'] . ' v' . $_CONFIG['version'] . '.' . "\n" .
(!$bDebug? '' : ' Dry run enabled, not running any database updates.' . "\n"));
// Check file passed as an argument.
if (!file_exists($sFile) || !is_file($sFile)) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Input is not a file.' . "\n\n");
die(EXIT_ERROR_INPUT_NOT_A_FILE);
}
if (!is_readable($sFile)) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Unreadable input file.' . "\n\n");
die(EXIT_ERROR_INPUT_UNREADABLE);
}
// Check headers. Isolate the center names, so we can ask the user about them.
$aHeaders = array();
$nHeaders = 0;
$nLine = 0;
$fInput = fopen($sFile, 'r');
if ($fInput === false) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Can not open file.' . "\n\n");
die(EXIT_ERROR_INPUT_CANT_OPEN);
}
while ($sLine = fgets($fInput)) {
$nLine++;
$sLine = strtolower(trim($sLine));
if (!$sLine) {
continue;
}
// First line should be headers.
$aHeaders = explode("\t", $sLine);
$nHeaders = count($aHeaders);
// Check for mandatory headers.
$aHeadersMissing = array();
foreach ($_CONFIG['columns_mandatory'] as $sColumn) {
if (!in_array($sColumn, $aHeaders, true)) {
$aHeadersMissing[] = $sColumn;
}
}
if ($aHeadersMissing) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: File does not conform to format; missing column' . (count($aHeadersMissing) == 1? '' : 's') . ': ' . implode(', ', $aHeadersMissing) . ".\n\n");
die(EXIT_ERROR_HEADER_FIELDS_INCORRECT);
}
break;
}
if (!$aHeaders) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: File does not conform to format; can not find headers.' . "\n\n");
die(EXIT_ERROR_HEADER_FIELDS_NOT_FOUND);
}
// Now we have the headers, and all required ones are there.
// Parse the rest, ignore everything we don't care about, assume the rest must be centers.
// Verify these and store.
$aCentersFound = array();
$nCentersFound = 0;
$aHeadersSorted = array_diff($aHeaders, $_CONFIG['columns_mandatory'], $_CONFIG['columns_ignore']);
sort($aHeadersSorted); // This makes it easier to find the centers and their *_link column.
foreach ($aHeadersSorted as $sHeader) {
// Are we a center name?
if (in_array($sHeader . $_CONFIG['columns_center_suffix'], $aHeadersSorted)) {
// Yes, this is a center. Its *_link column is present.
$aCentersFound[] = $sHeader;
$nCentersFound ++;
$_CONFIG['user']['center_' . $sHeader . '_id'] = 0;
} elseif (in_array(str_replace($_CONFIG['columns_center_suffix'], '', $sHeader), $aCentersFound)) {
// This is a center's *_link column.
continue;
} else {
// Column not recognized. Better warn, in case we're missing something.
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: File header contains unrecognized column: ' . $sHeader . ".\n" .
'In case you would like to ignore this column, please add it to the columns_ignore list.' . "\n\n");
die(EXIT_ERROR_HEADER_FIELDS_INCORRECT);
}
}
// Get settings file, if it exists.
$_SETT = array();
if (!file_exists($_CONFIG['settings_file'])) {
if (!touch($_CONFIG['settings_file'])) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Could not create settings file.' . "\n\n");
die(EXIT_ERROR_SETTINGS_CANT_CREATE);
}
} elseif (!is_file($_CONFIG['settings_file']) || !is_readable($_CONFIG['settings_file'])
|| !($_SETT = json_decode(file_get_contents($_CONFIG['settings_file']), true))) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Unreadable settings file.' . "\n\n");
die(EXIT_ERROR_SETTINGS_UNREADABLE);
}
// The settings file always replaces the standard defaults.
$_CONFIG['user'] = array_merge($_CONFIG['user'], $_SETT);
// User may have requested to continue without verifying the settings, but we may not have them all.
// If at least one setting evaluates to "false", we will ask anyway.
if ($_CONFIG['flags']['y']) {
foreach ($_CONFIG['user'] as $Value) {
if (!$Value) {
$_CONFIG['flags']['y'] = false;
break;
}
}
}
// Verify all the settings, if needed.
$aCenterIDs = array();
if (!$_CONFIG['flags']['y']) {
lovd_verifySettings('refseq_build', 'The genome build that the data file uses (hg19/hg38)', 'array', array('hg19', 'hg38'));
if (!lovd_verifySettings('lovd_path', 'Path of LOVD installation to load data into', 'lovd_path', '')) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Failed to get LOVD path.' . "\n\n");
die(EXIT_ERROR_CONNECTION_PROBLEM);
}
lovd_verifySettings('mutalyzer_cache_NC', 'File containing the Mutalyzer cache for genomic (NC) variants', 'file', '');
lovd_verifySettings('mutalyzer_cache_mapping', 'File containing the Mutalyzer cache for mappings from genome to transcript', 'file', '');
lovd_verifySettings('vkgl_generic_id', 'The LOVD user ID for the generic VKGL account', 'int', '1,99999');
// Verify all centers.
$aCenterIDs = array(); // Make sure IDs are unique.
foreach ($aCentersFound as $sCenter) {
while (true) {
lovd_verifySettings('center_' . $sCenter . '_id', 'The LOVD user ID for VKGL center ' . $sCenter, 'int', '1,99999');
if (in_array($_CONFIG['user']['center_' . $sCenter . '_id'], $aCenterIDs)) {
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' This ID is already assigned to a different center.' . "\n");
$_CONFIG['user']['center_' . $sCenter . '_id'] = 0;
} else {
$aCenterIDs[$sCenter] = $_CONFIG['user']['center_' . $sCenter . '_id'];
break;
}
}
}
lovd_verifySettings('public_singlelab_owners', 'Should single-lab records be publically linked to the submitting laboratory? (y/n)', 'array', array('y', 'n'));
// Delete LOVD variants no longer in the VKGL dataset? Should be left to "n" for all tests,
// otherwise incomplete VKGL files will result in lots of data marked for removal.
// Note that this doesn't actually really remove these variants, it will hide them and mark them as removed.
lovd_verifySettings('delete_redundant_variants', 'Do you want data no longer found in this input file removed from LOVD? (y/n)', 'array', array('y', 'n'));
}
// Save settings already, in case the connection breaks just below. Settings may be incorrect.
lovd_saveSettings();
// Open connection, and check if user accounts exist.
lovd_printIfVerbose(VERBOSITY_HIGH,
' Connecting to LOVD...');
// Find LOVD installation, run it's inc-init.php to get DB connection, initiate $_SETT, etc.
define('ROOT_PATH', $_CONFIG['user']['lovd_path'] . '/');
define('FORMAT_ALLOW_TEXTPLAIN', true);
$_GET['format'] = 'text/plain';
// To prevent notices when running inc-init.php.
$_SERVER = array_merge($_SERVER, array(
'HTTP_HOST' => 'localhost',
'REQUEST_URI' => '/' . basename(__FILE__),
'QUERY_STRING' => '',
'REQUEST_METHOD' => 'GET',
));
// If I put a require here, I can't nicely handle errors, because PHP will die if something is wrong.
// However, I need to get rid of the "headers already sent" warnings from inc-init.php.
// So, sadly if there is a problem connecting to LOVD, the script will die here without any output whatsoever.
ini_set('display_errors', '0');
ini_set('log_errors', '0'); // CLI logs errors to the screen, apparently.
// Let the LOVD believe we're accessing it through SSL. LOVDs that demand this, will otherwise block us.
// We have error messages surpressed anyway, as the LOVD in question will complain when it tries to define "SSL" as well.
define('SSL', true);
require ROOT_PATH . 'inc-init.php';
require ROOT_PATH . 'inc-lib-form.php';
require ROOT_PATH . 'inc-lib-variants.php'; // For lovd_fixHGVS().
ini_set('display_errors', '1'); // We do want to see errors from here on.
lovd_printIfVerbose(VERBOSITY_HIGH,
' Connected!' . "\n\n");
// Check given refseq build.
$sRefSeqBuild = $_DB->q('SELECT refseq_build FROM ' . TABLE_CONFIG)->fetchColumn();
$bRefSeqBuildOK = ($_CONFIG['user']['refseq_build'] == $sRefSeqBuild);
lovd_printIfVerbose(VERBOSITY_MEDIUM,
'RefSeq build set to ' . $_CONFIG['user']['refseq_build'] .
($bRefSeqBuildOK? '.' : ', but LOVD uses ' . $sRefSeqBuild . '!!!') . "\n\n");
if (!$bRefSeqBuildOK) {
$_CONFIG['user']['refseq_build'] = '';
}
// Check given user accounts.
// Get IDs. It is assumed that all numeric values in the user array are user IDs.
$aUserIDs = array_filter($_CONFIG['user'], function ($Val) { return (is_int($Val)); });
// Cast id to UNSIGNED to make sure our ints match.
$aUsers = $_DB->q('SELECT CAST(id AS UNSIGNED) AS id, name FROM ' . TABLE_USERS . ' WHERE id IN (?' . str_repeat(', ?', count($aUserIDs) - 1) . ') ORDER BY id',
array_values($aUserIDs))->fetchAllCombine();
$bAccountsOK = true;
$lCenters = max(array_map('strlen', $aCentersFound));
// The generic VKGL account.
// If not found, reset the ID so it doesn't get saved.
$bFound = (isset($aUsers[$_CONFIG['user']['vkgl_generic_id']]));
lovd_printIfVerbose(VERBOSITY_MEDIUM,
'Generic' . str_pad(' VKGL ID', $lCenters, '.') . '... LOVD account #' .
str_pad($_CONFIG['user']['vkgl_generic_id'], 5, '0', STR_PAD_LEFT) .
(!$bFound? ' --- not found!!!' : ' "' . $aUsers[$_CONFIG['user']['vkgl_generic_id']] . '"') . "\n");
if (!$bFound) {
$bAccountsOK = false;
$_CONFIG['user']['vkgl_generic_id'] = 0;
} else {
// str_pad() the ID, so we can match it with what's in the DB.
$_CONFIG['user']['vkgl_generic_id'] = str_pad($_CONFIG['user']['vkgl_generic_id'], 5, '0', STR_PAD_LEFT);
}
// The other centers that we have collected from the input file.
foreach ($aCentersFound as $sCenter) {
// If the user was changing settings, then print the center's name, and user name from LOVD.
// If not found, reset the ID so it doesn't get saved.
$bFound = (isset($aUsers[$_CONFIG['user']['center_' . $sCenter . '_id']]));
lovd_printIfVerbose(VERBOSITY_MEDIUM,
'Center ' . str_pad($sCenter, $lCenters, '.') . '... LOVD account #' .
str_pad($_CONFIG['user']['center_' . $sCenter . '_id'], 5, '0', STR_PAD_LEFT) .
(!$bFound? ' --- not found!!!' : ' "' . $aUsers[$_CONFIG['user']['center_' . $sCenter . '_id']] . '"') . "\n");
if (!$bFound) {
$bAccountsOK = false;
$_CONFIG['user']['center_' . $sCenter . '_id'] = 0;
} else {
// We need it for querying the database later; also str_pad() the ID, so we can match it with what's in the DB.
$aCenterIDs[$sCenter] = str_pad($_CONFIG['user']['center_' . $sCenter . '_id'], 5, '0', STR_PAD_LEFT);
}
}
lovd_printIfVerbose(VERBOSITY_MEDIUM, "\n");
if (!$bRefSeqBuildOK || !$bAccountsOK) {
// One of the settings is no good. Settings have been updated, save changes (but don't die if that doesn't work).
lovd_saveSettings(false);
// Now, die because of the incorrect settings.
lovd_printIfVerbose(VERBOSITY_LOW,
($bRefSeqBuildOK? '' : 'Error: Failed to set RefSeq build.' . "\n") .
($bAccountsOK? '' : 'Error: Failed to get all LOVD user accounts.' . "\n") . "\n");
die(EXIT_ERROR_SETTINGS_INCORRECT);
}
lovd_printIfVerbose(VERBOSITY_MEDIUM,
'Delete data from LOVD if no longer found in the input file: ' .
($_CONFIG['user']['delete_redundant_variants'] == 'y'? 'Yes' : 'No') . "\n\n");
// Load the caches, create if they don't exist. They can only not exist, when the defaults are used.
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [ ] Loading Mutalyzer cache files...' . "\n");
$_CACHE = array();
foreach (array('mutalyzer_cache_NC', 'mutalyzer_cache_mapping') as $sKeyName) {
$_CACHE[$sKeyName] = array();
if (!file_exists($_CONFIG['user'][$sKeyName])) {
// It doesn't exist, create it.
if (!touch($_CONFIG['user'][$sKeyName])) {
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Could not create Mutalyzer cache file.' . "\n\n");
die(EXIT_ERROR_CACHE_CANT_CREATE);
} else {
lovd_printIfVerbose(VERBOSITY_HIGH,
' Cache created: ' . $_CONFIG['user'][$sKeyName] . "\n");
}
} elseif (!is_file($_CONFIG['user'][$sKeyName]) || !is_readable($_CONFIG['user'][$sKeyName])) {
// It does exist, but we can't read it.
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Unreadable Mutalyzer cache file.' . "\n\n");
die(EXIT_ERROR_CACHE_UNREADABLE);
} else {
// Load the cache.
$aCache = file($_CONFIG['user'][$sKeyName], FILE_IGNORE_NEW_LINES);
$nCacheLine = 0;
$nCacheLines = count($aCache);
foreach ($aCache as $sVariant) {
$nCacheLine ++;
$aVariant = explode("\t", $sVariant);
if (count($aVariant) == 2) {
if ($sKeyName == 'mutalyzer_cache_mapping') {
// The mapping cache has a JSON structure.
$_CACHE[$sKeyName][$aVariant[0]] = json_decode($aVariant[1], true);
} else {
$_CACHE[$sKeyName][$aVariant[0]] = $aVariant[1];
}
} else {
// Malformed line.
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [' . str_pad(number_format(round($nCacheLine * 100 / $nCacheLines, 1), 1),
5, ' ', STR_PAD_LEFT) . '%] Warning: ' . ucfirst(str_replace('_', ' ', $sKeyName)) . ' line ' . $nCacheLine . ' malformed.' . "\n");
$nWarningsOccurred ++;
}
}
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [100.0%] ' . ucfirst(str_replace('_', ' ', $sKeyName)) . ' loaded, ' . count($_CACHE[$sKeyName]) . ' variants.' . "\n");
}
}
lovd_printIfVerbose(VERBOSITY_MEDIUM, "\n" .
' ' . date('H:i:s', time() - $tStart) . ' [ 0.0%] Parsing VKGL file...' . "\n");
// Read out all variants, with labels per center, and store cDNA/protein annotation.
$aData = array();
// 'disease' is currently empty. When we'll start using it, then add it to the mandatory columns and copy it here.
// 'comments' is currently the same as 'id'.
$aColumnsToUse = array_merge($_CONFIG['columns_mandatory'], $aCentersFound);
while ($sLine = fgets($fInput)) {
$nLine++;
$sLine = trim($sLine);
if (!$sLine) {
continue;
}
$aDataLine = explode("\t", $sLine);
// Trim quotes off of the data.
$aDataLine = array_map(function($sData) {
return trim($sData, '"');
}, $aDataLine);
$nDataColumns = count($aDataLine);
if ($nHeaders > $nDataColumns) {
// We accidentally trimmed off empty fields.
$aDataLine = array_pad($aDataLine, $nHeaders, '');
} elseif ($nHeaders < $nDataColumns) {
// Eh? More data received than headers.
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Data line ' . $nLine . ' has ' . count($aDataLine) . ' columns instead of the expected ' . $nHeaders . ".\n\n");
die(EXIT_ERROR_DATA_FIELD_COUNT_INCORRECT);
}
$aDataLine = array_combine($aHeaders, $aDataLine);
// Store data.
$aData[] = array_intersect_key($aDataLine, array_flip($aColumnsToUse));
}
$nVariants = count($aData);
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [100.0%] VKGL file successfully parsed, found ' . $nVariants . ' variants.' . "\n\n" .
' ' . date('H:i:s', time() - $tStart) . ' [ 0.0%] Verifying genomic variants and creating mappings...' . "\n");
// We might be running for some time.
set_time_limit(0);
// Correct all genomic variants, using the cache. Skip substitutions.
// And don't bother using the database, we'll assume the cache knows it all.
$nVariantsLost = 0;
$nVariantsDone = 0;
$nVariantsAddedToCache = 0;
$nPercentageComplete = 0; // Integer of percentage with one decimal (!), so you can see the progress.
$tProgressReported = microtime(true); // Don't report progress again within a certain amount of time.
foreach ($aData as $nKey => $aVariant) {
// VKGL stores chrM data as "MT".
if ($aVariant['chromosome'] == 'MT') {
$aVariant['chromosome'] = 'M';
}
$sID = $aVariant['id'];
if (!isset($_SETT['human_builds'][$_CONFIG['user']['refseq_build']]['ncbi_sequences'][$aVariant['chromosome']])) {
// Can't get chromosome's NC refseq?
lovd_printIfVerbose(VERBOSITY_LOW,
'Error: Variant ID ' . $sID . ' has unknown chromosome value ' . $aVariant['chromosome'] . ".\n\n");
die(EXIT_ERROR_DATA_CONTENT_ERROR);
}
// Translate all classification values to easier values.
// I need this cleaned up here already, so I can report which centers cause problems.
// Also store the genes per center, as the classification is specific for this gene.
$aVariant['classifications'] = array();
$aVariant['genes'] = array();
foreach ($aCentersFound as $sCenter) {
if ($aVariant[$sCenter]) {
$aVariant['classifications'][$sCenter] = str_replace(array('likely ', 'benign', 'pathogenic', 'vus'),
array('L', 'B', 'P', 'VUS'), strtolower($aVariant[$sCenter]));
$aVariant['genes'][$sCenter] = $aVariant['gene'];
}
unset($aVariant[$sCenter]);
}
// Use LOVD's functions to build the HGVS from the VCF fields.
$sVariant = lovd_fixHGVS('g.' . $aVariant['start'] .
($aVariant['ref'] != '.'?
$aVariant['ref'] . '>' . $aVariant['alt'] :
'_' . ($aVariant['start'] + 1) . 'ins' . $aVariant['alt']));
if (!lovd_getVariantInfo($sVariant, false, true)) {
// This is not recognized as a valid variant description.
// This can happen when Ref and Alt are both empty.
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [' . str_pad(number_format(
floor($nVariantsDone * 1000 / $nVariants) / 10, 1),
5, ' ', STR_PAD_LEFT) . '%] Warning: Error for variant ' . $sID . ' (' . implode(', ', array_keys($aVariant['classifications'])) . ").\n" .
' Could not construct DNA field.' . "\n" .
' {' . $aVariant['id'] . '|' . $aVariant['chromosome'] . '|' . $aVariant['start'] . '|' . $aVariant['ref'] . '|' . $aVariant['alt'] . '|' . $aVariant['gene'] . '|Error: Could not construct DNA field.|' . implode(',', array_keys($aVariant['classifications'])) . '}' . "\n");
$nWarningsOccurred ++;
$nVariantsLost ++;
$nVariantsDone ++;
unset($aData[$nKey]); // We don't want to continue working with this variant.
continue; // Next variant.
}
// Previously we were skipping substitutions for this step, but runMutalyzerLight provides us with
// all mappings as well, as well as all protein predictions, and we still need those.
// So to make the code much simpler, just run *everything* through here.
$sVariant =
$_SETT['human_builds'][$_CONFIG['user']['refseq_build']]['ncbi_sequences'][$aVariant['chromosome']] .
':' . $sVariant;
// The variant may be in the NC cache, but not yet in the mapping cache.
// This happens when the NC cache is used by another application, which doesn't build the mapping cache as well.
// Check if we need this call, if the variant is missing in one of the two caches.
$bUpdateCache = !isset($_CACHE['mutalyzer_cache_NC'][$sVariant]);
if (!$bUpdateCache) {
// But check the mapping cache too!
$sVariantCorrected = $_CACHE['mutalyzer_cache_NC'][$sVariant];
// Check if this is not a cached error message.
if ($sVariantCorrected[0] == '{') {
// This is a cached error message. Report, but don't cache.
$aError = json_decode($sVariantCorrected, true);
// I'm not too happy duplicating this code.
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [' . str_pad(number_format(
floor($nVariantsDone * 1000 / $nVariants) / 10, 1),
5, ' ', STR_PAD_LEFT) . '%] Warning: Error for variant ' . $sID . ' (' . implode(', ', array_keys($aVariant['classifications'])) . ").\n" .
' It was sent as ' . $sVariant . ".\n" .
(!$aError? '' : ' Error: ' . implode("\n" . str_repeat(' ', 26), $aError) . "\n") .
' {' . $aVariant['id'] . '|' . $aVariant['chromosome'] . '|' . $aVariant['start'] . '|' . $aVariant['ref'] . '|' . $aVariant['alt'] . '|' . $aVariant['gene'] . '|' . (!$aError? '' : 'Error: ' . implode(';', $aError)) . '|' . implode(',', array_keys($aVariant['classifications'])) . '}' . "\n");
$nWarningsOccurred ++;
$nVariantsLost ++;
$nVariantsDone ++;
unset($aData[$nKey]); // We don't want to continue working with this variant.
continue; // Next variant.
}
$bUpdateCache = !isset($_CACHE['mutalyzer_cache_mapping'][$sVariantCorrected]);
}
// Update cache if needed.
if ($bUpdateCache) {
// Hold on; is this a WT variant? If so, Mutalyzer doesn't handle that.
// Plus, we don't have to check its description.
$aResult = [];
if (substr($sVariant, -1) == '=') {
// Well, OK, don't blindly accept it, double-check.
$aLOVD = json_decode(file_get_contents('https://api.lovd.nl/v2/checkHGVS/' . rawurlencode($sVariant)), true);
if ($aLOVD && !$aLOVD['errors'] && $aLOVD['data'][0]['corrected_values']) {
// Fake a successful Mutalyzer result.
$aResult = [
'genomicDescription' => key($aLOVD['data'][0]['corrected_values']),
'legend' => [], // No transcripts; we'll use VV.
'transcriptDescriptions' => [], // No mappings; we'll use VV.
'proteinDescriptions' => [], // No mappings; we'll use VV.
];
}
}
if (!$aResult) {
// Call Mutalyzer only when we didn't call our own tool yet.
$aResult = json_decode(file_get_contents($_CONFIG['mutalyzer_URL'] . '/json/runMutalyzerLight?variant=' . $sVariant), true);
}
if (!$aResult || !isset($aResult['genomicDescription'])) {
// Error? Just report. They must be new variants, anyway.
// If this is a recognized Mutalyzer error, we want to cache this as well, so we won't keep running into it.
$aError = array();
if (!empty($aResult['errors']) && isset($aResult['messages'])) {
foreach ($aResult['messages'] as $aMessage) {
if (isset($aMessage['errorcode'])) {
// Cache this error.
$aError[$aMessage['errorcode']] = $aMessage['message'];
}
}
// Save to cache.
file_put_contents($_CONFIG['user']['mutalyzer_cache_NC'], $sVariant . "\t" . json_encode($aError) . "\n", FILE_APPEND);
$nVariantsAddedToCache ++;
}
lovd_printIfVerbose(VERBOSITY_MEDIUM,
' ' . date('H:i:s', time() - $tStart) . ' [' . str_pad(number_format(
floor($nVariantsDone * 1000 / $nVariants) / 10, 1),
5, ' ', STR_PAD_LEFT) . '%] Warning: Error for variant ' . $sID . ' (' . implode(', ', array_keys($aVariant['classifications'])) . ").\n" .
' It was sent as ' . $sVariant . ".\n" .
(!$aError? '' : ' Error: ' . implode("\n" . str_repeat(' ', 26), $aError) . "\n") .
' {' . $aVariant['id'] . '|' . $aVariant['chromosome'] . '|' . $aVariant['start'] . '|' . $aVariant['ref'] . '|' . $aVariant['alt'] . '|' . $aVariant['gene'] . '|' . (!$aError? '' : 'Error: ' . implode(';', $aError)) . '|' . implode(',', array_keys($aVariant['classifications'])) . '}' . "\n");
$nWarningsOccurred ++;
$nVariantsLost ++;
$nVariantsDone ++;
unset($aData[$nKey]); // We don't want to continue working with this variant.
continue; // Next variant.
}
$sVariantCorrected = $aResult['genomicDescription'];
// While we're here, let's not repeat this call later.
// The given mappings are already corrected, so let's use them.
$aMutalyzerTranscripts = array();
$aMutalyzerMappings = array();
foreach ($aResult['legend'] as $aLegend) {
// We'll store all mappings, since we don't know which ones we want.
if ($aVariant['chromosome'] == 'M' && empty($aLegend['id'])) {
$aLegend['id'] = $_SETT['human_builds'][$_CONFIG['user']['refseq_build']]['ncbi_sequences'][$aVariant['chromosome']] .
'(' . $aLegend['name'] . ')';
}
$aMutalyzerTranscripts[$aLegend['name']] = $aLegend['id'];
}
// Loop mappings on the transcript, resolving the transcript IDs.
foreach ($aResult['transcriptDescriptions'] as $sMapping) {
list(,$sTranscript,, $sDNA) = preg_split('/[():]/', $sMapping);
if (isset($aMutalyzerTranscripts[$sTranscript])) {
// This should always be true, but I won't complain if this fails, whatever.
$aMutalyzerMappings[$aMutalyzerTranscripts[$sTranscript]] = array(
'c' => $sDNA,
);
}
}
// Now get the protein descriptions, too.
foreach ($aResult['proteinDescriptions'] as $sMapping) {
list(,$sIsoform,, $sProtein) = preg_split('/[():]/', $sMapping, 4);
// Generate transcript name (v-number) from protein isoform name (i-number).
$sTranscript = str_replace('_i', '_v', $sIsoform);
if (isset($aMutalyzerMappings[$aMutalyzerTranscripts[$sTranscript]])) {
// This should always be true, but I won't complain if this fails, whatever.
$aMutalyzerMappings[$aMutalyzerTranscripts[$sTranscript]]['p'] = $sProtein;
}
}
// Add to caches; mapping cache and NC cache.
// There are multiple descriptions that can lead to the same corrected variant,
// so we might know this mapping already from an uncached, different alternative description.
if (!isset($_CACHE['mutalyzer_cache_mapping'][$sVariantCorrected])) {
// We trust the cache more than the new data.