forked from AlmaasLab/AutoKEGGRec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutoKEGGRec.m
1726 lines (1593 loc) · 81.5 KB
/
AutoKEGGRec.m
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
function [ outputStruct ] = AutoKEGGRec( organismCodes, varargin )
%
% Assembles one or more genome-scale metabolic reconstructions COBRA
% structures based on KEGG which are output to workspace and can be
% written to file. Reconstructions can be for single organisms,
% communities, or consolidated, i.e. the union of several organisms.
%
% USAGE:
%
% outputStruct = AutoKEGGRec(organismKEGGIDs, varargin)
%
% INPUTS:
%
% organismKEGGIDs: string array of KEGG organism IDs
%
% OPTIONAL INPUTS:
%
% varargin: Optional flags, altering the output structure.
% - 'ConsolidatedRec': Creates a consolidated
% reconstruction of the given organisms.
% - 'SingleRecs': Creates separate reconstructions for all
% given organisms.
% - 'CommunityRec': Creates a community reconstruction for
% all given organisms.
% - 'writeSBML': Uses the COBRA writeSBML function to save the
% reconstructions as SBML files in your "Current Folder".
% - 'OmittedData': Adds data to the output structure on
% reactions omitted during reconstruction.
% - 'OrgRxnGen': Adds the Organisms-Reactions-Genes-Matrix for the
% query organisms to the output structure.
% - 'DisconnectedReactions': Adds a cell to the output
% structure containing the KEGG reaction IDs for all
% reactions in the metabolic network not connected to the
% giant component.
% - 'GenePlot': Plots the number of reactions associated with
% X number of genes against X.
% - 'Histogram': Plots number of reactions present in X
% organisms against X.
%
% .. AUTHORS:
% - Emil Karlsen and Christian Schulz, April 2018 - Created
% - Christian Schulz, August 2018 - Added compound assembly and annotations + notes + changes in omitted output
% - Emil Karlsen, March 2024 - Compatibility patch for KEGG API updates +
% various minor changes and updates
%
% EXAMPLES:
%
% % Create a consolidated reconstruction of the E. coli K12 strains in KEGG
% % using most of the flags
% output = AutoKEGGRec(["eco","ecj","ecd","ebw","ecok"], 'ConsolidatedRec', 'SingleRecs', 'CommunityRec', 'OrgRxnGen', 'GenePlot', 'Histogram', 'OmittedData', 'DisconnectedReactions')
%
% % Create both a consolidated and a community reconstruction of the E.
% % coli K12 strains in KEGG
% output =
% AutoKEGGRec(["eco","ecj","ecd","ebw","ecok"],'ConsolidatedRec','CommunityRec')
%
% % Create separate reconstructions of the E. coli K12 strains in KEGG
% output = AutoKEGGRec(["eco","ecj","ecd","ebw","ecok"],'SingleRecs')
%
% NOTE:
%
% Organism IDs have to be KEGG IDs (e.g. "eco" or "T00007").
% They have to be given in a string array (e.g. ["eco","ecj","ecd"]).
%
% Refer to the Manual for further and more detailed instructions and to the paper for general explanations.
%
% New versions may be available:
%
% https://www.ntnu.edu/almaaslab/downloads
% https://github.com/emikar/AutoKEGGRec
%
%
%
%%
disp('Running AutoKEGGRec...')
disp('Please check the websites specified within the help function for the newest version.');
disp('')
pause(5)
tic
%% Input args
ConsolidatedRecFlag=false;
SingleRecsFlag=false;
CommunityRecFlag=false;
writeSBMLflag=false;
OrgRxnGenFlag = false;
GenePlotFlag = false;
HistogramFlag = false;
OmittedDataFlag = false;
DisconnectedReactionsFlag = false;
DebugFlag = false;
arguments=false;
recBeingBuilt = false;
% Check OrganismCodes input
if ~isstring(organismCodes)
error('The given Organism Codes have to be a list of strings!')
end
if length(char(organismCodes))<3
error('Missing or wrong organism codes.')
end
KeyWords = {'ConsolidatedRec', 'SingleRecs', 'CommunityRec', 'writeSBML', 'OrgRxnGen', 'GenePlot', 'Histogram', 'OmittedData', 'DisconnectedReactions', 'Debug'};
%Check flags
if numel(varargin) > 0
for argum=1:numel(varargin)
if ischar(varargin{argum})
if any(ismember(varargin{argum}, KeyWords))
arguments = true;
else
disp(varargin{argum})
error('Unrecognized command: "%s"\nPlease refer to the help function (F1) or the manual.',string(varargin{argum}));
end
end
end
else
arguments = true;
end
if arguments
if isempty(varargin)
disp("Default settings: Consolidated reconstruction as output.")
ConsolidatedRecFlag = true;
recBeingBuilt = true;
else
disp("The selected flags:")
for argum=1:numel(varargin)
n = find(strcmp(KeyWords,varargin(argum)));
switch n
case 1
ConsolidatedRecFlag = true;
recBeingBuilt = true;
disp("ConsolidatedRecflag")
case 2
SingleRecsFlag = true;
recBeingBuilt = true;
disp("SingleRecsflag")
case 3
CommunityRecFlag = true;
recBeingBuilt = true;
disp("CommunityRecflag")
case 4
writeSBMLflag = true;
disp("writeSBMLflag")
case 5
OrgRxnGenFlag = true;
disp("OrgRxnGenFlag")
case 6
GenePlotFlag = true;
disp("GenePlotFlag")
case 7
HistogramFlag = true;
disp("HistogramFlag")
case 8
OmittedDataFlag = true;
disp("OmittedDataFlag")
case 9
DisconnectedReactionsFlag = true;
disp("DisconnectedReactionsFlag")
case 10
DebugFlag = true;
disp("DebugFlag")
% Causes the annotation matrices to be written to file for inspection.
% Particularly useful to check for changes in the KEGG API.
end
end
end
else
error('Bad arguments');
end
if (writeSBMLflag) && ~recBeingBuilt
error('In order to write an SBML file, a reconstruction needs to be built.\nUse optional input ConsolidatedRec, SingleRecs, and/or CommunityRec. %s',"")
elseif (DisconnectedReactionsFlag) && ~recBeingBuilt
error('In order to identify disconnected reactions, a reconstruction needs to be built.\nUse optional input ConsolidatedRec, SingleRecs, and/or CommunityRec. %s',"")
end
%% Initialization (defining variables etc.)
apiRequestWaitTime = 0.1;
options = weboptions('Timeout', 500);
keggURL = "http://rest.kegg.jp/";
%Building URLs for retrieving organism gene and enzyme data
nOrganisms = length(organismCodes);
organismGenesToECURLs = strings(1,nOrganisms);
fprintf("\n \n");
disp("KEGG organism codes:")
disp(organismCodes)
for i=1:nOrganisms
organismGenesToECURLs(i) = keggURL+"link/"+organismCodes(i)+"/ec";
end
fprintf("\n \n");
disp("Starting accessing the KEGG Database for the requested organisms.")
%Building URLs for retrieving enzyme-reaction and reaction-metabolite
%linkage data.
ecToRxnURL = keggURL+"link/ec/rn";
rxnToMetURL = keggURL+"link/rn/cpd";
% Retrieving reaction, enzyme, and compound lists
rxnList = cellstr(webread(keggURL+"list/reaction", options));
enzList = cellstr(webread(keggURL+"list/enzyme", options));
metList = cellstr(webread(keggURL+"list/compound", options));
% Splitting into lines
rxnList = splitlines(rxnList);
enzList = splitlines(enzList);
metList = splitlines(metList);
% Splitting lines by tab
rxnList = split(rxnList, ' ');
enzList = split(enzList, ' ');
metList = split(metList, ' ');
% Keeping first element of each line
rxnList = rxnList(:,1);
enzList = enzList(:,1);
metList = metList(:,1);
% Adding prefixes to the KEGG IDs
rxnList = strcat("rn:", rxnList);
enzList = strcat("ec:", enzList);
metList = strcat("cpd:", metList);
nRxns = length(rxnList);
nEnzs = length(enzList);
nMets = length(metList);
%Building reaction, enzyme and compound references (name to #)
rxnRef = containers.Map(rxnList,1:length(rxnList));
enzRef = containers.Map(enzList,1:length(enzList));
metRef = containers.Map(metList,1:length(metList));
disp("All organism URLs have been built, and the reactions, compound and EC number linkage have been downloaded.")
%% Makes a cell array of string matrices associating EC numbers and genes
organismGeneToECLists = cell(1,nOrganisms);
ecToRxn = cell(1);
rxnToMet = cell(1);
% Make an nRxns-by-2 matrix of strings with EC numbers and associated genes
% for each organism, and retrieve enzyme-reaction and reaction-metabolite linkage
for i=1:nOrganisms+2
if i<=nOrganisms
urlIn = organismGenesToECURLs(i);
elseif i==nOrganisms+1
urlIn = ecToRxnURL;
elseif i==nOrganisms+2
urlIn = rxnToMetURL;
end
importedRawData = webread(urlIn, options);
splitData = strsplit(importedRawData);
spliDatLen = length(splitData);
if mod(spliDatLen,2)==1
iterNum = spliDatLen-1;
else
iterNum = spliDatLen;
end
linkageMat = repmat("",[iterNum/2 2]);
for j=1:iterNum
linkageMat(ceil(j/2),mod(j+1,2)+1) = splitData(j);
end
tableThing = table(linkageMat(:,1),linkageMat(:,2));
if i<=nOrganisms
organismGeneToECLists{i} = table2cell(tableThing);
elseif i==nOrganisms+1
ecToRxn = table2cell(tableThing);
elseif i==nOrganisms+2
rxnToMet = table2cell(tableThing);
end
end
time = toc;
fprintf("\nTime so far running AutoKEGGRec: %.0f seconds.\n\n", time);
disp("All organism gene-to-reaction linkages have been downloaded.")
%Building reaction-enyme matrix
rxnEnzMat = zeros(length(rxnList),length(enzList));
for i=1:length(ecToRxn)
rxnPos = rxnRef(char(ecToRxn{i,1}));
enzPos = enzRef(char(ecToRxn{i,2}));
rxnEnzMat(rxnPos,enzPos)=1;
end
%Building reaction-compound matrix
rxnMetMat = zeros(length(rxnList),length(metList));
for i=1:length(rxnToMet)
metPos = metRef(char(rxnToMet{i,1}));
rxnPos = rxnRef(char(rxnToMet{i,2}));
rxnMetMat(rxnPos,metPos)=1;
end
disp("Compound-to-reaction and reaction-to-enzyme matrices built. Starting organism-to-reaction matrix now.")
%% Building reaction-organism matrix
% Builds a binary matrix tying each reaction in KEGG to each of the query
% organisms
rxnOrganismMatrix = zeros(nOrganisms,nRxns);
omittedECNumbers = strings(0);
for i=1:nOrganisms
ECNumberIndexesToRemove = zeros(1,nOrganisms);
for j=1:length(organismGeneToECLists{i})
try
reactions = find(rxnEnzMat(:,enzRef(char(cellstr(organismGeneToECLists{i}(j,1)))))>0);
for k=1:length(reactions)
rxnOrganismMatrix(i,rxnRef(rxnList{reactions(k)})) = 1;
end
catch
warning("AutoKEGGRec: EC number: "+cellstr(organismGeneToECLists{i}(j,1))+" not found in KEGG database.")
omittedECNumbers = [omittedECNumbers; cellstr(organismGeneToECLists{i}(j,1))];
% Marking the EC number from the list of EC numbers to be
% checked for reactions for removal
ECNumberIndexesToRemove(j) = 1;
end
end
% Removing the EC numbers that did not return any reactions
organismGeneToECLists{i}(find(ECNumberIndexesToRemove),:) = [];
end
disp("Matrices built.")
if recBeingBuilt
disp("Commencing assembly of reconstruction(s).");
end
% Selecting all reactions in at least one organism
if nOrganisms == 1
rxnsToBuildList = find(rxnOrganismMatrix>0);
else
rxnsToBuildList = find(sum(rxnOrganismMatrix([1:end],:)>0));
end
%% Building reaction-organism matrix with genes
% Builds a string matrix tying each reaction in KEGG to each of the query
% organisms through the respective genes.
%
% NB: The reactions are assumed to depend on the genes in an OR-fashion
% NB2: ATP reaction
%
% Ex:
% Org1 Org2 ...
% Rx1 G1 | G2 G14 | G10
% Rx2 - G12
% :
rxnOrganismGeneMatrix = strings(nRxns,nOrganisms);
rxnOrganismGeneMatrixCounter = zeros(nRxns,nOrganisms);
for org=1:nOrganisms
for gene=1:length(organismGeneToECLists{org})
ecNum = char(string(organismGeneToECLists{org}(gene,1)));
ecIndex = enzRef(ecNum);
rxnIndicesForEC = find(rxnEnzMat(:,ecIndex)>0);
for rxnIndex=1:length(rxnIndicesForEC)
if rxnOrganismGeneMatrix(rxnIndicesForEC(rxnIndex),org)~=""
rxnOrganismGeneMatrix(rxnIndicesForEC(rxnIndex),org) = rxnOrganismGeneMatrix(rxnIndicesForEC(rxnIndex),org)+" | ";
end
geneName = string(organismGeneToECLists{org}(gene,2));
geneName = strrep(geneName,organismCodes(org)+":","");
%genes without organism code HERE
rxnOrganismGeneMatrix(rxnIndicesForEC(rxnIndex),org) = rxnOrganismGeneMatrix(rxnIndicesForEC(rxnIndex),org)+geneName;
rxnOrganismGeneMatrixCounter(rxnIndicesForEC(rxnIndex),org) = rxnOrganismGeneMatrixCounter(rxnIndicesForEC(rxnIndex),org)+1;
end
end
end
%% Plot number of genes per reaction for each organism
if GenePlotFlag
geneCounterList = zeros(max(max(rxnOrganismGeneMatrixCounter)),nOrganisms);
reactionCounter = 0;
subplotX = ceil(sqrt(nOrganisms));
subplotY = ceil(nOrganisms/ceil(sqrt(nOrganisms)));
figure
for org=1:nOrganisms
for rxn=1:nRxns
if rxnOrganismGeneMatrixCounter(rxn,org)>0
geneCounterList(rxnOrganismGeneMatrixCounter(rxn,org),org)=geneCounterList(rxnOrganismGeneMatrixCounter(rxn,org),org)+1;
reactionCounter = reactionCounter+1;
end
end
subplot(subplotX,subplotY,org)
geneCountsToPlot = geneCounterList;
geneCountsToPlot(max(find(geneCountsToPlot(:,org)~=0)),org)=0;
geneCountToPlot = geneCountsToPlot(1:max(find(geneCountsToPlot(:,org)~=0)),org);
bar(geneCountToPlot)
xlabel(['Number of genes per reaction']) % x-axis label
ylabel('Number of reactions') % y-axis label
set(gca, 'YScale', 'log')
title(['KEGG organism ID: ' organismCodes(org)])
end
end
%% Plot rxns for organism histogram
if HistogramFlag
figure;
organismHistData = sum(rxnOrganismMatrix);
histogram(organismHistData(organismHistData>0));
title(string('Number of Organisms (KEGG IDs: ' + strjoin(organismCodes,', ') + ') sharing the same reaction'))
xlabel("Number of organisms sharing number of reactions")
ylabel("Number of reactions")
histogramPlotHandle = gca;
set(histogramPlotHandle, 'YScale', 'log')
xLims = xlim;
set(histogramPlotHandle, 'xtick', 1:ceil(xLims(2)))
end
%% Getting all the reactions from KEGG according to matrix
if recBeingBuilt || OmittedDataFlag
fprintf("%-55s %10d\n", "Number of KEGG reactions for the KEGG organism(s) queried:", length(rxnsToBuildList));
disp("Downloading all reactions from KEGG (this takes a while).")
fprintf('Progress:\n');
fprintf(['\n' repmat('.',1,100) '\n\n']);
loadBarUpdatePoints = ceil(linspace(1,length(rxnsToBuildList)));
downloadedData = cell(length(rxnsToBuildList));
for i=1:length(rxnsToBuildList)
downloadedData{i} = cellstr(webread(keggURL+"get/"+rxnList(rxnsToBuildList(i)), options));
downloadedData{i} = replace(downloadedData{i},"///","");
pause(apiRequestWaitTime)
if ~isempty(find(loadBarUpdatePoints==i, 1))
fprintf('\b|\n');
end
end
equation_list_all = strings(1,length(rxnsToBuildList));
metaDataList = equation_list_all;
metaDataDumpList = equation_list_all;
reactionDumpList = equation_list_all;
glycanReactions = 0;
nContainingReactions = 0;
numGenReactions = 0;
numMovedReactions = 0;
sugarReactions = 0;
polymerReactions = 0;
for i=1:length(downloadedData)
webRxnData = string(downloadedData{i});
webRxnData = splitlines(webRxnData);
generalReac = webRxnData(contains(webRxnData,"COMMENT"));
rxnEquation = webRxnData(contains(webRxnData,"EQUATION"));
if ~isempty(webRxnData(contains(webRxnData,"REMARK")))
numMovedReactions = numMovedReactions + 1;
if ~isempty(rxnEquation(contains(rxnEquation, 'G')))
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction contains glycans, which have a C-compound ID as well. Check carefully. Check carefully!"]);
glycanReactions = glycanReactions+1;
% Removing reactions containing sugars (double reactions)
elseif ~isempty(rxnEquation(contains(rxnEquation, 'n')))
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction is a reaction containing n in the equation. Check carefully!"]);
nContainingReactions = nContainingReactions+1;
% Removing reactions containing polymers (double reactions)
else
equation_list_all(i) = replace(rxnEquation,"EQUATION ","");
numMovedReactions = numMovedReactions - 1;
metaDataList(i) = join(string(webRxnData),";");
%This way all the "same as suggar" , ... are sorted out, only
%the C-compounts are kept.
end
elseif ~isempty(generalReac(contains(generalReac,'GENERIC')))
numGenReactions = numGenReactions + 1;
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction is a generic reaction. Check carefully!"]);
%Generic reactions are removed
elseif ~isempty(generalReac(contains(generalReac,'GENERAL')))
numGenReactions = numGenReactions + 1;
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction is a genral reaction. Check carefully!"]);
%Generic reactions are removed
elseif ~isempty(generalReac(contains(generalReac,'general reaction')))
numGenReactions = numGenReactions + 1;
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction is a genral reaction. Check carefully!"]);
%Generic reactions are removed
else
if ~isempty(rxnEquation(contains(rxnEquation, 'G')))
% Reactions containing suggars that are not marked within the
% comment field; They are added to the reconstruction, but they are
% marked within the attention field.
sugarReactions = sugarReactions + 1;
equation_list_all(i) = replace(rxnEquation,"EQUATION ","");
metaDataList(i) = join(string(webRxnData),";");
metaDataList(i) = insertBefore(metaDataList(i),[";DEFINITION"],[";ATTENTION The reaction contains a sugar!"]);
elseif ~isempty(rxnEquation(contains(rxnEquation, 'n')))
% Reactions containing "n" within the reaction equation. This
% is meant to deal with polymer reactions. These are removed,
% since for the S-Matrix A + B <-> C + A becomes a problem. The
% user has the possibility to implement them later.
%
% First, the reactions are changed:
% nA + (n-1)B <-> C + (n+1)A becomes
% A + B <-> C + A
% The original equation is stored in the comments.
polymerReactions = polymerReactions + 1;
rxnEquation1 = string(rxnEquation);
rxnEquation1 = strsplit(rxnEquation1);
EQ = ("EQUATION ");
for ii=1:length(rxnEquation1)
totest = char(rxnEquation1(ii));
if ~isempty(totest(contains(totest, 'C'))) || ~isempty(totest(contains(totest, 'G')))
if ~isempty(totest(contains(totest, 'C')))
posC = strfind(totest, "C");
if ii<length(rxnEquation1)
trytest = rxnEquation1(ii+1);
if ~isempty(trytest(contains(trytest, '=')))
EQ = EQ + totest(posC:posC+5);
else
temp = totest(posC:posC+5) + " + ";
EQ = EQ + temp;
end
else
EQ = EQ + totest(posC:posC+5);
end
elseif ~isempty(totest(contains(totest, 'G')))
posG = strfind(totest, "G");
if ii<length(rxnEquation1)
trytest = rxnEquation1(ii+1);
if ~isempty(trytest(contains(trytest, '=')))
EQ = EQ + totest(posG:posG+5);
else
temp = totest(posG:posG+5) + " + ";
EQ = EQ + temp;
end
else
EQ = EQ + totest(posG:posG+5);
end
end
elseif ~isempty(totest(contains(totest, '=')))
totest = " " + totest + " ";
EQ = EQ + totest;
end
end
rxnEquation = EQ;
reactionDumpList(i) = replace(rxnEquation,"EQUATION ","");
metaDataDumpList(i) = join(string(webRxnData),";");
metaDataDumpList(i) = insertBefore(metaDataDumpList(i),[";DEFINITION"],[";ATTENTION The reaction is a polymer reaction. For the reconstruction, the polymerisation has been removed. The original reaction is stored!"]);
else
% "Normal" reactions are put into the List
equation_list_all(i) = replace(rxnEquation,"EQUATION ","");
rxnEquation = equation_list_all(i);
metaDataList(i) = join(string(webRxnData),";");
%Checking for equatic aberrations, ie. characters in
%biochemical equations that were not accounted for above.
charsToTest = char(rxnEquation);
greenLightedChars = '1234567890C<=>+ ';
for k=1:length(charsToTest)
if ~contains(greenLightedChars,charsToTest(k))
errorMsg = sprintf("Error using AutoKEGGRec: Unexpected sign in reaction equaton: %s\n",rxnEquation);
error(char(errorMsg));
end
end
end
end
if ~isempty(find(loadBarUpdatePoints==i))
fprintf('\b|\n');
end
end
fprintf("\n \n")
time = toc;
disp("All reactions needed have been fetched.")
fprintf("\nTime so far running AutoKEGGRec: %.0f seconds.\n\n", time);
%Reaction checking for double Compounds (e.g. C00029 + C00760 <=> C00015 +
%C00760); Moving them into the reactionDumpList
reactionsProducingTheirOwnSubstrate = 0;
for rxn=1:length(equation_list_all)
onlycompounds = false;
cpdNames = split(equation_list_all(rxn));
for i=1:length(cpdNames)
if length(char(cpdNames(i)))==6 && sum(count(cpdNames, cpdNames(i)))>1
onlycompounds = true;
end
end
if onlycompounds
reactionDumpList(rxn) = equation_list_all(rxn);
equation_list_all(rxn) = "";
metaDataDumpList(rxn) = metaDataList(rxn);
metaDataList(rxn) = "";
reactionsProducingTheirOwnSubstrate = reactionsProducingTheirOwnSubstrate + 1;
metaDataDumpList(rxn) = insertBefore(metaDataDumpList(rxn),[";DEFINITION"],[";ATTENTION The reaction hase the same compound on both sites of the reaction. Check carefully!"]);
end
end
rxnKeggNamesList = string(rxnList(rxnsToBuildList));
%% Removing the empty fields, that only the reactions stay within the matrix to not check for compounds again
deletionIndex = zeros(1,length(equation_list_all));
equation_list_keep = equation_list_all;
for i=1:length(equation_list_all)
if length(char(equation_list_keep(i)))<1
deletionIndex(i) = 1;
end
end
% Removing reactions not to be kept
equation_list_keep(find(deletionIndex)) = [];
%% Getting the Compound information from KEGG
% Getting the compounds
cpdlist = [];
for reac=1:length(equation_list_keep)
reactemp = split(equation_list_keep(reac));
for cmpd=1:length(reactemp)
if length(char(reactemp(cmpd))) == 6
cpdlist = [cpdlist, reactemp(cmpd)];
end
end
end
cpdlist = unique(cpdlist);
fprintf("%-55s %10d\n", "Number of unque KEGG compounds for the organism(s) queried:", length(cpdlist));
disp("Downloading all compounds from KEGG (this takes a while).")
% downloading the compound information from KEGG
downloadedDataCPD = cell(size(cpdlist));
fprintf('Progress: \n');
fprintf(['\n' repmat('.',1,100) '\n\n']);
loadBarUpdatePoints = ceil(linspace(1,length(cpdlist)));
for i=1:length(cpdlist)
downloadedDataCPD{i} = cellstr(webread(keggURL+"/get/"+cpdlist(i), options));
downloadedDataCPD{i} = replace(downloadedDataCPD{i},"///","");
pause(apiRequestWaitTime)
if ~isempty(find(loadBarUpdatePoints==i))
fprintf('\b|\n');
end
end
stringlisttosearchforCPD = {'ENTRY', 'NAME', 'FORMULA', 'MASS', 'MOL_WEIGHT', 'REMARK','COMMENT', 'REACTION', 'PATHWAY', 'MODULE', 'ENZYME', 'BRITE', 'DBLINKS', 'ATOM', 'BOND', 'COMPOSITION', 'NODE', 'EDGE'};
fprintf("\n \n")
time = toc;
disp("All compounds needed have been fetched.")
fprintf("\nTime so far running AutoKEGGRec: %.0f seconds.\n\n", time);
disp("Adding KEGG annotations to the compounds.")
CPDannotationMatrix = num2cell(zeros(length(downloadedDataCPD),length(stringlisttosearchforCPD)));
% Preparing the Annotation fields by reshaping the KEGG information into
% a cell of specified fields according to stringlisttosearchforCPD
for i=1:length(downloadedDataCPD)
WebCPDData = string(downloadedDataCPD{i});
WebCPDData = join(split(WebCPDData));
containingmodulesCPD=[];
for list=1:length(stringlisttosearchforCPD)
searchvarCPD = strfind(WebCPDData, stringlisttosearchforCPD(list));
if ~isempty(searchvarCPD)
containingmodulesCPD = [containingmodulesCPD, string(stringlisttosearchforCPD(list))];
end
end
annotationsStrListCPD = WebCPDData;
for inputelementinstringCPD=1:length(containingmodulesCPD)
annotationsStrListCPD = insertBefore(annotationsStrListCPD, containingmodulesCPD(inputelementinstringCPD), ["%$%"]);
annotationsStrListCPD = insertAfter(annotationsStrListCPD, containingmodulesCPD(inputelementinstringCPD), ["%$%"]);
end
annotationsStrListCPD=strsplit(annotationsStrListCPD, "%$%");
for inputelementinstringCPD=1:length(annotationsStrListCPD)
position_of_annotation = strcmp(stringlisttosearchforCPD, annotationsStrListCPD(inputelementinstringCPD));
if sum(position_of_annotation) == 1
CPDannotationMatrix(i, position_of_annotation) = {annotationsStrListCPD(inputelementinstringCPD+1)};
end
end
end
% Changing the compound name fields to the corresponding KEGG IDs
for cpd=1:length(CPDannotationMatrix(:,1))
splitstringCPD = split(string(CPDannotationMatrix(cpd)));
CPDannotationMatrix(cpd) = cellstr(splitstringCPD(2));
end
% Identify generic compounds according to their molelcular weight = 0
genericCPDs = string(CPDannotationMatrix(find(string(CPDannotationMatrix(1:end,4))=="0")));
% Identify reactions containing these generic compounds
reactionCheckList = [];
for reac=1:length(equation_list_keep)
reactemp = split(equation_list_keep(reac));
for cmpd=1:length(reactemp)
if length(char(reactemp(cmpd))) == 6 && contains(reactemp(cmpd), genericCPDs)
reactionCheckList = [reactionCheckList, equation_list_keep(reac)];
end
end
end
reactionCheckList = unique (reactionCheckList);
% Cleaning the reaction list of these reactions and adding them to the
% omitted reactions, adding a comment to the cleaned reactions, why
% they have been moved
for cleanreac = 1:length(equation_list_all)
if sum(strcmp(equation_list_all(cleanreac), reactionCheckList)) == 1
reactionDumpList(cleanreac) = string(equation_list_all(cleanreac));
equation_list_all(cleanreac) = "";
metaDataDumpList(cleanreac) = metaDataList(cleanreac);
if contains(metaDataDumpList(cleanreac), "ATTENTION")
metaDataDumpList(cleanreac) = insertBefore(metaDataDumpList(cleanreac),[";DEFINITION"],[" Furthermore, this reaction contains a generic compound or a compound without mass in KEGG. Check the compounds carefully before adding reaction to model!"]);
else
metaDataDumpList(cleanreac) = insertBefore(metaDataDumpList(cleanreac),[";DEFINITION"],[";ATTENTION This reactions contains a generic compound or a compound without mass in KEGG. Check the compounds carefully before adding reaction to model!"]);
end
metaDataList(cleanreac) = "";
end
end
% Removing reactions not to be kept from the reaction list
deletionIndex = zeros(1,length(equation_list_all));
equation_list_keep = equation_list_all;
for i=1:length(equation_list_all)
if length(char(equation_list_keep(i)))<1
deletionIndex(i) = 1;
end
end
equation_list_keep(find(deletionIndex)) = [];
%% Removing the empty fields, that only the reactions stay within the matrix
deletionIndexDUMP = zeros(1,length(reactionDumpList));
reactionDumpList2 = reactionDumpList;
for i=1:length(reactionDumpList)
if length(char(reactionDumpList2(i)))<1
deletionIndexDUMP(i) = 1;
end
end
reactionDumpList2(find(deletionIndexDUMP)) = [];
if OmittedDataFlag
dumpAnnotations=cellstr(metaDataDumpList);
dumpAnnotations = dumpAnnotations(~cellfun('isempty',dumpAnnotations));
end
end
%% Adding annotations to the omitted output
if OmittedDataFlag
%%% Compounds
omittedCPDs = struct();
for dumpcpds=1:length(genericCPDs)
omittedCPDs.(char(genericCPDs(dumpcpds)))= cell(length(stringlisttosearchforCPD),2);
posinCPDList = strcmp(CPDannotationMatrix(:,1), genericCPDs(dumpcpds));
for downw=1:length(stringlisttosearchforCPD)
omittedCPDs.(char(genericCPDs(dumpcpds))){downw,1} = string(stringlisttosearchforCPD(downw));
omittedCPDs.(char(genericCPDs(dumpcpds))){downw,2} = string(CPDannotationMatrix(posinCPDList,downw));
end
end
%%% Reactions
stringlisttosearchfor = {'ENTRY', 'NAME', 'ATTENTION', 'DEFINITION', 'EQUATION', 'COMMENT', 'RCLASS', 'ENZYME', 'PATHWAY', 'ORTHOLOGY', 'DBLINKS', 'REFERENCE', 'RHEA:'};
disp("Adding KEGG annotations to the reactions and compounds within the omitted data.")
for line=1:length(dumpAnnotations)
annotationsStrListdump=string(dumpAnnotations(line));
containingmodules={};
for list=1:length(stringlisttosearchfor)
searchvar = strfind(annotationsStrListdump, stringlisttosearchfor(list));
if ~isempty(searchvar)
containingmodules{end+1} = string(stringlisttosearchfor(list));
end
end
containingmodules=string(containingmodules);
annotationssplitsting=annotationsStrListdump;
for inputelementinstring=1:length(containingmodules)
if inputelementinstring==1
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(2) + " "));
relevantannotation = annotationssplitsting(1);
relevantannotation=strsplit(relevantannotation, (containingmodules(inputelementinstring)));
relevantannotation=relevantannotation(2);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=char(strtrim(temp2));
relevantannotation=temp2(1:6);
annotationssplitsting = annotationssplitsting(2);
elseif inputelementinstring==length(containingmodules)
if containingmodules(inputelementinstring)=='RHEA:'
annotationssplitsting=strsplit(annotationssplitsting, (":"));
relevantannotation = annotationssplitsting(2);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
else
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(inputelementinstring) + " "));
relevantannotation = annotationssplitsting(1);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
end
else
tempsplitnumber = inputelementinstring + 1;
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(tempsplitnumber) + " "));
relevantannotation = annotationssplitsting(1);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
if length(annotationssplitsting)>1
annotationssplitsting = annotationssplitsting(2);
else
annotationssplitsting=relevantannotation;
relevantannotation = 0;
end
end
position_of_annotation = strcmp(stringlisttosearchfor, containingmodules(inputelementinstring));
annotationMatrixdump(line, position_of_annotation) = {relevantannotation};
end
end
omittedrxns = struct();
for dumprxns=1:length(annotationMatrixdump(:,2))
omittedrxns.(char(annotationMatrixdump(dumprxns,1))) = cell(length(stringlisttosearchfor),2);
for downw=1:length(stringlisttosearchfor)
omittedrxns.(char(annotationMatrixdump(dumprxns,1))){downw,1} = string(stringlisttosearchfor(downw));
if isempty(annotationMatrixdump{dumprxns, downw})
omittedrxns.(char(annotationMatrixdump(dumprxns,1))){downw,2}= [];
else
omittedrxns.(char(annotationMatrixdump(dumprxns,1))){downw,2} = string(annotationMatrixdump(dumprxns, downw));
end
end
end
end
pause(3)
%% Building consolidated reconstruction
if recBeingBuilt
disp("Building consolidated reconstruction.");
pause(2)
annotations=cellstr(reshape(metaDataList,[length(metaDataList),1]));
% Removing empty annotations
annotations = annotations(~cellfun('isempty',annotations));
ReactionFormulas = cellstr(equation_list_keep);
ReactionNames = cellstr(rxnKeggNamesList);
ReactionNames2 = cellfun(@(x) x(1:end,4:9), ReactionNames, 'un',0);
ReactionNames2(find(deletionIndex)) = [];
lowerbounds = [ones(1,length(equation_list_keep))*-20];
upperbounds = [ones(1,length(equation_list_keep))*20];
[throwAwayText,consolidatedStruct] = evalc(char("createModel(ReactionNames2, ReactionNames2, ReactionFormulas, 'lowerBoundList', lowerbounds, 'upperBoundList', upperbounds);"));
%% Adding annotations to reactions
stringlisttosearchfor = {'ENTRY', 'NAME', 'ATTENTION', 'DEFINITION', 'EQUATION', 'COMMENT', 'RCLASS', 'ENZYME', 'PATHWAY', 'MODULE', 'BRITE', 'ORTHOLOGY', 'DBLINKS', 'REFERENCE', 'RHEA:'};
annotationsStrList=strings(1,length(annotations));
annotationMatrix = num2cell(zeros(length(annotations),length(stringlisttosearchfor)));
disp("Adding KEGG annotations to the reactions.")
for line=1:length(annotations)
annotationsStrList=string(annotations(line));
containingmodules={};
for list=1:length(stringlisttosearchfor)
searchvar = strfind(annotationsStrList, stringlisttosearchfor(list));
if ~isempty(searchvar)
containingmodules{end+1} = string(stringlisttosearchfor(list));
end
end
containingmodules=string(containingmodules);
annotationssplitsting=annotationsStrList;
for inputelementinstring=1:length(containingmodules)
if inputelementinstring==1
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(2) + " "));
relevantannotation = annotationssplitsting(1);
relevantannotation=strsplit(relevantannotation, (containingmodules(inputelementinstring)));
relevantannotation=relevantannotation(2);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=char(strtrim(temp2));
relevantannotation=temp2(1:6);
annotationssplitsting = annotationssplitsting(2);
elseif inputelementinstring==length(containingmodules)
if containingmodules(inputelementinstring)=='RHEA:'
annotationssplitsting=strsplit(annotationssplitsting, (":"));
relevantannotation = annotationssplitsting(2);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
else
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(inputelementinstring) + " "));
relevantannotation = annotationssplitsting(1);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
end
else
tempsplitnumber = inputelementinstring + 1;
annotationssplitsting=strsplit(annotationssplitsting, (";" + containingmodules(tempsplitnumber) + " "));
relevantannotation = annotationssplitsting(1);
temp2=relevantannotation;
temp1='';
while ~strcmp(temp1,temp2)
temp1=temp2;
temp2=regexprep(temp1,' ',' ');
end
temp2=strtrim(temp2);
relevantannotation=temp2;
if length(annotationssplitsting)>1
annotationssplitsting = annotationssplitsting(2);
else
annotationssplitsting=relevantannotation;
relevantannotation = 0;
end
end
position_of_annotation = strcmp(stringlisttosearchfor, containingmodules(inputelementinstring));
annotationMatrix(line, position_of_annotation) = {relevantannotation};
end
end
for rxn=1:length(annotationMatrix(:,2))
if string(annotationMatrix(rxn,2)) == "0"
annotationMatrix(rxn,2) = cellstr("Name not available. KEGG ID: "+string(cellstr(string(annotationMatrix(rxn,1)))));
end
end
% Writing annotationMatrix to file for debug
if DebugFlag
writetable(cell2table(annotationMatrix), 'annotationMatrix.csv', 'Delimiter', '\t')
end
% COBRA supported fields according to https://github.com/opencobra/cobratoolbox/blob/master/docs/source/notes/COBRAModelFields.md
dynamic_index = strcmp(stringlisttosearchfor, "ENTRY");
consolidatedStruct.rxnKeggID = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "NAME");
consolidatedStruct.rxnNames = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "REFERENCE");
consolidatedStruct.rxnReferences = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "ENZYME");
consolidatedStruct.rxnECNumbers = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "PATHWAY");
consolidatedStruct.subSystems = cell(length(cellstr(string(annotationMatrix(:,dynamic_index)))),1);
for rxn=1:length(cellstr(string(annotationMatrix(:,dynamic_index))))
consolidatedStruct.subSystems{rxn} = cellstr(string(annotationMatrix(rxn,dynamic_index)));
end
%COBRA not supported fields
dynamic_index = strcmp(stringlisttosearchfor, "ATTENTION");
consolidatedStruct.rxnAttention = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "DEFINITION");
consolidatedStruct.rxnDefinition = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "EQUATION");
consolidatedStruct.rxnEquation = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "COMMENT");
consolidatedStruct.rxnComment = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "RCLASS");
consolidatedStruct.rxnRclass = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "MODULE");
consolidatedStruct.rxnRhea = cellstr(string(annotationMatrix(:,dynamic_index)));
dynamic_index = strcmp(stringlisttosearchfor, "BRITE");